public WPopupMenuPeer(PopupMenu target) {
    this.target = target;
    MenuContainer parent = null;
    boolean isTrayIconPopup = false;
    isTrayIconPopup = AWTAccessor.getPopupMenuAccessor().isTrayIconPopup(target);
    if (isTrayIconPopup) {
      parent = AWTAccessor.getMenuComponentAccessor().getParent(target);
    } else {
      parent = target.getParent();
    }

    if (parent instanceof Component) {
      WComponentPeer parentPeer = (WComponentPeer) WToolkit.targetToPeer(parent);
      if (parentPeer == null) {
        // because the menu isn't a component (sigh) we first have to wait
        // for a failure to map the peer which should only happen for a
        // lightweight container, then find the actual native parent from
        // that component.
        parent = WToolkit.getNativeContainer((Component) parent);
        parentPeer = (WComponentPeer) WToolkit.targetToPeer(parent);
      }
      createMenu(parentPeer);
      // fix for 5088782: check if menu object is created successfully
      checkMenuCreation();
    } else {
      throw new IllegalArgumentException("illegal popup menu container class");
    }
  }
Beispiel #2
0
  public LWWindowPeer(
      Window target,
      PlatformComponent platformComponent,
      PlatformWindow platformWindow,
      PeerType peerType) {
    super(target, platformComponent);
    this.platformWindow = platformWindow;
    this.peerType = peerType;

    Window owner = target.getOwner();
    LWWindowPeer ownerPeer =
        owner == null ? null : (LWWindowPeer) AWTAccessor.getComponentAccessor().getPeer(owner);
    PlatformWindow ownerDelegate = (ownerPeer != null) ? ownerPeer.getPlatformWindow() : null;

    // The delegate.initialize() needs a non-null GC on X11.
    GraphicsConfiguration gc = getTarget().getGraphicsConfiguration();
    synchronized (getStateLock()) {
      // graphicsConfig should be updated according to the real window
      // bounds when the window is shown, see 4868278
      this.graphicsConfig = gc;
    }

    if (!target.isFontSet()) {
      target.setFont(DEFAULT_FONT);
    }

    if (!target.isBackgroundSet()) {
      target.setBackground(SystemColor.window);
    } else {
      // first we check if user provided alpha for background. This is
      // similar to what Apple's Java do.
      // Since JDK7 we should rely on setOpacity() only.
      // this.opacity = c.getAlpha();
    }

    if (!target.isForegroundSet()) {
      target.setForeground(SystemColor.windowText);
      // we should not call setForeground because it will call a repaint
      // which the peer may not be ready to do yet.
    }

    platformWindow.initialize(target, this, ownerDelegate);

    // Init warning window(for applets)
    SecurityWarningWindow warn = null;
    if (target.getWarningString() != null) {
      // accessSystemTray permission allows to display TrayIcon, TrayIcon tooltip
      // and TrayIcon balloon windows without a warning window.
      if (!AWTAccessor.getWindowAccessor().isTrayIconWindow(target)) {
        LWToolkit toolkit = (LWToolkit) Toolkit.getDefaultToolkit();
        warn = toolkit.createSecurityWarning(target, this);
      }
    }

    warningWindow = warn;
  }
Beispiel #3
0
    // Fix for 4915454 - override the default implementation to avoid
    // loading SystemFlavorMap and associated classes.
    @Override
    public void setTransferHandler(TransferHandler newHandler) {
      TransferHandler oldHandler =
          (TransferHandler)
              getClientProperty(
                  AWTAccessor.getClientPropertyKeyAccessor().getJComponent_TRANSFER_HANDLER());
      putClientProperty(
          AWTAccessor.getClientPropertyKeyAccessor().getJComponent_TRANSFER_HANDLER(), newHandler);

      firePropertyChange("transferHandler", oldHandler, newHandler);
    }
Beispiel #4
0
 /*
  * Retrieves the owner of the peer.
  * Note: this method returns the owner which can be activated, (i.e. the instance
  * of Frame or Dialog may be returned).
  */
 static LWWindowPeer getOwnerFrameDialog(LWWindowPeer peer) {
   Window owner = (peer != null ? peer.getTarget().getOwner() : null);
   while (owner != null && !(owner instanceof Frame || owner instanceof Dialog)) {
     owner = owner.getOwner();
   }
   return owner == null ? null : (LWWindowPeer) AWTAccessor.getComponentAccessor().getPeer(owner);
 }
Beispiel #5
0
  void initTextField() {
    setVisible(target.isVisible());

    setBounds(x, y, width, height, SET_BOUNDS);

    AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor();
    foreground = compAccessor.getForeground(target);
    if (foreground == null) foreground = SystemColor.textText;

    setForeground(foreground);

    background = compAccessor.getBackground(target);
    if (background == null) {
      if (((TextField) target).isEditable()) background = SystemColor.text;
      else background = SystemColor.control;
    }
    setBackground(background);

    if (!target.isBackgroundSet()) {
      // This is a way to set the background color of the TextArea
      // without calling setBackground - go through accessor
      compAccessor.setBackground(target, background);
    }
    if (!target.isForegroundSet()) {
      target.setForeground(SystemColor.textText);
    }

    setFont(font);
  }
Beispiel #6
0
  XTextFieldPeer(TextField target) {
    super(target);
    text = target.getText();
    xtext = new XAWTTextField(text, this, target.getParent());
    xtext.getDocument().addDocumentListener(xtext);
    xtext.setCursor(target.getCursor());
    XToolkit.specialPeerMap.put(xtext, this);

    initTextField();
    setText(target.getText());
    if (target.echoCharIsSet()) {
      setEchoChar(target.getEchoChar());
    } else setEchoChar((char) 0);

    int start = target.getSelectionStart();
    int end = target.getSelectionEnd();
    // Fix for 5100200
    // Restoring Motif behaviour
    // Since the end position of the selected text can be greater than the length of the text,
    // so we should set caret to max position of the text
    setCaretPosition(Math.min(end, text.length()));
    if (end > start) {
      // Should be called after setText() and setCaretPosition()
      select(start, end);
    }

    setEditable(target.isEditable());

    // After this line we should not change the component's text
    firstChangeSkipped = true;
    AWTAccessor.getComponentAccessor().setPeer(xtext, this);
  }
  public void addClient() {
    client =
        new Canvas() {
          public void paint(Graphics g) {
            super.paint(g);
          }
        };
    client.setBackground(new Color(30, 220, 40));
    clientCont.add(client);
    clientCont.validate();
    final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
    WindowIDProvider pid = (WindowIDProvider) acc.getPeer(client);
    log.fine("Added XEmbed server(Canvas) with X window ID " + pid.getWindow());
    Rectangle toFocusBounds = toFocus.getBounds();
    toFocusBounds.setLocation(toFocus.getLocationOnScreen());
    f.validate();

    // KDE doesn't accept clicks on title as activation - click below title
    Rectangle fbounds = f.getBounds();
    fbounds.y += f.getInsets().top;
    fbounds.height -= f.getInsets().top;

    Process proc =
        startClient(
            new Rectangle[] {
              fbounds,
              dummy.getBounds(),
              toFocusBounds,
              new Rectangle(b_modal.getLocationOnScreen(), b_modal.getSize()),
              new Rectangle(10, 130, 20, 20)
            },
            pid.getWindow());
    new ClientWatcher(client, proc, clientCont).start();
  }
Beispiel #8
0
 @SuppressWarnings("deprecation")
 public CPlatformWindow convertJComponentToTarget(final JRootPane p) {
   Component root = SwingUtilities.getRoot(p);
   final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
   if (root == null || acc.getPeer(root) == null) return null;
   return (CPlatformWindow) ((LWWindowPeer) acc.getPeer(root)).getPlatformWindow();
 }
Beispiel #9
0
 @Override
 public boolean updateGraphicsData(GraphicsConfiguration gc) {
   boolean result = super.updateGraphicsData(gc);
   Rectangle bounds = AWTAccessor.getFrameAccessor().getMaximizedBounds((Frame) target);
   if (bounds != null) {
     setMaximizedBounds(bounds);
   }
   return result;
 }
Beispiel #10
0
 @Override
 public void blockWindows(List<Window> windows) {
   // TODO: LWX will probably need some collectJavaToplevels to speed this up
   for (Window w : windows) {
     WindowPeer wp = (WindowPeer) AWTAccessor.getComponentAccessor().getPeer(w);
     if (wp != null) {
       wp.setModalBlocked((Dialog) getTarget(), true);
     }
   }
 }
 @Override
 public void print(Graphics g) {
   // We assume we print the whole frame,
   // so we expect no clip was set previously
   Shape shape = AWTAccessor.getWindowAccessor().getShape((Window) target);
   if (shape != null) {
     g.setClip(shape);
   }
   super.print(g);
 }
Beispiel #12
0
  private void postWindowStateChangedEvent(int newWindowState) {
    if (getTarget() instanceof Frame) {
      AWTAccessor.getFrameAccessor().setExtendedState((Frame) getTarget(), newWindowState);
    }
    WindowEvent stateChangedEvent =
        new WindowEvent(getTarget(), WindowEvent.WINDOW_STATE_CHANGED, windowState, newWindowState);
    postEvent(stateChangedEvent);
    windowState = newWindowState;

    updateSecurityWarningVisibility();
  }
Beispiel #13
0
 @Override
 public void repositionSecurityWarning() {
   if (warningWindow != null) {
     AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor();
     Window target = getTarget();
     int x = compAccessor.getX(target);
     int y = compAccessor.getY(target);
     int width = compAccessor.getWidth(target);
     int height = compAccessor.getHeight(target);
     warningWindow.reposition(x, y, width, height);
   }
 }
Beispiel #14
0
 XAWTTextField(String text, XComponentPeer xwin, Container parent) {
   super(text);
   this.xwin = xwin;
   setDoubleBuffered(true);
   setFocusable(false);
   AWTAccessor.getComponentAccessor().setParent(this, parent);
   setBackground(xwin.getPeerBackground());
   setForeground(xwin.getPeerForeground());
   setFont(xwin.getPeerFont());
   setCaretPosition(0);
   addActionListener(this);
   addNotify();
 }
Beispiel #15
0
  @Override
  public void setModalBlocked(Dialog blocker, boolean blocked) {
    synchronized (getPeerTreeLock()) {
      ComponentPeer peer = AWTAccessor.getComponentAccessor().getPeer(blocker);
      if (blocked && (peer instanceof LWWindowPeer)) {
        this.blocker = (LWWindowPeer) peer;
      } else {
        this.blocker = null;
      }
    }

    platformWindow.setModalBlocked(blocked);
  }
Beispiel #16
0
 @Override // PlatformWindow
 public void toFront() {
   final long nsWindowPtr = getNSWindowPtr();
   LWCToolkit lwcToolkit = (LWCToolkit) Toolkit.getDefaultToolkit();
   Window w = DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
   final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
   if (w != null
       && acc.getPeer(w) != null
       && ((LWWindowPeer) acc.getPeer(w)).getPeerType() == LWWindowPeer.PeerType.EMBEDDED_FRAME
       && !lwcToolkit.isApplicationActive()) {
     lwcToolkit.activateApplicationIgnoringOtherApps();
   }
   updateFocusabilityForAutoRequestFocus(false);
   nativePushNSWindowToFront(nsWindowPtr);
   updateFocusabilityForAutoRequestFocus(true);
 }
Beispiel #17
0
  /**
   * Sets a specified <code>Component</code> to be the glass pane for this root pane. The glass pane
   * should normally be a lightweight, transparent component, because it will be made visible when
   * ever the root pane needs to grab input events.
   *
   * <p>The new glass pane's visibility is changed to match that of the current glass pane. An
   * implication of this is that care must be taken when you want to replace the glass pane and make
   * it visible. Either of the following will work:
   *
   * <pre>
   *   root.setGlassPane(newGlassPane);
   *   newGlassPane.setVisible(true);
   * </pre>
   *
   * or:
   *
   * <pre>
   *   root.getGlassPane().setVisible(true);
   *   root.setGlassPane(newGlassPane);
   * </pre>
   *
   * @param glass the <code>Component</code> to use as the glass pane for this <code>JRootPane
   *     </code>
   * @exception NullPointerException if the <code>glass</code> parameter is <code>null</code>
   */
  public void setGlassPane(Component glass) {
    if (glass == null) {
      throw new NullPointerException("glassPane cannot be set to null.");
    }

    AWTAccessor.getComponentAccessor().setMixingCutoutShape(glass, new Rectangle());

    boolean visible = false;
    if (glassPane != null && glassPane.getParent() == this) {
      this.remove(glassPane);
      visible = glassPane.isVisible();
    }

    glass.setVisible(visible);
    glassPane = glass;
    this.add(glassPane, 0);
    if (visible) {
      repaint();
    }
  }
  public void updateGC() {
    int scrn = getScreenImOn();
    if (screenLog.isLoggable(PlatformLogger.Level.FINER)) {
      log.finer("Screen number: " + scrn);
    }

    // get current GD
    Win32GraphicsDevice oldDev = (Win32GraphicsDevice) winGraphicsConfig.getDevice();

    Win32GraphicsDevice newDev;
    GraphicsDevice devs[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
    // Occasionally during device addition/removal getScreenImOn can return
    // a non-existing screen number. Use the default device in this case.
    if (scrn >= devs.length) {
      newDev =
          (Win32GraphicsDevice)
              GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    } else {
      newDev = (Win32GraphicsDevice) devs[scrn];
    }

    // Set winGraphicsConfig to the default GC for the monitor this Window
    // is now mostly on.
    winGraphicsConfig = (Win32GraphicsConfig) newDev.getDefaultConfiguration();
    if (screenLog.isLoggable(PlatformLogger.Level.FINE)) {
      if (winGraphicsConfig == null) {
        screenLog.fine("Assertion (winGraphicsConfig != null) failed");
      }
    }

    // if on a different display, take off old GD and put on new GD
    if (oldDev != newDev) {
      oldDev.removeDisplayChangedListener(this);
      newDev.addDisplayChangedListener(this);
    }

    AWTAccessor.getComponentAccessor()
        .setGraphicsConfiguration((Component) target, winGraphicsConfig);
  }
Beispiel #19
0
  /*
   * Called by the delegate when a key is pressed.
   */
  @Override
  public void notifyKeyEvent(
      int id, long when, int modifiers, int keyCode, char keyChar, int keyLocation) {
    LWKeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
    Component focusOwner = kfmPeer.getCurrentFocusOwner();

    if (focusOwner == null) {
      focusOwner = kfmPeer.getCurrentFocusedWindow();
      if (focusOwner == null) {
        focusOwner = this.getTarget();
      }
    }

    KeyEvent keyEvent =
        new KeyEvent(focusOwner, id, when, modifiers, keyCode, keyChar, keyLocation);
    AWTAccessor.getKeyEventAccessor()
        .setExtendedKeyCode(
            keyEvent,
            (keyChar == KeyEvent.CHAR_UNDEFINED)
                ? keyCode
                : ExtendedKeyCodes.getExtendedKeyCodeForChar(keyChar));
    postEvent(keyEvent);
  }
  protected void startDrag(Transferable transferable, long[] formats, Map formatMap) {
    Component component = getTrigger().getComponent();
    Component c = null;
    XWindowPeer wpeer = null;

    for (c = component;
        c != null && !(c instanceof Window);
        c = AWTAccessor.getComponentAccessor().getParent(c)) ;

    if (c instanceof Window) {
      wpeer = (XWindowPeer) c.getPeer();
    }

    if (wpeer == null) {
      throw new InvalidDnDOperationException("Cannot find top-level for the drag source component");
    }

    long xcursor = 0;
    long rootWindow = 0;
    long dragWindow = 0;
    long timeStamp = 0;

    /* Retrieve the X cursor for the drag operation. */
    {
      Cursor cursor = getCursor();
      if (cursor != null) {
        xcursor = XGlobalCursorManager.getCursor(cursor);
      }
    }

    XToolkit.awtLock();
    try {
      if (proxyModeSourceWindow != 0) {
        throw new InvalidDnDOperationException("Proxy drag in progress");
      }
      if (dndInProgress) {
        throw new InvalidDnDOperationException("Drag in progress");
      }

      /* Determine the root window for the drag operation. */
      {
        long screen = XlibWrapper.XScreenNumberOfScreen(wpeer.getScreen());
        rootWindow = XlibWrapper.RootWindow(XToolkit.getDisplay(), screen);
      }

      dragWindow = XWindow.getXAWTRootWindow().getWindow();

      timeStamp = XToolkit.getCurrentServerTime();

      int dropActions = getDragSourceContext().getSourceActions();

      Iterator dragProtocols = XDragAndDropProtocols.getDragSourceProtocols();
      while (dragProtocols.hasNext()) {
        XDragSourceProtocol dragProtocol = (XDragSourceProtocol) dragProtocols.next();
        try {
          dragProtocol.initializeDrag(
              dropActions, transferable,
              formatMap, formats);
        } catch (XException xe) {
          throw (InvalidDnDOperationException) new InvalidDnDOperationException().initCause(xe);
        }
      }

      /* Install X grabs. */
      {
        int status;
        XWindowAttributes wattr = new XWindowAttributes();
        try {
          status = XlibWrapper.XGetWindowAttributes(XToolkit.getDisplay(), rootWindow, wattr.pData);

          if (status == 0) {
            throw new InvalidDnDOperationException("XGetWindowAttributes failed");
          }

          rootEventMask = wattr.get_your_event_mask();

          XlibWrapper.XSelectInput(
              XToolkit.getDisplay(), rootWindow, rootEventMask | ROOT_EVENT_MASK);
        } finally {
          wattr.dispose();
        }

        XBaseWindow.ungrabInput();

        status =
            XlibWrapper.XGrabPointer(
                XToolkit.getDisplay(),
                rootWindow,
                0,
                GRAB_EVENT_MASK,
                XConstants.GrabModeAsync,
                XConstants.GrabModeAsync,
                XConstants.None,
                xcursor,
                timeStamp);

        if (status != XConstants.GrabSuccess) {
          cleanup(timeStamp);
          throwGrabFailureException("Cannot grab pointer", status);
          return;
        }

        status =
            XlibWrapper.XGrabKeyboard(
                XToolkit.getDisplay(),
                rootWindow,
                0,
                XConstants.GrabModeAsync,
                XConstants.GrabModeAsync,
                timeStamp);

        if (status != XConstants.GrabSuccess) {
          cleanup(timeStamp);
          throwGrabFailureException("Cannot grab keyboard", status);
          return;
        }
      }

      /* Update the global state. */
      dndInProgress = true;
      dragInProgress = true;
      dragRootWindow = rootWindow;
      sourceActions = dropActions;
      sourceFormats = formats;
    } finally {
      XToolkit.awtUnlock();
    }

    /* This implementation doesn't use native context */
    setNativeContext(0);

    SunDropTargetContextPeer.setCurrentJVMLocalSourceTransferable(transferable);
  }
Beispiel #21
0
  @Override // PlatformWindow
  public void setVisible(boolean visible) {
    final long nsWindowPtr = getNSWindowPtr();

    // Configure stuff
    updateIconImages();
    updateFocusabilityForAutoRequestFocus(false);

    boolean wasMaximized = isMaximized();

    if (visible && target.isLocationByPlatform()) {
      nativeSetNSWindowLocationByPlatform(getNSWindowPtr());
    }

    // Actually show or hide the window
    LWWindowPeer blocker = (peer == null) ? null : peer.getBlocker();
    if (blocker == null || !visible) {
      // If it ain't blocked, or is being hidden, go regular way
      if (visible) {
        CWrapper.NSWindow.makeFirstResponder(nsWindowPtr, contentView.getAWTView());

        boolean isPopup = (target.getType() == Window.Type.POPUP);
        if (isPopup) {
          // Popups in applets don't activate applet's process
          CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
        } else {
          CWrapper.NSWindow.orderFront(nsWindowPtr);
        }

        boolean isKeyWindow = CWrapper.NSWindow.isKeyWindow(nsWindowPtr);
        if (!isKeyWindow) {
          CWrapper.NSWindow.makeKeyWindow(nsWindowPtr);
        }
      } else {
        // immediately hide the window
        CWrapper.NSWindow.orderOut(nsWindowPtr);
        // process the close
        CWrapper.NSWindow.close(nsWindowPtr);
      }
    } else {
      // otherwise, put it in a proper z-order
      CWrapper.NSWindow.orderWindow(
          nsWindowPtr,
          CWrapper.NSWindow.NSWindowBelow,
          ((CPlatformWindow) blocker.getPlatformWindow()).getNSWindowPtr());
    }
    this.visible = visible;

    // Manage the extended state when showing
    if (visible) {
      // Apply the extended state as expected in shared code
      if (target instanceof Frame) {
        if (!wasMaximized && isMaximized()) {
          // setVisible could have changed the native maximized state
          deliverZoom(true);
        } else {
          int frameState = ((Frame) target).getExtendedState();
          if ((frameState & Frame.ICONIFIED) != 0) {
            // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
            frameState = Frame.ICONIFIED;
          }
          switch (frameState) {
            case Frame.ICONIFIED:
              CWrapper.NSWindow.miniaturize(nsWindowPtr);
              break;
            case Frame.MAXIMIZED_BOTH:
              maximize();
              break;
            default: // NORMAL
              unmaximize(); // in case it was maximized, otherwise this is a no-op
              break;
          }
        }
      }
    }

    nativeSynthesizeMouseEnteredExitedEvents();

    // Configure stuff #2
    updateFocusabilityForAutoRequestFocus(true);

    // Manage parent-child relationship when showing
    final ComponentAccessor acc = AWTAccessor.getComponentAccessor();

    if (visible) {
      // Order myself above my parent
      if (owner != null && owner.isVisible()) {
        CWrapper.NSWindow.orderWindow(
            nsWindowPtr, CWrapper.NSWindow.NSWindowAbove, owner.getNSWindowPtr());
        applyWindowLevel(target);
      }

      // Order my own children above myself
      for (Window w : target.getOwnedWindows()) {
        final Object p = acc.getPeer(w);
        if (p instanceof LWWindowPeer) {
          CPlatformWindow pw = (CPlatformWindow) ((LWWindowPeer) p).getPlatformWindow();
          if (pw != null && pw.isVisible()) {
            CWrapper.NSWindow.orderWindow(
                pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove, nsWindowPtr);
            pw.applyWindowLevel(w);
          }
        }
      }
    }

    // Deal with the blocker of the window being shown
    if (blocker != null && visible) {
      // Make sure the blocker is above its siblings
      ((CPlatformWindow) blocker.getPlatformWindow()).orderAboveSiblings();
    }
  }
Beispiel #22
0
  /**
   * Execute applet events. Here is the state transition diagram
   *
   * <pre>{@literal
   *   Note: (XXX) is the action
   *         APPLET_XXX is the state
   *  (applet code loaded) --> APPLET_LOAD -- (applet init called)--> APPLET_INIT --
   *  (applet start called) --> APPLET_START -- (applet stop called) --> APPLET_STOP --
   *  (applet destroyed called) --> APPLET_DESTROY --> (applet gets disposed) -->
   *   APPLET_DISPOSE --> ...
   * }</pre>
   *
   * In the legacy lifecycle model. The applet gets loaded, inited and started. So it stays in the
   * APPLET_START state unless the applet goes away(refresh page or leave the page). So the applet
   * stop method called and the applet enters APPLET_STOP state. Then if the applet is revisited, it
   * will call applet start method and enter the APPLET_START state and stay there.
   *
   * <p>In the modern lifecycle model. When the applet first time visited, it is same as legacy
   * lifecycle model. However, when the applet page goes away. It calls applet stop method and
   * enters APPLET_STOP state and then applet destroyed method gets called and enters APPLET_DESTROY
   * state.
   *
   * <p>This code is also called by AppletViewer. In AppletViewer "Restart" menu, the applet is jump
   * from APPLET_STOP to APPLET_DESTROY and to APPLET_INIT .
   *
   * <p>Also, the applet can jump from APPLET_INIT state to APPLET_DESTROY (in Netscape/Mozilla
   * case). Same as APPLET_LOAD to APPLET_DISPOSE since all of this are triggered by browser.
   */
  @Override
  public void run() {

    Thread curThread = Thread.currentThread();
    if (curThread == loaderThread) {
      // if we are in the loader thread, cause
      // loading to occur.  We may exit this with
      // status being APPLET_DISPOSE, APPLET_ERROR,
      // or APPLET_LOAD
      runLoader();
      return;
    }

    boolean disposed = false;
    while (!disposed && !curThread.isInterrupted()) {
      AppletEvent evt;
      try {
        evt = getNextEvent();
      } catch (InterruptedException e) {
        showAppletStatus("bail");
        return;
      }

      // showAppletStatus("EVENT = " + evt.getID());
      try {
        switch (evt.getID()) {
          case APPLET_LOAD:
            if (!okToLoad()) {
              break;
            }
            // This complexity allows loading of applets to be
            // interruptable.  The actual thread loading runs
            // in a separate thread, so it can be interrupted
            // without harming the applet thread.
            // So that we don't have to worry about
            // concurrency issues, the main applet thread waits
            // until the loader thread terminates.
            // (one way or another).
            if (loaderThread == null) {
              setLoaderThread(new Thread(null, this, "AppletLoader", 0, false));
              loaderThread.start();
              // we get to go to sleep while this runs
              loaderThread.join();
              setLoaderThread(null);
            } else {
              // REMIND: issue an error -- this case should never
              // occur.
            }
            break;

          case APPLET_INIT:
            // AppletViewer "Restart" will jump from destroy method to
            // init, that is why we need to check status w/ APPLET_DESTROY
            if (status != APPLET_LOAD && status != APPLET_DESTROY) {
              showAppletStatus("notloaded");
              break;
            }
            applet.resize(defaultAppletSize);

            if (PerformanceLogger.loggingEnabled()) {
              PerformanceLogger.setTime("Applet Init");
              PerformanceLogger.outputLog();
            }
            applet.init();

            // Need the default(fallback) font to be created in this AppContext
            Font f = getFont();
            if (f == null
                || "dialog".equals(f.getFamily().toLowerCase(Locale.ENGLISH))
                    && f.getSize() == 12
                    && f.getStyle() == Font.PLAIN) {
              setFont(new Font(Font.DIALOG, Font.PLAIN, 12));
            }

            // Validate the applet in event dispatch thread
            // to avoid deadlock.
            try {
              final AppletPanel p = this;
              Runnable r =
                  new Runnable() {
                    @Override
                    public void run() {
                      p.validate();
                    }
                  };
              AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r);
            } catch (InterruptedException ie) {
            } catch (InvocationTargetException ite) {
            }

            status = APPLET_INIT;
            showAppletStatus("inited");
            break;

          case APPLET_START:
            {
              if (status != APPLET_INIT && status != APPLET_STOP) {
                showAppletStatus("notinited");
                break;
              }
              applet.resize(currentAppletSize);
              applet.start();

              // Validate and show the applet in event dispatch thread
              // to avoid deadlock.
              try {
                final AppletPanel p = this;
                final Applet a = applet;
                Runnable r =
                    new Runnable() {
                      @Override
                      public void run() {
                        p.validate();
                        a.setVisible(true);

                        // Fix for BugTraq ID 4041703.
                        // Set the default focus for an applet.
                        if (hasInitialFocus()) {
                          setDefaultFocus();
                        }
                      }
                    };
                AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r);
              } catch (InterruptedException ie) {
              } catch (InvocationTargetException ite) {
              }

              status = APPLET_START;
              showAppletStatus("started");
              break;
            }

          case APPLET_STOP:
            if (status != APPLET_START) {
              showAppletStatus("notstarted");
              break;
            }
            status = APPLET_STOP;

            // Hide the applet in event dispatch thread
            // to avoid deadlock.
            try {
              final Applet a = applet;
              Runnable r =
                  new Runnable() {
                    @Override
                    public void run() {
                      a.setVisible(false);
                    }
                  };
              AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r);
            } catch (InterruptedException ie) {
            } catch (InvocationTargetException ite) {
            }

            // During Applet.stop(), any AccessControlException on an involved Class remains in
            // the "memory" of the AppletClassLoader.  If the same instance of the ClassLoader is
            // reused, the same exception will occur during class loading.  Set the
            // AppletClassLoader's
            // exceptionStatusSet flag to allow recognition of what had happened
            // when reusing AppletClassLoader object.
            try {
              applet.stop();
            } catch (java.security.AccessControlException e) {
              setExceptionStatus(e);
              // rethrow exception to be handled as it normally would be.
              throw e;
            }
            showAppletStatus("stopped");
            break;

          case APPLET_DESTROY:
            if (status != APPLET_STOP && status != APPLET_INIT) {
              showAppletStatus("notstopped");
              break;
            }
            status = APPLET_DESTROY;

            // During Applet.destroy(), any AccessControlException on an involved Class remains in
            // the "memory" of the AppletClassLoader.  If the same instance of the ClassLoader is
            // reused, the same exception will occur during class loading.  Set the
            // AppletClassLoader's
            // exceptionStatusSet flag to allow recognition of what had happened
            // when reusing AppletClassLoader object.
            try {
              applet.destroy();
            } catch (java.security.AccessControlException e) {
              setExceptionStatus(e);
              // rethrow exception to be handled as it normally would be.
              throw e;
            }
            showAppletStatus("destroyed");
            break;

          case APPLET_DISPOSE:
            if (status != APPLET_DESTROY && status != APPLET_LOAD) {
              showAppletStatus("notdestroyed");
              break;
            }
            status = APPLET_DISPOSE;

            try {
              final Applet a = applet;
              Runnable r =
                  new Runnable() {
                    @Override
                    public void run() {
                      remove(a);
                    }
                  };
              AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r);
            } catch (InterruptedException ie) {
            } catch (InvocationTargetException ite) {
            }
            applet = null;
            showAppletStatus("disposed");
            disposed = true;
            break;

          case APPLET_QUIT:
            return;
        }
      } catch (Exception e) {
        status = APPLET_ERROR;
        if (e.getMessage() != null) {
          showAppletStatus("exception2", e.getClass().getName(), e.getMessage());
        } else {
          showAppletStatus("exception", e.getClass().getName());
        }
        showAppletException(e);
      } catch (ThreadDeath e) {
        showAppletStatus("death");
        return;
      } catch (Error e) {
        status = APPLET_ERROR;
        if (e.getMessage() != null) {
          showAppletStatus("error2", e.getClass().getName(), e.getMessage());
        } else {
          showAppletStatus("error", e.getClass().getName());
        }
        showAppletException(e);
      }
      clearLoadAbortRequest();
    }
  }
Beispiel #23
0
 // sync target and peer
 public void setExtendedState(int state) {
   AWTAccessor.getFrameAccessor().setExtendedState((Frame) target, state);
 }
Beispiel #24
0
 public int getExtendedState() {
   return AWTAccessor.getFrameAccessor().getExtendedState((Frame) target);
 }
Beispiel #25
0
 @Override
 void handleJavaKeyEvent(KeyEvent e) {
   AWTAccessor.getComponentAccessor().processEvent(xtext, e);
 }
  private void dragFrameFaster(JComponent f, int newX, int newY) {

    Rectangle previousBounds =
        new Rectangle(currentBounds.x, currentBounds.y, currentBounds.width, currentBounds.height);

    // move the frame
    currentBounds.x = newX;
    currentBounds.y = newY;

    if (didDrag) {
      // Only initiate cleanup if we have actually done a drag.
      emergencyCleanup(f);
    } else {
      didDrag = true;
      // We reset the danger field as until now we haven't actually
      // moved the internal frame so we don't need to initiate repaint.
      ((JInternalFrame) f).danger = false;
    }

    boolean floaterCollision = isFloaterCollision(previousBounds, currentBounds);

    // System.out.println(previousBounds);
    JComponent parent = (JComponent) f.getParent();
    Rectangle visBounds = previousBounds.intersection(desktopBounds);
    //  System.out.println(previousBounds);

    // System.out.println(visBounds);

    RepaintManager currentManager = RepaintManager.currentManager(f);

    currentManager.beginPaint();
    try {
      if (!floaterCollision) {
        currentManager.copyArea(
            parent,
            desktopGraphics,
            visBounds.x,
            visBounds.y,
            visBounds.width,
            visBounds.height,
            newX - previousBounds.x,
            newY - previousBounds.y,
            true);
      }

      f.setBounds(currentBounds);

      if (floaterCollision) {
        // since we couldn't blit we just redraw as fast as possible
        // the isDragging mucking is to avoid activating emergency
        // cleanup
        ((JInternalFrame) f).isDragging = false;
        parent.paintImmediately(currentBounds);
        ((JInternalFrame) f).isDragging = true;
      }

      // fake out the repaint manager.  We'll take care of everything

      currentManager.markCompletelyClean(parent);
      currentManager.markCompletelyClean(f);

      // compute the minimal newly exposed area
      // if the rects intersect then we use computeDifference.  Otherwise
      // we'll repaint the entire previous bounds
      Rectangle[] dirtyRects = null;
      if (previousBounds.intersects(currentBounds)) {
        dirtyRects = SwingUtilities.computeDifference(previousBounds, currentBounds);
      } else {
        dirtyRects = new Rectangle[1];
        dirtyRects[0] = previousBounds;
        //  System.out.println("no intersection");
      }
      ;

      // Fix the damage
      for (int i = 0; i < dirtyRects.length; i++) {
        parent.paintImmediately(dirtyRects[i]);
      }

      // new areas of blit were exposed
      if (!(visBounds.equals(previousBounds))) {
        dirtyRects = SwingUtilities.computeDifference(previousBounds, desktopBounds);
        for (int i = 0; i < dirtyRects.length; i++) {
          dirtyRects[i].x += newX - previousBounds.x;
          dirtyRects[i].y += newY - previousBounds.y;
          ((JInternalFrame) f).isDragging = false;

          parent.paintImmediately(dirtyRects[i]);
          ((JInternalFrame) f).isDragging = true;

          // System.out.println(dirtyRects[i]);
        }
      }
    } finally {
      currentManager.endPaint();
    }

    // update window if it's non-opaque
    Window topLevel = SwingUtilities.getWindowAncestor(f);
    Toolkit tk = Toolkit.getDefaultToolkit();
    if (!AWTAccessor.getWindowAccessor().isOpaque(topLevel)
        && (tk instanceof SunToolkit)
        && ((SunToolkit) tk).needUpdateWindow()) {
      AWTAccessor.getWindowAccessor().updateWindow(topLevel);
    }
  }
 // NOTE: This method may be called by privileged threads.
 //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
 public void handleResize(Rectangle bounds) {
   AWTAccessor.getComponentAccessor().setSize((Component) target, bounds.width, bounds.height);
   postEvent(new ComponentEvent(target, ComponentEvent.COMPONENT_RESIZED));
 }
Beispiel #28
0
  /*
   * Requests platform to set native focus on a frame/dialog.
   * In case of a simple window, triggers appropriate java focus change.
   */
  public boolean requestWindowFocus(CausedFocusEvent.Cause cause) {
    if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
      focusLog.fine("requesting native focus to " + this);
    }

    if (!focusAllowedFor()) {
      focusLog.fine("focus is not allowed");
      return false;
    }

    // if (platformWindow.rejectFocusRequest(cause)) {
    //    return false;
    // }

    AppContext targetAppContext = AWTAccessor.getComponentAccessor().getAppContext(getTarget());
    KeyboardFocusManager kfm =
        AWTAccessor.getKeyboardFocusManagerAccessor()
            .getCurrentKeyboardFocusManager(targetAppContext);
    Window currentActive = kfm.getActiveWindow();

    Window opposite = LWKeyboardFocusManagerPeer.getInstance().getCurrentFocusedWindow();

    // Make the owner active window.
    if (isSimpleWindow()) {
      focusLog.fine("This is a Simple Window.");
      LWWindowPeer owner = getOwnerFrameDialog(this);

      // If owner is not natively active, request native
      // activation on it w/o sending events up to java.
      if (owner != null && !owner.platformWindow.isActive()) {
        if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
          focusLog.fine("requesting native focus to the owner " + owner);
        }
        LWWindowPeer currentActivePeer =
            currentActive == null
                ? null
                : (LWWindowPeer) AWTAccessor.getComponentAccessor().getPeer(currentActive);

        // Ensure the opposite is natively active and suppress sending events.
        if (currentActivePeer != null && currentActivePeer.platformWindow.isActive()) {
          if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
            focusLog.fine("the opposite is " + currentActivePeer);
          }
          currentActivePeer.skipNextFocusChange = true;
        }
        owner.skipNextFocusChange = true;

        owner.platformWindow.requestWindowFocus();
      }

      // DKFM will synthesize all the focus/activation events correctly.
      changeFocusedWindow(true, opposite);
      focusLog.fine("DKFM will synthesize all the focus/activation events correctly");
      return true;

      // In case the toplevel is active but not focused, change focus directly,
      // as requesting native focus on it will not have effect.
    } else if (getTarget() == currentActive && !getTarget().hasFocus()) {

      changeFocusedWindow(true, opposite);
      focusLog.fine("toplevel is active but not focused, change focus directly");
      return true;
    }

    focusLog.fine("platformWindow.requestWindowFocus()");
    return platformWindow.requestWindowFocus();
  }