001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.BasicStroke;
007import java.awt.BorderLayout;
008import java.awt.Color;
009import java.awt.Component;
010import java.awt.Container;
011import java.awt.Dimension;
012import java.awt.Graphics;
013import java.awt.Graphics2D;
014import java.awt.Insets;
015import java.awt.Point;
016import java.awt.Rectangle;
017import java.awt.RenderingHints;
018import java.awt.Shape;
019import java.awt.event.ActionEvent;
020import java.awt.event.ActionListener;
021import java.awt.event.ComponentAdapter;
022import java.awt.event.ComponentEvent;
023import java.awt.event.ComponentListener;
024import java.awt.event.HierarchyEvent;
025import java.awt.event.HierarchyListener;
026import java.awt.event.MouseAdapter;
027import java.awt.event.MouseEvent;
028import java.awt.event.MouseListener;
029import java.awt.geom.RoundRectangle2D;
030import java.util.Deque;
031import java.util.LinkedList;
032import java.util.Objects;
033
034import javax.swing.AbstractAction;
035import javax.swing.GroupLayout;
036import javax.swing.JButton;
037import javax.swing.JFrame;
038import javax.swing.JLabel;
039import javax.swing.JLayeredPane;
040import javax.swing.JPanel;
041import javax.swing.JToolBar;
042import javax.swing.SwingUtilities;
043import javax.swing.Timer;
044
045import org.openstreetmap.josm.data.preferences.IntegerProperty;
046import org.openstreetmap.josm.gui.help.HelpBrowser;
047import org.openstreetmap.josm.gui.help.HelpUtil;
048import org.openstreetmap.josm.gui.util.GuiHelper;
049import org.openstreetmap.josm.tools.GuiSizesHelper;
050import org.openstreetmap.josm.tools.ImageProvider;
051import org.openstreetmap.josm.tools.Logging;
052
053/**
054 * Manages {@link Notification}s, i.e. displays them on screen.
055 * <p>
056 * Don't use this class directly, but use {@link Notification#show()}.
057 * <p>
058 * If multiple messages are sent in a short period of time, they are put in
059 * a queue and displayed one after the other.
060 * <p>
061 * The user can stop the timer (freeze the message) by moving the mouse cursor
062 * above the panel. As a visual cue, the background color changes from
063 * semi-transparent to opaque while the timer is frozen.
064 */
065class NotificationManager {
066
067    private final Timer hideTimer; // started when message is shown, responsible for hiding the message
068    private final Timer pauseTimer; // makes sure, there is a small pause between two consecutive messages
069    private final Timer unfreezeDelayTimer; // tiny delay before resuming the timer when mouse cursor is moved off the panel
070    private boolean running;
071
072    private Notification currentNotification;
073    private NotificationPanel currentNotificationPanel;
074
075    /** the component {@link #currentNotificationPanel} is aligned to, {@code null} while nothing is displayed */
076    private Component notificationAnchor;
077
078    /** keeps the displayed notification aligned when the layout around it changes, e.g. in fullscreen mode */
079    private final ComponentListener anchorListener = new ComponentAdapter() {
080        @Override
081        public void componentResized(ComponentEvent e) {
082            updateNotificationPosition();
083        }
084
085        @Override
086        public void componentMoved(ComponentEvent e) {
087            updateNotificationPosition();
088        }
089    };
090
091    /** realigns the displayed notification when toggling fullscreen, before the window is painted with it at its old position */
092    private final HierarchyListener showingListener = e -> {
093        if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && e.getComponent().isShowing()) {
094            updateNotificationPosition();
095        }
096    };
097
098    /** brings the displayed notification over to the map view as soon as one is opened, and back when it is closed */
099    private final MapFrameListener mapFrameListener = (oldFrame, newFrame) -> updateNotificationPosition();
100
101    private final Deque<Notification> queue;
102
103    private static final IntegerProperty pauseTime = new IntegerProperty("notification-default-pause-time-ms", 300); // milliseconds
104
105    private long displayTimeStart;
106    private long elapsedTime;
107
108    private static NotificationManager instance;
109
110    /** margin between the notification panel and the borders of its anchor, in unscaled pixels */
111    private static final int MARGIN = 10;
112
113    private static final Color PANEL_SEMITRANSPARENT = new Color(224, 236, 249, 230);
114    private static final Color PANEL_OPAQUE = new Color(224, 236, 249);
115
116    NotificationManager() {
117        queue = new LinkedList<>();
118        hideTimer = new Timer(Notification.TIME_DEFAULT, e -> this.stopHideTimer(null));
119        hideTimer.setRepeats(false);
120        pauseTimer = new Timer(pauseTime.get(), new PauseFinishedEvent());
121        pauseTimer.setRepeats(false);
122        unfreezeDelayTimer = new Timer(10, new UnfreezeEvent());
123        unfreezeDelayTimer.setRepeats(false);
124    }
125
126    /**
127     * Show the given notification (unless a duplicate notification is being shown at the moment or is already queued)
128     * @param note The note to show.
129     * @see Notification#show()
130     */
131    void showNotification(Notification note) {
132        synchronized (queue) {
133            if (Objects.equals(note, currentNotification) || queue.contains(note)) {
134                Logging.debug("Dropping duplicate notification {0}", note);
135                return;
136            }
137            queue.add(note);
138        }
139        // must not run while the monitor is held, see processQueue()
140        processQueue();
141    }
142
143    /**
144     * Show the given notification by replacing the given queued/displaying notification
145     * @param oldNotification the notification to replace
146     * @param newNotification the notification to show
147     */
148    void replaceExistingNotification(Notification oldNotification, Notification newNotification) {
149        boolean isDisplayed;
150        synchronized (queue) {
151            isDisplayed = Objects.equals(oldNotification, currentNotification);
152            if (!isDisplayed) {
153                queue.remove(oldNotification);
154            }
155        }
156        if (isDisplayed) {
157            // must not run while the monitor is held either, it waits for the EDT as well
158            stopHideTimer(oldNotification);
159        }
160        showNotification(newNotification);
161    }
162
163    /**
164     * Displays the next queued notification, unless one is being displayed already or the queue is empty.
165     * <p>
166     * Only the state transition is guarded by the monitor of {@link #queue}. The rest waits for the EDT, and the EDT
167     * takes that very monitor as well, so holding it any longer would deadlock every caller
168     * that is not the EDT itself.
169     */
170    private void processQueue() {
171        synchronized (queue) {
172            if (running) return;
173
174            currentNotification = queue.poll();
175            if (currentNotification == null) return;
176
177            // claim the slot before releasing the monitor, so that no concurrent call displays a second notification
178            running = true;
179        }
180
181        GuiHelper.runInEDTAndWait(() -> {
182            currentNotificationPanel = new NotificationPanel(currentNotification, new FreezeMouseListener(), e -> this.stopHideTimer(null));
183            currentNotificationPanel.addHierarchyListener(showingListener);
184            currentNotificationPanel.validate();
185
186            currentNotificationPanel.setSize(currentNotificationPanel.getPreferredSize());
187
188            JFrame parentWindow = MainApplication.getMainFrame();
189            if (parentWindow != null) {
190                parentWindow.getLayeredPane().add(currentNotificationPanel, JLayeredPane.POPUP_LAYER, 0);
191                MainApplication.addMapFrameListener(mapFrameListener);
192                updateNotificationPosition();
193            }
194            currentNotificationPanel.setVisible(true);
195        });
196
197        elapsedTime = 0;
198        startHideTimer();
199    }
200
201    /**
202     * Aligns the displayed notification to the map view, or to the content pane while no map view is displayed,
203     * and keeps listening to that anchor for as long as the notification is displayed.
204     */
205    private void updateNotificationPosition() {
206        JFrame parentWindow = MainApplication.getMainFrame();
207        if (currentNotificationPanel == null || parentWindow == null) {
208            return;
209        }
210        Component anchor = MainApplication.isDisplayingMapView() ? MainApplication.getMap().mapView : parentWindow.getContentPane();
211        if (anchor != notificationAnchor) {
212            // the map view is created and destroyed along with the layers, so the anchor may change while displaying
213            detachAnchorListener();
214            notificationAnchor = anchor;
215            anchor.addComponentListener(anchorListener);
216        }
217        // a map view that has just been created is not laid out yet; its first resize event brings the notification over
218        Component target = anchor.getHeight() > 0 ? anchor : parentWindow.getContentPane();
219        currentNotificationPanel.setLocation(getNotificationPosition(target, parentWindow.getLayeredPane(),
220                currentNotificationPanel.getSize(), GuiSizesHelper.getSizeDpiAdjusted(MARGIN)));
221    }
222
223    /**
224     * Stops listening to the anchor of the notification that is no longer displayed.
225     */
226    private void detachAnchorListener() {
227        if (notificationAnchor != null) {
228            notificationAnchor.removeComponentListener(anchorListener);
229            notificationAnchor = null;
230        }
231    }
232
233    /**
234     * Computes the position of a notification panel in the coordinate system of {@code container}, which unlike
235     * the one of the main window does not depend on the window decorations, i.e. on fullscreen mode.
236     * <p>
237     * The panel is aligned to the bottom left corner of {@code anchor}, or to its top left corner if it is taller,
238     * so that the beginning of a long message stays readable.
239     *
240     * @param anchor the component the notification is aligned to, e.g. the map view
241     * @param container the container the notification panel is added to
242     * @param size the size of the notification panel
243     * @param margin the margin to keep between the notification panel and the borders of {@code anchor}
244     * @return the location of the upper left corner of the notification panel
245     */
246    static Point getNotificationPosition(Component anchor, Container container, Dimension size, int margin) {
247        Rectangle bounds = SwingUtilities.convertRectangle(anchor.getParent(), anchor.getBounds(), container);
248        int y = Math.max(bounds.y + margin, bounds.y + bounds.height - size.height - margin);
249        return new Point(bounds.x + margin, y);
250    }
251
252    private void startHideTimer() {
253        int remaining = (int) (currentNotification.getDuration() - elapsedTime);
254        if (remaining < 300) {
255            remaining = 300;
256        }
257        displayTimeStart = System.currentTimeMillis();
258        hideTimer.setInitialDelay(remaining);
259        hideTimer.restart();
260    }
261
262    /**
263     * Hides the displayed notification and starts the pause before the next one.
264     *
265     * @param expected the notification to hide, or {@code null} for whichever is displayed. Nothing happens if
266     *                 another notification is displayed by now.
267     */
268    private void stopHideTimer(Notification expected) {
269        // may be reached from any thread through replaceExistingNotification()
270        GuiHelper.runInEDTAndWait(() -> {
271            if (currentNotificationPanel == null || (expected != null && !Objects.equals(expected, currentNotification))) {
272                return;
273            }
274            hideTimer.stop();
275            detachAnchorListener();
276            MainApplication.removeMapFrameListener(mapFrameListener);
277            currentNotificationPanel.setVisible(false);
278            JFrame parent = MainApplication.getMainFrame();
279            if (parent != null) {
280                parent.getLayeredPane().remove(currentNotificationPanel);
281            }
282            currentNotificationPanel = null;
283            synchronized (queue) {
284                // forget it, or an identical notification shown during the pause is dropped as a duplicate
285                currentNotification = null;
286            }
287            pauseTimer.restart();
288        });
289    }
290
291    private final class PauseFinishedEvent implements ActionListener {
292
293        @Override
294        public void actionPerformed(ActionEvent e) {
295            synchronized (queue) {
296                running = false;
297            }
298            processQueue();
299        }
300    }
301
302    private final class UnfreezeEvent implements ActionListener {
303
304        @Override
305        public void actionPerformed(ActionEvent e) {
306            // AWT still delivers the mouse exit event of a panel that has just been removed
307            if (currentNotificationPanel != null) {
308                currentNotificationPanel.setNotificationBackground(PANEL_SEMITRANSPARENT);
309                currentNotificationPanel.repaint();
310                startHideTimer();
311            }
312        }
313    }
314
315    private static class NotificationPanel extends JPanel {
316
317        static final class ShowNoteHelpAction extends AbstractAction {
318            private final Notification note;
319
320            ShowNoteHelpAction(Notification note) {
321                super(tr("Help"));
322                putValue(SHORT_DESCRIPTION, tr("Show help information"));
323                new ImageProvider("help").getResource().attachImageIcon(this, true);
324                this.note = note;
325            }
326
327            @Override
328            public void actionPerformed(ActionEvent e) {
329                SwingUtilities.invokeLater(() -> HelpBrowser.setUrlForHelpTopic(note.getHelpTopic()));
330            }
331        }
332
333        private JPanel innerPanel;
334
335        NotificationPanel(Notification note, MouseListener freeze, ActionListener hideListener) {
336            setVisible(false);
337            build(note, freeze, hideListener);
338        }
339
340        public void setNotificationBackground(Color c) {
341            innerPanel.setBackground(c);
342        }
343
344        private void build(final Notification note, MouseListener freeze, ActionListener hideListener) {
345            // the default FlowLayout would add gaps around the visible notification
346            setLayout(new BorderLayout());
347            JButton btnClose = new JButton();
348            btnClose.addActionListener(hideListener);
349            btnClose.setIcon(ImageProvider.get("misc", "grey_x"));
350            btnClose.setPreferredSize(GuiSizesHelper.getDimensionDpiAdjusted(new Dimension(50, 50)));
351            btnClose.setMargin(new Insets(0, 0, 1, 1));
352            btnClose.setContentAreaFilled(false);
353            // put it in JToolBar to get a better appearance
354            JToolBar tbClose = new JToolBar();
355            tbClose.setFloatable(false);
356            tbClose.setBorderPainted(false);
357            tbClose.setOpaque(false);
358            tbClose.add(btnClose);
359
360            JToolBar tbHelp = null;
361            if (note.getHelpTopic() != null) {
362                JButton btnHelp = new JButton(new ShowNoteHelpAction(note));
363                HelpUtil.setHelpContext(btnHelp, note.getHelpTopic());
364                btnHelp.setOpaque(false);
365                tbHelp = new JToolBar();
366                tbHelp.setFloatable(false);
367                tbHelp.setBorderPainted(false);
368                tbHelp.setOpaque(false);
369                tbHelp.add(btnHelp);
370            }
371
372            setOpaque(false);
373            innerPanel = new RoundedPanel();
374            innerPanel.setBackground(PANEL_SEMITRANSPARENT);
375            innerPanel.setForeground(Color.BLACK);
376
377            GroupLayout layout = new GroupLayout(innerPanel);
378            innerPanel.setLayout(layout);
379            layout.setAutoCreateGaps(true);
380            layout.setAutoCreateContainerGaps(true);
381
382            add(innerPanel, BorderLayout.CENTER);
383
384            JLabel icon = null;
385            if (note.getIcon() != null) {
386                icon = new JLabel(note.getIcon());
387            }
388            Component content = note.getContent();
389            GroupLayout.SequentialGroup hgroup = layout.createSequentialGroup();
390            if (icon != null) {
391                hgroup.addComponent(icon);
392            }
393            if (tbHelp != null) {
394                hgroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
395                        .addComponent(content)
396                        .addComponent(tbHelp)
397                );
398            } else {
399                hgroup.addComponent(content);
400            }
401            hgroup.addComponent(tbClose);
402            GroupLayout.ParallelGroup vgroup = layout.createParallelGroup();
403            if (icon != null) {
404                vgroup.addComponent(icon);
405            }
406            vgroup.addComponent(content);
407            vgroup.addComponent(tbClose);
408            layout.setHorizontalGroup(hgroup);
409
410            if (tbHelp != null) {
411                layout.setVerticalGroup(layout.createSequentialGroup()
412                        .addGroup(vgroup)
413                        .addComponent(tbHelp)
414                );
415            } else {
416                layout.setVerticalGroup(vgroup);
417            }
418
419            /*
420             * The timer stops when the mouse cursor is above the panel.
421             *
422             * This is not straightforward, because the JPanel will get a
423             * mouseExited event when the cursor moves on top of the JButton
424             * inside the panel.
425             *
426             * The current hacky solution is to register the freeze MouseListener
427             * not only to the panel, but to all the components inside the panel.
428             *
429             * Moving the mouse cursor from one component to the next would
430             * cause some flickering (timer is started and stopped for a fraction
431             * of a second, background color is switched twice), so there is
432             * a tiny delay before the timer really resumes.
433             */
434            addMouseListenerToAllChildComponents(this, freeze);
435        }
436
437        private static void addMouseListenerToAllChildComponents(Component comp, MouseListener listener) {
438            comp.addMouseListener(listener);
439            if (comp instanceof Container) {
440                for (Component c: ((Container) comp).getComponents()) {
441                    addMouseListenerToAllChildComponents(c, listener);
442                }
443            }
444        }
445    }
446
447    class FreezeMouseListener extends MouseAdapter {
448        @Override
449        public void mouseEntered(MouseEvent e) {
450            if (unfreezeDelayTimer.isRunning()) {
451                unfreezeDelayTimer.stop();
452            } else if (currentNotificationPanel != null) {
453                // AWT still delivers events for a panel that has just been removed
454                hideTimer.stop();
455                elapsedTime += System.currentTimeMillis() - displayTimeStart;
456                currentNotificationPanel.setNotificationBackground(PANEL_OPAQUE);
457                currentNotificationPanel.repaint();
458            }
459        }
460
461        @Override
462        public void mouseExited(MouseEvent e) {
463            unfreezeDelayTimer.restart();
464        }
465    }
466
467    /**
468     * A panel with rounded edges and line border.
469     */
470    public static class RoundedPanel extends JPanel {
471
472        RoundedPanel() {
473            super();
474            setOpaque(false);
475        }
476
477        @Override
478        protected void paintComponent(Graphics graphics) {
479            // paint on a copy, so that neither the antialiasing hint nor the stroke leak into the given context
480            Graphics2D g = (Graphics2D) graphics.create();
481            try {
482                g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
483                g.setColor(getBackground());
484                float lineWidth = 1.4f;
485                // the outline goes on the content box, not around the empty border
486                Insets insets = getInsets();
487                Shape rect = new RoundRectangle2D.Double(
488                        insets.left + lineWidth/2d,
489                        insets.top + lineWidth/2d,
490                        getWidth() - insets.left - insets.right - lineWidth,
491                        getHeight() - insets.top - insets.bottom - lineWidth,
492                        20, 20);
493
494                g.fill(rect);
495                g.setColor(getForeground());
496                g.setStroke(new BasicStroke(lineWidth));
497                g.draw(rect);
498            } finally {
499                g.dispose();
500            }
501            super.paintComponent(graphics);
502        }
503    }
504
505    public static synchronized NotificationManager getInstance() {
506        if (instance == null) {
507            instance = new NotificationManager();
508        }
509        return instance;
510    }
511}