InfoWindow.java 18.7 KB
Newer Older
1
/*
O
ohair 已提交
2
 * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
3 4 5 6
 * 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
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 12 13 14 15 16 17 18 19 20
 *
 * 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.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 */

package sun.awt.X11;

import java.awt.*;
import java.awt.event.*;
import java.awt.peer.TrayIconPeer;
import sun.awt.*;
import java.awt.image.*;
import java.text.BreakIterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.lang.reflect.InvocationTargetException;

/**
 * An utility window class. This is a base class for Tooltip and Balloon.
 */
public abstract class InfoWindow extends Window {
    private Container container;
    private Closer closer;

    protected InfoWindow(Frame parent, Color borderColor) {
        super(parent);
48
        setType(Window.Type.POPUP);
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 151 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
        container = new Container() {
            @Override
            public Insets getInsets() {
                return new Insets(1, 1, 1, 1);
            }
        };
        setLayout(new BorderLayout());
        setBackground(borderColor);
        add(container, BorderLayout.CENTER);
        container.setLayout(new BorderLayout());

        closer = new Closer();
    }

    public Component add(Component c) {
        container.add(c, BorderLayout.CENTER);
        return c;
    }

    protected void setCloser(Runnable action, int time) {
        closer.set(action, time);
    }

    // Must be executed on EDT.
    protected void show(Point corner, int indent) {
        assert SunToolkit.isDispatchThreadForAppContext(this);

        pack();

        Dimension size = getSize();
        // TODO: When 6356322 is fixed we should get screen bounds in
        // this way: eframe.getGraphicsConfiguration().getBounds().
        Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();

        if (corner.x < scrSize.width/2 && corner.y < scrSize.height/2) { // 1st square
            setLocation(corner.x + indent, corner.y + indent);

        } else if (corner.x >= scrSize.width/2 && corner.y < scrSize.height/2) { // 2nd square
            setLocation(corner.x - indent - size.width, corner.y + indent);

        } else if (corner.x < scrSize.width/2 && corner.y >= scrSize.height/2) { // 3rd square
            setLocation(corner.x + indent, corner.y - indent - size.height);

        } else if (corner.x >= scrSize.width/2 && corner.y >= scrSize.height/2) { // 4th square
            setLocation(corner.x - indent - size.width, corner.y - indent - size.height);
        }

        super.show();
        closer.schedule();
    }

    public void hide() {
        closer.close();
    }

    private class Closer implements Runnable {
        Runnable action;
        int time;

        public void run() {
            doClose();
        }

        void set(Runnable action, int time) {
            this.action = action;
            this.time = time;
        }

        void schedule() {
            XToolkit.schedule(this, time);
        }

        void close() {
            XToolkit.remove(this);
            doClose();
        }

        // WARNING: this method may be executed on Toolkit thread.
        private void doClose() {
            SunToolkit.executeOnEventHandlerThread(InfoWindow.this, new Runnable() {
                public void run() {
                    InfoWindow.super.hide();
                    invalidate();
                    if (action != null) {
                        action.run();
                    }
                }
            });
        }
    }


    private interface LiveArguments {
        /** Whether the target of the InfoWindow is disposed. */
        boolean isDisposed();

        /** The bounds of the target of the InfoWindow. */
        Rectangle getBounds();
    }

    public static class Tooltip extends InfoWindow {

        public interface LiveArguments extends InfoWindow.LiveArguments {
            /** The tooltip to be displayed. */
            String getTooltipString();
        }

        private final Object target;
        private final LiveArguments liveArguments;

        private final Label textLabel = new Label("");
        private final Runnable starter = new Runnable() {
                public void run() {
                    display();
                }};

        private final static int TOOLTIP_SHOW_TIME = 10000;
        private final static int TOOLTIP_START_DELAY_TIME = 1000;
        private final static int TOOLTIP_MAX_LENGTH = 64;
        private final static int TOOLTIP_MOUSE_CURSOR_INDENT = 5;
        private final static Color TOOLTIP_BACKGROUND_COLOR = new Color(255, 255, 220);
        private final static Font TOOLTIP_TEXT_FONT = XWindow.getDefaultFont();

        public Tooltip(Frame parent, Object target,
                LiveArguments liveArguments)
        {
            super(parent, Color.black);

            this.target = target;
            this.liveArguments = liveArguments;

            XTrayIconPeer.suppressWarningString(this);

            setCloser(null, TOOLTIP_SHOW_TIME);
            textLabel.setBackground(TOOLTIP_BACKGROUND_COLOR);
            textLabel.setFont(TOOLTIP_TEXT_FONT);
            add(textLabel);
        }

        /*
         * WARNING: this method is executed on Toolkit thread!
         */
        private void display() {
            // Execute on EDT to avoid deadlock (see 6280857).
            SunToolkit.executeOnEventHandlerThread(target, new Runnable() {
                    public void run() {
                        if (liveArguments.isDisposed()) {
                            return;
                        }
198 199 200 201 202 203 204 205 206 207

                        String tooltipString = liveArguments.getTooltipString();
                        if (tooltipString == null) {
                            return;
                        } else if (tooltipString.length() >  TOOLTIP_MAX_LENGTH) {
                            textLabel.setText(tooltipString.substring(0, TOOLTIP_MAX_LENGTH));
                        } else {
                            textLabel.setText(tooltipString);
                        }

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 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 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
                        Point pointer = (Point)AccessController.doPrivileged(new PrivilegedAction() {
                                public Object run() {
                                    if (!isPointerOverTrayIcon(liveArguments.getBounds())) {
                                        return null;
                                    }
                                    return MouseInfo.getPointerInfo().getLocation();
                                }
                            });
                        if (pointer == null) {
                            return;
                        }
                        show(new Point(pointer.x, pointer.y), TOOLTIP_MOUSE_CURSOR_INDENT);
                    }
                });
        }

        public void enter() {
            XToolkit.schedule(starter, TOOLTIP_START_DELAY_TIME);
        }

        public void exit() {
            XToolkit.remove(starter);
            if (isVisible()) {
                hide();
            }
        }

        private boolean isPointerOverTrayIcon(Rectangle trayRect) {
            Point p = MouseInfo.getPointerInfo().getLocation();
            return !(p.x < trayRect.x || p.x > (trayRect.x + trayRect.width) ||
                     p.y < trayRect.y || p.y > (trayRect.y + trayRect.height));
        }
    }

    public static class Balloon extends InfoWindow {

        public interface LiveArguments extends InfoWindow.LiveArguments {
            /** The action to be performed upon clicking the baloon. */
            String getActionCommand();
        }

        private final LiveArguments liveArguments;
        private final Object target;

        private final static int BALLOON_SHOW_TIME = 10000;
        private final static int BALLOON_TEXT_MAX_LENGTH = 256;
        private final static int BALLOON_WORD_LINE_MAX_LENGTH = 16;
        private final static int BALLOON_WORD_LINE_MAX_COUNT = 4;
        private final static int BALLOON_ICON_WIDTH = 32;
        private final static int BALLOON_ICON_HEIGHT = 32;
        private final static int BALLOON_TRAY_ICON_INDENT = 0;
        private final static Color BALLOON_CAPTION_BACKGROUND_COLOR = new Color(200, 200 ,255);
        private final static Font BALLOON_CAPTION_FONT = new Font(Font.DIALOG, Font.BOLD, 12);

        private Panel mainPanel = new Panel();
        private Panel captionPanel = new Panel();
        private Label captionLabel = new Label("");
        private Button closeButton = new Button("X");
        private Panel textPanel = new Panel();
        private XTrayIconPeer.IconCanvas iconCanvas = new XTrayIconPeer.IconCanvas(BALLOON_ICON_WIDTH, BALLOON_ICON_HEIGHT);
        private Label[] lineLabels = new Label[BALLOON_WORD_LINE_MAX_COUNT];
        private ActionPerformer ap = new ActionPerformer();

        private Image iconImage;
        private Image errorImage;
        private Image warnImage;
        private Image infoImage;
        private boolean gtkImagesLoaded;

        private Displayer displayer = new Displayer();

        public Balloon(Frame parent, Object target, LiveArguments liveArguments) {
            super(parent, new Color(90, 80 ,190));
            this.liveArguments = liveArguments;
            this.target = target;

            XTrayIconPeer.suppressWarningString(this);

            setCloser(new Runnable() {
                    public void run() {
                        if (textPanel != null) {
                            textPanel.removeAll();
                            textPanel.setSize(0, 0);
                            iconCanvas.setSize(0, 0);
                            XToolkit.awtLock();
                            try {
                                displayer.isDisplayed = false;
                                XToolkit.awtLockNotifyAll();
                            } finally {
                                XToolkit.awtUnlock();
                            }
                        }
                    }
                }, BALLOON_SHOW_TIME);

            add(mainPanel);

            captionLabel.setFont(BALLOON_CAPTION_FONT);
            captionLabel.addMouseListener(ap);

            captionPanel.setLayout(new BorderLayout());
            captionPanel.add(captionLabel, BorderLayout.WEST);
            captionPanel.add(closeButton, BorderLayout.EAST);
            captionPanel.setBackground(BALLOON_CAPTION_BACKGROUND_COLOR);
            captionPanel.addMouseListener(ap);

            closeButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        hide();
                    }
                });

            mainPanel.setLayout(new BorderLayout());
            mainPanel.setBackground(Color.white);
            mainPanel.add(captionPanel, BorderLayout.NORTH);
            mainPanel.add(iconCanvas, BorderLayout.WEST);
            mainPanel.add(textPanel, BorderLayout.CENTER);

            iconCanvas.addMouseListener(ap);

            for (int i = 0; i < BALLOON_WORD_LINE_MAX_COUNT; i++) {
                lineLabels[i] = new Label();
                lineLabels[i].addMouseListener(ap);
                lineLabels[i].setBackground(Color.white);
            }

            displayer.start();
        }

        public void display(String caption, String text, String messageType) {
            if (!gtkImagesLoaded) {
                loadGtkImages();
            }
            displayer.display(caption, text, messageType);
        }

        private void _display(String caption, String text, String messageType) {
            captionLabel.setText(caption);

            BreakIterator iter = BreakIterator.getWordInstance();
            if (text != null) {
                iter.setText(text);
                int start = iter.first(), end;
                int nLines = 0;

                do {
                    end = iter.next();

                    if (end == BreakIterator.DONE ||
                        text.substring(start, end).length() >= 50)
                    {
                        lineLabels[nLines].setText(text.substring(start, end == BreakIterator.DONE ?
                                                                  iter.last() : end));
                        textPanel.add(lineLabels[nLines++]);
                        start = end;
                    }
                    if (nLines == BALLOON_WORD_LINE_MAX_COUNT) {
                        if (end != BreakIterator.DONE) {
                            lineLabels[nLines - 1].setText(
                                new String(lineLabels[nLines - 1].getText() + " ..."));
                        }
                        break;
                    }
                } while (end != BreakIterator.DONE);


                textPanel.setLayout(new GridLayout(nLines, 1));
            }

            if ("ERROR".equals(messageType)) {
                iconImage = errorImage;
            } else if ("WARNING".equals(messageType)) {
                iconImage = warnImage;
            } else if ("INFO".equals(messageType)) {
                iconImage = infoImage;
            } else {
                iconImage = null;
            }

            if (iconImage != null) {
                Dimension tpSize = textPanel.getSize();
                iconCanvas.setSize(BALLOON_ICON_WIDTH, (BALLOON_ICON_HEIGHT > tpSize.height ?
                                                        BALLOON_ICON_HEIGHT : tpSize.height));
                iconCanvas.validate();
            }

            SunToolkit.executeOnEventHandlerThread(target, new Runnable() {
                    public void run() {
                        if (liveArguments.isDisposed()) {
                            return;
                        }
                        Point parLoc = getParent().getLocationOnScreen();
                        Dimension parSize = getParent().getSize();
                        show(new Point(parLoc.x + parSize.width/2, parLoc.y + parSize.height/2),
                             BALLOON_TRAY_ICON_INDENT);
                        if (iconImage != null) {
                            iconCanvas.updateImage(iconImage); // call it after the show(..) above
                        }
                    }
                });
        }

        public void dispose() {
            displayer.interrupt();
            super.dispose();
        }

        private void loadGtkImages() {
            if (!gtkImagesLoaded) {
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
                //check whether the gtk version is >= 3.10 as the Icon names were
                //changed from this release
                UNIXToolkit tk = (UNIXToolkit) Toolkit.getDefaultToolkit();
                if (tk.checkGtkVersion(3, 10, 0)) {
                    errorImage = (Image) tk.getDesktopProperty(
                            "gtk.icon.dialog-error.6.rtl");
                    warnImage = (Image) tk.getDesktopProperty(
                            "gtk.icon.dialog-warning.6.rtl");
                    infoImage = (Image) tk.getDesktopProperty(
                            "gtk.icon.dialog-information.6.rtl");
                } else {
                    errorImage = (Image) tk.getDesktopProperty(
                            "gtk.icon.gtk-dialog-error.6.rtl");
                    warnImage = (Image) tk.getDesktopProperty(
                            "gtk.icon.gtk-dialog-warning.6.rtl");
                    infoImage = (Image) tk.getDesktopProperty(
                            "gtk.icon.gtk-dialog-info.6.rtl");
                }
435 436 437 438 439 440 441 442 443 444 445 446
                gtkImagesLoaded = true;
            }
        }

        private class ActionPerformer extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                // hide the balloon by any click
                hide();
                if (e.getButton() == MouseEvent.BUTTON1) {
                    ActionEvent aev = new ActionEvent(target, ActionEvent.ACTION_PERFORMED,
                                                      liveArguments.getActionCommand(),
                                                      e.getWhen(), e.getModifiers());
447
                    XToolkit.postEvent(XToolkit.targetToAppContext(aev.getSource()), aev);
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 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
                }
            }
        }

        private class Displayer extends Thread {
            final int MAX_CONCURRENT_MSGS = 10;

            ArrayBlockingQueue<Message> messageQueue = new ArrayBlockingQueue<Message>(MAX_CONCURRENT_MSGS);
            boolean isDisplayed;

            Displayer() {
                setDaemon(true);
            }

            public void run() {
                while (true) {
                    Message msg = null;
                    try {
                        msg = (Message)messageQueue.take();
                    } catch (InterruptedException e) {
                        return;
                    }

                    /*
                     * Wait till the previous message is displayed if any
                     */
                    XToolkit.awtLock();
                    try {
                        while (isDisplayed) {
                            try {
                                XToolkit.awtLockWait();
                            } catch (InterruptedException e) {
                                return;
                            }
                        }
                        isDisplayed = true;
                    } finally {
                        XToolkit.awtUnlock();
                    }
                    _display(msg.caption, msg.text, msg.messageType);
                }
            }

            void display(String caption, String text, String messageType) {
                messageQueue.offer(new Message(caption, text, messageType));
            }
        }

        private static class Message {
            String caption, text, messageType;

            Message(String caption, String text, String messageType) {
                this.caption = caption;
                this.text = text;
                this.messageType = messageType;
            }
        }
    }
}