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.BorderLayout;
007import java.awt.Component;
008import java.awt.Container;
009import java.awt.Dimension;
010import java.awt.Font;
011import java.awt.GridBagLayout;
012import java.awt.Rectangle;
013import java.awt.event.ActionEvent;
014import java.awt.event.KeyEvent;
015import java.util.ArrayList;
016import java.util.Collection;
017import java.util.HashMap;
018import java.util.List;
019import java.util.Map;
020import java.util.concurrent.CopyOnWriteArrayList;
021
022import javax.swing.AbstractAction;
023import javax.swing.AbstractButton;
024import javax.swing.Action;
025import javax.swing.BorderFactory;
026import javax.swing.BoxLayout;
027import javax.swing.ButtonGroup;
028import javax.swing.ImageIcon;
029import javax.swing.JButton;
030import javax.swing.JCheckBoxMenuItem;
031import javax.swing.JComponent;
032import javax.swing.JPanel;
033import javax.swing.JPopupMenu;
034import javax.swing.JSplitPane;
035import javax.swing.JToggleButton;
036import javax.swing.JToolBar;
037import javax.swing.KeyStroke;
038import javax.swing.border.Border;
039import javax.swing.event.PopupMenuEvent;
040import javax.swing.event.PopupMenuListener;
041import javax.swing.plaf.basic.BasicSplitPaneDivider;
042import javax.swing.plaf.basic.BasicSplitPaneUI;
043
044import org.openstreetmap.josm.actions.LassoModeAction;
045import org.openstreetmap.josm.actions.mapmode.DeleteAction;
046import org.openstreetmap.josm.actions.mapmode.DrawAction;
047import org.openstreetmap.josm.actions.mapmode.ExtrudeAction;
048import org.openstreetmap.josm.actions.mapmode.ImproveWayAccuracyAction;
049import org.openstreetmap.josm.actions.mapmode.MapMode;
050import org.openstreetmap.josm.actions.mapmode.ParallelWayAction;
051import org.openstreetmap.josm.actions.mapmode.SelectAction;
052import org.openstreetmap.josm.actions.mapmode.ZoomAction;
053import org.openstreetmap.josm.data.ViewportData;
054import org.openstreetmap.josm.data.preferences.BooleanProperty;
055import org.openstreetmap.josm.data.preferences.IntegerProperty;
056import org.openstreetmap.josm.gui.dialogs.ChangesetDialog;
057import org.openstreetmap.josm.gui.dialogs.CommandStackDialog;
058import org.openstreetmap.josm.gui.dialogs.ConflictDialog;
059import org.openstreetmap.josm.gui.dialogs.DialogsPanel;
060import org.openstreetmap.josm.gui.dialogs.FilterDialog;
061import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
062import org.openstreetmap.josm.gui.dialogs.MapPaintDialog;
063import org.openstreetmap.josm.gui.dialogs.MinimapDialog;
064import org.openstreetmap.josm.gui.dialogs.NotesDialog;
065import org.openstreetmap.josm.gui.dialogs.RelationListDialog;
066import org.openstreetmap.josm.gui.dialogs.SelectionListDialog;
067import org.openstreetmap.josm.gui.dialogs.ToggleDialog;
068import org.openstreetmap.josm.gui.dialogs.UserListDialog;
069import org.openstreetmap.josm.gui.dialogs.ValidatorDialog;
070import org.openstreetmap.josm.gui.dialogs.properties.PropertiesDialog;
071import org.openstreetmap.josm.gui.layer.Layer;
072import org.openstreetmap.josm.gui.layer.LayerManager.LayerAddEvent;
073import org.openstreetmap.josm.gui.layer.LayerManager.LayerChangeListener;
074import org.openstreetmap.josm.gui.layer.LayerManager.LayerOrderChangeEvent;
075import org.openstreetmap.josm.gui.layer.LayerManager.LayerRemoveEvent;
076import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeEvent;
077import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeListener;
078import org.openstreetmap.josm.gui.util.AdvancedKeyPressDetector;
079import org.openstreetmap.josm.spi.preferences.Config;
080import org.openstreetmap.josm.spi.preferences.PreferenceChangedListener;
081import org.openstreetmap.josm.tools.Destroyable;
082import org.openstreetmap.josm.tools.GBC;
083import org.openstreetmap.josm.tools.ImageProvider;
084import org.openstreetmap.josm.tools.Shortcut;
085
086/**
087 * One Map frame with one dataset behind. This is the container gui class whose
088 * display can be set to the different views.
089 *
090 * @author imi
091 */
092public class MapFrame extends JPanel implements Destroyable, ActiveLayerChangeListener, LayerChangeListener {
093    /**
094     * Default width of the toggle dialog area.
095     */
096    public static final int DEF_TOGGLE_DLG_WIDTH = 330;
097
098    private static final IntegerProperty TOGGLE_DIALOGS_WIDTH = new IntegerProperty("toggleDialogs.width", DEF_TOGGLE_DLG_WIDTH);
099    /**
100     * Do not require to switch modes (potlatch style workflow) for drawing/selecting map modes.
101     * @since 12347
102     */
103    public static final BooleanProperty MODELESS = new BooleanProperty("modeless", false);
104    /**
105     * The current mode, this frame operates.
106     */
107    public MapMode mapMode;
108
109    /**
110     * The view control displayed.
111     */
112    public final MapView mapView;
113
114    /**
115     * This object allows to detect key press and release events
116     */
117    public final transient AdvancedKeyPressDetector keyDetector = new AdvancedKeyPressDetector();
118
119    /**
120     * The toolbar with the action icons. To add new toggle dialog buttons,
121     * use addToggleDialog, to add a new map mode button use addMapMode.
122     */
123    private JComponent sideToolBar = new JToolBar(JToolBar.VERTICAL);
124    private final ButtonGroup toolBarActionsGroup = new ButtonGroup();
125    private final JToolBar toolBarActions = new JToolBar(JToolBar.VERTICAL);
126    private final JToolBar toolBarToggle = new JToolBar(JToolBar.VERTICAL);
127
128    private final List<ToggleDialog> allDialogs = new ArrayList<>();
129    private final List<IconToggleButton> allDialogButtons = new ArrayList<>();
130    /**
131     * All map mode buttons. Should only be read form the outside
132     */
133    public final List<IconToggleButton> allMapModeButtons = new ArrayList<>();
134
135    private final ListAllButtonsAction listAllDialogsAction = new ListAllButtonsAction(allDialogButtons);
136    private final ListAllButtonsAction listAllMapModesAction = new ListAllButtonsAction(allMapModeButtons);
137    private final JButton listAllToggleDialogsButton = new JButton(listAllDialogsAction);
138    private final JButton listAllMapModesButton = new JButton(listAllMapModesAction);
139
140    {
141        listAllDialogsAction.setButton(listAllToggleDialogsButton);
142        listAllMapModesAction.setButton(listAllMapModesButton);
143    }
144
145    // Toggle dialogs
146
147    /** Conflict dialog */
148    public final ConflictDialog conflictDialog;
149    /** Filter dialog */
150    public final FilterDialog filterDialog;
151    /** Relation list dialog */
152    public final RelationListDialog relationListDialog;
153    /** Validator dialog */
154    public final ValidatorDialog validatorDialog;
155    /** Selection list dialog */
156    public final SelectionListDialog selectionListDialog;
157    /** Properties dialog */
158    public final PropertiesDialog propertiesDialog;
159    /** Map paint dialog */
160    public final MapPaintDialog mapPaintDialog;
161    /** Notes dialog */
162    public final NotesDialog noteDialog;
163
164    // Map modes
165
166    /** Select mode */
167    public final SelectAction mapModeSelect;
168    /** Draw mode */
169    public final DrawAction mapModeDraw;
170    /** Zoom mode */
171    public final ZoomAction mapModeZoom;
172    /** Delete mode */
173    public final DeleteAction mapModeDelete;
174    /** Select Lasso mode */
175    public LassoModeAction mapModeSelectLasso;
176
177    private final transient Map<Layer, MapMode> lastMapMode = new HashMap<>();
178
179    /**
180     * The status line below the map
181     */
182    public MapStatus statusLine;
183
184    /**
185     * The split pane with the mapview (leftPanel) and toggle dialogs (dialogsPanel).
186     */
187    private final JSplitPane splitPane;
188    private final JPanel leftPanel;
189    private final DialogsPanel dialogsPanel;
190
191    /**
192     * Constructs a new {@code MapFrame}.
193     * @param viewportData the initial viewport of the map. Can be null, then
194     * the viewport is derived from the layer data.
195     * @since 11713
196     */
197    public MapFrame(ViewportData viewportData) {
198        setSize(400, 400);
199        setLayout(new BorderLayout());
200
201        mapView = new MapView(MainApplication.getLayerManager(), viewportData);
202
203        splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
204
205        leftPanel = new JPanel(new GridBagLayout());
206        leftPanel.add(mapView, GBC.std().fill());
207        splitPane.setLeftComponent(leftPanel);
208
209        dialogsPanel = new DialogsPanel(splitPane);
210        splitPane.setRightComponent(dialogsPanel);
211
212        /**
213         * All additional space goes to the mapView
214         */
215        splitPane.setResizeWeight(1.0);
216
217        /**
218         * Some beautifications.
219         */
220        splitPane.setDividerSize(5);
221        splitPane.setBorder(null);
222        splitPane.setUI(new NoBorderSplitPaneUI());
223
224        // JSplitPane supports F6 and F8 shortcuts by default, but we need them for Audio actions
225        splitPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0), new Object());
226        splitPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0), new Object());
227
228        add(splitPane, BorderLayout.CENTER);
229
230        dialogsPanel.setLayout(new BoxLayout(dialogsPanel, BoxLayout.Y_AXIS));
231        dialogsPanel.setPreferredSize(new Dimension(TOGGLE_DIALOGS_WIDTH.get(), 0));
232        dialogsPanel.setMinimumSize(new Dimension(24, 0));
233        mapView.setMinimumSize(new Dimension(10, 0));
234
235        // toolBarActions, map mode buttons
236        mapModeSelect = new SelectAction(this);
237        mapModeSelectLasso = new LassoModeAction();
238        mapModeDraw = new DrawAction();
239        mapModeZoom = new ZoomAction(this);
240        mapModeDelete = new DeleteAction();
241
242        addMapMode(new IconToggleButton(mapModeSelect));
243        addMapMode(new IconToggleButton(mapModeSelectLasso, true));
244        addMapMode(new IconToggleButton(mapModeDraw));
245        addMapMode(new IconToggleButton(mapModeZoom, true));
246        addMapMode(new IconToggleButton(mapModeDelete, true));
247        addMapMode(new IconToggleButton(new ParallelWayAction(this), true));
248        addMapMode(new IconToggleButton(new ExtrudeAction(), true));
249        addMapMode(new IconToggleButton(new ImproveWayAccuracyAction(), false));
250        toolBarActionsGroup.setSelected(allMapModeButtons.get(0).getModel(), true);
251        toolBarActions.setFloatable(false);
252
253        // toolBarToggles, toggle dialog buttons
254        LayerListDialog.createInstance(mapView.getLayerManager());
255        propertiesDialog = new PropertiesDialog();
256        selectionListDialog = new SelectionListDialog();
257        relationListDialog = new RelationListDialog();
258        conflictDialog = new ConflictDialog();
259        validatorDialog = new ValidatorDialog();
260        filterDialog = new FilterDialog();
261        mapPaintDialog = new MapPaintDialog();
262        noteDialog = new NotesDialog();
263
264        addToggleDialog(LayerListDialog.getInstance());
265        addToggleDialog(propertiesDialog);
266        addToggleDialog(selectionListDialog);
267        addToggleDialog(relationListDialog);
268        addToggleDialog(new MinimapDialog());
269        addToggleDialog(new CommandStackDialog());
270        addToggleDialog(new UserListDialog());
271        addToggleDialog(conflictDialog);
272        addToggleDialog(validatorDialog);
273        addToggleDialog(filterDialog);
274        addToggleDialog(new ChangesetDialog(), true);
275        addToggleDialog(mapPaintDialog);
276        addToggleDialog(noteDialog);
277        toolBarToggle.setFloatable(false);
278
279        // status line below the map
280        statusLine = new MapStatus(this);
281        MainApplication.getLayerManager().addLayerChangeListener(this);
282        MainApplication.getLayerManager().addActiveLayerChangeListener(this);
283
284        boolean unregisterTab = Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isPresent();
285        if (unregisterTab) {
286            for (JComponent c: allDialogButtons) {
287                c.setFocusTraversalKeysEnabled(false);
288            }
289            for (JComponent c: allMapModeButtons) {
290                c.setFocusTraversalKeysEnabled(false);
291            }
292        }
293
294        if (Config.getPref().getBoolean("debug.advanced-keypress-detector.enable", true)) {
295            keyDetector.register();
296        }
297    }
298
299    /**
300     * Enables the select tool
301     * @param onlyIfModeless Only enable if modeless mode is active
302     * @return <code>true</code> if it is selected
303     */
304    public boolean selectSelectTool(boolean onlyIfModeless) {
305        if (onlyIfModeless && !MODELESS.get())
306            return false;
307
308        return selectMapMode(mapModeSelect);
309    }
310
311    /**
312     * Enables the draw tool
313     * @param onlyIfModeless Only enable if modeless mode is active
314     * @return <code>true</code> if it is selected
315     */
316    public boolean selectDrawTool(boolean onlyIfModeless) {
317        if (onlyIfModeless && !MODELESS.get())
318            return false;
319
320        return selectMapMode(mapModeDraw);
321    }
322
323    /**
324     * Enables the zoom tool
325     * @param onlyIfModeless Only enable if modeless mode is active
326     * @return <code>true</code> if it is selected
327     */
328    public boolean selectZoomTool(boolean onlyIfModeless) {
329        if (onlyIfModeless && !MODELESS.get())
330            return false;
331
332        return selectMapMode(mapModeZoom);
333    }
334
335    /**
336     * Called as some kind of destructor when the last layer has been removed.
337     * Delegates the call to all Destroyables within this component (e.g. MapModes)
338     */
339    @Override
340    public void destroy() {
341        MainApplication.getLayerManager().removeLayerChangeListener(this);
342        MainApplication.getLayerManager().removeActiveLayerChangeListener(this);
343        dialogsPanel.destroy();
344        Config.getPref().removePreferenceChangeListener(sidetoolbarPreferencesChangedListener);
345        for (int i = 0; i < toolBarActions.getComponentCount(); ++i) {
346            if (toolBarActions.getComponent(i) instanceof Destroyable) {
347                ((Destroyable) toolBarActions.getComponent(i)).destroy();
348            }
349        }
350        toolBarActions.removeAll();
351        for (int i = 0; i < toolBarToggle.getComponentCount(); ++i) {
352            if (toolBarToggle.getComponent(i) instanceof Destroyable) {
353                ((Destroyable) toolBarToggle.getComponent(i)).destroy();
354            }
355        }
356        toolBarToggle.removeAll();
357
358        statusLine.destroy();
359        mapView.destroy();
360        keyDetector.unregister();
361
362        allDialogs.clear();
363        allDialogButtons.clear();
364        allMapModeButtons.clear();
365    }
366
367    /**
368     * Gets the action of the default (first) map mode
369     * @return That action
370     */
371    public Action getDefaultButtonAction() {
372        return ((AbstractButton) toolBarActions.getComponent(0)).getAction();
373    }
374
375    /**
376     * Open all ToggleDialogs that have their preferences property set. Close all others.
377     */
378    public void initializeDialogsPane() {
379        dialogsPanel.initialize(allDialogs);
380    }
381
382    /**
383     * Adds a new toggle dialog to the left button list. It is displayed in expert and normal mode
384     * @param dlg The dialog
385     * @return The button
386     */
387    public IconToggleButton addToggleDialog(final ToggleDialog dlg) {
388        return addToggleDialog(dlg, false);
389    }
390
391    /**
392     * Call this to add new toggle dialogs to the left button-list
393     * @param dlg The toggle dialog. It must not be in the list already.
394     * @param isExpert {@code true} if it's reserved to expert mode
395     * @return button allowing to toggle the dialog
396     */
397    public IconToggleButton addToggleDialog(final ToggleDialog dlg, boolean isExpert) {
398        final IconToggleButton button = new IconToggleButton(dlg.getToggleAction(), isExpert);
399        button.setShowHideButtonListener(dlg);
400        button.setInheritsPopupMenu(true);
401        dlg.setButton(button);
402        toolBarToggle.add(button);
403        allDialogs.add(dlg);
404        allDialogButtons.add(button);
405        button.applyButtonHiddenPreferences();
406        if (dialogsPanel.initialized) {
407            dialogsPanel.add(dlg);
408        }
409        return button;
410    }
411
412    /**
413     * Call this to remove existing toggle dialog from the left button-list
414     * @param dlg The toggle dialog. It must be already in the list.
415     * @since 10851
416     */
417    public void removeToggleDialog(final ToggleDialog dlg) {
418        final JToggleButton button = dlg.getButton();
419        if (button != null) {
420            allDialogButtons.remove(button);
421            toolBarToggle.remove(button);
422        }
423        dialogsPanel.remove(dlg);
424        allDialogs.remove(dlg);
425    }
426
427    /**
428     * Adds a new map mode button
429     * @param b The map mode button with a {@link MapMode} action.
430     */
431    public void addMapMode(IconToggleButton b) {
432        if (!(b.getAction() instanceof MapMode))
433            throw new IllegalArgumentException("MapMode action must be subclass of MapMode");
434        allMapModeButtons.add(b);
435        toolBarActionsGroup.add(b);
436        toolBarActions.add(b);
437        b.applyButtonHiddenPreferences();
438        b.setInheritsPopupMenu(true);
439    }
440
441    /**
442     * Fires an property changed event "visible".
443     * @param aFlag {@code true} if display should be visible
444     */
445    @Override public void setVisible(boolean aFlag) {
446        boolean old = isVisible();
447        super.setVisible(aFlag);
448        if (old != aFlag) {
449            firePropertyChange("visible", old, aFlag);
450        }
451    }
452
453    /**
454     * Change the operating map mode for the view. Will call unregister on the
455     * old MapMode and register on the new one. Now this function also verifies
456     * if new map mode is correct mode for current layer and does not change mode
457     * in such cases.
458     * @param newMapMode The new mode to set.
459     * @return {@code true} if mode is really selected
460     */
461    public boolean selectMapMode(MapMode newMapMode) {
462        return selectMapMode(newMapMode, mapView.getLayerManager().getActiveLayer());
463    }
464
465    /**
466     * Another version of the selectMapMode for changing layer action.
467     * Pass newly selected layer to this method.
468     * @param newMapMode The new mode to set.
469     * @param newLayer newly selected layer
470     * @return {@code true} if mode is really selected
471     */
472    public boolean selectMapMode(MapMode newMapMode, Layer newLayer) {
473        if (newMapMode == null || !newMapMode.layerIsSupported(newLayer))
474            return false;
475
476        MapMode oldMapMode = this.mapMode;
477        if (newMapMode == oldMapMode)
478            return true;
479        if (oldMapMode != null) {
480            oldMapMode.exitMode();
481        }
482        this.mapMode = newMapMode;
483        newMapMode.enterMode();
484        lastMapMode.put(newLayer, newMapMode);
485        fireMapModeChanged(oldMapMode, newMapMode);
486        return true;
487    }
488
489    /**
490     * Fill the given panel by adding all necessary components to the different
491     * locations.
492     *
493     * @param panel The container to fill. Must have a BorderLayout.
494     */
495    public void fillPanel(Container panel) {
496        panel.add(this, BorderLayout.CENTER);
497
498        /**
499         * sideToolBar: add map modes icons
500         */
501        if (Config.getPref().getBoolean("sidetoolbar.mapmodes.visible", true)) {
502            toolBarActions.setAlignmentX(0.5f);
503            toolBarActions.setBorder(null);
504            toolBarActions.setInheritsPopupMenu(true);
505            sideToolBar.add(toolBarActions);
506            listAllMapModesButton.setAlignmentX(0.5f);
507            listAllMapModesButton.setBorder(null);
508            listAllMapModesButton.setFont(listAllMapModesButton.getFont().deriveFont(Font.PLAIN));
509            listAllMapModesButton.setInheritsPopupMenu(true);
510            sideToolBar.add(listAllMapModesButton);
511        }
512
513        /**
514         * sideToolBar: add toggle dialogs icons
515         */
516        if (Config.getPref().getBoolean("sidetoolbar.toggledialogs.visible", true)) {
517            ((JToolBar) sideToolBar).addSeparator(new Dimension(0, 18));
518            toolBarToggle.setAlignmentX(0.5f);
519            toolBarToggle.setBorder(null);
520            toolBarToggle.setInheritsPopupMenu(true);
521            sideToolBar.add(toolBarToggle);
522            listAllToggleDialogsButton.setAlignmentX(0.5f);
523            listAllToggleDialogsButton.setBorder(null);
524            listAllToggleDialogsButton.setFont(listAllToggleDialogsButton.getFont().deriveFont(Font.PLAIN));
525            listAllToggleDialogsButton.setInheritsPopupMenu(true);
526            sideToolBar.add(listAllToggleDialogsButton);
527        }
528
529        /**
530         * sideToolBar: add dynamic popup menu
531         */
532        sideToolBar.setComponentPopupMenu(new SideToolbarPopupMenu());
533        ((JToolBar) sideToolBar).setFloatable(false);
534        sideToolBar.setBorder(BorderFactory.createEmptyBorder(0, 1, 0, 1));
535
536        /**
537         * sideToolBar: decide scroll- and visibility
538         */
539        if (Config.getPref().getBoolean("sidetoolbar.scrollable", true)) {
540            final ScrollViewport svp = new ScrollViewport(sideToolBar, ScrollViewport.VERTICAL_DIRECTION);
541            sideToolBar = svp;
542        }
543        sideToolBar.setVisible(Config.getPref().getBoolean("sidetoolbar.visible", true));
544        sidetoolbarPreferencesChangedListener = e -> {
545            if ("sidetoolbar.visible".equals(e.getKey())) {
546                sideToolBar.setVisible(Config.getPref().getBoolean("sidetoolbar.visible"));
547            }
548        };
549        Config.getPref().addPreferenceChangeListener(sidetoolbarPreferencesChangedListener);
550
551        /**
552         * sideToolBar: add it to the panel
553         */
554        panel.add(sideToolBar, BorderLayout.WEST);
555
556        /**
557         * statusLine: add to panel
558         */
559        if (statusLine != null && Config.getPref().getBoolean("statusline.visible", true)) {
560            panel.add(statusLine, BorderLayout.SOUTH);
561        }
562    }
563
564    static final class NoBorderSplitPaneUI extends BasicSplitPaneUI {
565        static final class NoBorderBasicSplitPaneDivider extends BasicSplitPaneDivider {
566            NoBorderBasicSplitPaneDivider(BasicSplitPaneUI ui) {
567                super(ui);
568            }
569
570            @Override
571            public void setBorder(Border b) {
572                // Do nothing
573            }
574        }
575
576        @Override
577        public BasicSplitPaneDivider createDefaultDivider() {
578            return new NoBorderBasicSplitPaneDivider(this);
579        }
580    }
581
582    private final class SideToolbarPopupMenu extends JPopupMenu {
583        private static final int staticMenuEntryCount = 2;
584        private final JCheckBoxMenuItem doNotHide = new JCheckBoxMenuItem(new AbstractAction(tr("Do not hide toolbar")) {
585            @Override
586            public void actionPerformed(ActionEvent e) {
587                boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState();
588                Config.getPref().putBoolean("sidetoolbar.always-visible", sel);
589            }
590        });
591        {
592            addPopupMenuListener(new PopupMenuListener() {
593                @Override
594                public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
595                    final Object src = ((JPopupMenu) e.getSource()).getInvoker();
596                    if (src instanceof IconToggleButton) {
597                        insert(new Separator(), 0);
598                        insert(new AbstractAction() {
599                            {
600                                putValue(NAME, tr("Hide this button"));
601                                putValue(SHORT_DESCRIPTION, tr("Click the arrow at the bottom to show it again."));
602                            }
603
604                            @Override
605                            public void actionPerformed(ActionEvent e) {
606                                ((IconToggleButton) src).setButtonHidden(true);
607                                validateToolBarsVisibility();
608                            }
609                        }, 0);
610                    }
611                    doNotHide.setSelected(Config.getPref().getBoolean("sidetoolbar.always-visible", true));
612                }
613
614                @Override
615                public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
616                    while (getComponentCount() > staticMenuEntryCount) {
617                        remove(0);
618                    }
619                }
620
621                @Override
622                public void popupMenuCanceled(PopupMenuEvent e) {
623                    // Do nothing
624                }
625            });
626
627            add(new AbstractAction(tr("Hide edit toolbar")) {
628                @Override
629                public void actionPerformed(ActionEvent e) {
630                    Config.getPref().putBoolean("sidetoolbar.visible", false);
631                }
632            });
633            add(doNotHide);
634        }
635    }
636
637    class ListAllButtonsAction extends AbstractAction {
638
639        private JButton button;
640        private final transient Collection<? extends HideableButton> buttons;
641
642        ListAllButtonsAction(Collection<? extends HideableButton> buttons) {
643            this.buttons = buttons;
644        }
645
646        public void setButton(JButton button) {
647            this.button = button;
648            final ImageIcon icon = ImageProvider.get("audio-fwd");
649            putValue(SMALL_ICON, icon);
650            button.setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight() + 64));
651        }
652
653        @Override
654        public void actionPerformed(ActionEvent e) {
655            JPopupMenu menu = new JPopupMenu();
656            for (HideableButton b : buttons) {
657                final HideableButton t = b;
658                menu.add(new JCheckBoxMenuItem(new AbstractAction() {
659                    {
660                        putValue(NAME, t.getActionName());
661                        putValue(SMALL_ICON, t.getIcon());
662                        putValue(SELECTED_KEY, t.isButtonVisible());
663                        putValue(SHORT_DESCRIPTION, tr("Hide or show this toggle button"));
664                    }
665
666                    @Override
667                    public void actionPerformed(ActionEvent e) {
668                        if ((Boolean) getValue(SELECTED_KEY)) {
669                            t.showButton();
670                        } else {
671                            t.hideButton();
672                        }
673                        validateToolBarsVisibility();
674                    }
675                }));
676            }
677            if (button != null) {
678                Rectangle bounds = button.getBounds();
679                menu.show(button, bounds.x + bounds.width, 0);
680            }
681        }
682    }
683
684    /**
685     * Validate the visibility of all tool bars and hide the ones that should be hidden
686     */
687    public void validateToolBarsVisibility() {
688        for (IconToggleButton b : allDialogButtons) {
689            b.applyButtonHiddenPreferences();
690        }
691        toolBarToggle.repaint();
692        for (IconToggleButton b : allMapModeButtons) {
693            b.applyButtonHiddenPreferences();
694        }
695        toolBarActions.repaint();
696    }
697
698    /**
699     * Replies the instance of a toggle dialog of type <code>type</code> managed by this map frame
700     *
701     * @param <T> toggle dialog type
702     * @param type the class of the toggle dialog, i.e. UserListDialog.class
703     * @return the instance of a toggle dialog of type <code>type</code> managed by this
704     * map frame; null, if no such dialog exists
705     *
706     */
707    public <T> T getToggleDialog(Class<T> type) {
708        return dialogsPanel.getToggleDialog(type);
709    }
710
711    /**
712     * Shows or hides the side dialog panel
713     * @param visible The new visibility
714     */
715    public void setDialogsPanelVisible(boolean visible) {
716        rememberToggleDialogWidth();
717        dialogsPanel.setVisible(visible);
718        splitPane.setDividerLocation(visible ? splitPane.getWidth() - TOGGLE_DIALOGS_WIDTH.get() : 0);
719        splitPane.setDividerSize(visible ? 5 : 0);
720    }
721
722    /**
723     * Remember the current width of the (possibly resized) toggle dialog area
724     */
725    public void rememberToggleDialogWidth() {
726        if (dialogsPanel.isVisible()) {
727            TOGGLE_DIALOGS_WIDTH.put(splitPane.getWidth() - splitPane.getDividerLocation());
728        }
729    }
730
731    /**
732     * Remove panel from top of MapView by class
733     * @param type type of panel
734     */
735    public void removeTopPanel(Class<?> type) {
736        int n = leftPanel.getComponentCount();
737        for (int i = 0; i < n; i++) {
738            Component c = leftPanel.getComponent(i);
739            if (type.isInstance(c)) {
740                leftPanel.remove(i);
741                leftPanel.doLayout();
742                return;
743            }
744        }
745    }
746
747    /**
748     * Find panel on top of MapView by class
749     * @param <T> type
750     * @param type type of panel
751     * @return found panel
752     */
753    public <T> T getTopPanel(Class<T> type) {
754        int n = leftPanel.getComponentCount();
755        for (int i = 0; i < n; i++) {
756            Component c = leftPanel.getComponent(i);
757            if (type.isInstance(c))
758                return type.cast(c);
759        }
760        return null;
761    }
762
763    /**
764     * Add component {@code c} on top of MapView
765     * @param c component
766     */
767    public void addTopPanel(Component c) {
768        leftPanel.add(c, GBC.eol().fill(GBC.HORIZONTAL), leftPanel.getComponentCount()-1);
769        leftPanel.doLayout();
770        c.doLayout();
771    }
772
773    /**
774     * Interface to notify listeners of the change of the mapMode.
775     * @since 10600 (functional interface)
776     */
777    @FunctionalInterface
778    public interface MapModeChangeListener {
779        /**
780         * Trigerred when map mode changes.
781         * @param oldMapMode old map mode
782         * @param newMapMode new map mode
783         */
784        void mapModeChange(MapMode oldMapMode, MapMode newMapMode);
785    }
786
787    /**
788     * the mapMode listeners
789     */
790    private static final CopyOnWriteArrayList<MapModeChangeListener> mapModeChangeListeners = new CopyOnWriteArrayList<>();
791
792    private transient PreferenceChangedListener sidetoolbarPreferencesChangedListener;
793    /**
794     * Adds a mapMode change listener
795     *
796     * @param listener the listener. Ignored if null or already registered.
797     */
798    public static void addMapModeChangeListener(MapModeChangeListener listener) {
799        if (listener != null) {
800            mapModeChangeListeners.addIfAbsent(listener);
801        }
802    }
803
804    /**
805     * Removes a mapMode change listener
806     *
807     * @param listener the listener. Ignored if null or already registered.
808     */
809    public static void removeMapModeChangeListener(MapModeChangeListener listener) {
810        mapModeChangeListeners.remove(listener);
811    }
812
813    protected static void fireMapModeChanged(MapMode oldMapMode, MapMode newMapMode) {
814        for (MapModeChangeListener l : mapModeChangeListeners) {
815            l.mapModeChange(oldMapMode, newMapMode);
816        }
817    }
818
819    @Override
820    public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
821        boolean modeChanged = false;
822        Layer newLayer = e.getSource().getActiveLayer();
823        if (mapMode == null || !mapMode.layerIsSupported(newLayer)) {
824            MapMode newMapMode = getLastMapMode(newLayer);
825            modeChanged = newMapMode != mapMode;
826            if (newMapMode != null) {
827                // it would be nice to select first supported mode when layer is first selected,
828                // but it don't work well with for example editgpx layer
829                selectMapMode(newMapMode, newLayer);
830            } else if (mapMode != null) {
831                mapMode.exitMode(); // if new mode is null - simply exit from previous mode
832                mapMode = null;
833            }
834        }
835        // if this is really a change (and not the first active layer)
836        if (e.getPreviousActiveLayer() != null && !modeChanged && mapMode != null) {
837            // Let mapmodes know about new active layer
838            mapMode.exitMode();
839            mapMode.enterMode();
840        }
841
842        // After all listeners notice new layer, some buttons will be disabled/enabled
843        // and possibly need to be hidden/shown.
844        validateToolBarsVisibility();
845    }
846
847    private MapMode getLastMapMode(Layer newLayer) {
848        MapMode mode = lastMapMode.get(newLayer);
849        if (mode == null) {
850            // if no action is selected - try to select default action
851            Action defaultMode = getDefaultButtonAction();
852            if (defaultMode instanceof MapMode && ((MapMode) defaultMode).layerIsSupported(newLayer)) {
853                mode = (MapMode) defaultMode;
854            }
855        }
856        return mode;
857    }
858
859    @Override
860    public void layerAdded(LayerAddEvent e) {
861        // ignored
862    }
863
864    @Override
865    public void layerRemoving(LayerRemoveEvent e) {
866        lastMapMode.remove(e.getRemovedLayer());
867    }
868
869    @Override
870    public void layerOrderChanged(LayerOrderChangeEvent e) {
871        // ignored
872    }
873
874}