001/**
002 * MenuScroller.java    1.5.0 04/02/12
003 * License: use / modify without restrictions (see https://tips4java.wordpress.com/about/)
004 * Heavily modified for JOSM needs => drop unused features and replace static scrollcount approach by dynamic behaviour
005 */
006package org.openstreetmap.josm.gui;
007
008import java.awt.Color;
009import java.awt.Component;
010import java.awt.Dimension;
011import java.awt.Graphics;
012import java.awt.event.ActionEvent;
013import java.awt.event.ActionListener;
014import java.awt.event.MouseWheelEvent;
015import java.awt.event.MouseWheelListener;
016import java.util.Arrays;
017
018import javax.swing.Icon;
019import javax.swing.JMenu;
020import javax.swing.JMenuItem;
021import javax.swing.JPopupMenu;
022import javax.swing.JSeparator;
023import javax.swing.Timer;
024import javax.swing.event.ChangeEvent;
025import javax.swing.event.ChangeListener;
026import javax.swing.event.PopupMenuEvent;
027import javax.swing.event.PopupMenuListener;
028
029import org.openstreetmap.josm.gui.util.WindowGeometry;
030import org.openstreetmap.josm.tools.Logging;
031
032/**
033 * A class that provides scrolling capabilities to a long menu dropdown or
034 * popup menu. A number of items can optionally be frozen at the top of the menu.
035 * <p>
036 * <b>Implementation note:</B> The default scrolling interval is 150 milliseconds.
037 * @author Darryl, https://tips4java.wordpress.com/2009/02/01/menu-scroller/
038 * @since 4593
039 */
040public class MenuScroller {
041
042    private JPopupMenu menu;
043    private Component[] menuItems;
044    private final MenuScrollItem upItem;
045    private final MenuScrollItem downItem;
046    private final MenuScrollListener menuListener = new MenuScrollListener();
047    private final MouseWheelListener mouseWheelListener = new MouseScrollListener();
048    private int topFixedCount;
049    private int firstIndex;
050
051    private static final int ARROW_ICON_HEIGHT = 10;
052
053    private int computeScrollCount(int startIndex) {
054        int result = 15;
055        if (menu != null) {
056            // Compute max height of current screen
057            int maxHeight = WindowGeometry.getMaxDimensionOnScreen(menu).height - MainApplication.getMainFrame().getInsets().top;
058
059            // Remove top fixed part height
060            if (topFixedCount > 0) {
061                for (int i = 0; i < topFixedCount; i++) {
062                    maxHeight -= menuItems[i].getPreferredSize().height;
063                }
064                maxHeight -= new JSeparator().getPreferredSize().height;
065            }
066
067            // Remove height of our two arrow items + insets
068            maxHeight -= menu.getInsets().top;
069            maxHeight -= upItem.getPreferredSize().height;
070            maxHeight -= downItem.getPreferredSize().height;
071            maxHeight -= menu.getInsets().bottom;
072
073            // Compute scroll count
074            result = 0;
075            int height = 0;
076            for (int i = startIndex; i < menuItems.length && height <= maxHeight; i++, result++) {
077                height += menuItems[i].getPreferredSize().height;
078            }
079
080            if (height > maxHeight) {
081                // Remove extra item from count
082                result--;
083            } else {
084                // Increase scroll count to take into account upper items that will be displayed
085                // after firstIndex is updated
086                for (int i = startIndex-1; i >= 0 && height <= maxHeight; i--, result++) {
087                    height += menuItems[i].getPreferredSize().height;
088                }
089                if (height > maxHeight) {
090                    result--;
091                }
092            }
093        }
094        return result;
095    }
096
097    /**
098     * Registers a menu to be scrolled with the default scrolling interval.
099     *
100     * @param menu the menu
101     * @return the MenuScroller
102     */
103    public static MenuScroller setScrollerFor(JMenu menu) {
104        return new MenuScroller(menu);
105    }
106
107    /**
108     * Registers a popup menu to be scrolled with the default scrolling interval.
109     *
110     * @param menu the popup menu
111     * @return the MenuScroller
112     */
113    public static MenuScroller setScrollerFor(JPopupMenu menu) {
114        return new MenuScroller(menu);
115    }
116
117    /**
118     * Registers a menu to be scrolled, with the specified scrolling interval.
119     *
120     * @param menu the menu
121     * @param interval the scroll interval, in milliseconds
122     * @return the MenuScroller
123     * @throws IllegalArgumentException if scrollCount or interval is 0 or negative
124     * @since 7463
125     */
126    public static MenuScroller setScrollerFor(JMenu menu, int interval) {
127        return new MenuScroller(menu, interval);
128    }
129
130    /**
131     * Registers a popup menu to be scrolled, with the specified scrolling interval.
132     *
133     * @param menu the popup menu
134     * @param interval the scroll interval, in milliseconds
135     * @return the MenuScroller
136     * @throws IllegalArgumentException if scrollCount or interval is 0 or negative
137     * @since 7463
138     */
139    public static MenuScroller setScrollerFor(JPopupMenu menu, int interval) {
140        return new MenuScroller(menu, interval);
141    }
142
143    /**
144     * Registers a menu to be scrolled, with the specified scrolling interval,
145     * and the specified numbers of items fixed at the top of the menu.
146     *
147     * @param menu the menu
148     * @param interval the scroll interval, in milliseconds
149     * @param topFixedCount the number of items to fix at the top.  May be 0.
150     * @return the MenuScroller
151     * @throws IllegalArgumentException if scrollCount or interval is 0 or
152     * negative or if topFixedCount is negative
153     * @since 7463
154     */
155    public static MenuScroller setScrollerFor(JMenu menu, int interval, int topFixedCount) {
156        return new MenuScroller(menu, interval, topFixedCount);
157    }
158
159    /**
160     * Registers a popup menu to be scrolled, with the specified scrolling interval,
161     * and the specified numbers of items fixed at the top of the popup menu.
162     *
163     * @param menu the popup menu
164     * @param interval the scroll interval, in milliseconds
165     * @param topFixedCount the number of items to fix at the top. May be 0
166     * @return the MenuScroller
167     * @throws IllegalArgumentException if scrollCount or interval is 0 or
168     * negative or if topFixedCount is negative
169     * @since 7463
170     */
171    public static MenuScroller setScrollerFor(JPopupMenu menu, int interval, int topFixedCount) {
172        return new MenuScroller(menu, interval, topFixedCount);
173    }
174
175    /**
176     * Constructs a <code>MenuScroller</code> that scrolls a menu with the
177     * default scrolling interval.
178     *
179     * @param menu the menu
180     * @throws IllegalArgumentException if scrollCount is 0 or negative
181     */
182    public MenuScroller(JMenu menu) {
183        this(menu, 150);
184    }
185
186    /**
187     * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the
188     * default scrolling interval.
189     *
190     * @param menu the popup menu
191     * @throws IllegalArgumentException if scrollCount is 0 or negative
192     */
193    public MenuScroller(JPopupMenu menu) {
194        this(menu, 150);
195    }
196
197    /**
198     * Constructs a <code>MenuScroller</code> that scrolls a menu with the
199     * specified scrolling interval.
200     *
201     * @param menu the menu
202     * @param interval the scroll interval, in milliseconds
203     * @throws IllegalArgumentException if scrollCount or interval is 0 or negative
204     * @since 7463
205     */
206    public MenuScroller(JMenu menu, int interval) {
207        this(menu, interval, 0);
208    }
209
210    /**
211     * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the
212     * specified scrolling interval.
213     *
214     * @param menu the popup menu
215     * @param interval the scroll interval, in milliseconds
216     * @throws IllegalArgumentException if scrollCount or interval is 0 or negative
217     * @since 7463
218     */
219    public MenuScroller(JPopupMenu menu, int interval) {
220        this(menu, interval, 0);
221    }
222
223    /**
224     * Constructs a <code>MenuScroller</code> that scrolls a menu with the
225     * specified scrolling interval, and the specified numbers of items fixed at
226     * the top of the menu.
227     *
228     * @param menu the menu
229     * @param interval the scroll interval, in milliseconds
230     * @param topFixedCount the number of items to fix at the top.  May be 0
231     * @throws IllegalArgumentException if scrollCount or interval is 0 or
232     * negative or if topFixedCount is negative
233     * @since 7463
234     */
235    public MenuScroller(JMenu menu, int interval, int topFixedCount) {
236        this(menu.getPopupMenu(), interval, topFixedCount);
237    }
238
239    /**
240     * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the
241     * specified scrolling interval, and the specified numbers of items fixed at
242     * the top of the popup menu.
243     *
244     * @param menu the popup menu
245     * @param interval the scroll interval, in milliseconds
246     * @param topFixedCount the number of items to fix at the top.  May be 0
247     * @throws IllegalArgumentException if scrollCount or interval is 0 or
248     * negative or if topFixedCount is negative
249     * @since 7463
250     */
251    public MenuScroller(JPopupMenu menu, int interval, int topFixedCount) {
252        if (interval <= 0) {
253            throw new IllegalArgumentException("interval must be greater than 0");
254        }
255        if (topFixedCount < 0) {
256            throw new IllegalArgumentException("topFixedCount cannot be negative");
257        }
258
259        upItem = new MenuScrollItem(MenuIcon.UP, -1, interval);
260        downItem = new MenuScrollItem(MenuIcon.DOWN, +1, interval);
261        setTopFixedCount(topFixedCount);
262
263        this.menu = menu;
264        menu.addPopupMenuListener(menuListener);
265        menu.addMouseWheelListener(mouseWheelListener);
266    }
267
268    /**
269     * Returns the number of items fixed at the top of the menu or popup menu.
270     *
271     * @return the number of items
272     */
273    public int getTopFixedCount() {
274        return topFixedCount;
275    }
276
277    /**
278     * Sets the number of items to fix at the top of the menu or popup menu.
279     *
280     * @param topFixedCount the number of items
281     */
282    public void setTopFixedCount(int topFixedCount) {
283        if (firstIndex <= topFixedCount) {
284            firstIndex = topFixedCount;
285        } else {
286            firstIndex += (topFixedCount - this.topFixedCount);
287        }
288        this.topFixedCount = topFixedCount;
289    }
290
291    /**
292     * Removes this MenuScroller from the associated menu and restores the
293     * default behavior of the menu.
294     */
295    public void dispose() {
296        if (menu != null) {
297            menu.removePopupMenuListener(menuListener);
298            menu.removeMouseWheelListener(mouseWheelListener);
299            menu.setPreferredSize(null);
300            menu = null;
301        }
302    }
303
304    private void refreshMenu() {
305        if (menuItems != null && menuItems.length > 0) {
306
307            int allItemsHeight = Arrays.stream(menuItems).mapToInt(item -> item.getPreferredSize().height).sum();
308            int allowedHeight = WindowGeometry.getMaxDimensionOnScreen(menu).height - MainApplication.getMainFrame().getInsets().top;
309            boolean mustScroll = allItemsHeight > allowedHeight;
310            if (mustScroll) {
311                firstIndex = Math.min(menuItems.length-1, Math.max(topFixedCount, firstIndex));
312                int scrollCount = computeScrollCount(firstIndex);
313                firstIndex = Math.min(menuItems.length - scrollCount, firstIndex);
314
315                upItem.setEnabled(firstIndex > topFixedCount);
316                downItem.setEnabled(firstIndex + scrollCount < menuItems.length);
317
318                menu.removeAll();
319                for (int i = 0; i < topFixedCount; i++) {
320                    menu.add(menuItems[i]);
321                }
322                if (topFixedCount > 0) {
323                    menu.addSeparator();
324                }
325
326                menu.add(upItem);
327                for (int i = firstIndex; i < scrollCount + firstIndex; i++) {
328                    menu.add(menuItems[i]);
329                }
330                menu.add(downItem);
331
332                int preferredWidth = 0;
333                for (Component item : menuItems) {
334                    preferredWidth = Math.max(preferredWidth, item.getPreferredSize().width);
335                }
336                menu.setPreferredSize(new Dimension(preferredWidth, menu.getPreferredSize().height));
337
338            } else if (!Arrays.equals(menu.getComponents(), menuItems)) {
339                // Scroll is not needed but menu is not up to date
340                menu.removeAll();
341                for (Component item : menuItems) {
342                    menu.add(item);
343                }
344            }
345
346            menu.revalidate();
347            menu.repaint();
348        }
349    }
350
351    private final class MenuScrollListener implements PopupMenuListener {
352
353        @Override
354        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
355            setMenuItems();
356        }
357
358        @Override
359        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
360            restoreMenuItems();
361        }
362
363        @Override
364        public void popupMenuCanceled(PopupMenuEvent e) {
365            restoreMenuItems();
366        }
367
368        private void setMenuItems() {
369            menuItems = menu.getComponents();
370            refreshMenu();
371        }
372
373        private void restoreMenuItems() {
374            menu.removeAll();
375            for (Component component : menuItems) {
376                menu.add(component);
377            }
378        }
379    }
380
381    private class MenuScrollTimer extends Timer {
382
383        MenuScrollTimer(final int increment, int interval) {
384            super(interval, new ActionListener() {
385
386                @Override
387                public void actionPerformed(ActionEvent e) {
388                    firstIndex += increment;
389                    refreshMenu();
390                }
391            });
392        }
393    }
394
395    private class MenuScrollItem extends JMenuItem
396            implements ChangeListener {
397
398        private final MenuScrollTimer timer;
399
400        MenuScrollItem(MenuIcon icon, int increment, int interval) {
401            setIcon(icon);
402            setDisabledIcon(icon);
403            timer = new MenuScrollTimer(increment, interval);
404            addChangeListener(this);
405        }
406
407        @Override
408        public void stateChanged(ChangeEvent e) {
409            if (isArmed() && !timer.isRunning()) {
410                timer.start();
411            }
412            if (!isArmed() && timer.isRunning()) {
413                timer.stop();
414            }
415        }
416    }
417
418    private enum MenuIcon implements Icon {
419
420        UP(9, 1, 9),
421        DOWN(1, 9, 1);
422        private static final int[] XPOINTS = {1, 5, 9};
423        @SuppressWarnings("ImmutableEnumChecker")
424        private final int[] yPoints;
425
426        MenuIcon(int... yPoints) {
427            this.yPoints = yPoints;
428        }
429
430        @Override
431        public void paintIcon(Component c, Graphics g, int x, int y) {
432            Dimension size = c.getSize();
433            Graphics g2 = g.create(size.width / 2 - 5, size.height / 2 - 5, 10, 10);
434            g2.setColor(Color.GRAY);
435            g2.drawPolygon(XPOINTS, yPoints, 3);
436            if (c.isEnabled()) {
437                g2.setColor(Color.BLACK);
438                g2.fillPolygon(XPOINTS, yPoints, 3);
439            }
440            g2.dispose();
441        }
442
443        @Override
444        public int getIconWidth() {
445            return 0;
446        }
447
448        @Override
449        public int getIconHeight() {
450            return ARROW_ICON_HEIGHT;
451        }
452    }
453
454    private final class MouseScrollListener implements MouseWheelListener {
455        @Override
456        public void mouseWheelMoved(MouseWheelEvent mwe) {
457            firstIndex += mwe.getWheelRotation();
458            refreshMenu();
459            if (Logging.isDebugEnabled()) {
460                Logging.debug("{0} consuming event {1}", getClass().getName(), mwe);
461            }
462            mwe.consume();
463        }
464    }
465}