1 /*
   2  * Copyright (c) 2011, 2015, 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 
  26 package sun.lwawt.macosx;
  27 
  28 import sun.awt.AWTAccessor;
  29 import sun.awt.SunToolkit;
  30 
  31 import javax.swing.*;
  32 import java.awt.*;
  33 import java.awt.event.*;
  34 import java.awt.geom.Point2D;
  35 import java.awt.image.BufferedImage;
  36 import java.awt.peer.TrayIconPeer;
  37 import java.beans.PropertyChangeEvent;
  38 import java.beans.PropertyChangeListener;
  39 
  40 import static sun.awt.AWTAccessor.*;
  41 
  42 public class CTrayIcon extends CFRetainedResource implements TrayIconPeer {
  43     private TrayIcon target;
  44     private PopupMenu popup;
  45     private JDialog messageDialog;
  46     private DialogEventHandler handler;
  47 
  48     // In order to construct MouseEvent object, we need to specify a
  49     // Component target. Because TrayIcon isn't Component's subclass,
  50     // we use this dummy frame instead
  51     private final Frame dummyFrame;
  52 
  53     // A bitmask that indicates what mouse buttons produce MOUSE_CLICKED events
  54     // on MOUSE_RELEASE. Click events are only generated if there were no drag
  55     // events between MOUSE_PRESSED and MOUSE_RELEASED for particular button
  56     private static int mouseClickButtons = 0;
  57 
  58     CTrayIcon(TrayIcon target) {
  59         super(0, true);
  60 
  61         this.messageDialog = null;
  62         this.handler = null;
  63         this.target = target;
  64         this.popup = target.getPopupMenu();
  65         this.dummyFrame = new Frame();
  66         setPtr(createModel());
  67 
  68         //if no one else is creating the peer.
  69         checkAndCreatePopupPeer();
  70         updateImage();
  71     }
  72 
  73     private CPopupMenu checkAndCreatePopupPeer() {
  74         CPopupMenu menuPeer = null;
  75         if (popup != null) {
  76             try {
  77                 final MenuComponentAccessor acc = getMenuComponentAccessor();
  78                 menuPeer = acc.getPeer(popup);
  79                 if (menuPeer == null) {
  80                     popup.addNotify();
  81                     menuPeer = acc.getPeer(popup);
  82                 }
  83             } catch (Exception e) {
  84                 e.printStackTrace();
  85             }
  86         }
  87         return menuPeer;
  88     }
  89 
  90     private long createModel() {
  91         return nativeCreate();
  92     }
  93 
  94     private long getModel() {
  95         return ptr;
  96     }
  97 
  98     private native long nativeCreate();
  99 
 100     //invocation from the AWTTrayIcon.m
 101     public long getPopupMenuModel(){
 102         if(popup != null) {
 103             PopupMenu newPopup = target.getPopupMenu();
 104             if (popup != newPopup) {
 105                 if (newPopup != null) {
 106                     popup = newPopup;
 107                 } else {
 108                     return 0L;
 109                 }
 110             }
 111         } else {
 112             return 0L;
 113         }
 114 
 115         return checkAndCreatePopupPeer().getModel();
 116     }
 117 
 118     /**
 119      * We display tray icon message as a small dialog with OK button.
 120      * This is lame, but JDK 1.6 does basically the same. There is a new
 121      * kind of window in Lion, NSPopover, so perhaps it could be used it
 122      * to implement better looking notifications.
 123      */
 124     public void displayMessage(final String caption, final String text,
 125                                final String messageType) {
 126 
 127         if (SwingUtilities.isEventDispatchThread()) {
 128             displayMessageOnEDT(caption, text, messageType);
 129         } else {
 130             try {
 131                 SwingUtilities.invokeAndWait(new Runnable() {
 132                     public void run() {
 133                         displayMessageOnEDT(caption, text, messageType);
 134                     }
 135                 });
 136             } catch (Exception e) {
 137                 throw new AssertionError(e);
 138             }
 139         }
 140     }
 141 
 142     @Override
 143     public void dispose() {
 144         if (messageDialog != null) {
 145             disposeMessageDialog();
 146         }
 147 
 148         dummyFrame.dispose();
 149 
 150         if (popup != null) {
 151             popup.removeNotify();
 152         }
 153 
 154         LWCToolkit.targetDisposedPeer(target, this);
 155         target = null;
 156 
 157         super.dispose();
 158     }
 159 
 160     @Override
 161     public void setToolTip(String tooltip) {
 162         nativeSetToolTip(getModel(), tooltip);
 163     }
 164 
 165     //adds tooltip to the NSStatusBar's NSButton.
 166     private native void nativeSetToolTip(long trayIconModel, String tooltip);
 167 
 168     @Override
 169     public void showPopupMenu(int x, int y) {
 170         //Not used. The popupmenu is shown from the native code.
 171     }
 172 
 173     @Override
 174     public void updateImage() {
 175         Image image = target.getImage();
 176         if (image == null) return;
 177 
 178         MediaTracker tracker = new MediaTracker(new Button(""));
 179         tracker.addImage(image, 0);
 180         try {
 181             tracker.waitForAll();
 182         } catch (InterruptedException ignore) { }
 183 
 184         if (image.getWidth(null) <= 0 ||
 185             image.getHeight(null) <= 0)
 186         {
 187             return;
 188         }
 189 
 190         CImage cimage = CImage.getCreator().createFromImage(image);
 191         setNativeImage(getModel(), cimage.ptr, target.isImageAutoSize());
 192     }
 193 
 194     private native void setNativeImage(final long model, final long nsimage, final boolean autosize);
 195 
 196     private void postEvent(final AWTEvent event) {
 197         SunToolkit.executeOnEventHandlerThread(target, new Runnable() {
 198             public void run() {
 199                 SunToolkit.postEvent(SunToolkit.targetToAppContext(target), event);
 200             }
 201         });
 202     }
 203 
 204     //invocation from the AWTTrayIcon.m
 205     private void handleMouseEvent(NSEvent nsEvent) {
 206         int buttonNumber = nsEvent.getButtonNumber();
 207         final SunToolkit tk = (SunToolkit)Toolkit.getDefaultToolkit();
 208         if ((buttonNumber > 2 && !tk.areExtraMouseButtonsEnabled())
 209                 || buttonNumber > tk.getNumberOfButtons() - 1) {
 210             return;
 211         }
 212 
 213         int jeventType = NSEvent.nsToJavaEventType(nsEvent.getType());
 214 
 215         int jbuttonNumber = MouseEvent.NOBUTTON;
 216         int jclickCount = 0;
 217         if (jeventType != MouseEvent.MOUSE_MOVED) {
 218             jbuttonNumber = NSEvent.nsToJavaButton(buttonNumber);
 219             jclickCount = nsEvent.getClickCount();
 220         }
 221 
 222         int jmodifiers = NSEvent.nsToJavaMouseModifiers(buttonNumber,
 223                 nsEvent.getModifierFlags());
 224         boolean isPopupTrigger = NSEvent.isPopupTrigger(jmodifiers);
 225 
 226         int eventButtonMask = (jbuttonNumber > 0)?
 227                 MouseEvent.getMaskForButton(jbuttonNumber) : 0;
 228         long when = System.currentTimeMillis();
 229 
 230         if (jeventType == MouseEvent.MOUSE_PRESSED) {
 231             mouseClickButtons |= eventButtonMask;
 232         } else if (jeventType == MouseEvent.MOUSE_DRAGGED) {
 233             mouseClickButtons = 0;
 234         }
 235 
 236         // The MouseEvent's coordinates are relative to screen
 237         int absX = nsEvent.getAbsX();
 238         int absY = nsEvent.getAbsY();
 239 
 240         MouseEvent mouseEvent = new MouseEvent(dummyFrame, jeventType, when,
 241                 jmodifiers, absX, absY, absX, absY, jclickCount, isPopupTrigger,
 242                 jbuttonNumber);
 243         mouseEvent.setSource(target);
 244         postEvent(mouseEvent);
 245 
 246         // fire ACTION event
 247         if (jeventType == MouseEvent.MOUSE_PRESSED && isPopupTrigger) {
 248             final String cmd = target.getActionCommand();
 249             final ActionEvent event = new ActionEvent(target,
 250                     ActionEvent.ACTION_PERFORMED, cmd);
 251             postEvent(event);
 252         }
 253 
 254         // synthesize CLICKED event
 255         if (jeventType == MouseEvent.MOUSE_RELEASED) {
 256             if ((mouseClickButtons & eventButtonMask) != 0) {
 257                 MouseEvent clickEvent = new MouseEvent(dummyFrame,
 258                         MouseEvent.MOUSE_CLICKED, when, jmodifiers, absX, absY,
 259                         absX, absY, jclickCount, isPopupTrigger, jbuttonNumber);
 260                 clickEvent.setSource(target);
 261                 postEvent(clickEvent);
 262             }
 263 
 264             mouseClickButtons &= ~eventButtonMask;
 265         }
 266     }
 267 
 268     private native Point2D nativeGetIconLocation(long trayIconModel);
 269 
 270     public void displayMessageOnEDT(String caption, String text,
 271                                     String messageType) {
 272         if (messageDialog != null) {
 273             disposeMessageDialog();
 274         }
 275 
 276         // obtain icon to show along the message
 277         Icon icon = getIconForMessageType(messageType);
 278         if (icon != null) {
 279             icon = new ImageIcon(scaleIcon(icon, 0.75));
 280         }
 281 
 282         // We want the message dialog text area to be about 1/8 of the screen
 283         // size. There is nothing special about this value, it's just makes the
 284         // message dialog to look nice
 285         Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
 286         int textWidth = screenSize.width / 8;
 287 
 288         // create dialog to show
 289         messageDialog = createMessageDialog(caption, text, textWidth, icon);
 290 
 291         // finally, show the dialog to user
 292         showMessageDialog();
 293     }
 294 
 295     /**
 296      * Creates dialog window used to display the message
 297      */
 298     private JDialog createMessageDialog(String caption, String text,
 299                                      int textWidth, Icon icon) {
 300         JDialog dialog;
 301         handler = new DialogEventHandler();
 302 
 303         JTextArea captionArea = null;
 304         if (caption != null) {
 305             captionArea = createTextArea(caption, textWidth, false, true);
 306         }
 307 
 308         JTextArea textArea = null;
 309         if (text != null){
 310             textArea = createTextArea(text, textWidth, true, false);
 311         }
 312 
 313         Object[] panels = null;
 314         if (captionArea != null) {
 315             if (textArea != null) {
 316                 panels = new Object[] {captionArea, new JLabel(), textArea};
 317             } else {
 318                 panels = new Object[] {captionArea};
 319             }
 320         } else {
 321            if (textArea != null) {
 322                 panels = new Object[] {textArea};
 323             }
 324         }
 325 
 326         // We want message dialog with small title bar. There is a client
 327         // property property that does it, however, it must be set before
 328         // dialog's native window is created. This is why we create option
 329         // pane and dialog separately
 330         final JOptionPane op = new JOptionPane(panels);
 331         op.setIcon(icon);
 332         op.addPropertyChangeListener(handler);
 333 
 334         // Make Ok button small. Most likely won't work for L&F other then Aqua
 335         try {
 336             JPanel buttonPanel = (JPanel)op.getComponent(1);
 337             JButton ok = (JButton)buttonPanel.getComponent(0);
 338             ok.putClientProperty("JComponent.sizeVariant", "small");
 339         } catch (Throwable t) {
 340             // do nothing, we tried and failed, no big deal
 341         }
 342 
 343         dialog = new JDialog((Dialog) null);
 344         JRootPane rp = dialog.getRootPane();
 345 
 346         // gives us dialog window with small title bar and not zoomable
 347         rp.putClientProperty(CPlatformWindow.WINDOW_STYLE, "small");
 348         rp.putClientProperty(CPlatformWindow.WINDOW_ZOOMABLE, "false");
 349 
 350         dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
 351         dialog.setModal(false);
 352         dialog.setModalExclusionType(Dialog.ModalExclusionType.TOOLKIT_EXCLUDE);
 353         dialog.setAlwaysOnTop(true);
 354         dialog.setAutoRequestFocus(false);
 355         dialog.setResizable(false);
 356         dialog.setContentPane(op);
 357 
 358         dialog.addWindowListener(handler);
 359 
 360         // suppress security warning for untrusted windows
 361         AWTAccessor.getWindowAccessor().setTrayIconWindow(dialog, true);
 362 
 363         dialog.pack();
 364 
 365         return dialog;
 366     }
 367 
 368     private void showMessageDialog() {
 369 
 370         Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
 371         Point2D iconLoc = nativeGetIconLocation(getModel());
 372 
 373         int dialogY = (int)iconLoc.getY();
 374         int dialogX = (int)iconLoc.getX();
 375         if (dialogX + messageDialog.getWidth() > screenSize.width) {
 376             dialogX = screenSize.width - messageDialog.getWidth();
 377         }
 378 
 379         messageDialog.setLocation(dialogX, dialogY);
 380         messageDialog.setVisible(true);
 381     }
 382 
 383    private void disposeMessageDialog() {
 384         if (SwingUtilities.isEventDispatchThread()) {
 385             disposeMessageDialogOnEDT();
 386         } else {
 387             try {
 388                 SwingUtilities.invokeAndWait(new Runnable() {
 389                     public void run() {
 390                         disposeMessageDialogOnEDT();
 391                     }
 392                 });
 393             } catch (Exception e) {
 394                 throw new AssertionError(e);
 395             }
 396         }
 397    }
 398 
 399     private void disposeMessageDialogOnEDT() {
 400         if (messageDialog != null) {
 401             messageDialog.removeWindowListener(handler);
 402             messageDialog.removePropertyChangeListener(handler);
 403             messageDialog.dispose();
 404 
 405             messageDialog = null;
 406             handler = null;
 407         }
 408     }
 409 
 410     /**
 411      * Scales an icon using specified scale factor
 412      *
 413      * @param icon        icon to scale
 414      * @param scaleFactor scale factor to use
 415      * @return scaled icon as BuffedredImage
 416      */
 417     private static BufferedImage scaleIcon(Icon icon, double scaleFactor) {
 418         if (icon == null) {
 419             return null;
 420         }
 421 
 422         int w = icon.getIconWidth();
 423         int h = icon.getIconHeight();
 424 
 425         GraphicsEnvironment ge =
 426                 GraphicsEnvironment.getLocalGraphicsEnvironment();
 427         GraphicsDevice gd = ge.getDefaultScreenDevice();
 428         GraphicsConfiguration gc = gd.getDefaultConfiguration();
 429 
 430         // convert icon into image
 431         BufferedImage iconImage = gc.createCompatibleImage(w, h,
 432                 Transparency.TRANSLUCENT);
 433         Graphics2D g = iconImage.createGraphics();
 434         icon.paintIcon(null, g, 0, 0);
 435         g.dispose();
 436 
 437         // and scale it nicely
 438         int scaledW = (int) (w * scaleFactor);
 439         int scaledH = (int) (h * scaleFactor);
 440         BufferedImage scaledImage = gc.createCompatibleImage(scaledW, scaledH,
 441                 Transparency.TRANSLUCENT);
 442         g = scaledImage.createGraphics();
 443         g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
 444                 RenderingHints.VALUE_INTERPOLATION_BILINEAR);
 445         g.drawImage(iconImage, 0, 0, scaledW, scaledH, null);
 446         g.dispose();
 447 
 448         return scaledImage;
 449     }
 450 
 451 
 452     /**
 453      * Gets Aqua icon used in message dialog.
 454      */
 455     private static Icon getIconForMessageType(String messageType) {
 456         if (messageType.equals("ERROR")) {
 457             return UIManager.getIcon("OptionPane.errorIcon");
 458         } else if (messageType.equals("WARNING")) {
 459             return UIManager.getIcon("OptionPane.warningIcon");
 460         } else {
 461             // this is just an application icon
 462             return UIManager.getIcon("OptionPane.informationIcon");
 463         }
 464     }
 465 
 466     private static JTextArea createTextArea(String text, int width,
 467                                             boolean isSmall, boolean isBold) {
 468         JTextArea textArea = new JTextArea(text);
 469 
 470         textArea.setLineWrap(true);
 471         textArea.setWrapStyleWord(true);
 472         textArea.setEditable(false);
 473         textArea.setFocusable(false);
 474         textArea.setBorder(null);
 475         textArea.setBackground(new JLabel().getBackground());
 476 
 477         if (isSmall) {
 478             textArea.putClientProperty("JComponent.sizeVariant", "small");
 479         }
 480 
 481         if (isBold) {
 482             Font font = textArea.getFont();
 483             Font boldFont = new Font(font.getName(), Font.BOLD, font.getSize());
 484             textArea.setFont(boldFont);
 485         }
 486 
 487         textArea.setSize(width, 1);
 488 
 489         return textArea;
 490     }
 491 
 492     /**
 493      * Implements all the Listeners needed by message dialog
 494      */
 495     private final class DialogEventHandler extends WindowAdapter
 496             implements PropertyChangeListener {
 497 
 498         public void windowClosing(WindowEvent we) {
 499                 disposeMessageDialog();
 500         }
 501 
 502         public void propertyChange(PropertyChangeEvent e) {
 503             if (messageDialog == null) {
 504                 return;
 505             }
 506 
 507             String prop = e.getPropertyName();
 508             Container cp = messageDialog.getContentPane();
 509 
 510             if (messageDialog.isVisible() && e.getSource() == cp &&
 511                     (prop.equals(JOptionPane.VALUE_PROPERTY))) {
 512                 disposeMessageDialog();
 513             }
 514         }
 515     }
 516 }
 517