1 /*
   2  * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package sun.awt.X11;
  26 
  27 import java.awt.AWTEvent;
  28 import java.awt.AWTException;
  29 import java.awt.BufferCapabilities;
  30 import java.awt.Color;
  31 import java.awt.Component;
  32 import java.awt.Container;
  33 import java.awt.Cursor;
  34 import java.awt.Dimension;
  35 import java.awt.Font;
  36 import java.awt.FontMetrics;
  37 import java.awt.Graphics;
  38 import java.awt.GraphicsConfiguration;
  39 import java.awt.Image;
  40 import java.awt.Insets;
  41 import java.awt.KeyboardFocusManager;
  42 import java.awt.Rectangle;
  43 import java.awt.SystemColor;
  44 import java.awt.Toolkit;
  45 import java.awt.Window;
  46 import java.awt.dnd.DropTarget;
  47 import java.awt.dnd.peer.DropTargetPeer;
  48 import java.awt.event.FocusEvent;
  49 import java.awt.event.InputEvent;
  50 import java.awt.event.InputMethodEvent;
  51 import java.awt.event.KeyEvent;
  52 import java.awt.event.MouseEvent;
  53 import java.awt.event.MouseWheelEvent;
  54 import java.awt.event.PaintEvent;
  55 import java.awt.event.WindowEvent;
  56 import java.awt.event.InvocationEvent;
  57 import java.awt.image.ImageObserver;
  58 import java.awt.image.ImageProducer;
  59 import java.awt.image.VolatileImage;
  60 import java.awt.peer.ComponentPeer;
  61 import java.awt.peer.ContainerPeer;
  62 import java.awt.peer.LightweightPeer;
  63 import java.lang.reflect.*;
  64 import java.security.*;
  65 import java.util.Collection;
  66 import java.util.HashSet;
  67 import java.util.Set;
  68 import java.util.Vector;
  69 import sun.util.logging.PlatformLogger;
  70 
  71 import sun.awt.*;
  72 import sun.awt.event.IgnorePaintEvent;
  73 import sun.awt.image.SunVolatileImage;
  74 import sun.awt.image.ToolkitImage;
  75 import sun.java2d.BackBufferCapsProvider;
  76 import sun.java2d.pipe.Region;
  77 
  78 public class XComponentPeer extends XWindow implements ComponentPeer, DropTargetPeer,
  79     BackBufferCapsProvider
  80 {
  81     private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.X11.XComponentPeer");
  82     private static final PlatformLogger buffersLog = PlatformLogger.getLogger("sun.awt.X11.XComponentPeer.multibuffer");
  83     private static final PlatformLogger focusLog = PlatformLogger.getLogger("sun.awt.X11.focus.XComponentPeer");
  84     private static final PlatformLogger fontLog = PlatformLogger.getLogger("sun.awt.X11.font.XComponentPeer");
  85     private static final PlatformLogger enableLog = PlatformLogger.getLogger("sun.awt.X11.enable.XComponentPeer");
  86     private static final PlatformLogger shapeLog = PlatformLogger.getLogger("sun.awt.X11.shape.XComponentPeer");
  87 
  88     boolean paintPending = false;
  89     boolean isLayouting = false;
  90     boolean enabled;
  91 
  92     // Actually used only by XDecoratedPeer
  93     protected int boundsOperation;
  94 
  95     Color foreground;
  96     Color background;
  97 
  98     // Colors calculated as on Motif using MotifColorUtilties.
  99     // If you use these, call updateMotifColors() in the peer's Constructor and
 100     // setBackground().  Examples are XCheckboxPeer and XButtonPeer.
 101     Color darkShadow;
 102     Color lightShadow;
 103     Color selectColor;
 104 
 105     Font font;
 106     private long backBuffer = 0;
 107     private VolatileImage xBackBuffer = null;
 108 
 109     static Color[] systemColors;
 110 
 111     XComponentPeer() {
 112     }
 113 
 114     XComponentPeer (XCreateWindowParams params) {
 115         super(params);
 116     }
 117 
 118     XComponentPeer(Component target, long parentWindow, Rectangle bounds) {
 119         super(target, parentWindow, bounds);
 120     }
 121 
 122     /**
 123      * Standard peer constructor, with corresponding Component
 124      */
 125     XComponentPeer(Component target) {
 126         super(target);
 127     }
 128 
 129 
 130     void preInit(XCreateWindowParams params) {
 131         super.preInit(params);
 132         boundsOperation = DEFAULT_OPERATION;
 133     }
 134     void postInit(XCreateWindowParams params) {
 135         super.postInit(params);
 136         Color c;
 137         Font  f;
 138         Cursor cursor;
 139 
 140         pSetCursor(target.getCursor());
 141 
 142         foreground = target.getForeground();
 143         background = target.getBackground();
 144         font = target.getFont();
 145 
 146         if (isInitialReshape()) {
 147             Rectangle r = target.getBounds();
 148             reshape(r.x, r.y, r.width, r.height);
 149         }
 150 
 151         enabled = target.isEnabled();
 152 
 153         // If any of our heavyweight ancestors are disable, we should be too
 154         // See 6176875 for more information
 155         Component comp = target;
 156         while( !(comp == null || comp instanceof Window) ) {
 157             comp = comp.getParent();
 158             if( comp != null && !comp.isEnabled() && !comp.isLightweight() ){
 159                 setEnabled(false);
 160                 break;
 161             }
 162         }
 163         enableLog.fine("Initial enable state: {0}", Boolean.valueOf(enabled));
 164 
 165         if (target.isVisible()) {
 166             setVisible(true);
 167         }
 168     }
 169 
 170     protected boolean isInitialReshape() {
 171         return true;
 172     }
 173 
 174     public void reparent(ContainerPeer newNativeParent) {
 175         XComponentPeer newPeer = (XComponentPeer)newNativeParent;
 176         XToolkit.awtLock();
 177         try {
 178             XlibWrapper.XReparentWindow(XToolkit.getDisplay(), getWindow(), newPeer.getContentWindow(), x, y);
 179             parentWindow = newPeer;
 180         } finally {
 181             XToolkit.awtUnlock();
 182         }
 183     }
 184     public boolean isReparentSupported() {
 185         return System.getProperty("sun.awt.X11.XComponentPeer.reparentNotSupported", "false").equals("false");
 186     }
 187 
 188     public boolean isObscured() {
 189         Container container  = (target instanceof Container) ?
 190             (Container)target : target.getParent();
 191 
 192         if (container == null) {
 193             return true;
 194         }
 195 
 196         Container parent;
 197         while ((parent = container.getParent()) != null) {
 198             container = parent;
 199         }
 200 
 201         if (container instanceof Window) {
 202             XWindowPeer wpeer = (XWindowPeer)(container.getPeer());
 203             if (wpeer != null) {
 204                 return (wpeer.winAttr.visibilityState !=
 205                         wpeer.winAttr.AWT_UNOBSCURED);
 206             }
 207         }
 208         return true;
 209     }
 210 
 211     public boolean canDetermineObscurity() {
 212         return true;
 213     }
 214 
 215     /*************************************************
 216      * FOCUS STUFF
 217      *************************************************/
 218 
 219     /**
 220      * Keeps the track of focused state of the _NATIVE_ window
 221      */
 222     boolean bHasFocus = false;
 223 
 224     /**
 225      * Descendants should use this method to determine whether or not native window
 226      * has focus.
 227      */
 228     final public boolean hasFocus() {
 229         return bHasFocus;
 230     }
 231 
 232     /**
 233      * Called when component receives focus
 234      */
 235     public void focusGained(FocusEvent e) {
 236         focusLog.fine("{0}", e);
 237         bHasFocus = true;
 238     }
 239 
 240     /**
 241      * Called when component loses focus
 242      */
 243     public void focusLost(FocusEvent e) {
 244         focusLog.fine("{0}", e);
 245         bHasFocus = false;
 246     }
 247 
 248     public boolean isFocusable() {
 249         /* should be implemented by other sub-classes */
 250         return false;
 251     }
 252 
 253     private static Class seClass;
 254     private static Constructor seCtor;
 255 
 256     final static AWTEvent wrapInSequenced(AWTEvent event) {
 257         try {
 258             if (seClass == null) {
 259                 seClass = Class.forName("java.awt.SequencedEvent");
 260             }
 261 
 262             if (seCtor == null) {
 263                 seCtor = (Constructor) AccessController.doPrivileged(new PrivilegedExceptionAction() {
 264                         public Object run() throws Exception {
 265                             Constructor ctor = seClass.getConstructor(new Class[] { AWTEvent.class });
 266                             ctor.setAccessible(true);
 267                             return ctor;
 268                         }
 269                     });
 270             }
 271 
 272             return (AWTEvent) seCtor.newInstance(new Object[] { event });
 273         }
 274         catch (ClassNotFoundException e) {
 275             throw new NoClassDefFoundError("java.awt.SequencedEvent.");
 276         }
 277         catch (PrivilegedActionException ex) {
 278             throw new NoClassDefFoundError("java.awt.SequencedEvent.");
 279         }
 280         catch (InstantiationException e) {
 281             assert false;
 282         }
 283         catch (IllegalAccessException e) {
 284             assert false;
 285         }
 286         catch (InvocationTargetException e) {
 287             assert false;
 288         }
 289 
 290         return null;
 291     }
 292 
 293     // TODO: consider moving it to KeyboardFocusManagerPeerImpl
 294     final public boolean requestFocus(Component lightweightChild, boolean temporary,
 295                                       boolean focusedWindowChangeAllowed, long time,
 296                                       CausedFocusEvent.Cause cause)
 297     {
 298         if (XKeyboardFocusManagerPeer.
 299             processSynchronousLightweightTransfer(target, lightweightChild, temporary,
 300                                                   focusedWindowChangeAllowed, time))
 301         {
 302             return true;
 303         }
 304 
 305         int result = XKeyboardFocusManagerPeer.
 306             shouldNativelyFocusHeavyweight(target, lightweightChild,
 307                                            temporary, focusedWindowChangeAllowed,
 308                                            time, cause);
 309 
 310         switch (result) {
 311           case XKeyboardFocusManagerPeer.SNFH_FAILURE:
 312               return false;
 313           case XKeyboardFocusManagerPeer.SNFH_SUCCESS_PROCEED:
 314               // Currently we just generate focus events like we deal with lightweight instead of calling
 315               // XSetInputFocus on native window
 316               if (focusLog.isLoggable(PlatformLogger.FINER)) focusLog.finer("Proceeding with request to " +
 317                   lightweightChild + " in " + target);
 318               /**
 319                * The problems with requests in non-focused window arise because shouldNativelyFocusHeavyweight
 320                * checks that native window is focused while appropriate WINDOW_GAINED_FOCUS has not yet
 321                * been processed - it is in EventQueue. Thus, SNFH allows native request and stores request record
 322                * in requests list - and it breaks our requests sequence as first record on WGF should be the last
 323                * focus owner which had focus before WLF. So, we should not add request record for such requests
 324                * but store this component in mostRecent - and return true as before for compatibility.
 325                */
 326               Window parentWindow = SunToolkit.getContainingWindow(target);
 327               if (parentWindow == null) {
 328                   return rejectFocusRequestHelper("WARNING: Parent window is null");
 329               }
 330               XWindowPeer wpeer = (XWindowPeer)parentWindow.getPeer();
 331               if (wpeer == null) {
 332                   return rejectFocusRequestHelper("WARNING: Parent window's peer is null");
 333               }
 334               /*
 335                * Passing null 'actualFocusedWindow' as we don't want to restore focus on it
 336                * when a component inside a Frame is requesting focus.
 337                * See 6314575 for details.
 338                */
 339               boolean res = wpeer.requestWindowFocus(null);
 340 
 341               if (focusLog.isLoggable(PlatformLogger.FINER)) focusLog.finer("Requested window focus: " + res);
 342               // If parent window can be made focused and has been made focused(synchronously)
 343               // then we can proceed with children, otherwise we retreat.
 344               if (!(res && parentWindow.isFocused())) {
 345                   return rejectFocusRequestHelper("Waiting for asynchronous processing of the request");
 346               }
 347               return XKeyboardFocusManagerPeer.deliverFocus(lightweightChild,
 348                                                             (Component)target,
 349                                                             temporary,
 350                                                             focusedWindowChangeAllowed,
 351                                                             time, cause);
 352               // Motif compatibility code
 353           case XKeyboardFocusManagerPeer.SNFH_SUCCESS_HANDLED:
 354               // Either lightweight or excessive request - all events are generated.
 355               return true;
 356         }
 357         return false;
 358     }
 359 
 360     private boolean rejectFocusRequestHelper(String logMsg) {
 361         if (focusLog.isLoggable(PlatformLogger.FINER)) focusLog.finer(logMsg);
 362         XKeyboardFocusManagerPeer.removeLastFocusRequest(target);
 363         return false;
 364     }
 365 
 366     void handleJavaFocusEvent(AWTEvent e) {
 367         if (focusLog.isLoggable(PlatformLogger.FINER)) focusLog.finer(e.toString());
 368         if (e.getID() == FocusEvent.FOCUS_GAINED) {
 369             focusGained((FocusEvent)e);
 370         } else {
 371             focusLost((FocusEvent)e);
 372         }
 373     }
 374 
 375     void handleJavaWindowFocusEvent(AWTEvent e) {
 376     }
 377 
 378     /*************************************************
 379      * END OF FOCUS STUFF
 380      *************************************************/
 381 
 382 
 383 
 384     public void setVisible(boolean b) {
 385         xSetVisible(b);
 386     }
 387 
 388     public void hide() {
 389         setVisible(false);
 390     }
 391 
 392 
 393     /**
 394      * @see java.awt.peer.ComponentPeer
 395      */
 396     public void setEnabled(boolean value) {
 397         enableLog.fine("{0}ing {1}", (value?"Enabl":"Disabl"), this);
 398         boolean repaintNeeded = (enabled != value);
 399         enabled = value;
 400         if (target instanceof Container) {
 401             Component list[] = ((Container)target).getComponents();
 402             for (int i = 0; i < list.length; ++i) {
 403                 boolean childEnabled = list[i].isEnabled();
 404                 ComponentPeer p = list[i].getPeer();
 405                 if ( p != null ) {
 406                     p.setEnabled(value && childEnabled);
 407                 }
 408             }
 409         }
 410         if (repaintNeeded) {
 411             repaint();
 412         }
 413     }
 414 
 415     //
 416     // public so aw/Window can call it
 417     //
 418     public boolean isEnabled() {
 419         return enabled;
 420     }
 421 
 422 
 423 
 424     public void enable() {
 425         setEnabled(true);
 426     }
 427 
 428     public void disable() {
 429         setEnabled(false);
 430     }
 431 
 432     public void paint(Graphics g) {
 433     }
 434     public void repaint(long tm, int x, int y, int width, int height) {
 435         repaint();
 436     }
 437 
 438 
 439     public Graphics getGraphics() {
 440         return getGraphics(surfaceData, getPeerForeground(), getPeerBackground(), getPeerFont());
 441     }
 442 
 443 
 444 
 445     public void print(Graphics g) {
 446         // clear rect here to emulate X clears rect before Expose
 447         g.setColor(target.getBackground());
 448         g.fillRect(0, 0, target.getWidth(), target.getHeight());
 449         g.setColor(target.getForeground());
 450         // paint peer
 451         paint(g);
 452         // allow target to change the picture
 453         target.print(g);
 454     }
 455 
 456     public void setBounds(int x, int y, int width, int height, int op) {
 457         this.x = x;
 458         this.y = y;
 459         this.width = width;
 460         this.height = height;
 461         xSetBounds(x,y,width,height);
 462         validateSurface();
 463         layout();
 464     }
 465 
 466     public void reshape(int x, int y, int width, int height) {
 467         setBounds(x, y, width, height, SET_BOUNDS);
 468     }
 469 
 470     public void coalescePaintEvent(PaintEvent e) {
 471         Rectangle r = e.getUpdateRect();
 472         if (!(e instanceof IgnorePaintEvent)) {
 473             paintArea.add(r, e.getID());
 474         }
 475         if (true) {
 476             switch(e.getID()) {
 477               case PaintEvent.UPDATE:
 478                   if (log.isLoggable(PlatformLogger.FINER)) {
 479                       log.finer("XCP coalescePaintEvent : UPDATE : add : x = " +
 480                             r.x + ", y = " + r.y + ", width = " + r.width + ",height = " + r.height);
 481                   }
 482                   return;
 483               case PaintEvent.PAINT:
 484                   if (log.isLoggable(PlatformLogger.FINER)) {
 485                       log.finer("XCP coalescePaintEvent : PAINT : add : x = " +
 486                             r.x + ", y = " + r.y + ", width = " + r.width + ",height = " + r.height);
 487                   }
 488                   return;
 489             }
 490         }
 491     }
 492 
 493     XWindowPeer getParentTopLevel() {
 494         AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor();
 495         Container parent = (target instanceof Container) ? ((Container)target) : (compAccessor.getParent(target));
 496         // Search for parent window
 497         while (parent != null && !(parent instanceof Window)) {
 498             parent = compAccessor.getParent(parent);
 499         }
 500         if (parent != null) {
 501             return (XWindowPeer)compAccessor.getPeer(parent);
 502         } else {
 503             return null;
 504         }
 505     }
 506 
 507     /* This method is intended to be over-ridden by peers to perform user interaction */
 508     void handleJavaMouseEvent(MouseEvent e) {
 509         switch (e.getID()) {
 510           case MouseEvent.MOUSE_PRESSED:
 511               if (target == e.getSource() &&
 512                   !target.isFocusOwner() &&
 513                   XKeyboardFocusManagerPeer.shouldFocusOnClick(target))
 514               {
 515                   XWindowPeer parentXWindow = getParentTopLevel();
 516                   Window parentWindow = ((Window)parentXWindow.getTarget());
 517                   // Simple windows are non-focusable in X terms but focusable in Java terms.
 518                   // As X-non-focusable they don't receive any focus events - we should generate them
 519                   // by ourselfves.
 520 //                   if (parentXWindow.isFocusableWindow() /*&& parentXWindow.isSimpleWindow()*/ &&
 521 //                       !(getCurrentNativeFocusedWindow() == parentWindow))
 522 //                   {
 523 //                       setCurrentNativeFocusedWindow(parentWindow);
 524 //                       WindowEvent wfg = new WindowEvent(parentWindow, WindowEvent.WINDOW_GAINED_FOCUS);
 525 //                       parentWindow.dispatchEvent(wfg);
 526 //                   }
 527                   XKeyboardFocusManagerPeer.requestFocusFor(target, CausedFocusEvent.Cause.MOUSE_EVENT);
 528               }
 529               break;
 530         }
 531     }
 532 
 533     /* This method is intended to be over-ridden by peers to perform user interaction */
 534     void handleJavaKeyEvent(KeyEvent e) {
 535     }
 536 
 537     /* This method is intended to be over-ridden by peers to perform user interaction */
 538     void handleJavaMouseWheelEvent(MouseWheelEvent e) {
 539     }
 540 
 541 
 542     /* This method is intended to be over-ridden by peers to perform user interaction */
 543     void handleJavaInputMethodEvent(InputMethodEvent e) {
 544     }
 545 
 546     void handleF10JavaKeyEvent(KeyEvent e) {
 547         if (e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() == KeyEvent.VK_F10) {
 548             XWindowPeer winPeer = this.getToplevelXWindow();
 549             if (winPeer instanceof XFramePeer) {
 550                 XMenuBarPeer mPeer = ((XFramePeer)winPeer).getMenubarPeer();
 551                 if (mPeer != null) {
 552                     mPeer.handleF10KeyPress(e);
 553                 }
 554             }
 555         }
 556     }
 557 
 558     public void handleEvent(java.awt.AWTEvent e) {
 559         if ((e instanceof InputEvent) && !((InputEvent)e).isConsumed() && target.isEnabled())  {
 560             if (e instanceof MouseEvent) {
 561                 if (e instanceof MouseWheelEvent) {
 562                     handleJavaMouseWheelEvent((MouseWheelEvent) e);
 563                 }
 564                 else
 565                     handleJavaMouseEvent((MouseEvent) e);
 566             }
 567             else if (e instanceof KeyEvent) {
 568                 handleF10JavaKeyEvent((KeyEvent)e);
 569                 handleJavaKeyEvent((KeyEvent)e);
 570             }
 571         }
 572         else if (e instanceof KeyEvent && !((InputEvent)e).isConsumed()) {
 573             // even if target is disabled.
 574             handleF10JavaKeyEvent((KeyEvent)e);
 575         }
 576         else if (e instanceof InputMethodEvent) {
 577             handleJavaInputMethodEvent((InputMethodEvent) e);
 578         }
 579 
 580         int id = e.getID();
 581 
 582         switch(id) {
 583           case PaintEvent.PAINT:
 584               // Got native painting
 585               paintPending = false;
 586               // Fallthrough to next statement
 587           case PaintEvent.UPDATE:
 588               // Skip all painting while layouting and all UPDATEs
 589               // while waiting for native paint
 590               if (!isLayouting && !paintPending) {
 591                   paintArea.paint(target,false);
 592               }
 593               return;
 594           case FocusEvent.FOCUS_LOST:
 595           case FocusEvent.FOCUS_GAINED:
 596               handleJavaFocusEvent(e);
 597               break;
 598           case WindowEvent.WINDOW_LOST_FOCUS:
 599           case WindowEvent.WINDOW_GAINED_FOCUS:
 600               handleJavaWindowFocusEvent(e);
 601               break;
 602           default:
 603               break;
 604         }
 605 
 606     }
 607 
 608     public Dimension getMinimumSize() {
 609         return target.getSize();
 610     }
 611 
 612     public Dimension getPreferredSize() {
 613         return getMinimumSize();
 614     }
 615 
 616     public void layout() {}
 617 
 618     public java.awt.Toolkit getToolkit() {
 619         return Toolkit.getDefaultToolkit();
 620     }
 621 
 622     void updateMotifColors(Color bg) {
 623         int red = bg.getRed();
 624         int green = bg.getGreen();
 625         int blue = bg.getBlue();
 626 
 627         darkShadow = new Color(MotifColorUtilities.calculateBottomShadowFromBackground(red,green,blue));
 628         lightShadow = new Color(MotifColorUtilities.calculateTopShadowFromBackground(red,green,blue));
 629         selectColor= new Color(MotifColorUtilities.calculateSelectFromBackground(red,green,blue));
 630     }
 631 
 632     /*
 633      * Draw a 3D rectangle using the Motif colors.
 634      * "Normal" rectangles have shadows on the bottom.
 635      * "Depressed" rectangles (such as pressed buttons) have shadows on the top,
 636      * in which case true should be passed for topShadow.
 637      */
 638     public void drawMotif3DRect(Graphics g,
 639                                           int x, int y, int width, int height,
 640                                           boolean topShadow) {
 641         g.setColor(topShadow ? darkShadow : lightShadow);
 642         g.drawLine(x, y, x+width, y);       // top
 643         g.drawLine(x, y+height, x, y);      // left
 644 
 645         g.setColor(topShadow ? lightShadow : darkShadow );
 646         g.drawLine(x+1, y+height, x+width, y+height); // bottom
 647         g.drawLine(x+width, y+height, x+width, y+1);  // right
 648     }
 649 
 650     public void setBackground(Color c) {
 651         if (log.isLoggable(PlatformLogger.FINE)) log.fine("Set background to " + c);
 652         synchronized (getStateLock()) {
 653             background = c;
 654         }
 655         super.setBackground(c);
 656         repaint();
 657     }
 658 
 659     public void setForeground(Color c) {
 660         if (log.isLoggable(PlatformLogger.FINE)) log.fine("Set foreground to " + c);
 661         synchronized (getStateLock()) {
 662             foreground = c;
 663         }
 664         repaint();
 665     }
 666 
 667     /**
 668      * Gets the font metrics for the specified font.
 669      * @param font the font for which font metrics is to be
 670      *      obtained
 671      * @return the font metrics for <code>font</code>
 672      * @see       #getFont
 673      * @see       #getPeer
 674      * @see       java.awt.peer.ComponentPeer#getFontMetrics(Font)
 675      * @see       Toolkit#getFontMetrics(Font)
 676      * @since     JDK1.0
 677      */
 678     public FontMetrics getFontMetrics(Font font) {
 679         if (fontLog.isLoggable(PlatformLogger.FINE)) fontLog.fine("Getting font metrics for " + font);
 680         return sun.font.FontDesignMetrics.getMetrics(font);
 681     }
 682 
 683     public void setFont(Font f) {
 684         synchronized (getStateLock()) {
 685             if (f == null) {
 686                 f = XWindow.getDefaultFont();
 687             }
 688             font = f;
 689         }
 690         // as it stands currently we dont need to do layout or repaint since
 691         // layout is done in the Component upon setFont.
 692         //layout();
 693         // target.repaint();
 694         //repaint()?
 695     }
 696 
 697     public Font getFont() {
 698         return font;
 699     }
 700 
 701     public void updateCursorImmediately() {
 702         XGlobalCursorManager.getCursorManager().updateCursorImmediately();
 703     }
 704 
 705     public final void pSetCursor(Cursor cursor) {
 706         this.pSetCursor(cursor, true);
 707     }
 708 
 709     /*
 710      * The method changes the cursor.
 711      * @param cursor - a new cursor to change to.
 712      * @param ignoreSubComponents - if {@code true} is passed then
 713      *                              the new cursor will be installed on window.
 714      *                              if {@code false} is passed then
 715      *                              subsequent components will try to handle
 716      *                              this request and install their cursor.
 717      */
 718     //ignoreSubComponents not used here
 719     public void pSetCursor(Cursor cursor, boolean ignoreSubComponents) {
 720         XToolkit.awtLock();
 721         try {
 722             long xcursor = XGlobalCursorManager.getCursor(cursor);
 723 
 724             XSetWindowAttributes xwa = new XSetWindowAttributes();
 725             xwa.set_cursor(xcursor);
 726 
 727             long valuemask = XConstants.CWCursor;
 728 
 729             XlibWrapper.XChangeWindowAttributes(XToolkit.getDisplay(),getWindow(),valuemask,xwa.pData);
 730             XlibWrapper.XFlush(XToolkit.getDisplay());
 731             xwa.dispose();
 732         } finally {
 733             XToolkit.awtUnlock();
 734         }
 735     }
 736 
 737     public Image createImage(ImageProducer producer) {
 738         return new ToolkitImage(producer);
 739     }
 740 
 741     public Image createImage(int width, int height) {
 742         return graphicsConfig.createAcceleratedImage(target, width, height);
 743     }
 744 
 745     public VolatileImage createVolatileImage(int width, int height) {
 746         return new SunVolatileImage(target, width, height);
 747     }
 748 
 749     public boolean prepareImage(Image img, int w, int h, ImageObserver o) {
 750         return getToolkit().prepareImage(img, w, h, o);
 751     }
 752 
 753     public int checkImage(Image img, int w, int h, ImageObserver o) {
 754         return getToolkit().checkImage(img, w, h, o);
 755     }
 756 
 757     public Dimension preferredSize() {
 758         return getPreferredSize();
 759     }
 760 
 761     public Dimension minimumSize() {
 762         return getMinimumSize();
 763     }
 764 
 765     public Insets getInsets() {
 766         return new Insets(0, 0, 0, 0);
 767     }
 768 
 769     public void beginValidate() {
 770     }
 771 
 772     public void endValidate() {
 773     }
 774 
 775 
 776     /**
 777      * DEPRECATED:  Replaced by getInsets().
 778      */
 779 
 780     public Insets insets() {
 781         return getInsets();
 782     }
 783 
 784     // Returns true if we are inside begin/endLayout and
 785     // are waiting for native painting
 786     public boolean isPaintPending() {
 787         return paintPending && isLayouting;
 788     }
 789 
 790     public boolean handlesWheelScrolling() {
 791         return false;
 792     }
 793 
 794     public void beginLayout() {
 795         // Skip all painting till endLayout
 796         isLayouting = true;
 797 
 798     }
 799 
 800     public void endLayout() {
 801         if (!paintPending && !paintArea.isEmpty()
 802             && !AWTAccessor.getComponentAccessor().getIgnoreRepaint(target))
 803         {
 804             // if not waiting for native painting repaint damaged area
 805             postEvent(new PaintEvent(target, PaintEvent.PAINT,
 806                                      new Rectangle()));
 807         }
 808         isLayouting = false;
 809     }
 810 
 811     public Color getWinBackground() {
 812         return getPeerBackground();
 813     }
 814 
 815     static int[] getRGBvals(Color c) {
 816 
 817         int rgbvals[] = new int[3];
 818 
 819         rgbvals[0] = c.getRed();
 820         rgbvals[1] = c.getGreen();
 821         rgbvals[2] = c.getBlue();
 822 
 823         return rgbvals;
 824     }
 825 
 826     static final int BACKGROUND_COLOR = 0;
 827     static final int HIGHLIGHT_COLOR = 1;
 828     static final int SHADOW_COLOR = 2;
 829     static final int FOREGROUND_COLOR = 3;
 830 
 831     public Color[] getGUIcolors() {
 832         Color c[] = new Color[4];
 833         float backb, highb, shadowb, hue, saturation;
 834         c[BACKGROUND_COLOR] = getWinBackground();
 835         if (c[BACKGROUND_COLOR] == null) {
 836             c[BACKGROUND_COLOR] = super.getWinBackground();
 837         }
 838         if (c[BACKGROUND_COLOR] == null) {
 839             c[BACKGROUND_COLOR] = Color.lightGray;
 840         }
 841 
 842         int[] rgb = getRGBvals(c[BACKGROUND_COLOR]);
 843 
 844         float[] hsb = Color.RGBtoHSB(rgb[0],rgb[1],rgb[2],null);
 845 
 846         hue = hsb[0];
 847         saturation = hsb[1];
 848         backb = hsb[2];
 849 
 850 
 851 /*      Calculate Highlight Brightness  */
 852 
 853         highb = backb + 0.2f;
 854         shadowb = backb - 0.4f;
 855         if ((highb > 1.0) ) {
 856             if  ((1.0 - backb) < 0.05) {
 857                 highb = shadowb + 0.25f;
 858             } else {
 859                 highb = 1.0f;
 860             }
 861         } else {
 862             if (shadowb < 0.0) {
 863                 if ((backb - 0.0) < 0.25) {
 864                     highb = backb + 0.75f;
 865                     shadowb = highb - 0.2f;
 866                 } else {
 867                     shadowb = 0.0f;
 868                 }
 869             }
 870         }
 871         c[HIGHLIGHT_COLOR] = Color.getHSBColor(hue,saturation,highb);
 872         c[SHADOW_COLOR] = Color.getHSBColor(hue,saturation,shadowb);
 873 
 874 
 875 /*
 876   c[SHADOW_COLOR] = c[BACKGROUND_COLOR].darker();
 877   int r2 = c[SHADOW_COLOR].getRed();
 878   int g2 = c[SHADOW_COLOR].getGreen();
 879   int b2 = c[SHADOW_COLOR].getBlue();
 880 */
 881 
 882         c[FOREGROUND_COLOR] = getPeerForeground();
 883         if (c[FOREGROUND_COLOR] == null) {
 884             c[FOREGROUND_COLOR] = Color.black;
 885         }
 886 /*
 887   if ((c[BACKGROUND_COLOR].equals(c[HIGHLIGHT_COLOR]))
 888   && (c[BACKGROUND_COLOR].equals(c[SHADOW_COLOR]))) {
 889   c[SHADOW_COLOR] = new Color(c[BACKGROUND_COLOR].getRed() + 75,
 890   c[BACKGROUND_COLOR].getGreen() + 75,
 891   c[BACKGROUND_COLOR].getBlue() + 75);
 892   c[HIGHLIGHT_COLOR] = c[SHADOW_COLOR].brighter();
 893   } else if (c[BACKGROUND_COLOR].equals(c[HIGHLIGHT_COLOR])) {
 894   c[HIGHLIGHT_COLOR] = c[SHADOW_COLOR];
 895   c[SHADOW_COLOR] = c[SHADOW_COLOR].darker();
 896   }
 897 */
 898         if (! isEnabled()) {
 899             c[BACKGROUND_COLOR] = c[BACKGROUND_COLOR].darker();
 900             // Reduce the contrast
 901             // Calculate the NTSC gray (NB: REC709 L* might be better!)
 902             // for foreground and background; then multiply the foreground
 903             // by the average lightness
 904 
 905 
 906             Color tc = c[BACKGROUND_COLOR];
 907             int bg = tc.getRed() * 30 + tc.getGreen() * 59 + tc.getBlue() * 11;
 908 
 909             tc = c[FOREGROUND_COLOR];
 910             int fg = tc.getRed() * 30 + tc.getGreen() * 59 + tc.getBlue() * 11;
 911 
 912             float ave = (float) ((fg + bg) / 51000.0);
 913             // 255 * 100 * 2
 914 
 915             Color newForeground = new Color((int) (tc.getRed() * ave),
 916                                             (int) (tc.getGreen() * ave),
 917                                             (int) (tc.getBlue() * ave));
 918 
 919             if (newForeground.equals(c[FOREGROUND_COLOR])) {
 920                 // This probably means the foreground color is black or white
 921                 newForeground = new Color(ave, ave, ave);
 922             }
 923             c[FOREGROUND_COLOR] = newForeground;
 924 
 925         }
 926 
 927 
 928         return c;
 929     }
 930 
 931     /**
 932      * Returns an array of Colors similar to getGUIcolors(), but using the
 933      * System colors.  This is useful if pieces of a Component (such as
 934      * the integrated scrollbars of a List) should retain the System color
 935      * instead of the background color set by Component.setBackground().
 936      */
 937     static Color[] getSystemColors() {
 938         if (systemColors == null) {
 939             systemColors = new Color[4];
 940             systemColors[BACKGROUND_COLOR] = SystemColor.window;
 941             systemColors[HIGHLIGHT_COLOR] = SystemColor.controlLtHighlight;
 942             systemColors[SHADOW_COLOR] = SystemColor.controlShadow;
 943             systemColors[FOREGROUND_COLOR] = SystemColor.windowText;
 944         }
 945         return systemColors;
 946     }
 947 
 948     /**
 949      * Draw a 3D oval.
 950      */
 951     public void draw3DOval(Graphics g, Color colors[],
 952                            int x, int y, int w, int h, boolean raised)
 953         {
 954         Color c = g.getColor();
 955         g.setColor(raised ? colors[HIGHLIGHT_COLOR] : colors[SHADOW_COLOR]);
 956         g.drawArc(x, y, w, h, 45, 180);
 957         g.setColor(raised ? colors[SHADOW_COLOR] : colors[HIGHLIGHT_COLOR]);
 958         g.drawArc(x, y, w, h, 225, 180);
 959         g.setColor(c);
 960     }
 961 
 962     public void draw3DRect(Graphics g, Color colors[],
 963                            int x, int y, int width, int height, boolean raised)
 964         {
 965             Color c = g.getColor();
 966             g.setColor(raised ? colors[HIGHLIGHT_COLOR] : colors[SHADOW_COLOR]);
 967             g.drawLine(x, y, x, y + height);
 968             g.drawLine(x + 1, y, x + width - 1, y);
 969             g.setColor(raised ? colors[SHADOW_COLOR] : colors[HIGHLIGHT_COLOR]);
 970             g.drawLine(x + 1, y + height, x + width, y + height);
 971             g.drawLine(x + width, y, x + width, y + height - 1);
 972             g.setColor(c);
 973         }
 974 
 975     /*
 976      * drawXXX() methods are used to print the native components by
 977      * rendering the Motif look ourselves.
 978      * ToDo(aim): needs to query native motif for more accurate color
 979      * information.
 980      */
 981     void draw3DOval(Graphics g, Color bg,
 982                     int x, int y, int w, int h, boolean raised)
 983         {
 984             Color c = g.getColor();
 985             Color shadow = bg.darker();
 986             Color highlight = bg.brighter();
 987 
 988             g.setColor(raised ? highlight : shadow);
 989             g.drawArc(x, y, w, h, 45, 180);
 990             g.setColor(raised ? shadow : highlight);
 991             g.drawArc(x, y, w, h, 225, 180);
 992             g.setColor(c);
 993         }
 994 
 995     void draw3DRect(Graphics g, Color bg,
 996                     int x, int y, int width, int height,
 997                     boolean raised) {
 998         Color c = g.getColor();
 999         Color shadow = bg.darker();
1000         Color highlight = bg.brighter();
1001 
1002         g.setColor(raised ? highlight : shadow);
1003         g.drawLine(x, y, x, y + height);
1004         g.drawLine(x + 1, y, x + width - 1, y);
1005         g.setColor(raised ? shadow : highlight);
1006         g.drawLine(x + 1, y + height, x + width, y + height);
1007         g.drawLine(x + width, y, x + width, y + height - 1);
1008         g.setColor(c);
1009     }
1010 
1011     void drawScrollbar(Graphics g, Color bg, int thickness, int length,
1012                int min, int max, int val, int vis, boolean horizontal) {
1013         Color c = g.getColor();
1014         double f = (double)(length - 2*(thickness-1)) / Math.max(1, ((max - min) + vis));
1015         int v1 = thickness + (int)(f * (val - min));
1016         int v2 = (int)(f * vis);
1017         int w2 = thickness-4;
1018         int tpts_x[] = new int[3];
1019         int tpts_y[] = new int[3];
1020 
1021         if (length < 3*w2 ) {
1022             v1 = v2 = 0;
1023             if (length < 2*w2 + 2) {
1024                 w2 = (length-2)/2;
1025             }
1026         } else  if (v2 < 7) {
1027             // enforce a minimum handle size
1028             v1 = Math.max(0, v1 - ((7 - v2)>>1));
1029             v2 = 7;
1030         }
1031 
1032         int ctr   = thickness/2;
1033         int sbmin = ctr - w2/2;
1034         int sbmax = ctr + w2/2;
1035 
1036         // paint the background slightly darker
1037         {
1038             Color d = new Color((int) (bg.getRed()   * 0.85),
1039                                 (int) (bg.getGreen() * 0.85),
1040                                 (int) (bg.getBlue()  * 0.85));
1041 
1042             g.setColor(d);
1043             if (horizontal) {
1044                 g.fillRect(0, 0, length, thickness);
1045             } else {
1046                 g.fillRect(0, 0, thickness, length);
1047             }
1048         }
1049 
1050         // paint the thumb and arrows in the normal background color
1051         g.setColor(bg);
1052         if (v1 > 0) {
1053             if (horizontal) {
1054                 g.fillRect(v1, 3, v2, thickness-3);
1055             } else {
1056                 g.fillRect(3, v1, thickness-3, v2);
1057             }
1058         }
1059 
1060         tpts_x[0] = ctr;    tpts_y[0] = 2;
1061         tpts_x[1] = sbmin;  tpts_y[1] = w2;
1062         tpts_x[2] = sbmax;  tpts_y[2] = w2;
1063         if (horizontal) {
1064             g.fillPolygon(tpts_y, tpts_x, 3);
1065         } else {
1066             g.fillPolygon(tpts_x, tpts_y, 3);
1067         }
1068 
1069         tpts_y[0] = length-2;
1070         tpts_y[1] = length-w2;
1071         tpts_y[2] = length-w2;
1072         if (horizontal) {
1073             g.fillPolygon(tpts_y, tpts_x, 3);
1074         } else {
1075             g.fillPolygon(tpts_x, tpts_y, 3);
1076         }
1077 
1078         Color highlight = bg.brighter();
1079 
1080         // // // // draw the "highlighted" edges
1081         g.setColor(highlight);
1082 
1083         // outline & arrows
1084         if (horizontal) {
1085             g.drawLine(1, thickness, length - 1, thickness);
1086             g.drawLine(length - 1, 1, length - 1, thickness);
1087 
1088             // arrows
1089             g.drawLine(1, ctr, w2, sbmin);
1090             g.drawLine(length - w2, sbmin, length - w2, sbmax);
1091             g.drawLine(length - w2, sbmin, length - 2, ctr);
1092 
1093         } else {
1094             g.drawLine(thickness, 1, thickness, length - 1);
1095             g.drawLine(1, length - 1, thickness, length - 1);
1096 
1097             // arrows
1098             g.drawLine(ctr, 1, sbmin, w2);
1099             g.drawLine(sbmin, length - w2, sbmax, length - w2);
1100             g.drawLine(sbmin, length - w2, ctr, length - 2);
1101         }
1102 
1103         // thumb
1104         if (v1 > 0) {
1105             if (horizontal) {
1106                 g.drawLine(v1, 2, v1 + v2, 2);
1107                 g.drawLine(v1, 2, v1, thickness-3);
1108             } else {
1109                 g.drawLine(2, v1, 2, v1 + v2);
1110                 g.drawLine(2, v1, thickness-3, v1);
1111             }
1112         }
1113 
1114         Color shadow = bg.darker();
1115 
1116         // // // // draw the "shadowed" edges
1117         g.setColor(shadow);
1118 
1119         // outline && arrows
1120         if (horizontal) {
1121             g.drawLine(0, 0, 0, thickness);
1122             g.drawLine(0, 0, length - 1, 0);
1123 
1124             // arrows
1125             g.drawLine(w2, sbmin, w2, sbmax);
1126             g.drawLine(w2, sbmax, 1, ctr);
1127             g.drawLine(length-2, ctr, length-w2, sbmax);
1128 
1129         } else {
1130             g.drawLine(0, 0, thickness, 0);
1131             g.drawLine(0, 0, 0, length - 1);
1132 
1133             // arrows
1134             g.drawLine(sbmin, w2, sbmax, w2);
1135             g.drawLine(sbmax, w2, ctr, 1);
1136             g.drawLine(ctr, length-2, sbmax, length-w2);
1137         }
1138 
1139         // thumb
1140         if (v1 > 0) {
1141             if (horizontal) {
1142                 g.drawLine(v1 + v2, 2, v1 + v2, thickness-2);
1143                 g.drawLine(v1, thickness-2, v1 + v2, thickness-2);
1144             } else {
1145                 g.drawLine(2, v1 + v2, thickness-2, v1 + v2);
1146                 g.drawLine(thickness-2, v1, thickness-2, v1 + v2);
1147             }
1148         }
1149         g.setColor(c);
1150     }
1151 
1152     /**
1153      * The following multibuffering-related methods delegate to our
1154      * associated GraphicsConfig (X11 or GLX) to handle the appropriate
1155      * native windowing system specific actions.
1156      */
1157 
1158     private BufferCapabilities backBufferCaps;
1159 
1160     public void createBuffers(int numBuffers, BufferCapabilities caps)
1161       throws AWTException
1162     {
1163         if (buffersLog.isLoggable(PlatformLogger.FINE)) {
1164             buffersLog.fine("createBuffers(" + numBuffers + ", " + caps + ")");
1165         }
1166         // set the caps first, they're used when creating the bb
1167         backBufferCaps = caps;
1168         backBuffer = graphicsConfig.createBackBuffer(this, numBuffers, caps);
1169         xBackBuffer = graphicsConfig.createBackBufferImage(target,
1170                                                            backBuffer);
1171     }
1172 
1173     @Override
1174     public BufferCapabilities getBackBufferCaps() {
1175         return backBufferCaps;
1176     }
1177 
1178     public void flip(int x1, int y1, int x2, int y2,
1179                      BufferCapabilities.FlipContents flipAction)
1180     {
1181         if (buffersLog.isLoggable(PlatformLogger.FINE)) {
1182             buffersLog.fine("flip(" + flipAction + ")");
1183         }
1184         if (backBuffer == 0) {
1185             throw new IllegalStateException("Buffers have not been created");
1186         }
1187         graphicsConfig.flip(this, target, xBackBuffer,
1188                             x1, y1, x2, y2, flipAction);
1189     }
1190 
1191     public Image getBackBuffer() {
1192         if (buffersLog.isLoggable(PlatformLogger.FINE)) {
1193             buffersLog.fine("getBackBuffer()");
1194         }
1195         if (backBuffer == 0) {
1196             throw new IllegalStateException("Buffers have not been created");
1197         }
1198         return xBackBuffer;
1199     }
1200 
1201     public void destroyBuffers() {
1202         if (buffersLog.isLoggable(PlatformLogger.FINE)) {
1203             buffersLog.fine("destroyBuffers()");
1204         }
1205         graphicsConfig.destroyBackBuffer(backBuffer);
1206         backBuffer = 0;
1207         xBackBuffer = null;
1208     }
1209 
1210     // End of multi-buffering
1211 
1212     public void notifyTextComponentChange(boolean add){
1213         Container parent = AWTAccessor.getComponentAccessor().getParent(target);
1214         while(!(parent == null ||
1215                 parent instanceof java.awt.Frame ||
1216                 parent instanceof java.awt.Dialog)) {
1217             parent = AWTAccessor.getComponentAccessor().getParent(parent);
1218         }
1219 
1220 /*      FIX ME - FIX ME need to implement InputMethods
1221     if (parent instanceof java.awt.Frame ||
1222         parent instanceof java.awt.Dialog) {
1223         if (add)
1224         ((MInputMethodControl)parent.getPeer()).addTextComponent((MComponentPeer)this);
1225         else
1226         ((MInputMethodControl)parent.getPeer()).removeTextComponent((MComponentPeer)this);
1227     }
1228 */
1229     }
1230 
1231     /**
1232      * Returns true if this event is disabled and shouldn't be processed by window
1233      * Currently if target component is disabled the following event will be disabled on window:
1234      * ButtonPress, ButtonRelease, KeyPress, KeyRelease, EnterNotify, LeaveNotify, MotionNotify
1235      */
1236     protected boolean isEventDisabled(XEvent e) {
1237         if (enableLog.isLoggable(PlatformLogger.FINEST)) {
1238             enableLog.finest("Component is {1}, checking for disabled event {0}", e, (isEnabled()?"enabled":"disable"));
1239         }
1240         if (!isEnabled()) {
1241             switch (e.get_type()) {
1242               case XConstants.ButtonPress:
1243               case XConstants.ButtonRelease:
1244               case XConstants.KeyPress:
1245               case XConstants.KeyRelease:
1246               case XConstants.EnterNotify:
1247               case XConstants.LeaveNotify:
1248               case XConstants.MotionNotify:
1249                   if (enableLog.isLoggable(PlatformLogger.FINER)) {
1250                       enableLog.finer("Event {0} is disable", e);
1251                   }
1252                   return true;
1253             }
1254         }
1255         switch(e.get_type()) {
1256           case XConstants.MapNotify:
1257           case XConstants.UnmapNotify:
1258               return true;
1259         }
1260         return super.isEventDisabled(e);
1261     }
1262 
1263     Color getPeerBackground() {
1264         return background;
1265     }
1266 
1267     Color getPeerForeground() {
1268         return foreground;
1269     }
1270 
1271     Font getPeerFont() {
1272         return font;
1273     }
1274 
1275     Dimension getPeerSize() {
1276         return new Dimension(width,height);
1277     }
1278 
1279     public void setBoundsOperation(int operation) {
1280         synchronized(getStateLock()) {
1281             if (boundsOperation == DEFAULT_OPERATION) {
1282                 boundsOperation = operation;
1283             } else if (operation == RESET_OPERATION) {
1284                 boundsOperation = DEFAULT_OPERATION;
1285             }
1286         }
1287     }
1288 
1289     static String operationToString(int operation) {
1290         switch (operation) {
1291           case SET_LOCATION:
1292               return "SET_LOCATION";
1293           case SET_SIZE:
1294               return "SET_SIZE";
1295           case SET_CLIENT_SIZE:
1296               return "SET_CLIENT_SIZE";
1297           default:
1298           case SET_BOUNDS:
1299               return "SET_BOUNDS";
1300         }
1301     }
1302 
1303     /**
1304      * Lowers this component at the bottom of the above HW peer. If the above parameter
1305      * is null then the method places this component at the top of the Z-order.
1306      */
1307     public void setZOrder(ComponentPeer above) {
1308         long aboveWindow = (above != null) ? ((XComponentPeer)above).getWindow() : 0;
1309 
1310         XToolkit.awtLock();
1311         try{
1312             XlibWrapper.SetZOrder(XToolkit.getDisplay(), getWindow(), aboveWindow);
1313         }finally{
1314             XToolkit.awtUnlock();
1315         }
1316     }
1317 
1318     private void addTree(Collection order, Set set, Container cont) {
1319         for (int i = 0; i < cont.getComponentCount(); i++) {
1320             Component comp = cont.getComponent(i);
1321             ComponentPeer peer = comp.getPeer();
1322             if (peer instanceof XComponentPeer) {
1323                 Long window = Long.valueOf(((XComponentPeer)peer).getWindow());
1324                 if (!set.contains(window)) {
1325                     set.add(window);
1326                     order.add(window);
1327                 }
1328             } else if (comp instanceof Container) {
1329                 // It is lightweight container, it might contain heavyweight components attached to this
1330                 // peer
1331                 addTree(order, set, (Container)comp);
1332             }
1333         }
1334     }
1335 
1336     /****** DropTargetPeer implementation ********************/
1337 
1338     public void addDropTarget(DropTarget dt) {
1339         Component comp = target;
1340         while(!(comp == null || comp instanceof Window)) {
1341             comp = comp.getParent();
1342         }
1343 
1344         if (comp instanceof Window) {
1345             XWindowPeer wpeer = (XWindowPeer)(comp.getPeer());
1346             if (wpeer != null) {
1347                 wpeer.addDropTarget();
1348             }
1349         }
1350     }
1351 
1352     public void removeDropTarget(DropTarget dt) {
1353         Component comp = target;
1354         while(!(comp == null || comp instanceof Window)) {
1355             comp = comp.getParent();
1356         }
1357 
1358         if (comp instanceof Window) {
1359             XWindowPeer wpeer = (XWindowPeer)(comp.getPeer());
1360             if (wpeer != null) {
1361                 wpeer.removeDropTarget();
1362             }
1363         }
1364     }
1365 
1366     /**
1367      * Applies the shape to the X-window.
1368      * @since 1.7
1369      */
1370     public void applyShape(Region shape) {
1371         if (XlibUtil.isShapingSupported()) {
1372             if (shapeLog.isLoggable(PlatformLogger.FINER)) {
1373                 shapeLog.finer(
1374                         "*** INFO: Setting shape: PEER: " + this
1375                         + "; WINDOW: " + getWindow()
1376                         + "; TARGET: " + target
1377                         + "; SHAPE: " + shape);
1378             }
1379             XToolkit.awtLock();
1380             try {
1381                 if (shape != null) {
1382                     XlibWrapper.SetRectangularShape(
1383                             XToolkit.getDisplay(),
1384                             getWindow(),
1385                             shape.getLoX(), shape.getLoY(),
1386                             shape.getHiX(), shape.getHiY(),
1387                             (shape.isRectangular() ? null : shape)
1388                             );
1389                 } else {
1390                     XlibWrapper.SetRectangularShape(
1391                             XToolkit.getDisplay(),
1392                             getWindow(),
1393                             0, 0,
1394                             0, 0,
1395                             null
1396                             );
1397                 }
1398             } finally {
1399                 XToolkit.awtUnlock();
1400             }
1401         } else {
1402             if (shapeLog.isLoggable(PlatformLogger.FINER)) {
1403                 shapeLog.finer("*** WARNING: Shaping is NOT supported!");
1404             }
1405         }
1406     }
1407 
1408     public boolean updateGraphicsData(GraphicsConfiguration gc) {
1409         int oldVisual = -1, newVisual = -1;
1410 
1411         if (graphicsConfig != null) {
1412             oldVisual = graphicsConfig.getVisual();
1413         }
1414         if (gc != null && gc instanceof X11GraphicsConfig) {
1415             newVisual = ((X11GraphicsConfig)gc).getVisual();
1416         }
1417 
1418         // If the new visual differs from the old one, the peer must be
1419         // recreated because X11 does not allow changing the visual on the fly.
1420         // So we even skip the initGraphicsConfiguration() call.
1421         // The initial assignment should happen though, hence the != -1 thing.
1422         if (oldVisual != -1 && oldVisual != newVisual) {
1423             return true;
1424         }
1425 
1426         initGraphicsConfiguration();
1427         doValidateSurface();
1428         return false;
1429     }
1430 }