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