001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.dialogs;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.AWTEvent;
007import java.awt.BorderLayout;
008import java.awt.Component;
009import java.awt.Dimension;
010import java.awt.FlowLayout;
011import java.awt.Graphics;
012import java.awt.GraphicsEnvironment;
013import java.awt.GridBagConstraints;
014import java.awt.GridBagLayout;
015import java.awt.GridLayout;
016import java.awt.Rectangle;
017import java.awt.Toolkit;
018import java.awt.event.AWTEventListener;
019import java.awt.event.ActionEvent;
020import java.awt.event.ActionListener;
021import java.awt.event.ComponentAdapter;
022import java.awt.event.ComponentEvent;
023import java.awt.event.MouseEvent;
024import java.awt.event.WindowAdapter;
025import java.awt.event.WindowEvent;
026import java.beans.PropertyChangeEvent;
027import java.util.ArrayList;
028import java.util.Arrays;
029import java.util.Collection;
030import java.util.LinkedList;
031import java.util.List;
032
033import javax.swing.AbstractAction;
034import javax.swing.BorderFactory;
035import javax.swing.ButtonGroup;
036import javax.swing.ImageIcon;
037import javax.swing.JButton;
038import javax.swing.JCheckBoxMenuItem;
039import javax.swing.JComponent;
040import javax.swing.JDialog;
041import javax.swing.JLabel;
042import javax.swing.JMenu;
043import javax.swing.JPanel;
044import javax.swing.JPopupMenu;
045import javax.swing.JRadioButtonMenuItem;
046import javax.swing.JScrollPane;
047import javax.swing.JToggleButton;
048import javax.swing.Scrollable;
049import javax.swing.SwingConstants;
050import javax.swing.SwingUtilities;
051
052import org.openstreetmap.josm.actions.JosmAction;
053import org.openstreetmap.josm.data.preferences.BooleanProperty;
054import org.openstreetmap.josm.data.preferences.ParametrizedEnumProperty;
055import org.openstreetmap.josm.gui.MainApplication;
056import org.openstreetmap.josm.gui.MainMenu;
057import org.openstreetmap.josm.gui.ShowHideButtonListener;
058import org.openstreetmap.josm.gui.SideButton;
059import org.openstreetmap.josm.gui.dialogs.DialogsPanel.Action;
060import org.openstreetmap.josm.gui.help.HelpBrowser;
061import org.openstreetmap.josm.gui.help.HelpUtil;
062import org.openstreetmap.josm.gui.help.Helpful;
063import org.openstreetmap.josm.gui.preferences.PreferenceDialog;
064import org.openstreetmap.josm.gui.preferences.PreferenceSetting;
065import org.openstreetmap.josm.gui.preferences.SubPreferenceSetting;
066import org.openstreetmap.josm.gui.preferences.TabPreferenceSetting;
067import org.openstreetmap.josm.gui.util.GuiHelper;
068import org.openstreetmap.josm.gui.util.WindowGeometry;
069import org.openstreetmap.josm.gui.util.WindowGeometry.WindowGeometryException;
070import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;
071import org.openstreetmap.josm.spi.preferences.Config;
072import org.openstreetmap.josm.spi.preferences.PreferenceChangeEvent;
073import org.openstreetmap.josm.spi.preferences.PreferenceChangedListener;
074import org.openstreetmap.josm.tools.Destroyable;
075import org.openstreetmap.josm.tools.GBC;
076import org.openstreetmap.josm.tools.ImageProvider;
077import org.openstreetmap.josm.tools.Logging;
078import org.openstreetmap.josm.tools.Shortcut;
079import org.openstreetmap.josm.tools.Utils;
080
081/**
082 * This class is a toggle dialog that can be turned on and off.
083 * @since 8
084 */
085public class ToggleDialog extends JPanel implements ShowHideButtonListener, Helpful, AWTEventListener, Destroyable, PreferenceChangedListener {
086
087    /**
088     * The button-hiding strategy in toggler dialogs.
089     */
090    public enum ButtonHidingType {
091        /** Buttons are always shown (default) **/
092        ALWAYS_SHOWN,
093        /** Buttons are always hidden **/
094        ALWAYS_HIDDEN,
095        /** Buttons are dynamically hidden, i.e. only shown when mouse cursor is in dialog */
096        DYNAMIC
097    }
098
099    /**
100     * Property to enable dynamic buttons globally.
101     * @since 6752
102     */
103    public static final BooleanProperty PROP_DYNAMIC_BUTTONS = new BooleanProperty("dialog.dynamic.buttons", false);
104    private static final String SELECTED = "selected";
105
106    private final transient ParametrizedEnumProperty<ButtonHidingType> propButtonHiding =
107            new ParametrizedEnumProperty<>(ButtonHidingType.class, ButtonHidingType.DYNAMIC) {
108                @Override
109                protected String getKey(String... params) {
110                    return preferencePrefix + ".buttonhiding";
111                }
112
113                @Override
114                protected ButtonHidingType parse(String s) {
115                    try {
116                        return super.parse(s);
117                    } catch (IllegalArgumentException e) {
118                        // Legacy settings
119                        Logging.trace(e);
120                        return Boolean.parseBoolean(s) ? ButtonHidingType.DYNAMIC : ButtonHidingType.ALWAYS_SHOWN;
121                    }
122                }
123            };
124
125    /** The action to toggle this dialog */
126    protected final ToggleDialogAction toggleAction;
127    protected String preferencePrefix;
128    protected final String name;
129
130    /** DialogsPanel that manages all ToggleDialogs */
131    protected DialogsPanel dialogsPanel;
132
133    protected TitleBar titleBar;
134
135    /**
136     * Indicates whether the dialog is showing or not.
137     */
138    protected boolean isShowing;
139
140    /**
141     * If isShowing is true, indicates whether the dialog is docked or not, e. g.
142     * shown as part of the main window or as a separate dialog window.
143     */
144    protected boolean isDocked;
145
146    /**
147     * If isShowing and isDocked are true, indicates whether the dialog is
148     * currently minimized or not.
149     */
150    protected boolean isCollapsed;
151
152    /**
153     * Indicates whether dynamic button hiding is active or not.
154     */
155    protected ButtonHidingType buttonHiding;
156
157    /** the preferred height if the toggle dialog is expanded */
158    private final int preferredHeight;
159
160    /** the JDialog displaying the toggle dialog as undocked dialog */
161    protected JDialog detachedDialog;
162
163    protected JToggleButton button;
164    private JPanel buttonsPanel;
165    private final transient List<javax.swing.Action> buttonActions = new ArrayList<>();
166
167    /** holds the menu entry in the windows menu. Required to properly
168     * toggle the checkbox on show/hide
169     */
170    protected JCheckBoxMenuItem windowMenuItem;
171
172    private final JRadioButtonMenuItem alwaysShown = new JRadioButtonMenuItem(new AbstractAction(tr("Always shown")) {
173        @Override
174        public void actionPerformed(ActionEvent e) {
175            setIsButtonHiding(ButtonHidingType.ALWAYS_SHOWN);
176        }
177    });
178
179    private final JRadioButtonMenuItem dynamic = new JRadioButtonMenuItem(new AbstractAction(tr("Dynamic")) {
180        @Override
181        public void actionPerformed(ActionEvent e) {
182            setIsButtonHiding(ButtonHidingType.DYNAMIC);
183        }
184    });
185
186    private final JRadioButtonMenuItem alwaysHidden = new JRadioButtonMenuItem(new AbstractAction(tr("Always hidden")) {
187        @Override
188        public void actionPerformed(ActionEvent e) {
189            setIsButtonHiding(ButtonHidingType.ALWAYS_HIDDEN);
190        }
191    });
192
193    /**
194     * The linked preferences class (optional). If set, accessible from the title bar with a dedicated button
195     */
196    protected Class<? extends PreferenceSetting> preferenceClass;
197
198    /**
199     * Constructor
200     *
201     * @param name  the name of the dialog
202     * @param iconName the name of the icon to be displayed
203     * @param tooltip  the tool tip
204     * @param shortcut  the shortcut
205     * @param preferredHeight the preferred height for the dialog
206     */
207    public ToggleDialog(String name, String iconName, String tooltip, Shortcut shortcut, int preferredHeight) {
208        this(name, iconName, tooltip, shortcut, preferredHeight, false);
209    }
210
211    /**
212     * Constructor
213
214     * @param name  the name of the dialog
215     * @param iconName the name of the icon to be displayed
216     * @param tooltip  the tool tip
217     * @param shortcut  the shortcut
218     * @param preferredHeight the preferred height for the dialog
219     * @param defShow if the dialog should be shown by default, if there is no preference
220     */
221    public ToggleDialog(String name, String iconName, String tooltip, Shortcut shortcut, int preferredHeight, boolean defShow) {
222        this(name, iconName, tooltip, shortcut, preferredHeight, defShow, null);
223    }
224
225    /**
226     * Constructor
227     *
228     * @param name  the name of the dialog
229     * @param iconName the name of the icon to be displayed
230     * @param tooltip  the tool tip
231     * @param shortcut  the shortcut
232     * @param preferredHeight the preferred height for the dialog
233     * @param defShow if the dialog should be shown by default, if there is no preference
234     * @param prefClass the preferences settings class, or null if not applicable
235     */
236    public ToggleDialog(String name, String iconName, String tooltip, Shortcut shortcut, int preferredHeight, boolean defShow,
237            Class<? extends PreferenceSetting> prefClass) {
238        this(name, iconName, tooltip, shortcut, preferredHeight, defShow, prefClass, false);
239    }
240
241    /**
242     * Constructor
243     *
244     * @param name  the name of the dialog
245     * @param iconName the name of the icon to be displayed
246     * @param tooltip  the tool tip
247     * @param shortcut  the shortcut
248     * @param preferredHeight the preferred height for the dialog
249     * @param defShow if the dialog should be shown by default, if there is no preference
250     * @param prefClass the preferences settings class, or null if not applicable
251     * @param isExpert {@code true} if this dialog should only be displayed in expert mode
252     * @since 15650
253     */
254    public ToggleDialog(String name, String iconName, String tooltip, Shortcut shortcut, int preferredHeight, boolean defShow,
255            Class<? extends PreferenceSetting> prefClass, boolean isExpert) {
256        super(new BorderLayout());
257        this.preferencePrefix = iconName;
258        this.name = name;
259        this.preferenceClass = prefClass;
260
261        /* Use the full width of the parent element */
262        setPreferredSize(new Dimension(0, preferredHeight));
263        /* Override any minimum sizes of child elements so the user can resize freely */
264        setMinimumSize(new Dimension(0, 0));
265        this.preferredHeight = Config.getPref().getInt(preferencePrefix+".preferredHeight", preferredHeight);
266        toggleAction = new ToggleDialogAction(name, "dialogs/"+iconName, tooltip, shortcut, helpTopic());
267
268        isShowing = Config.getPref().getBoolean(preferencePrefix+".visible", defShow);
269        isDocked = Config.getPref().getBoolean(preferencePrefix+".docked", true);
270        isCollapsed = Config.getPref().getBoolean(preferencePrefix+".minimized", false);
271        buttonHiding = propButtonHiding.get();
272
273        /* show the minimize button */
274        titleBar = new TitleBar(name, iconName);
275        add(titleBar, BorderLayout.NORTH);
276
277        setBorder(BorderFactory.createEtchedBorder());
278
279        MainApplication.redirectToMainContentPane(this);
280        Config.getPref().addPreferenceChangeListener(this);
281
282        registerInWindowMenu(isExpert);
283    }
284
285    /**
286     * Registers this dialog in the window menu. Called in the constructor.
287     * @param isExpert {@code true} if this dialog should only be displayed in expert mode
288     * @since 15650
289     */
290    protected void registerInWindowMenu(boolean isExpert) {
291        windowMenuItem = MainMenu.addWithCheckbox(MainApplication.getMenu().windowMenu,
292                (JosmAction) getToggleAction(),
293                MainMenu.WINDOW_MENU_GROUP.TOGGLE_DIALOG, isExpert, true);
294    }
295
296    /**
297     * The action to toggle the visibility state of this toggle dialog.
298     * <p>
299     * Emits {@link PropertyChangeEvent}s for the property <code>selected</code>:
300     * <ul>
301     *   <li>true, if the dialog is currently visible</li>
302     *   <li>false, if the dialog is currently invisible</li>
303     * </ul>
304     *
305     */
306    public final class ToggleDialogAction extends JosmAction {
307
308        private ToggleDialogAction(String name, String iconName, String tooltip, Shortcut shortcut, String helpId) {
309            super(name, iconName, tooltip, shortcut, false, false);
310            setHelpId(helpId);
311        }
312
313        @Override
314        public void actionPerformed(ActionEvent e) {
315            toggleButtonHook();
316            if (getValue("toolbarbutton") instanceof JButton) {
317                ((JButton) getValue("toolbarbutton")).setSelected(!isShowing);
318            }
319            if (isShowing) {
320                hideDialog();
321                if (dialogsPanel != null) {
322                    dialogsPanel.reconstruct(Action.ELEMENT_SHRINKS, null);
323                }
324                hideNotify();
325            } else {
326                showDialog();
327                if (isDocked && isCollapsed) {
328                    expand();
329                }
330                if (isDocked && dialogsPanel != null) {
331                    dialogsPanel.reconstruct(Action.INVISIBLE_TO_DEFAULT, ToggleDialog.this);
332                }
333                showNotify();
334            }
335        }
336
337        @Override
338        public String toString() {
339            return "ToggleDialogAction [" + ToggleDialog.this + ']';
340        }
341    }
342
343    /**
344     * Shows the dialog
345     */
346    public void showDialog() {
347        setIsShowing(true);
348        if (!isDocked) {
349            detach();
350        } else {
351            dock();
352            this.setVisible(true);
353        }
354        // toggling the selected value in order to enforce PropertyChangeEvents
355        setIsShowing(true);
356        if (windowMenuItem != null) {
357            windowMenuItem.setState(true);
358        }
359        toggleAction.putValue(SELECTED, Boolean.FALSE);
360        toggleAction.putValue(SELECTED, Boolean.TRUE);
361    }
362
363    /**
364     * Changes the state of the dialog such that the user can see the content.
365     * (takes care of the panel reconstruction)
366     */
367    public void unfurlDialog() {
368        if (isDialogInDefaultView())
369            return;
370        if (isDialogInCollapsedView()) {
371            expand();
372            dialogsPanel.reconstruct(Action.COLLAPSED_TO_DEFAULT, this);
373        } else if (!isDialogShowing()) {
374            showDialog();
375            if (isDocked && isCollapsed) {
376                expand();
377            }
378            if (isDocked) {
379                dialogsPanel.reconstruct(Action.INVISIBLE_TO_DEFAULT, this);
380            }
381            showNotify();
382        }
383    }
384
385    @Override
386    public void buttonHidden() {
387        if (Boolean.TRUE.equals(toggleAction.getValue(SELECTED))) {
388            toggleAction.actionPerformed(null);
389        }
390    }
391
392    @Override
393    public void buttonShown() {
394        unfurlDialog();
395    }
396
397    /**
398     * Hides the dialog
399     */
400    public void hideDialog() {
401        closeDetachedDialog();
402        this.setVisible(false);
403        if (windowMenuItem != null) {
404            windowMenuItem.setState(false);
405        }
406        setIsShowing(false);
407        toggleAction.putValue(SELECTED, Boolean.FALSE);
408    }
409
410    /**
411     * Displays the toggle dialog in the toggle dialog view on the right
412     * of the main map window.
413     *
414     */
415    protected void dock() {
416        detachedDialog = null;
417        titleBar.setVisible(true);
418        setIsDocked(true);
419    }
420
421    /**
422     * Display the dialog in a detached window.
423     *
424     */
425    protected void detach() {
426        setContentVisible(true);
427        this.setVisible(true);
428        titleBar.setVisible(false);
429        if (!GraphicsEnvironment.isHeadless()) {
430            detachedDialog = new DetachedDialog();
431            detachedDialog.setVisible(true);
432        }
433        setIsShowing(true);
434        setIsDocked(false);
435    }
436
437    /**
438     * Collapses the toggle dialog to the title bar only
439     *
440     */
441    public void collapse() {
442        if (isDialogInDefaultView()) {
443            int titlebarHeight = Config.getPref().getInt("toggledialog.titlebar.height", 
444                (int) (20 * Config.getPref().getDouble("gui.scale", 1.0)));
445            setContentVisible(false);
446            setIsCollapsed(true);
447            setPreferredSize(new Dimension(0, titlebarHeight));
448            setMaximumSize(new Dimension(Integer.MAX_VALUE, titlebarHeight));
449            setMinimumSize(new Dimension(Integer.MAX_VALUE, titlebarHeight));
450            titleBar.lblMinimized.setIcon(ImageProvider.get("misc", "minimized"));
451        } else
452            throw new IllegalStateException();
453    }
454
455    /**
456     * Expands the toggle dialog
457     */
458    protected void expand() {
459        if (isDialogInCollapsedView()) {
460            setContentVisible(true);
461            setIsCollapsed(false);
462            setPreferredSize(new Dimension(0, preferredHeight));
463            setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
464            titleBar.lblMinimized.setIcon(ImageProvider.get("misc", "normal"));
465        } else
466            throw new IllegalStateException();
467    }
468
469    /**
470     * Sets the visibility of all components in this toggle dialog, except the title bar
471     *
472     * @param visible true, if the components should be visible; false otherwise
473     */
474    protected void setContentVisible(boolean visible) {
475        Component[] comps = getComponents();
476        for (Component comp : comps) {
477            if (comp != titleBar && (!visible || comp != buttonsPanel || buttonHiding != ButtonHidingType.ALWAYS_HIDDEN)) {
478                comp.setVisible(visible);
479            }
480        }
481    }
482
483    @Override
484    public void destroy() {
485        if (dialogsPanel != null) {
486            dialogsPanel.remove(this);
487            dialogsPanel = null;
488        }
489        rememberHeight();
490        closeDetachedDialog();
491        if (isShowing) {
492            hideNotify();
493        }
494        MainApplication.getMenu().windowMenu.remove(windowMenuItem);
495        try {
496            Toolkit.getDefaultToolkit().removeAWTEventListener(this);
497        } catch (SecurityException e) {
498            Logging.log(Logging.LEVEL_ERROR, "Unable to remove AWT event listener", e);
499        }
500        Config.getPref().removePreferenceChangeListener(this);
501        GuiHelper.destroyComponents(this, false);
502        titleBar.destroy();
503        titleBar = null;
504        this.buttonActions.clear();
505    }
506
507    /**
508     * Closes the detached dialog if this toggle dialog is currently displayed in a detached dialog.
509     */
510    public void closeDetachedDialog() {
511        if (detachedDialog != null) {
512            detachedDialog.setVisible(false);
513            detachedDialog.getContentPane().removeAll();
514            detachedDialog.dispose();
515        }
516    }
517
518    /**
519     * Called when toggle dialog is shown (after it was created or expanded). Descendants may overwrite this
520     * method, it's a good place to register listeners needed to keep dialog updated
521     */
522    public void showNotify() {
523        // Do nothing
524    }
525
526    /**
527     * Called when toggle dialog is hidden (collapsed, removed, MapFrame is removed, ...). Good place to unregister listeners
528     */
529    public void hideNotify() {
530        // Do nothing
531    }
532
533    /**
534     * The title bar displayed in docked mode
535     */
536    protected class TitleBar extends JPanel implements Destroyable {
537        /** the label which shows whether the toggle dialog is expanded or collapsed */
538        private final JLabel lblMinimized;
539        /** the label which displays the dialog's title **/
540        private final JLabel lblTitle;
541        private final JComponent lblTitleWeak;
542        /** the button which shows whether buttons are dynamic or not */
543        private final JButton buttonsHide;
544        /** the contextual menu **/
545        private DialogPopupMenu popupMenu;
546
547        private MouseEventHandler mouseEventHandler;
548
549        @SuppressWarnings("unchecked")
550        public TitleBar(String toggleDialogName, String iconName) {
551            setLayout(new GridBagLayout());
552
553            lblMinimized = new JLabel(ImageProvider.get("misc", "normal"));
554            add(lblMinimized);
555
556            // scale down the dialog icon
557            ImageIcon icon = ImageProvider.get("dialogs", iconName, ImageProvider.ImageSizes.SMALLICON);
558            lblTitle = new JLabel("", icon, SwingConstants.TRAILING);
559            lblTitle.setIconTextGap(8);
560
561            JPanel conceal = new JPanel();
562            conceal.add(lblTitle);
563            conceal.setVisible(false);
564            add(conceal, GBC.std());
565
566            // Cannot add the label directly since it would displace other elements on resize
567            lblTitleWeak = new JComponent() {
568                @Override
569                public void paintComponent(Graphics g) {
570                    super.paintComponent(g);
571                    lblTitle.paint(g);
572                }
573            };
574            int titlebarHeight = Config.getPref().getInt("toggledialog.titlebar.height", 
575                (int) (20 * Config.getPref().getDouble("gui.scale", 1.0)));
576            lblTitleWeak.setPreferredSize(new Dimension(Integer.MAX_VALUE, titlebarHeight));
577            lblTitleWeak.setMinimumSize(new Dimension(0, titlebarHeight));
578            add(lblTitleWeak, GBC.std().fill(GridBagConstraints.HORIZONTAL));
579
580            buttonsHide = new JButton(ImageProvider.get("misc", buttonHiding != ButtonHidingType.ALWAYS_SHOWN
581                ? /* ICON(misc/)*/ "buttonhide" :  /* ICON(misc/)*/ "buttonshow"));
582            addButton(buttonsHide, tr("Toggle dynamic buttons"), e -> {
583                JRadioButtonMenuItem item = (buttonHiding == ButtonHidingType.DYNAMIC) ? alwaysShown : dynamic;
584                item.setSelected(true);
585                item.getAction().actionPerformed(null);
586            });
587
588            // show the pref button if applicable
589            if (preferenceClass != null) {
590                addButton(new JButton(ImageProvider.get("preference_small", ImageProvider.ImageSizes.SMALLICON)),
591                        tr("Open preferences for this panel"), e -> {
592                    final PreferenceDialog p = new PreferenceDialog(MainApplication.getMainFrame());
593                    SwingUtilities.invokeLater(() -> {
594                        if (TabPreferenceSetting.class.isAssignableFrom(preferenceClass)) {
595                            p.selectPreferencesTabByClass((Class<? extends TabPreferenceSetting>) preferenceClass);
596                        } else if (SubPreferenceSetting.class.isAssignableFrom(preferenceClass)) {
597                            p.selectSubPreferencesTabByClass((Class<? extends SubPreferenceSetting>) preferenceClass);
598                        }
599                    });
600                    p.setVisible(true);
601                });
602            }
603
604            // show the help button
605            addButton(new JButton(ImageProvider.get("help", ImageProvider.ImageSizes.SMALLICON)),
606                    tr("Open help for this panel"), e -> HelpBrowser.setUrlForHelpTopic(helpTopic()));
607
608            // show the sticky button
609            addButton(new JButton(ImageProvider.get("misc", "sticky")), tr("Undock the panel"), e -> {
610                detach();
611                if (dialogsPanel != null) {
612                    dialogsPanel.reconstruct(Action.ELEMENT_SHRINKS, null);
613                }
614            });
615
616            // show the close button
617            addButton(new JButton(ImageProvider.get("misc", "close")),
618                    tr("Close this panel. You can reopen it with the buttons in the left toolbar."), e -> {
619                hideDialog();
620                if (dialogsPanel != null) {
621                    dialogsPanel.reconstruct(Action.ELEMENT_SHRINKS, null);
622                }
623                hideNotify();
624            });
625
626            setToolTipText(tr("Click to minimize/maximize the panel content"));
627            setTitle(toggleDialogName);
628        }
629
630        protected final Component addButton(JButton button, String tooltip, ActionListener actionListener) {
631            button.setBorder(BorderFactory.createEmptyBorder());
632            button.addActionListener(actionListener);
633            button.setToolTipText(tooltip);
634            return add(button);
635        }
636
637        public void setTitle(String title) {
638            lblTitle.setText(title);
639            lblTitleWeak.repaint();
640        }
641
642        public String getTitle() {
643            return lblTitle.getText();
644        }
645
646        /**
647         * This is the popup menu used for the title bar.
648         */
649        public class DialogPopupMenu extends JPopupMenu {
650
651            /**
652             * Constructs a new {@code DialogPopupMenu}.
653             */
654            DialogPopupMenu() {
655                alwaysShown.setSelected(buttonHiding == ButtonHidingType.ALWAYS_SHOWN);
656                dynamic.setSelected(buttonHiding == ButtonHidingType.DYNAMIC);
657                alwaysHidden.setSelected(buttonHiding == ButtonHidingType.ALWAYS_HIDDEN);
658                ButtonGroup buttonHidingGroup = new ButtonGroup();
659                JMenu buttonHidingMenu = new JMenu(tr("Side buttons"));
660                for (JRadioButtonMenuItem rb : new JRadioButtonMenuItem[]{alwaysShown, dynamic, alwaysHidden}) {
661                    buttonHidingGroup.add(rb);
662                    buttonHidingMenu.add(rb);
663                }
664                add(buttonHidingMenu);
665                for (javax.swing.Action action: buttonActions) {
666                    add(action);
667                }
668            }
669        }
670
671        /**
672         * Registers the mouse listeners.
673         * <p>
674         * Should be called once after this title was added to the dialog.
675         */
676        public final void registerMouseListener() {
677            popupMenu = new DialogPopupMenu();
678            mouseEventHandler = new MouseEventHandler();
679            addMouseListener(mouseEventHandler);
680        }
681
682        class MouseEventHandler extends PopupMenuLauncher {
683            /**
684             * Constructs a new {@code MouseEventHandler}.
685             */
686            MouseEventHandler() {
687                super(popupMenu);
688            }
689
690            @Override
691            public void mouseClicked(MouseEvent e) {
692                if (SwingUtilities.isLeftMouseButton(e)) {
693                    if (isCollapsed) {
694                        expand();
695                        dialogsPanel.reconstruct(Action.COLLAPSED_TO_DEFAULT, ToggleDialog.this);
696                    } else {
697                        collapse();
698                        dialogsPanel.reconstruct(Action.ELEMENT_SHRINKS, null);
699                    }
700                }
701            }
702        }
703
704        @Override
705        public void destroy() {
706            removeMouseListener(mouseEventHandler);
707            this.mouseEventHandler = null;
708            this.popupMenu = null;
709        }
710    }
711
712    /**
713     * The dialog class used to display toggle dialogs in a detached window.
714     *
715     */
716    private class DetachedDialog extends JDialog {
717        DetachedDialog() {
718            super(GuiHelper.getFrameForComponent(MainApplication.getMainFrame()));
719            getContentPane().add(ToggleDialog.this);
720            addWindowListener(new WindowAdapter() {
721                @Override public void windowClosing(WindowEvent e) {
722                    rememberGeometry();
723                    getContentPane().removeAll();
724                    dispose();
725                    if (dockWhenClosingDetachedDlg()) {
726                        dock();
727                        if (isDialogInCollapsedView()) {
728                            setContentVisible(false);
729                            dialogsPanel.reconstruct(Action.ELEMENT_SHRINKS, null);
730                        } else {
731                            dialogsPanel.reconstruct(Action.INVISIBLE_TO_DEFAULT, ToggleDialog.this);
732                        }
733                    } else {
734                        hideDialog();
735                        hideNotify();
736                    }
737                }
738            });
739            addComponentListener(new ComponentAdapter() {
740                @Override
741                public void componentMoved(ComponentEvent e) {
742                    rememberGeometry();
743                }
744
745                @Override
746                public void componentResized(ComponentEvent e) {
747                    rememberGeometry();
748                }
749            });
750
751            try {
752                new WindowGeometry(preferencePrefix+".geometry").applySafe(this);
753            } catch (WindowGeometryException e) {
754                Logging.debug(e);
755                ToggleDialog.this.setPreferredSize(ToggleDialog.this.getDefaultDetachedSize());
756                pack();
757                setLocationRelativeTo(MainApplication.getMainFrame());
758            }
759            super.setTitle(titleBar.getTitle());
760            HelpUtil.setHelpContext(getRootPane(), helpTopic());
761        }
762
763        protected void rememberGeometry() {
764            if (detachedDialog != null && detachedDialog.isShowing()) {
765                new WindowGeometry(detachedDialog).remember(preferencePrefix+".geometry");
766            }
767        }
768    }
769
770    /**
771     * Replies the action to toggle the visible state of this toggle dialog
772     *
773     * @return the action to toggle the visible state of this toggle dialog
774     */
775    public AbstractAction getToggleAction() {
776        return toggleAction;
777    }
778
779    /**
780     * Replies the prefix for the preference settings of this dialog.
781     *
782     * @return the prefix for the preference settings of this dialog.
783     */
784    public String getPreferencePrefix() {
785        return preferencePrefix;
786    }
787
788    /**
789     * Sets the dialogsPanel managing all toggle dialogs.
790     * @param dialogsPanel The panel managing all toggle dialogs
791     */
792    public void setDialogsPanel(DialogsPanel dialogsPanel) {
793        this.dialogsPanel = dialogsPanel;
794    }
795
796    /**
797     * Replies the name of this toggle dialog
798     */
799    @Override
800    public String getName() {
801        return "toggleDialog." + preferencePrefix;
802    }
803
804    /**
805     * Sets the title.
806     * @param title The dialog's title
807     */
808    public void setTitle(String title) {
809        if (titleBar != null) {
810            titleBar.setTitle(title);
811        }
812        if (detachedDialog != null) {
813            detachedDialog.setTitle(title);
814        }
815    }
816
817    protected void setIsShowing(boolean val) {
818        isShowing = val;
819        Config.getPref().putBoolean(preferencePrefix+".visible", val);
820        stateChanged();
821    }
822
823    protected void setIsDocked(boolean val) {
824        if (buttonsPanel != null) {
825            buttonsPanel.setVisible(!val || buttonHiding != ButtonHidingType.ALWAYS_HIDDEN);
826        }
827        isDocked = val;
828        Config.getPref().putBoolean(preferencePrefix+".docked", val);
829        stateChanged();
830    }
831
832    protected void setIsCollapsed(boolean val) {
833        isCollapsed = val;
834        Config.getPref().putBoolean(preferencePrefix+".minimized", val);
835        stateChanged();
836    }
837
838    protected void setIsButtonHiding(ButtonHidingType val) {
839        buttonHiding = val;
840        propButtonHiding.put(val);
841        refreshHidingButtons();
842    }
843
844    /**
845     * Returns the preferred height of this dialog.
846     * @return The preferred height if the toggle dialog is expanded
847     */
848    public int getPreferredHeight() {
849        return preferredHeight;
850    }
851
852    @Override
853    public String helpTopic() {
854        String help = getClass().getName();
855        help = help.substring(help.lastIndexOf('.')+1, help.length()-6);
856        return "Dialog/"+help;
857    }
858
859    @Override
860    public String toString() {
861        return name;
862    }
863
864    /**
865     * Determines if this dialog is showing either as docked or as detached dialog.
866     * @return {@code true} if this dialog is showing either as docked or as detached dialog
867     */
868    public boolean isDialogShowing() {
869        return isShowing;
870    }
871
872    /**
873     * Determines if this dialog is docked and expanded.
874     * @return {@code true} if this dialog is docked and expanded
875     */
876    public boolean isDialogInDefaultView() {
877        return isShowing && isDocked && !isCollapsed;
878    }
879
880    /**
881     * Determines if this dialog is docked and collapsed.
882     * @return {@code true} if this dialog is docked and collapsed
883     */
884    public boolean isDialogInCollapsedView() {
885        return isShowing && isDocked && isCollapsed;
886    }
887
888    /**
889     * Sets the button from the button list that is used to display this dialog.
890     * <p>
891     * Note: This is ignored by the {@link ToggleDialog} for now.
892     * @param button The button for this dialog.
893     */
894    public void setButton(JToggleButton button) {
895        this.button = button;
896    }
897
898    /**
899     * Gets the button from the button list that is used to display this dialog.
900     * @return button The button for this dialog.
901     */
902    public JToggleButton getButton() {
903        return button;
904    }
905
906    /*
907     * The following methods are intended to be overridden, in order to customize
908     * the toggle dialog behavior.
909     */
910
911    /**
912     * Returns the default size of the detached dialog.
913     * Override this method to customize the initial dialog size.
914     * @return the default size of the detached dialog
915     */
916    protected Dimension getDefaultDetachedSize() {
917        return new Dimension(dialogsPanel.getWidth(), preferredHeight);
918    }
919
920    /**
921     * Do something when the toggleButton is pressed.
922     */
923    protected void toggleButtonHook() {
924        // Do nothing
925    }
926
927    protected boolean dockWhenClosingDetachedDlg() {
928        return dialogsPanel != null && titleBar != null;
929    }
930
931    /**
932     * primitive stateChangedListener for subclasses
933     */
934    protected void stateChanged() {
935        // Do nothing
936    }
937
938    /**
939     * Create a component with the given layout for this component.
940     * @param data The content to be displayed
941     * @param scroll <code>true</code> if it should be wrapped in a {@link JScrollPane}
942     * @param buttons The buttons to add.
943     * @return The component.
944     */
945    protected Component createLayout(Component data, boolean scroll, Collection<SideButton> buttons) {
946        return createLayout(data, scroll, buttons, (Collection<SideButton>[]) null);
947    }
948
949    @SafeVarargs
950    protected final Component createLayout(Component data, boolean scroll, Collection<SideButton> firstButtons,
951            Collection<SideButton>... nextButtons) {
952        if (scroll) {
953            JScrollPane sp = new JScrollPane(data);
954            if (!(data instanceof Scrollable)) {
955                GuiHelper.setDefaultIncrement(sp);
956            }
957            data = sp;
958        }
959        LinkedList<Collection<SideButton>> buttons = new LinkedList<>();
960        buttons.addFirst(firstButtons);
961        if (nextButtons != null) {
962            buttons.addAll(Arrays.asList(nextButtons));
963        }
964        add(data, BorderLayout.CENTER);
965        if (!buttons.isEmpty() && !Utils.isEmpty(buttons.get(0))) {
966            buttonsPanel = new JPanel(new GridLayout(buttons.size(), 1));
967            for (Collection<SideButton> buttonRow : buttons) {
968                if (buttonRow == null) {
969                    continue;
970                }
971                final JPanel buttonRowPanel = new JPanel(Config.getPref().getBoolean("dialog.align.left", false)
972                        ? new FlowLayout(FlowLayout.LEFT) : new GridLayout(1, buttonRow.size()));
973                buttonsPanel.add(buttonRowPanel);
974                for (SideButton sideButton : buttonRow) {
975                    buttonRowPanel.add(sideButton);
976                    javax.swing.Action action = sideButton.getAction();
977                    if (action != null) {
978                        buttonActions.add(action);
979                    } else {
980                        Logging.warn("Button " + sideButton + " doesn't have action defined");
981                        Logging.error(new Exception());
982                    }
983                }
984            }
985            add(buttonsPanel, BorderLayout.SOUTH);
986            dynamicButtonsPropertyChanged();
987        } else {
988            titleBar.buttonsHide.setVisible(false);
989        }
990
991        // Register title bar mouse listener only after buttonActions has been initialized to have a complete popup menu
992        titleBar.registerMouseListener();
993
994        return data;
995    }
996
997    /**
998     * Clear button actions. Should be used when recreating the layout with sidebuttons, and the previous sidebuttons are no longer desired.
999     * @since 16113
1000     */
1001    public void clearButtonActions() {
1002        buttonActions.clear();
1003    }
1004
1005    @Override
1006    public void eventDispatched(AWTEvent event) {
1007        if (event instanceof MouseEvent && isShowing() && !isCollapsed && isDocked && buttonHiding == ButtonHidingType.DYNAMIC
1008                && buttonsPanel != null) {
1009            Rectangle b = this.getBounds();
1010            b.setLocation(getLocationOnScreen());
1011            if (b.contains(((MouseEvent) event).getLocationOnScreen())) {
1012                if (!buttonsPanel.isVisible()) {
1013                    buttonsPanel.setVisible(true);
1014                }
1015            } else if (buttonsPanel.isVisible()) {
1016                buttonsPanel.setVisible(false);
1017            }
1018        }
1019    }
1020
1021    @Override
1022    public void preferenceChanged(PreferenceChangeEvent e) {
1023        if (e.getKey().equals(PROP_DYNAMIC_BUTTONS.getKey())) {
1024            dynamicButtonsPropertyChanged();
1025        }
1026    }
1027
1028    private void dynamicButtonsPropertyChanged() {
1029        boolean propEnabled = PROP_DYNAMIC_BUTTONS.get();
1030        try {
1031            if (propEnabled) {
1032                Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.MOUSE_MOTION_EVENT_MASK);
1033            } else {
1034                Toolkit.getDefaultToolkit().removeAWTEventListener(this);
1035            }
1036        } catch (SecurityException e) {
1037            Logging.log(Logging.LEVEL_ERROR, "Unable to add/remove AWT event listener", e);
1038        }
1039        titleBar.buttonsHide.setVisible(propEnabled);
1040        refreshHidingButtons();
1041    }
1042
1043    private void refreshHidingButtons() {
1044        titleBar.buttonsHide.setIcon(ImageProvider.get("misc", buttonHiding != ButtonHidingType.ALWAYS_SHOWN
1045            ?  /* ICON(misc/)*/ "buttonhide" :  /* ICON(misc/)*/ "buttonshow"));
1046        titleBar.buttonsHide.setEnabled(buttonHiding != ButtonHidingType.ALWAYS_HIDDEN);
1047        if (buttonsPanel != null) {
1048            buttonsPanel.setVisible(buttonHiding != ButtonHidingType.ALWAYS_HIDDEN || !isDocked);
1049        }
1050        stateChanged();
1051    }
1052
1053    /**
1054     * Returns the last used height stored in preferences or preferredHeight.
1055     * @return the last used height stored in preferences or preferredHeight
1056     * @since 14425
1057     */
1058    public int getLastHeight() {
1059        return Config.getPref().getInt(preferencePrefix+".lastHeight", preferredHeight);
1060    }
1061
1062    /**
1063     * Store the current height in preferences so that we can restore it.
1064     * @since 14425
1065     */
1066    public void rememberHeight() {
1067        int h = getHeight();
1068        Config.getPref().put(preferencePrefix+".lastHeight", Integer.toString(h));
1069    }
1070}