source: josm/trunk/src/org/openstreetmap/josm/gui/NotificationManager.java@ 17299

Last change on this file since 17299 was 16913, checked in by simon04, 4 years ago

fix #19698 - Refactoring: make private fields final

  • Property svn:eol-style set to native
File size: 13.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.BasicStroke;
7import java.awt.Color;
8import java.awt.Component;
9import java.awt.Container;
10import java.awt.Dimension;
11import java.awt.Graphics;
12import java.awt.Graphics2D;
13import java.awt.Insets;
14import java.awt.Point;
15import java.awt.RenderingHints;
16import java.awt.Shape;
17import java.awt.event.ActionEvent;
18import java.awt.event.ActionListener;
19import java.awt.event.MouseAdapter;
20import java.awt.event.MouseEvent;
21import java.awt.event.MouseListener;
22import java.awt.geom.RoundRectangle2D;
23import java.util.Deque;
24import java.util.LinkedList;
25import java.util.Objects;
26
27import javax.swing.AbstractAction;
28import javax.swing.BorderFactory;
29import javax.swing.GroupLayout;
30import javax.swing.JButton;
31import javax.swing.JFrame;
32import javax.swing.JLabel;
33import javax.swing.JLayeredPane;
34import javax.swing.JPanel;
35import javax.swing.JToolBar;
36import javax.swing.SwingUtilities;
37import javax.swing.Timer;
38
39import org.openstreetmap.josm.data.preferences.IntegerProperty;
40import org.openstreetmap.josm.gui.help.HelpBrowser;
41import org.openstreetmap.josm.gui.help.HelpUtil;
42import org.openstreetmap.josm.gui.util.GuiHelper;
43import org.openstreetmap.josm.tools.ImageProvider;
44import org.openstreetmap.josm.tools.Logging;
45
46/**
47 * Manages {@link Notification}s, i.e. displays them on screen.
48 *
49 * Don't use this class directly, but use {@link Notification#show()}.
50 *
51 * If multiple messages are sent in a short period of time, they are put in
52 * a queue and displayed one after the other.
53 *
54 * The user can stop the timer (freeze the message) by moving the mouse cursor
55 * above the panel. As a visual cue, the background color changes from
56 * semi-transparent to opaque while the timer is frozen.
57 */
58class NotificationManager {
59
60 private final Timer hideTimer; // started when message is shown, responsible for hiding the message
61 private final Timer pauseTimer; // makes sure, there is a small pause between two consecutive messages
62 private final Timer unfreezeDelayTimer; // tiny delay before resuming the timer when mouse cursor is moved off the panel
63 private boolean running;
64
65 private Notification currentNotification;
66 private NotificationPanel currentNotificationPanel;
67 private final Deque<Notification> queue;
68
69 private static final IntegerProperty pauseTime = new IntegerProperty("notification-default-pause-time-ms", 300); // milliseconds
70
71 private long displayTimeStart;
72 private long elapsedTime;
73
74 private static NotificationManager instance;
75
76 private static final Color PANEL_SEMITRANSPARENT = new Color(224, 236, 249, 230);
77 private static final Color PANEL_OPAQUE = new Color(224, 236, 249);
78
79 NotificationManager() {
80 queue = new LinkedList<>();
81 hideTimer = new Timer(Notification.TIME_DEFAULT, e -> this.stopHideTimer());
82 hideTimer.setRepeats(false);
83 pauseTimer = new Timer(pauseTime.get(), new PauseFinishedEvent());
84 pauseTimer.setRepeats(false);
85 unfreezeDelayTimer = new Timer(10, new UnfreezeEvent());
86 unfreezeDelayTimer.setRepeats(false);
87 }
88
89 /**
90 * Show the given notification (unless a duplicate notification is being shown at the moment or at the end of the queue)
91 * @param note The note to show.
92 * @see Notification#show()
93 */
94 public void showNotification(Notification note) {
95 synchronized (queue) {
96 if (Objects.equals(note, currentNotification) || Objects.equals(note, queue.peekLast())) {
97 Logging.debug("Dropping duplicate notification {0}", note);
98 return;
99 }
100 queue.add(note);
101 processQueue();
102 }
103 }
104
105 private void processQueue() {
106 if (running) return;
107
108 currentNotification = queue.poll();
109 if (currentNotification == null) return;
110
111 GuiHelper.runInEDTAndWait(() -> {
112 currentNotificationPanel = new NotificationPanel(currentNotification, new FreezeMouseListener(), e -> this.stopHideTimer());
113 currentNotificationPanel.validate();
114
115 int margin = 5;
116 JFrame parentWindow = MainApplication.getMainFrame();
117 Dimension size = currentNotificationPanel.getPreferredSize();
118 if (parentWindow != null) {
119 int x;
120 int y;
121 MapFrame map = MainApplication.getMap();
122 if (MainApplication.isDisplayingMapView() && map.mapView.getHeight() > 0) {
123 MapView mv = map.mapView;
124 Point mapViewPos = SwingUtilities.convertPoint(mv.getParent(), mv.getX(), mv.getY(), MainApplication.getMainFrame());
125 x = mapViewPos.x + margin;
126 y = mapViewPos.y + mv.getHeight() - map.statusLine.getHeight() - size.height - margin;
127 } else {
128 x = margin;
129 y = parentWindow.getHeight() - MainApplication.getToolbar().control.getSize().height - size.height - margin;
130 }
131 parentWindow.getLayeredPane().add(currentNotificationPanel, JLayeredPane.POPUP_LAYER, 0);
132
133 currentNotificationPanel.setLocation(x, y);
134 }
135 currentNotificationPanel.setSize(size);
136 currentNotificationPanel.setVisible(true);
137 });
138
139 running = true;
140 elapsedTime = 0;
141
142 startHideTimer();
143 }
144
145 private void startHideTimer() {
146 int remaining = (int) (currentNotification.getDuration() - elapsedTime);
147 if (remaining < 300) {
148 remaining = 300;
149 }
150 displayTimeStart = System.currentTimeMillis();
151 hideTimer.setInitialDelay(remaining);
152 hideTimer.restart();
153 }
154
155 private void stopHideTimer() {
156 hideTimer.stop();
157 if (currentNotificationPanel != null) {
158 currentNotificationPanel.setVisible(false);
159 JFrame parent = MainApplication.getMainFrame();
160 if (parent != null) {
161 parent.getLayeredPane().remove(currentNotificationPanel);
162 }
163 currentNotificationPanel = null;
164 }
165 pauseTimer.restart();
166 }
167
168 private class PauseFinishedEvent implements ActionListener {
169
170 @Override
171 public void actionPerformed(ActionEvent e) {
172 synchronized (queue) {
173 running = false;
174 processQueue();
175 }
176 }
177 }
178
179 private class UnfreezeEvent implements ActionListener {
180
181 @Override
182 public void actionPerformed(ActionEvent e) {
183 if (currentNotificationPanel != null) {
184 currentNotificationPanel.setNotificationBackground(PANEL_SEMITRANSPARENT);
185 currentNotificationPanel.repaint();
186 }
187 startHideTimer();
188 }
189 }
190
191 private static class NotificationPanel extends JPanel {
192
193 static final class ShowNoteHelpAction extends AbstractAction {
194 private final Notification note;
195
196 ShowNoteHelpAction(Notification note) {
197 this.note = note;
198 }
199
200 @Override
201 public void actionPerformed(ActionEvent e) {
202 SwingUtilities.invokeLater(() -> HelpBrowser.setUrlForHelpTopic(note.getHelpTopic()));
203 }
204 }
205
206 private JPanel innerPanel;
207
208 NotificationPanel(Notification note, MouseListener freeze, ActionListener hideListener) {
209 setVisible(false);
210 build(note, freeze, hideListener);
211 }
212
213 public void setNotificationBackground(Color c) {
214 innerPanel.setBackground(c);
215 }
216
217 private void build(final Notification note, MouseListener freeze, ActionListener hideListener) {
218 JButton btnClose = new JButton();
219 btnClose.addActionListener(hideListener);
220 btnClose.setIcon(ImageProvider.get("misc", "grey_x"));
221 btnClose.setPreferredSize(new Dimension(50, 50));
222 btnClose.setMargin(new Insets(0, 0, 1, 1));
223 btnClose.setContentAreaFilled(false);
224 // put it in JToolBar to get a better appearance
225 JToolBar tbClose = new JToolBar();
226 tbClose.setFloatable(false);
227 tbClose.setBorderPainted(false);
228 tbClose.setOpaque(false);
229 tbClose.add(btnClose);
230
231 JToolBar tbHelp = null;
232 if (note.getHelpTopic() != null) {
233 JButton btnHelp = new JButton(tr("Help"));
234 btnHelp.setIcon(ImageProvider.get("help"));
235 btnHelp.setToolTipText(tr("Show help information"));
236 HelpUtil.setHelpContext(btnHelp, note.getHelpTopic());
237 btnHelp.addActionListener(new ShowNoteHelpAction(note));
238 btnHelp.setOpaque(false);
239 tbHelp = new JToolBar();
240 tbHelp.setFloatable(false);
241 tbHelp.setBorderPainted(false);
242 tbHelp.setOpaque(false);
243 tbHelp.add(btnHelp);
244 }
245
246 setOpaque(false);
247 innerPanel = new RoundedPanel();
248 innerPanel.setBackground(PANEL_SEMITRANSPARENT);
249 innerPanel.setForeground(Color.BLACK);
250
251 GroupLayout layout = new GroupLayout(innerPanel);
252 innerPanel.setLayout(layout);
253 layout.setAutoCreateGaps(true);
254 layout.setAutoCreateContainerGaps(true);
255
256 innerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
257 add(innerPanel);
258
259 JLabel icon = null;
260 if (note.getIcon() != null) {
261 icon = new JLabel(note.getIcon());
262 }
263 Component content = note.getContent();
264 GroupLayout.SequentialGroup hgroup = layout.createSequentialGroup();
265 if (icon != null) {
266 hgroup.addComponent(icon);
267 }
268 if (tbHelp != null) {
269 hgroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
270 .addComponent(content)
271 .addComponent(tbHelp)
272 );
273 } else {
274 hgroup.addComponent(content);
275 }
276 hgroup.addComponent(tbClose);
277 GroupLayout.ParallelGroup vgroup = layout.createParallelGroup();
278 if (icon != null) {
279 vgroup.addComponent(icon);
280 }
281 vgroup.addComponent(content);
282 vgroup.addComponent(tbClose);
283 layout.setHorizontalGroup(hgroup);
284
285 if (tbHelp != null) {
286 layout.setVerticalGroup(layout.createSequentialGroup()
287 .addGroup(vgroup)
288 .addComponent(tbHelp)
289 );
290 } else {
291 layout.setVerticalGroup(vgroup);
292 }
293
294 /*
295 * The timer stops when the mouse cursor is above the panel.
296 *
297 * This is not straightforward, because the JPanel will get a
298 * mouseExited event when the cursor moves on top of the JButton
299 * inside the panel.
300 *
301 * The current hacky solution is to register the freeze MouseListener
302 * not only to the panel, but to all the components inside the panel.
303 *
304 * Moving the mouse cursor from one component to the next would
305 * cause some flickering (timer is started and stopped for a fraction
306 * of a second, background color is switched twice), so there is
307 * a tiny delay before the timer really resumes.
308 */
309 addMouseListenerToAllChildComponents(this, freeze);
310 }
311
312 private static void addMouseListenerToAllChildComponents(Component comp, MouseListener listener) {
313 comp.addMouseListener(listener);
314 if (comp instanceof Container) {
315 for (Component c: ((Container) comp).getComponents()) {
316 addMouseListenerToAllChildComponents(c, listener);
317 }
318 }
319 }
320 }
321
322 class FreezeMouseListener extends MouseAdapter {
323 @Override
324 public void mouseEntered(MouseEvent e) {
325 if (unfreezeDelayTimer.isRunning()) {
326 unfreezeDelayTimer.stop();
327 } else {
328 hideTimer.stop();
329 elapsedTime += System.currentTimeMillis() - displayTimeStart;
330 currentNotificationPanel.setNotificationBackground(PANEL_OPAQUE);
331 currentNotificationPanel.repaint();
332 }
333 }
334
335 @Override
336 public void mouseExited(MouseEvent e) {
337 unfreezeDelayTimer.restart();
338 }
339 }
340
341 /**
342 * A panel with rounded edges and line border.
343 */
344 public static class RoundedPanel extends JPanel {
345
346 RoundedPanel() {
347 super();
348 setOpaque(false);
349 }
350
351 @Override
352 protected void paintComponent(Graphics graphics) {
353 Graphics2D g = (Graphics2D) graphics;
354 g.setRenderingHint(
355 RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
356 g.setColor(getBackground());
357 float lineWidth = 1.4f;
358 Shape rect = new RoundRectangle2D.Double(
359 lineWidth/2d + getInsets().left,
360 lineWidth/2d + getInsets().top,
361 getWidth() - lineWidth/2d - getInsets().left - getInsets().right,
362 getHeight() - lineWidth/2d - getInsets().top - getInsets().bottom,
363 20, 20);
364
365 g.fill(rect);
366 g.setColor(getForeground());
367 g.setStroke(new BasicStroke(lineWidth));
368 g.draw(rect);
369 super.paintComponent(graphics);
370 }
371 }
372
373 public static synchronized NotificationManager getInstance() {
374 if (instance == null) {
375 instance = new NotificationManager();
376 }
377 return instance;
378 }
379}
Note: See TracBrowser for help on using the repository browser.