XBaseWindow.java 41.4 KB
Newer Older
D
duke 已提交
1
/*
X
xdono 已提交
2
 * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package sun.awt.X11;

import java.awt.*;
import sun.awt.*;
import java.util.logging.*;
import java.util.*;

33
public class XBaseWindow {
D
duke 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    private static final Logger log = Logger.getLogger("sun.awt.X11.XBaseWindow");
    private static final Logger insLog = Logger.getLogger("sun.awt.X11.insets.XBaseWindow");
    private static final Logger eventLog = Logger.getLogger("sun.awt.X11.event.XBaseWindow");
    private static final Logger focusLog = Logger.getLogger("sun.awt.X11.focus.XBaseWindow");
    private static final Logger grabLog = Logger.getLogger("sun.awt.X11.grab.XBaseWindow");

    public static final String
        PARENT_WINDOW = "parent window", // parent window, Long
        BOUNDS = "bounds", // bounds of the window, Rectangle
        OVERRIDE_REDIRECT = "overrideRedirect", // override_redirect setting, Boolean
        EVENT_MASK = "event mask", // event mask, Integer
        VALUE_MASK = "value mask", // value mask, Long
        BORDER_PIXEL = "border pixel", // border pixel value, Integer
        COLORMAP = "color map", // color map, Long
        DEPTH = "visual depth", // depth, Integer
        VISUAL_CLASS = "visual class", // visual class, Integer
        VISUAL = "visual", // visual, Long
        EMBEDDED = "embedded", // is embedded?, Boolean
        DELAYED = "delayed", // is creation delayed?, Boolean
        PARENT = "parent", // parent peer
        BACKGROUND_PIXMAP = "pixmap", // background pixmap
        VISIBLE = "visible", // whether it is visible by default
        SAVE_UNDER = "save under", // save content under this window
        BACKING_STORE = "backing store", // enables double buffering
        BIT_GRAVITY = "bit gravity"; // copy old content on geometry change
    private XCreateWindowParams delayedParams;

    Set<Long> children = new HashSet<Long>();
    long window;
    boolean visible;
    boolean mapped;
    boolean embedded;
    Rectangle maxBounds;
    volatile XBaseWindow parentWindow;

    private boolean disposed;

    private long screen;
    private XSizeHints hints;
    private XWMHints wmHints;

    final static int MIN_SIZE = 1;
    final static int DEF_LOCATION = 1;

    private static XAtom wm_client_leader;

    static enum InitialiseState {
        INITIALISING,
        NOT_INITIALISED,
        INITIALISED,
        FAILED_INITIALISATION
    };

    private InitialiseState initialising;

    int x;
    int y;
    int width;
    int height;

    void awtLock() {
        XToolkit.awtLock();
    }

    void awtUnlock() {
        XToolkit.awtUnlock();
    }

    void awtLockNotifyAll() {
        XToolkit.awtLockNotifyAll();
    }

    void awtLockWait() throws InterruptedException {
        XToolkit.awtLockWait();
    }

    // To prevent errors from overriding obsolete methods
    protected final void init(long parentWindow, Rectangle bounds) {}
    protected final void preInit() {}
    protected final void postInit() {}

    // internal lock for synchronizing state changes and paint calls, initialized in preInit.
    // the order with other locks: AWTLock -> stateLock
    static class StateLock extends Object { }
    protected StateLock state_lock;

    /**
     * Called for delayed inits during construction
     */
    void instantPreInit(XCreateWindowParams params) {
        state_lock = new StateLock();
        initialising = InitialiseState.NOT_INITIALISED;
    }

    /**
     * Called before window creation, descendants should override to initialize the data,
     * initialize params.
     */
    void preInit(XCreateWindowParams params) {
        state_lock = new StateLock();
        initialising = InitialiseState.NOT_INITIALISED;
        embedded = Boolean.TRUE.equals(params.get(EMBEDDED));
        visible = Boolean.TRUE.equals(params.get(VISIBLE));

        Object parent = params.get(PARENT);
        if (parent instanceof XBaseWindow) {
            parentWindow = (XBaseWindow)parent;
        } else {
            Long parentWindowID = (Long)params.get(PARENT_WINDOW);
            if (parentWindowID != null) {
                parentWindow = XToolkit.windowToXWindow(parentWindowID);
            }
        }

        Long eventMask = (Long)params.get(EVENT_MASK);
        if (eventMask != null) {
            long mask = eventMask.longValue();
151
            mask |= XConstants.SubstructureNotifyMask;
D
duke 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
            params.put(EVENT_MASK, mask);
        }

        screen = -1;
    }

    /**
     * Called after window creation, descendants should override to initialize Window
     * with class-specific values and perform post-initialization actions.
     */
    void postInit(XCreateWindowParams params) {
        if (log.isLoggable(Level.FINE)) log.fine("WM name is " + getWMName());
        updateWMName();

        // Set WM_CLIENT_LEADER property
        initClientLeader();
    }

    /**
     * Creates window using parameters <code>params</code>
     * If params contain flag DELAYED doesn't do anything.
     * Note: Descendants can call this method to create the window
     * at the time different to instance construction.
     */
    protected final void init(XCreateWindowParams params) {
        awtLock();
        initialising = InitialiseState.INITIALISING;
        awtUnlock();

        try {
            if (!Boolean.TRUE.equals(params.get(DELAYED))) {
                preInit(params);
                create(params);
                postInit(params);
            } else {
                instantPreInit(params);
                delayedParams = params;
            }
            awtLock();
            initialising = InitialiseState.INITIALISED;
            awtLockNotifyAll();
            awtUnlock();
        } catch (RuntimeException re) {
            awtLock();
            initialising = InitialiseState.FAILED_INITIALISATION;
            awtLockNotifyAll();
            awtUnlock();
            throw re;
        } catch (Throwable t) {
            log.log(Level.WARNING, "Exception during peer initialization", t);
            awtLock();
            initialising = InitialiseState.FAILED_INITIALISATION;
            awtLockNotifyAll();
            awtUnlock();
        }
    }

    public boolean checkInitialised() {
        awtLock();
        try {
            switch (initialising) {
              case INITIALISED:
                  return true;
              case INITIALISING:
                  try {
                      while (initialising != InitialiseState.INITIALISED) {
                          awtLockWait();
                      }
                  } catch (InterruptedException ie) {
                      return false;
                  }
                  return true;
              case NOT_INITIALISED:
              case FAILED_INITIALISATION:
                  return false;
              default:
                  return false;
            }
        } finally {
            awtUnlock();
        }
    }

    /*
     * Creates an invisible InputOnly window without an associated Component.
     */
    XBaseWindow() {
        this(new XCreateWindowParams());
    }

    /**
     * Creates normal child window
     */
    XBaseWindow(long parentWindow, Rectangle bounds) {
        this(new XCreateWindowParams(new Object[] {
            BOUNDS, bounds,
            PARENT_WINDOW, Long.valueOf(parentWindow)}));
    }

    /**
     * Creates top-level window
     */
    XBaseWindow(Rectangle bounds) {
        this(new XCreateWindowParams(new Object[] {
            BOUNDS, bounds
        }));
    }

    public XBaseWindow (XCreateWindowParams params) {
        init(params);
    }

    /* This create is used by the XEmbeddedFramePeer since it has to create the window
       as a child of the netscape window. This netscape window is passed in as wid */
    XBaseWindow(long parentWindow) {
        this(new XCreateWindowParams(new Object[] {
            PARENT_WINDOW, Long.valueOf(parentWindow),
            EMBEDDED, Boolean.TRUE
        }));
    }

    /**
     * Verifies that all required parameters are set. If not, sets them to default values.
     * Verifies values of critical parameters, adjust their values when needed.
     * @throws IllegalArgumentException if params is null
     */
    protected void checkParams(XCreateWindowParams params) {
        if (params == null) {
            throw new IllegalArgumentException("Window creation parameters are null");
        }
        params.putIfNull(PARENT_WINDOW, Long.valueOf(XToolkit.getDefaultRootWindow()));
        params.putIfNull(BOUNDS, new Rectangle(DEF_LOCATION, DEF_LOCATION, MIN_SIZE, MIN_SIZE));
284 285 286 287
        params.putIfNull(DEPTH, Integer.valueOf((int)XConstants.CopyFromParent));
        params.putIfNull(VISUAL, Long.valueOf(XConstants.CopyFromParent));
        params.putIfNull(VISUAL_CLASS, Integer.valueOf((int)XConstants.InputOnly));
        params.putIfNull(VALUE_MASK, Long.valueOf(XConstants.CWEventMask));
D
duke 已提交
288 289 290 291 292 293 294 295
        Rectangle bounds = (Rectangle)params.get(BOUNDS);
        bounds.width = Math.max(MIN_SIZE, bounds.width);
        bounds.height = Math.max(MIN_SIZE, bounds.height);

        Long eventMaskObj = (Long)params.get(EVENT_MASK);
        long eventMask = eventMaskObj != null ? eventMaskObj.longValue() : 0;
        // We use our own synthetic grab see XAwtState.getGrabWindow()
        // (see X vol. 1, 8.3.3.2)
296
        eventMask |= XConstants.PropertyChangeMask | XConstants.OwnerGrabButtonMask;
D
duke 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
        params.put(EVENT_MASK, Long.valueOf(eventMask));
    }

    /**
     * Creates window with parameters specified by <code>params</code>
     * @see #init
     */
    private final void create(XCreateWindowParams params) {
        XToolkit.awtLock();
        try {
            XSetWindowAttributes xattr = new XSetWindowAttributes();
            try {
                checkParams(params);

                long value_mask = ((Long)params.get(VALUE_MASK)).longValue();

                Long eventMask = (Long)params.get(EVENT_MASK);
                xattr.set_event_mask(eventMask.longValue());
315
                value_mask |= XConstants.CWEventMask;
D
duke 已提交
316 317 318 319

                Long border_pixel = (Long)params.get(BORDER_PIXEL);
                if (border_pixel != null) {
                    xattr.set_border_pixel(border_pixel.longValue());
320
                    value_mask |= XConstants.CWBorderPixel;
D
duke 已提交
321 322 323 324 325
                }

                Long colormap = (Long)params.get(COLORMAP);
                if (colormap != null) {
                    xattr.set_colormap(colormap.longValue());
326
                    value_mask |= XConstants.CWColormap;
D
duke 已提交
327 328 329 330
                }
                Long background_pixmap = (Long)params.get(BACKGROUND_PIXMAP);
                if (background_pixmap != null) {
                    xattr.set_background_pixmap(background_pixmap.longValue());
331
                    value_mask |= XConstants.CWBackPixmap;
D
duke 已提交
332 333 334 335 336 337 338 339 340 341
                }

                Long parentWindow = (Long)params.get(PARENT_WINDOW);
                Rectangle bounds = (Rectangle)params.get(BOUNDS);
                Integer depth = (Integer)params.get(DEPTH);
                Integer visual_class = (Integer)params.get(VISUAL_CLASS);
                Long visual = (Long)params.get(VISUAL);
                Boolean overrideRedirect = (Boolean)params.get(OVERRIDE_REDIRECT);
                if (overrideRedirect != null) {
                    xattr.set_override_redirect(overrideRedirect.booleanValue());
342
                    value_mask |= XConstants.CWOverrideRedirect;
D
duke 已提交
343 344 345 346 347
                }

                Boolean saveUnder = (Boolean)params.get(SAVE_UNDER);
                if (saveUnder != null) {
                    xattr.set_save_under(saveUnder.booleanValue());
348
                    value_mask |= XConstants.CWSaveUnder;
D
duke 已提交
349 350 351 352 353
                }

                Integer backingStore = (Integer)params.get(BACKING_STORE);
                if (backingStore != null) {
                    xattr.set_backing_store(backingStore.intValue());
354
                    value_mask |= XConstants.CWBackingStore;
D
duke 已提交
355 356 357 358 359
                }

                Integer bitGravity = (Integer)params.get(BIT_GRAVITY);
                if (bitGravity != null) {
                    xattr.set_bit_gravity(bitGravity.intValue());
360
                    value_mask |= XConstants.CWBitGravity;
D
duke 已提交
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
                }

                if (log.isLoggable(Level.FINE)) {
                    log.fine("Creating window for " + this + " with the following attributes: \n" + params);
                }
                window = XlibWrapper.XCreateWindow(XToolkit.getDisplay(),
                                   parentWindow.longValue(),
                                   bounds.x, bounds.y, // location
                                   bounds.width, bounds.height, // size
                                   0, // border
                                   depth.intValue(), // depth
                                   visual_class.intValue(), // class
                                   visual.longValue(), // visual
                                   value_mask,  // value mask
                                   xattr.pData); // attributes

                if (window == 0) {
                    throw new IllegalStateException("Couldn't create window because of wrong parameters. Run with NOISY_AWT to see details");
                }
                XToolkit.addToWinMap(window, this);
            } finally {
                xattr.dispose();
            }
        } finally {
            XToolkit.awtUnlock();
        }
    }

    public XCreateWindowParams getDelayedParams() {
        return delayedParams;
    }

    protected String getWMName() {
        return XToolkit.getCorrectXIDString(getClass().getName());
    }

    protected void initClientLeader() {
        XToolkit.awtLock();
        try {
            if (wm_client_leader == null) {
                wm_client_leader = XAtom.get("WM_CLIENT_LEADER");
            }
            wm_client_leader.setWindowProperty(this, getXAWTRootWindow());
        } finally {
            XToolkit.awtUnlock();
        }
    }

    static XRootWindow getXAWTRootWindow() {
        return XRootWindow.getInstance();
    }

    void destroy() {
        XToolkit.awtLock();
        try {
            if (hints != null) {
                XlibWrapper.XFree(hints.pData);
                hints = null;
            }
            XToolkit.removeFromWinMap(getWindow(), this);
            XlibWrapper.XDestroyWindow(XToolkit.getDisplay(), getWindow());
            if (XPropertyCache.isCachingSupported()) {
                XPropertyCache.clearCache(window);
            }
            window = -1;
            if( !isDisposed() ) {
                setDisposed( true );
            }

            XAwtState.getGrabWindow(); // Magic - getGrabWindow clear state if grabbing window is disposed of.
        } finally {
            XToolkit.awtUnlock();
        }
    }

    void flush() {
        XToolkit.awtLock();
        try {
            XlibWrapper.XFlush(XToolkit.getDisplay());
        } finally {
            XToolkit.awtUnlock();
        }
    }

    /**
     * Helper function to set W
     */
    public final void setWMHints(XWMHints hints) {
        XToolkit.awtLock();
        try {
            XlibWrapper.XSetWMHints(XToolkit.getDisplay(), getWindow(), hints.pData);
        } finally {
            XToolkit.awtUnlock();
        }
    }

    public XWMHints getWMHints() {
        if (wmHints == null) {
            wmHints = new XWMHints(XlibWrapper.XAllocWMHints());
//              XlibWrapper.XGetWMHints(XToolkit.getDisplay(),
//                                      getWindow(),
//                                      wmHints.pData);
        }
        return wmHints;
    }


    /*
     * Call this method under AWTLock.
     * The lock should be acquired untill all operations with XSizeHints are completed.
     */
    public XSizeHints getHints() {
        if (hints == null) {
            long p_hints = XlibWrapper.XAllocSizeHints();
            hints = new XSizeHints(p_hints);
//              XlibWrapper.XGetWMNormalHints(XToolkit.getDisplay(), getWindow(), p_hints, XlibWrapper.larg1);
            // TODO: Shouldn't we listen for WM updates on this property?
        }
        return hints;
    }

    public void setSizeHints(long flags, int x, int y, int width, int height) {
        if (insLog.isLoggable(Level.FINER)) insLog.finer("Setting hints, flags " + XlibWrapper.hintsToString(flags));
        XToolkit.awtLock();
        try {
            XSizeHints hints = getHints();
            // Note: if PPosition is not set in flags this means that
            // we want to reset PPosition in hints.  This is necessary
            // for locationByPlatform functionality
490
            if ((flags & XUtilConstants.PPosition) != 0) {
D
duke 已提交
491 492 493
                hints.set_x(x);
                hints.set_y(y);
            }
494
            if ((flags & XUtilConstants.PSize) != 0) {
D
duke 已提交
495 496
                hints.set_width(width);
                hints.set_height(height);
497 498
            } else if ((hints.get_flags() & XUtilConstants.PSize) != 0) {
                flags |= XUtilConstants.PSize;
D
duke 已提交
499
            }
500
            if ((flags & XUtilConstants.PMinSize) != 0) {
D
duke 已提交
501 502
                hints.set_min_width(width);
                hints.set_min_height(height);
503 504
            } else if ((hints.get_flags() & XUtilConstants.PMinSize) != 0) {
                flags |= XUtilConstants.PMinSize;
D
duke 已提交
505 506 507
                //Fix for 4320050: Minimum size for java.awt.Frame is not being enforced.
                //We don't need to reset minimum size if it's already set
            }
508
            if ((flags & XUtilConstants.PMaxSize) != 0) {
D
duke 已提交
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
                if (maxBounds != null) {
                    if (maxBounds.width != Integer.MAX_VALUE) {
                        hints.set_max_width(maxBounds.width);
                    } else {
                        hints.set_max_width(XToolkit.getDefaultScreenWidth());
                    }
                    if (maxBounds.height != Integer.MAX_VALUE) {
                        hints.set_max_height(maxBounds.height);
                    } else {
                        hints.set_max_height(XToolkit.getDefaultScreenHeight());
                    }
                } else {
                    hints.set_max_width(width);
                    hints.set_max_height(height);
                }
524 525
            } else if ((hints.get_flags() & XUtilConstants.PMaxSize) != 0) {
                flags |= XUtilConstants.PMaxSize;
D
duke 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
                if (maxBounds != null) {
                    if (maxBounds.width != Integer.MAX_VALUE) {
                        hints.set_max_width(maxBounds.width);
                    } else {
                        hints.set_max_width(XToolkit.getDefaultScreenWidth());
                    }
                    if (maxBounds.height != Integer.MAX_VALUE) {
                        hints.set_max_height(maxBounds.height);
                    } else {
                        hints.set_max_height(XToolkit.getDefaultScreenHeight());
                    }
                } else {
                    // Leave intact
                }
            }
541
            flags |= XUtilConstants.PWinGravity;
D
duke 已提交
542
            hints.set_flags(flags);
543
            hints.set_win_gravity((int)XConstants.NorthWestGravity);
D
duke 已提交
544 545 546 547 548 549 550 551 552 553 554
            if (insLog.isLoggable(Level.FINER)) insLog.finer("Setting hints, resulted flags " + XlibWrapper.hintsToString(flags) +
                                                             ", values " + hints);
            XlibWrapper.XSetWMNormalHints(XToolkit.getDisplay(), getWindow(), hints.pData);
        } finally {
            XToolkit.awtUnlock();
        }
    }

    public boolean isMinSizeSet() {
        XSizeHints hints = getHints();
        long flags = hints.get_flags();
555
        return ((flags & XUtilConstants.PMinSize) == XUtilConstants.PMinSize);
D
duke 已提交
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
    }

    /**
     * This lock object can be used to protect instance data from concurrent access
     * by two threads. If both state lock and AWT lock are taken, AWT Lock should be taken first.
     */
    Object getStateLock() {
        return state_lock;
    }

    public long getWindow() {
        return window;
    }
    public long getContentWindow() {
        return window;
    }

    public XBaseWindow getContentXWindow() {
        return XToolkit.windowToXWindow(getContentWindow());
    }

    public Rectangle getBounds() {
        return new Rectangle(x, y, width, height);
    }
    public Dimension getSize() {
        return new Dimension(width, height);
    }


    public void toFront() {
        XToolkit.awtLock();
        try {
            XlibWrapper.XRaiseWindow(XToolkit.getDisplay(), getWindow());
        } finally {
            XToolkit.awtUnlock();
        }
    }
    public void xRequestFocus(long time) {
        XToolkit.awtLock();
        try {
            if (focusLog.isLoggable(Level.FINER)) focusLog.finer("XSetInputFocus on " + Long.toHexString(getWindow()) + " with time " + time);
            XlibWrapper.XSetInputFocus2(XToolkit.getDisplay(), getWindow(), time);
        } finally {
            XToolkit.awtUnlock();
        }
    }
    public void xRequestFocus() {
        XToolkit.awtLock();
        try {
            if (focusLog.isLoggable(Level.FINER)) focusLog.finer("XSetInputFocus on " + Long.toHexString(getWindow()));
             XlibWrapper.XSetInputFocus(XToolkit.getDisplay(), getWindow());
        } finally {
            XToolkit.awtUnlock();
        }
    }

    public static long xGetInputFocus() {
        XToolkit.awtLock();
        try {
            return XlibWrapper.XGetInputFocus(XToolkit.getDisplay());
        } finally {
            XToolkit.awtUnlock();
        }
    }

    public void xSetVisible(boolean visible) {
        if (log.isLoggable(Level.FINE)) log.fine("Setting visible on " + this + " to " + visible);
        XToolkit.awtLock();
        try {
            this.visible = visible;
            if (visible) {
                XlibWrapper.XMapWindow(XToolkit.getDisplay(), getWindow());
            }
            else {
                XlibWrapper.XUnmapWindow(XToolkit.getDisplay(), getWindow());
            }
            XlibWrapper.XFlush(XToolkit.getDisplay());
        } finally {
            XToolkit.awtUnlock();
        }
    }

    boolean isMapped() {
        return mapped;
    }

    void updateWMName() {
        String name = getWMName();
        XToolkit.awtLock();
        try {
            if (name == null) {
                name = " ";
            }
            XAtom nameAtom = XAtom.get(XAtom.XA_WM_NAME);
            nameAtom.setProperty(getWindow(), name);
            XAtom netNameAtom = XAtom.get("_NET_WM_NAME");
            netNameAtom.setPropertyUTF8(getWindow(), name);
        } finally {
            XToolkit.awtUnlock();
        }
    }
    void setWMClass(String[] cl) {
        if (cl.length != 2) {
            throw new IllegalArgumentException("WM_CLASS_NAME consists of exactly two strings");
        }
        XToolkit.awtLock();
        try {
            XAtom xa = XAtom.get(XAtom.XA_WM_CLASS);
            xa.setProperty8(getWindow(), cl[0] + '\0' + cl[1]);
        } finally {
            XToolkit.awtUnlock();
        }
    }

    boolean isVisible() {
        return visible;
    }

    static long getScreenOfWindow(long window) {
        XToolkit.awtLock();
        try {
            return XlibWrapper.getScreenOfWindow(XToolkit.getDisplay(), window);
        } finally {
            XToolkit.awtUnlock();
        }
    }
    long getScreenNumber() {
        XToolkit.awtLock();
        try {
            return XlibWrapper.XScreenNumberOfScreen(getScreen());
        } finally {
            XToolkit.awtUnlock();
        }
    }

    long getScreen() {
        if (screen == -1) { // Not initialized
            screen = getScreenOfWindow(window);
        }
        return screen;
    }

    public void xSetBounds(Rectangle bounds) {
        xSetBounds(bounds.x, bounds.y, bounds.width, bounds.height);
    }

    public void xSetBounds(int x, int y, int width, int height) {
        if (getWindow() == 0) {
            insLog.warning("Attempt to resize uncreated window");
            throw new IllegalStateException("Attempt to resize uncreated window");
        }
        insLog.fine("Setting bounds on " + this + " to (" + x + ", " + y + "), " + width + "x" + height);
        if (width <= 0) {
            width = 1;
        }
        if (height <= 0) {
            height = 1;
        }
        XToolkit.awtLock();
        try {
             XlibWrapper.XMoveResizeWindow(XToolkit.getDisplay(), getWindow(), x,y,width,height);
        } finally {
            XToolkit.awtUnlock();
        }
    }

    /**
     * Translate coordinates from one window into another.  Optimized
     * for XAWT - uses cached data when possible.  Preferable over
     * pure XTranslateCoordinates.
     * @return coordinates relative to dst, or null if error happened
     */
    static Point toOtherWindow(long src, long dst, int x, int y) {
        Point rpt = new Point(0, 0);

        // Check if both windows belong to XAWT - then no X calls are necessary

        XBaseWindow srcPeer = XToolkit.windowToXWindow(src);
        XBaseWindow dstPeer = XToolkit.windowToXWindow(dst);

        if (srcPeer != null && dstPeer != null) {
            // (x, y) is relative to src
            rpt.x = x + srcPeer.getAbsoluteX() - dstPeer.getAbsoluteX();
            rpt.y = y + srcPeer.getAbsoluteY() - dstPeer.getAbsoluteY();
        } else if (dstPeer != null && XlibUtil.isRoot(src, dstPeer.getScreenNumber())) {
            // from root into peer
            rpt.x = x - dstPeer.getAbsoluteX();
            rpt.y = y - dstPeer.getAbsoluteY();
        } else if (srcPeer != null && XlibUtil.isRoot(dst, srcPeer.getScreenNumber())) {
            // from peer into root
            rpt.x = x + srcPeer.getAbsoluteX();
            rpt.y = y + srcPeer.getAbsoluteY();
        } else {
            rpt = XlibUtil.translateCoordinates(src, dst, new Point(x, y));
        }
        return rpt;
    }

    /*
     * Convert to global coordinates.
     */
    Rectangle toGlobal(Rectangle rec) {
        Point p = toGlobal(rec.getLocation());
        Rectangle newRec = new Rectangle(rec);
        if (p != null) {
            newRec.setLocation(p);
        }
        return newRec;
    }

    Point toGlobal(Point pt) {
        Point p = toGlobal(pt.x, pt.y);
        if (p != null) {
            return p;
        } else {
            return new Point(pt);
        }
    }

    Point toGlobal(int x, int y) {
        long root;
        XToolkit.awtLock();
        try {
            root = XlibWrapper.RootWindow(XToolkit.getDisplay(),
                    getScreenNumber());
        } finally {
            XToolkit.awtUnlock();
        }
        Point p = toOtherWindow(getContentWindow(), root, x, y);
        if (p != null) {
            return p;
        } else {
            return new Point(x, y);
        }
    }

    /*
     * Convert to local coordinates.
     */
    Point toLocal(Point pt) {
        Point p = toLocal(pt.x, pt.y);
        if (p != null) {
            return p;
        } else {
            return new Point(pt);
        }
    }

    Point toLocal(int x, int y) {
        long root;
        XToolkit.awtLock();
        try {
            root = XlibWrapper.RootWindow(XToolkit.getDisplay(),
                    getScreenNumber());
        } finally {
            XToolkit.awtUnlock();
        }
        Point p = toOtherWindow(root, getContentWindow(), x, y);
        if (p != null) {
            return p;
        } else {
            return new Point(x, y);
        }
    }

    /**
     * We should always grab both keyboard and pointer to control event flow
     * on popups. This also simplifies synthetic grab implementation.
     * The active grab overrides activated automatic grab.
     */
    public boolean grabInput() {
        grabLog.log(Level.FINE, "Grab input on {0}", new Object[] {this});

        XToolkit.awtLock();
        try {
            if (XAwtState.getGrabWindow() == this &&
                XAwtState.isManualGrab())
            {
                grabLog.fine("    Already Grabbed");
                return true;
            }
            //6273031: PIT. Choice drop down does not close once it is right clicked to show a popup menu
            //remember previous window having grab and if it's not null ungrab it.
            XBaseWindow prevGrabWindow = XAwtState.getGrabWindow();
840 841 842
            final int eventMask = (int) (XConstants.ButtonPressMask | XConstants.ButtonReleaseMask
                | XConstants.EnterWindowMask | XConstants.LeaveWindowMask | XConstants.PointerMotionMask
                | XConstants.ButtonMotionMask);
D
duke 已提交
843 844 845
            final int ownerEvents = 1;


846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
            //6714678: IDE (Netbeans, Eclipse, JDeveloper) Debugger hangs
            //process on Linux
            //The user must pass the sun.awt.disablegrab property to disable
            //taking grabs. This prevents hanging of the GUI when a breakpoint
            //is hit while a popup window taking the grab is open.
            if (!XToolkit.getSunAwtDisableGrab()) {
                int ptrGrab = XlibWrapper.XGrabPointer(XToolkit.getDisplay(),
                        getContentWindow(), ownerEvents, eventMask, XConstants.GrabModeAsync,
                        XConstants.GrabModeAsync, XConstants.None, (XWM.isMotif() ? XToolkit.arrowCursor : XConstants.None),
                        XConstants.CurrentTime);
                // Check grab results to be consistent with X server grab
                if (ptrGrab != XConstants.GrabSuccess) {
                    XlibWrapper.XUngrabPointer(XToolkit.getDisplay(), XConstants.CurrentTime);
                    XAwtState.setGrabWindow(null);
                    grabLog.fine("    Grab Failure - mouse");
                    return false;
                }

                int keyGrab = XlibWrapper.XGrabKeyboard(XToolkit.getDisplay(),
                        getContentWindow(), ownerEvents, XConstants.GrabModeAsync, XConstants.GrabModeAsync,
                        XConstants.CurrentTime);
                if (keyGrab != XConstants.GrabSuccess) {
                    XlibWrapper.XUngrabPointer(XToolkit.getDisplay(), XConstants.CurrentTime);
                    XlibWrapper.XUngrabKeyboard(XToolkit.getDisplay(), XConstants.CurrentTime);
                    XAwtState.setGrabWindow(null);
                    grabLog.fine("    Grab Failure - keyboard");
                    return false;
                }
D
duke 已提交
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
            }
            if (prevGrabWindow != null) {
                prevGrabWindow.ungrabInputImpl();
            }
            XAwtState.setGrabWindow(this);
            grabLog.fine("    Grab - success");
            return true;
        } finally {
            XToolkit.awtUnlock();
        }
    }

    static void ungrabInput() {
        XToolkit.awtLock();
        try {
            XBaseWindow grabWindow = XAwtState.getGrabWindow();
            grabLog.log(Level.FINE, "UnGrab input on {0}", new Object[] {grabWindow});
            if (grabWindow != null) {
                grabWindow.ungrabInputImpl();
893 894 895 896
                if (!XToolkit.getSunAwtDisableGrab()) {
                    XlibWrapper.XUngrabPointer(XToolkit.getDisplay(), XConstants.CurrentTime);
                    XlibWrapper.XUngrabKeyboard(XToolkit.getDisplay(), XConstants.CurrentTime);
                }
D
duke 已提交
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
                XAwtState.setGrabWindow(null);
                // we need to call XFlush() here to force ungrab
                // see 6384219 for details
                XlibWrapper.XFlush(XToolkit.getDisplay());
            }
        } finally {
            XToolkit.awtUnlock();
        }
    }

    // called from ungrabInput, used in popup windows to hide theirselfs in ungrabbing
    void ungrabInputImpl() {
    }

    static void checkSecurity() {
        if (XToolkit.isSecurityWarningEnabled() && XToolkit.isToolkitThread()) {
            StackTraceElement stack[] = (new Throwable()).getStackTrace();
            log.warning(stack[1] + ": Security violation: calling user code on toolkit thread");
        }
    }

    public Set<Long> getChildren() {
        synchronized (getStateLock()) {
            return new HashSet<Long>(children);
        }
    }

    // -------------- Event handling ----------------
    public void handleMapNotifyEvent(XEvent xev) {
        mapped = true;
    }
    public void handleUnmapNotifyEvent(XEvent xev) {
        mapped = false;
    }
    public void handleReparentNotifyEvent(XEvent xev) {
        if (eventLog.isLoggable(Level.FINER)) {
            XReparentEvent msg = xev.get_xreparent();
            eventLog.finer(msg.toString());
        }
    }
    public void handlePropertyNotify(XEvent xev) {
        XPropertyEvent msg = xev.get_xproperty();
        if (XPropertyCache.isCachingSupported()) {
            XPropertyCache.clearCache(window, XAtom.get(msg.get_atom()));
        }
        if (eventLog.isLoggable(Level.FINER)) {
            eventLog.log(Level.FINER, "{0}", new Object[] {msg});
        }
    }

    public void handleDestroyNotify(XEvent xev) {
        XAnyEvent xany = xev.get_xany();
        if (xany.get_window() == getWindow()) {
            XToolkit.removeFromWinMap(getWindow(), this);
            if (XPropertyCache.isCachingSupported()) {
                XPropertyCache.clearCache(getWindow());
            }
        }
        if (xany.get_window() != getWindow()) {
            synchronized (getStateLock()) {
                children.remove(xany.get_window());
            }
        }
    }

    public void handleCreateNotify(XEvent xev) {
        XAnyEvent xany = xev.get_xany();
        if (xany.get_window() != getWindow()) {
            synchronized (getStateLock()) {
                children.add(xany.get_window());
            }
        }
    }

    public void handleClientMessage(XEvent xev) {
        if (eventLog.isLoggable(Level.FINER)) {
            XClientMessageEvent msg = xev.get_xclient();
            eventLog.finer(msg.toString());
        }
    }

    public void handleVisibilityEvent(XEvent xev) {
    }
    public void handleKeyPress(XEvent xev) {
    }
    public void handleKeyRelease(XEvent xev) {
    }
    public void handleExposeEvent(XEvent xev) {
    }
    /**
     * Activate automatic grab on first ButtonPress,
     * deactivate on full mouse release
     */
    public void handleButtonPressRelease(XEvent xev) {
        XButtonEvent xbe = xev.get_xbutton();
992 993 994 995 996 997 998 999
        /*
         * Ignore the buttons above 20 due to the bit limit for
         * InputEvent.BUTTON_DOWN_MASK.
         * One more bit is reserved for FIRST_HIGH_BIT.
         */
        if (xbe.get_button() > SunToolkit.MAX_BUTTONS_SUPPORTED) {
            return;
        }
1000
        int buttonState = 0;
1001 1002
        final int buttonsNumber = ((SunToolkit)(Toolkit.getDefaultToolkit())).getNumberOfButtons();
        for (int i = 0; i<buttonsNumber; i++){
1003
            buttonState |= (xbe.get_state() & XConstants.buttonsMask[i]);
1004
        }
D
duke 已提交
1005
        switch (xev.get_type()) {
1006
        case XConstants.ButtonPress:
D
duke 已提交
1007 1008 1009 1010
            if (buttonState == 0) {
                XAwtState.setAutoGrabWindow(this);
            }
            break;
1011
        case XConstants.ButtonRelease:
D
duke 已提交
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
            if (isFullRelease(buttonState, xbe.get_button())) {
                XAwtState.setAutoGrabWindow(null);
            }
            break;
        }
    }
    public void handleMotionNotify(XEvent xev) {
    }
    public void handleXCrossingEvent(XEvent xev) {
    }
    public void handleConfigureNotifyEvent(XEvent xev) {
        XConfigureEvent xe = xev.get_xconfigure();
        insLog.log(Level.FINER, "Configure, {0}",
                   new Object[] {xe});
        x = xe.get_x();
        y = xe.get_y();
        width = xe.get_width();
        height = xe.get_height();
    }
    /**
     * Checks ButtonRelease released all Mouse buttons
     */
    static boolean isFullRelease(int buttonState, int button) {
1035 1036 1037
        final int buttonsNumber = ((SunToolkit)(Toolkit.getDefaultToolkit())).getNumberOfButtons();

        if (button < 0 || button > buttonsNumber) {
1038 1039 1040
            return buttonState == 0;
        } else {
            return buttonState == XConstants.buttonsMask[button - 1];
D
duke 已提交
1041 1042 1043 1044 1045
        }
    }

    static boolean isGrabbedEvent(XEvent ev, XBaseWindow target) {
        switch (ev.get_type()) {
1046 1047 1048 1049 1050
          case XConstants.ButtonPress:
          case XConstants.ButtonRelease:
          case XConstants.MotionNotify:
          case XConstants.KeyPress:
          case XConstants.KeyRelease:
D
duke 已提交
1051
              return true;
1052 1053
          case XConstants.LeaveNotify:
          case XConstants.EnterNotify:
D
duke 已提交
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
              // We shouldn't dispatch this events to the grabbed components (see 6317481)
              // But this logic is important if the grabbed component is top-level (see realSync)
              return (target instanceof XWindowPeer);
          default:
              return false;
        }
    }
    /**
     * Dispatches event to the grab Window or event source window depending
     * on whether the grab is active and on the event type
     */
    static void dispatchToWindow(XEvent ev) {
        XBaseWindow target = XAwtState.getGrabWindow();
        if (target == null || !isGrabbedEvent(ev, target)) {
            target = XToolkit.windowToXWindow(ev.get_xany().get_window());
        }
        if (target != null && target.checkInitialised()) {
            target.dispatchEvent(ev);
        }
    }

    public void dispatchEvent(XEvent xev) {
        if (eventLog.isLoggable(Level.FINEST)) eventLog.finest(xev.toString());
        int type = xev.get_type();

        if (isDisposed()) {
            return;
        }

        switch (type)
        {
1085
          case XConstants.VisibilityNotify:
D
duke 已提交
1086 1087
              handleVisibilityEvent(xev);
              break;
1088
          case XConstants.ClientMessage:
D
duke 已提交
1089 1090
              handleClientMessage(xev);
              break;
1091 1092
          case XConstants.Expose :
          case XConstants.GraphicsExpose :
D
duke 已提交
1093 1094
              handleExposeEvent(xev);
              break;
1095 1096
          case XConstants.ButtonPress:
          case XConstants.ButtonRelease:
D
duke 已提交
1097 1098 1099
              handleButtonPressRelease(xev);
              break;

1100
          case XConstants.MotionNotify:
D
duke 已提交
1101 1102
              handleMotionNotify(xev);
              break;
1103
          case XConstants.KeyPress:
D
duke 已提交
1104 1105
              handleKeyPress(xev);
              break;
1106
          case XConstants.KeyRelease:
D
duke 已提交
1107 1108
              handleKeyRelease(xev);
              break;
1109 1110
          case XConstants.EnterNotify:
          case XConstants.LeaveNotify:
D
duke 已提交
1111 1112
              handleXCrossingEvent(xev);
              break;
1113
          case XConstants.ConfigureNotify:
D
duke 已提交
1114 1115
              handleConfigureNotifyEvent(xev);
              break;
1116
          case XConstants.MapNotify:
D
duke 已提交
1117 1118
              handleMapNotifyEvent(xev);
              break;
1119
          case XConstants.UnmapNotify:
D
duke 已提交
1120 1121
              handleUnmapNotifyEvent(xev);
              break;
1122
          case XConstants.ReparentNotify:
D
duke 已提交
1123 1124
              handleReparentNotifyEvent(xev);
              break;
1125
          case XConstants.PropertyNotify:
D
duke 已提交
1126 1127
              handlePropertyNotify(xev);
              break;
1128
          case XConstants.DestroyNotify:
D
duke 已提交
1129 1130
              handleDestroyNotify(xev);
              break;
1131
          case XConstants.CreateNotify:
D
duke 已提交
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
              handleCreateNotify(xev);
              break;
        }
    }
    protected boolean isEventDisabled(XEvent e) {
        return false;
    }

    int getX() {
        return x;
    }

    int getY() {
        return y;
    }

    int getWidth() {
        return width;
    }

    int getHeight() {
        return height;
    }

    void setDisposed(boolean d) {
        disposed = d;
    }

    boolean isDisposed() {
        return disposed;
    }

    public int getAbsoluteX() {
        XBaseWindow pw = getParentWindow();
        if (pw != null) {
            return pw.getAbsoluteX() + getX();
        } else {
            // Overridden for top-levels as their (x,y) is Java (x, y), not native location
            return getX();
        }
    }

    public int getAbsoluteY() {
        XBaseWindow pw = getParentWindow();
        if (pw != null) {
            return pw.getAbsoluteY() + getY();
        } else {
            return getY();
        }
    }

    public XBaseWindow getParentWindow() {
        return parentWindow;
    }

    public XWindowPeer getToplevelXWindow() {
        XBaseWindow bw = this;
        while (bw != null && !(bw instanceof XWindowPeer)) {
            bw = bw.getParentWindow();
        }
        return (XWindowPeer)bw;
    }
    public String toString() {
        return super.toString() + "(" + Long.toString(getWindow(), 16) + ")";
    }

    /**
     * Returns whether the given point is inside of the window.  Coordinates are local.
     */
    public boolean contains(int x, int y) {
        return x >= 0 && y >= 0 && x < getWidth() && y < getHeight();
    }

    /**
     * Returns whether the given point is inside of the window.  Coordinates are global.
     */
    public boolean containsGlobal(int x, int y) {
        return x >= getAbsoluteX() && y >= getAbsoluteY() && x < (getAbsoluteX()+getWidth()) && y < (getAbsoluteY()+getHeight());
    }

}