001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.dialogs.relation;
003
004import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
005import static org.openstreetmap.josm.tools.I18n.tr;
006
007import java.awt.BorderLayout;
008import java.awt.Dimension;
009import java.awt.FlowLayout;
010import java.awt.GridBagConstraints;
011import java.awt.GridBagLayout;
012import java.awt.Window;
013import java.awt.datatransfer.Clipboard;
014import java.awt.datatransfer.FlavorListener;
015import java.awt.event.ActionEvent;
016import java.awt.event.FocusAdapter;
017import java.awt.event.FocusEvent;
018import java.awt.event.InputEvent;
019import java.awt.event.KeyEvent;
020import java.awt.event.MouseAdapter;
021import java.awt.event.MouseEvent;
022import java.awt.event.WindowAdapter;
023import java.awt.event.WindowEvent;
024import java.util.ArrayList;
025import java.util.Arrays;
026import java.util.Collection;
027import java.util.Collections;
028import java.util.EnumSet;
029import java.util.List;
030import java.util.Set;
031import java.util.stream.Collectors;
032
033import javax.swing.AbstractAction;
034import javax.swing.Action;
035import javax.swing.BorderFactory;
036import javax.swing.InputMap;
037import javax.swing.JButton;
038import javax.swing.JComponent;
039import javax.swing.JLabel;
040import javax.swing.JMenuItem;
041import javax.swing.JOptionPane;
042import javax.swing.JPanel;
043import javax.swing.JRootPane;
044import javax.swing.JScrollPane;
045import javax.swing.JSplitPane;
046import javax.swing.JTabbedPane;
047import javax.swing.JTable;
048import javax.swing.JToolBar;
049import javax.swing.KeyStroke;
050import javax.swing.SwingConstants;
051import javax.swing.event.TableModelListener;
052
053import org.openstreetmap.josm.actions.JosmAction;
054import org.openstreetmap.josm.command.ChangeMembersCommand;
055import org.openstreetmap.josm.command.Command;
056import org.openstreetmap.josm.data.UndoRedoHandler;
057import org.openstreetmap.josm.data.UndoRedoHandler.CommandQueueListener;
058import org.openstreetmap.josm.data.osm.DefaultNameFormatter;
059import org.openstreetmap.josm.data.osm.OsmPrimitive;
060import org.openstreetmap.josm.data.osm.Relation;
061import org.openstreetmap.josm.data.osm.RelationMember;
062import org.openstreetmap.josm.data.osm.Tag;
063import org.openstreetmap.josm.data.validation.tests.RelationChecker;
064import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
065import org.openstreetmap.josm.gui.MainApplication;
066import org.openstreetmap.josm.gui.MainMenu;
067import org.openstreetmap.josm.gui.Notification;
068import org.openstreetmap.josm.gui.ScrollViewport;
069import org.openstreetmap.josm.gui.datatransfer.ClipboardUtils;
070import org.openstreetmap.josm.gui.dialogs.relation.actions.AbstractRelationEditorAction;
071import org.openstreetmap.josm.gui.dialogs.relation.actions.AddSelectedAfterSelection;
072import org.openstreetmap.josm.gui.dialogs.relation.actions.AddSelectedAtEndAction;
073import org.openstreetmap.josm.gui.dialogs.relation.actions.AddSelectedAtStartAction;
074import org.openstreetmap.josm.gui.dialogs.relation.actions.AddSelectedBeforeSelection;
075import org.openstreetmap.josm.gui.dialogs.relation.actions.ApplyAction;
076import org.openstreetmap.josm.gui.dialogs.relation.actions.CancelAction;
077import org.openstreetmap.josm.gui.dialogs.relation.actions.CopyMembersAction;
078import org.openstreetmap.josm.gui.dialogs.relation.actions.DeleteCurrentRelationAction;
079import org.openstreetmap.josm.gui.dialogs.relation.actions.DownloadIncompleteMembersAction;
080import org.openstreetmap.josm.gui.dialogs.relation.actions.DownloadSelectedIncompleteMembersAction;
081import org.openstreetmap.josm.gui.dialogs.relation.actions.DuplicateRelationAction;
082import org.openstreetmap.josm.gui.dialogs.relation.actions.EditAction;
083import org.openstreetmap.josm.gui.dialogs.relation.actions.IRelationEditorActionAccess;
084import org.openstreetmap.josm.gui.dialogs.relation.actions.IRelationEditorActionGroup;
085import org.openstreetmap.josm.gui.dialogs.relation.actions.MoveDownAction;
086import org.openstreetmap.josm.gui.dialogs.relation.actions.MoveUpAction;
087import org.openstreetmap.josm.gui.dialogs.relation.actions.OKAction;
088import org.openstreetmap.josm.gui.dialogs.relation.actions.PasteMembersAction;
089import org.openstreetmap.josm.gui.dialogs.relation.actions.RefreshAction;
090import org.openstreetmap.josm.gui.dialogs.relation.actions.RemoveAction;
091import org.openstreetmap.josm.gui.dialogs.relation.actions.RemoveSelectedAction;
092import org.openstreetmap.josm.gui.dialogs.relation.actions.ReverseAction;
093import org.openstreetmap.josm.gui.dialogs.relation.actions.SelectAction;
094import org.openstreetmap.josm.gui.dialogs.relation.actions.SelectPrimitivesForSelectedMembersAction;
095import org.openstreetmap.josm.gui.dialogs.relation.actions.SelectedMembersForSelectionAction;
096import org.openstreetmap.josm.gui.dialogs.relation.actions.SetRoleAction;
097import org.openstreetmap.josm.gui.dialogs.relation.actions.SortAction;
098import org.openstreetmap.josm.gui.dialogs.relation.actions.SortBelowAction;
099import org.openstreetmap.josm.gui.help.ContextSensitiveHelpAction;
100import org.openstreetmap.josm.gui.help.HelpUtil;
101import org.openstreetmap.josm.gui.layer.OsmDataLayer;
102import org.openstreetmap.josm.gui.tagging.TagEditorModel;
103import org.openstreetmap.josm.gui.tagging.TagEditorPanel;
104import org.openstreetmap.josm.gui.tagging.ac.AutoCompletingTextField;
105import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionList;
106import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionManager;
107import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;
108import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetHandler;
109import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetType;
110import org.openstreetmap.josm.gui.tagging.presets.TaggingPresets;
111import org.openstreetmap.josm.gui.util.WindowGeometry;
112import org.openstreetmap.josm.spi.preferences.Config;
113import org.openstreetmap.josm.tools.CheckParameterUtil;
114import org.openstreetmap.josm.tools.InputMapUtils;
115import org.openstreetmap.josm.tools.Logging;
116import org.openstreetmap.josm.tools.Shortcut;
117import org.openstreetmap.josm.tools.Utils;
118
119/**
120 * This dialog is for editing relations.
121 * @since 343
122 */
123public class GenericRelationEditor extends RelationEditor implements CommandQueueListener {
124    /** the tag table and its model */
125    private final TagEditorPanel tagEditorPanel;
126    private final ReferringRelationsBrowser referrerBrowser;
127
128    /** the member table and its model */
129    private final MemberTable memberTable;
130    private final MemberTableModel memberTableModel;
131
132    /** the selection table and its model */
133    private final SelectionTable selectionTable;
134    private final SelectionTableModel selectionTableModel;
135
136    private final AutoCompletingTextField tfRole;
137    private final RelationEditorActionAccess actionAccess;
138
139    /**
140     * the menu item in the windows menu. Required to properly hide on dialog close.
141     */
142    private JMenuItem windowMenuItem;
143    /**
144     * Action for performing the {@link RefreshAction}
145     */
146    private final RefreshAction refreshAction;
147    /**
148     * Action for performing the {@link ApplyAction}
149     */
150    private final ApplyAction applyAction;
151    /**
152     * Action for performing the {@link SelectAction}
153     */
154    private final SelectAction selectAction;
155    /**
156     * Action for performing the {@link CancelAction}
157     */
158    private final CancelAction cancelAction;
159    /**
160     * A list of listeners that need to be notified on clipboard content changes.
161     */
162    private final ArrayList<FlavorListener> clipboardListeners = new ArrayList<>();
163    /**
164     * Flag that signals that this instance of the relation editor is currently saving the relation
165     */
166    private boolean isSaving;
167
168    /**
169     * Creates a new relation editor for the given relation. The relation will be saved if the user
170     * selects "ok" in the editor.
171     * <p>
172     * If no relation is given, will create an editor for a new relation.
173     *
174     * @param layer the {@link OsmDataLayer} the new or edited relation belongs to
175     * @param relation relation to edit, or null to create a new one.
176     * @param selectedMembers a collection of members which shall be selected initially
177     */
178    public GenericRelationEditor(OsmDataLayer layer, Relation relation, Collection<RelationMember> selectedMembers) {
179        super(layer, relation);
180
181        setRememberWindowGeometry(getClass().getName() + ".geometry",
182                WindowGeometry.centerInWindow(MainApplication.getMainFrame(), new Dimension(700, 650)));
183
184        final TaggingPresetHandler presetHandler = new TaggingPresetHandler() {
185
186            @Override
187            public void updateTags(List<Tag> tags) {
188                tagEditorPanel.getModel().updateTags(tags);
189            }
190
191            @Override
192            public Collection<OsmPrimitive> getSelection() {
193                // Creating a new relation will open the window. The relation, in that case, will be null.
194                if (getRelation() == null) {
195                    Relation relation = new Relation();
196                    tagEditorPanel.getModel().applyToPrimitive(relation);
197                    memberTableModel.applyToRelation(relation);
198                    return Collections.singletonList(relation);
199                }
200                return Collections.singletonList(getRelation());
201            }
202        };
203
204        // init the various models
205        //
206        memberTableModel = new MemberTableModel(relation, getLayer(), presetHandler);
207        memberTableModel.register();
208        selectionTableModel = new SelectionTableModel(getLayer());
209        selectionTableModel.register();
210        ReferringRelationsBrowserModel referrerModel = new ReferringRelationsBrowserModel(relation);
211
212        tagEditorPanel = new TagEditorPanel(relation, presetHandler);
213        populateModels(relation);
214        tagEditorPanel.getModel().ensureOneTag();
215
216        // setting up the member table
217        memberTable = new MemberTable(getLayer(), getRelation(), memberTableModel);
218        memberTable.addMouseListener(new MemberTableDblClickAdapter());
219        memberTableModel.addMemberModelListener(memberTable);
220
221        MemberRoleCellEditor ce = (MemberRoleCellEditor) memberTable.getColumnModel().getColumn(0).getCellEditor();
222        selectionTable = new SelectionTable(selectionTableModel, memberTableModel);
223        selectionTable.setRowHeight(ce.getEditor().getPreferredSize().height);
224
225        LeftButtonToolbar leftButtonToolbar = new LeftButtonToolbar(new RelationEditorActionAccess());
226        tfRole = buildRoleTextField(this);
227
228        JSplitPane pane = buildSplitPane(
229                buildTagEditorPanel(tagEditorPanel),
230                buildMemberEditorPanel(leftButtonToolbar, new RelationEditorActionAccess()),
231                this);
232        pane.setPreferredSize(new Dimension(100, 100));
233
234        JPanel pnl = new JPanel(new BorderLayout());
235        pnl.add(pane, BorderLayout.CENTER);
236        pnl.setBorder(BorderFactory.createRaisedBevelBorder());
237
238        getContentPane().setLayout(new BorderLayout());
239        final JTabbedPane tabbedPane;
240        tabbedPane = new JTabbedPane();
241        tabbedPane.add(tr("Tags and Members"), pnl);
242        referrerBrowser = new ReferringRelationsBrowser(getLayer(), referrerModel);
243        tabbedPane.add(tr("Parent Relations"), referrerBrowser);
244        tabbedPane.add(tr("Child Relations"), new ChildRelationBrowser(getLayer(), relation));
245        tabbedPane.addChangeListener(e -> {
246            JTabbedPane sourceTabbedPane = (JTabbedPane) e.getSource();
247            int index = sourceTabbedPane.getSelectedIndex();
248            String title = sourceTabbedPane.getTitleAt(index);
249            if (title.equals(tr("Parent Relations"))) {
250                referrerBrowser.init();
251            }
252        });
253
254        actionAccess = new RelationEditorActionAccess();
255
256        refreshAction = new RefreshAction(actionAccess);
257        applyAction = new ApplyAction(actionAccess);
258        selectAction = new SelectAction(actionAccess);
259        // Action for performing the {@link DuplicateRelationAction}
260        final DuplicateRelationAction duplicateAction = new DuplicateRelationAction(actionAccess);
261        // Action for performing the {@link DeleteCurrentRelationAction}
262        final DeleteCurrentRelationAction deleteAction = new DeleteCurrentRelationAction(actionAccess);
263
264        this.memberTableModel.addTableModelListener(applyAction);
265        this.tagEditorPanel.getModel().addTableModelListener(applyAction);
266
267        addPropertyChangeListener(deleteAction);
268
269        // Action for performing the {@link OKAction}
270        final OKAction okAction = new OKAction(actionAccess);
271        cancelAction = new CancelAction(actionAccess);
272
273        getContentPane().add(buildToolBar(refreshAction, applyAction, selectAction, duplicateAction, deleteAction), BorderLayout.NORTH);
274        getContentPane().add(tabbedPane, BorderLayout.CENTER);
275        getContentPane().add(buildOkCancelButtonPanel(okAction, deleteAction, cancelAction), BorderLayout.SOUTH);
276
277        setSize(findMaxDialogSize());
278
279        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
280        addWindowListener(
281                new WindowAdapter() {
282                    @Override
283                    public void windowOpened(WindowEvent e) {
284                        cleanSelfReferences(memberTableModel, getRelation());
285                    }
286
287                    @Override
288                    public void windowClosing(WindowEvent e) {
289                        cancel();
290                    }
291                }
292        );
293        InputMapUtils.addCtrlEnterAction(getRootPane(), okAction);
294        // CHECKSTYLE.OFF: LineLength
295        registerCopyPasteAction(tagEditorPanel.getPasteAction(), "PASTE_TAGS",
296                Shortcut.registerShortcut("system:pastestyle", tr("Edit: {0}", tr("Paste Tags")), KeyEvent.VK_V, Shortcut.CTRL_SHIFT).getKeyStroke(),
297                getRootPane(), memberTable, selectionTable);
298        // CHECKSTYLE.ON: LineLength
299
300        KeyStroke key = Shortcut.getPasteKeyStroke();
301        if (key != null) {
302            // handle uncommon situation, that user has no keystroke assigned to paste
303            registerCopyPasteAction(new PasteMembersAction(actionAccess) {
304                private static final long serialVersionUID = 1L;
305
306                @Override
307                public void actionPerformed(ActionEvent e) {
308                    super.actionPerformed(e);
309                    tfRole.requestFocusInWindow();
310                }
311            }, "PASTE_MEMBERS", key, getRootPane(), memberTable, selectionTable);
312        }
313        key = Shortcut.getCopyKeyStroke();
314        if (key != null) {
315            // handle uncommon situation, that user has no keystroke assigned to copy
316            registerCopyPasteAction(new CopyMembersAction(actionAccess, true),
317                    "COPY_MEMBERS", key, getRootPane(), memberTable, selectionTable);
318        }
319        key = Shortcut.getCutKeyStroke();
320        if (key != null) {
321            // handle uncommon situation, that user has no keystroke assigned to cut
322            registerCopyPasteAction(new CopyMembersAction(actionAccess, false),
323                    "CUT_MEMBERS", key, getRootPane(), memberTable, selectionTable);
324        }
325        tagEditorPanel.setNextFocusComponent(memberTable);
326        selectionTable.setFocusable(false);
327        memberTableModel.setSelectedMembers(selectedMembers);
328        HelpUtil.setHelpContext(getRootPane(), ht("/Dialog/RelationEditor"));
329        UndoRedoHandler.getInstance().addCommandQueueListener(this);
330    }
331
332    @Override
333    public void reloadDataFromRelation() {
334        setRelation(getRelation());
335        populateModels(getRelation());
336        refreshAction.updateEnabledState();
337    }
338
339    private void populateModels(Relation relation) {
340        if (relation != null) {
341            tagEditorPanel.getModel().initFromPrimitive(relation);
342            memberTableModel.populate(relation);
343            if (!getLayer().data.getRelations().contains(relation)) {
344                // treat it as a new relation if it doesn't exist in the data set yet.
345                setRelation(null);
346            }
347        } else {
348            tagEditorPanel.getModel().clear();
349            memberTableModel.populate(null);
350        }
351    }
352
353    /**
354     * Apply changes.
355     * @see ApplyAction
356     */
357    public void apply() {
358        applyAction.actionPerformed(null);
359    }
360
361    /**
362     * Select relation.
363     * @see SelectAction
364     * @since 12933
365     */
366    public void select() {
367        selectAction.actionPerformed(null);
368    }
369
370    /**
371     * Cancel changes.
372     * @see CancelAction
373     */
374    public void cancel() {
375        cancelAction.actionPerformed(null);
376    }
377
378    /**
379     * Creates the toolbar
380     * @param actions relation toolbar actions
381     * @return the toolbar
382     * @since 12933
383     */
384    protected static JToolBar buildToolBar(AbstractRelationEditorAction... actions) {
385        JToolBar tb = new JToolBar();
386        tb.setFloatable(false);
387        for (AbstractRelationEditorAction action : actions) {
388            tb.add(action);
389        }
390        return tb;
391    }
392
393    /**
394     * builds the panel with the OK and the Cancel button
395     * @param okAction OK action
396     * @param deleteAction  Delete action
397     * @param cancelAction Cancel action
398     *
399     * @return the panel with the OK and the Cancel button
400     */
401    protected final JPanel buildOkCancelButtonPanel(OKAction okAction, DeleteCurrentRelationAction deleteAction,
402            CancelAction cancelAction) {
403        final JPanel pnl = new JPanel(new FlowLayout(FlowLayout.CENTER));
404        final JButton okButton = new JButton(okAction);
405        final JButton deleteButton = new JButton(deleteAction);
406        okButton.setPreferredSize(deleteButton.getPreferredSize());
407        pnl.add(okButton);
408        pnl.add(deleteButton);
409        pnl.add(new JButton(cancelAction));
410        pnl.add(new JButton(new ContextSensitiveHelpAction(ht("/Dialog/RelationEditor"))));
411        // Keep users from saving invalid relations -- a relation MUST have at least a tag with the key "type"
412        // AND must contain at least one other OSM object.
413        final TableModelListener listener = l -> updateOkPanel(okButton, deleteButton);
414        listener.tableChanged(null);
415        this.memberTableModel.addTableModelListener(listener);
416        this.tagEditorPanel.getModel().addTableModelListener(listener);
417        return pnl;
418    }
419
420    /**
421     * Update the OK panel area with a temporary relation that looks if it were to be saved now.
422     * @param okButton The OK button
423     * @param deleteButton The delete button
424     */
425    private void updateOkPanel(JButton okButton, JButton deleteButton) {
426        boolean useful = this.actionAccess.wouldRelationBeUseful();
427        okButton.setVisible(useful || this.getRelationSnapshot() == null);
428        deleteButton.setVisible(!useful && this.getRelationSnapshot() != null);
429        if (this.getRelationSnapshot() == null && !useful) {
430            okButton.setText(tr("Delete"));
431        } else {
432            okButton.setText(tr("OK"));
433        }
434    }
435
436    /**
437     * builds the panel with the tag editor
438     * @param tagEditorPanel tag editor panel
439     *
440     * @return the panel with the tag editor
441     */
442    protected static JPanel buildTagEditorPanel(TagEditorPanel tagEditorPanel) {
443        JPanel pnl = new JPanel(new GridBagLayout());
444
445        GridBagConstraints gc = new GridBagConstraints();
446        gc.gridx = 0;
447        gc.gridy = 0;
448        gc.gridheight = 1;
449        gc.gridwidth = 1;
450        gc.fill = GridBagConstraints.HORIZONTAL;
451        gc.anchor = GridBagConstraints.FIRST_LINE_START;
452        gc.weightx = 1.0;
453        gc.weighty = 0.0;
454        pnl.add(new JLabel(tr("Tags")), gc);
455
456        gc.gridx = 0;
457        gc.gridy = 1;
458        gc.fill = GridBagConstraints.BOTH;
459        gc.anchor = GridBagConstraints.CENTER;
460        gc.weightx = 1.0;
461        gc.weighty = 1.0;
462        pnl.add(tagEditorPanel, gc);
463        return pnl;
464    }
465
466    /**
467     * builds the role text field
468     * @param re relation editor
469     * @return the role text field
470     */
471    protected static AutoCompletingTextField buildRoleTextField(final IRelationEditor re) {
472        final AutoCompletingTextField tfRole = new AutoCompletingTextField(10);
473        tfRole.setToolTipText(tr("Enter a role and apply it to the selected relation members"));
474        tfRole.addFocusListener(new FocusAdapter() {
475            @Override
476            public void focusGained(FocusEvent e) {
477                tfRole.selectAll();
478            }
479        });
480        tfRole.setAutoCompletionList(new AutoCompletionList());
481        tfRole.addFocusListener(
482                new FocusAdapter() {
483                    @Override
484                    public void focusGained(FocusEvent e) {
485                        AutoCompletionList list = tfRole.getAutoCompletionList();
486                        if (list != null) {
487                            list.clear();
488                            AutoCompletionManager.of(re.getLayer().data).populateWithMemberRoles(list, re.getRelation());
489                        }
490                    }
491                }
492        );
493        tfRole.setText(Config.getPref().get("relation.editor.generic.lastrole", ""));
494        return tfRole;
495    }
496
497    /**
498     * builds the panel for the relation member editor
499     * @param leftButtonToolbar left button toolbar
500     * @param editorAccess The relation editor
501     *
502     * @return the panel for the relation member editor
503     */
504    static JPanel buildMemberEditorPanel(
505            LeftButtonToolbar leftButtonToolbar, IRelationEditorActionAccess editorAccess) {
506        final JPanel pnl = new JPanel(new GridBagLayout());
507        final JScrollPane scrollPane = new JScrollPane(editorAccess.getMemberTable());
508
509        GridBagConstraints gc = new GridBagConstraints();
510        gc.gridx = 0;
511        gc.gridy = 0;
512        gc.gridwidth = 2;
513        gc.fill = GridBagConstraints.HORIZONTAL;
514        gc.anchor = GridBagConstraints.FIRST_LINE_START;
515        gc.weightx = 1.0;
516        gc.weighty = 0.0;
517        pnl.add(new JLabel(tr("Members")), gc);
518
519        gc.gridx = 0;
520        gc.gridy = 1;
521        gc.gridheight = 2;
522        gc.gridwidth = 1;
523        gc.fill = GridBagConstraints.VERTICAL;
524        gc.anchor = GridBagConstraints.NORTHWEST;
525        gc.weightx = 0.0;
526        gc.weighty = 1.0;
527        pnl.add(new ScrollViewport(leftButtonToolbar, ScrollViewport.VERTICAL_DIRECTION), gc);
528
529        gc.gridx = 1;
530        gc.gridy = 1;
531        gc.gridheight = 1;
532        gc.fill = GridBagConstraints.BOTH;
533        gc.anchor = GridBagConstraints.CENTER;
534        gc.weightx = 0.6;
535        gc.weighty = 1.0;
536        pnl.add(scrollPane, gc);
537
538        // --- role editing
539        JPanel p3 = new JPanel(new FlowLayout(FlowLayout.LEFT));
540        p3.add(new JLabel(tr("Apply Role:")));
541        p3.add(editorAccess.getTextFieldRole());
542        SetRoleAction setRoleAction = new SetRoleAction(editorAccess);
543        editorAccess.getMemberTableModel().getSelectionModel().addListSelectionListener(setRoleAction);
544        editorAccess.getTextFieldRole().getDocument().addDocumentListener(setRoleAction);
545        editorAccess.getTextFieldRole().addActionListener(setRoleAction);
546        editorAccess.getMemberTableModel().getSelectionModel().addListSelectionListener(
547                e -> editorAccess.getTextFieldRole().setEnabled(editorAccess.getMemberTable().getSelectedRowCount() > 0)
548        );
549        editorAccess.getTextFieldRole().setEnabled(editorAccess.getMemberTable().getSelectedRowCount() > 0);
550        JButton btnApply = new JButton(setRoleAction);
551        btnApply.setPreferredSize(new Dimension(20, 20));
552        btnApply.setText("");
553        p3.add(btnApply);
554
555        gc.gridx = 1;
556        gc.gridy = 2;
557        gc.fill = GridBagConstraints.HORIZONTAL;
558        gc.anchor = GridBagConstraints.LAST_LINE_START;
559        gc.weightx = 1.0;
560        gc.weighty = 0.0;
561        pnl.add(p3, gc);
562
563        JPanel pnl2 = new JPanel(new GridBagLayout());
564
565        gc.gridx = 0;
566        gc.gridy = 0;
567        gc.gridheight = 1;
568        gc.gridwidth = 3;
569        gc.fill = GridBagConstraints.HORIZONTAL;
570        gc.anchor = GridBagConstraints.FIRST_LINE_START;
571        gc.weightx = 1.0;
572        gc.weighty = 0.0;
573        pnl2.add(new JLabel(tr("Selection")), gc);
574
575        gc.gridx = 0;
576        gc.gridy = 1;
577        gc.gridheight = 1;
578        gc.gridwidth = 1;
579        gc.fill = GridBagConstraints.VERTICAL;
580        gc.anchor = GridBagConstraints.NORTHWEST;
581        gc.weightx = 0.0;
582        gc.weighty = 1.0;
583        pnl2.add(new ScrollViewport(buildSelectionControlButtonToolbar(editorAccess),
584                ScrollViewport.VERTICAL_DIRECTION), gc);
585
586        gc.gridx = 1;
587        gc.gridy = 1;
588        gc.weightx = 1.0;
589        gc.weighty = 1.0;
590        gc.fill = GridBagConstraints.BOTH;
591        pnl2.add(buildSelectionTablePanel(editorAccess.getSelectionTable()), gc);
592
593        final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
594        splitPane.setLeftComponent(pnl);
595        splitPane.setRightComponent(pnl2);
596        splitPane.setOneTouchExpandable(false);
597        if (editorAccess.getEditor() instanceof Window) {
598            ((Window) editorAccess.getEditor()).addWindowListener(new WindowAdapter() {
599                @Override
600                public void windowOpened(WindowEvent e) {
601                    // has to be called when the window is visible, otherwise no effect
602                    splitPane.setDividerLocation(0.6);
603                }
604            });
605        }
606
607        JPanel pnl3 = new JPanel(new BorderLayout());
608        pnl3.add(splitPane, BorderLayout.CENTER);
609
610        return pnl3;
611    }
612
613    /**
614     * builds the panel with the table displaying the currently selected primitives
615     * @param selectionTable selection table
616     *
617     * @return panel with current selection
618     */
619    protected static JPanel buildSelectionTablePanel(SelectionTable selectionTable) {
620        JPanel pnl = new JPanel(new BorderLayout());
621        pnl.add(new JScrollPane(selectionTable), BorderLayout.CENTER);
622        return pnl;
623    }
624
625    /**
626     * builds the {@link JSplitPane} which divides the editor in an upper and a lower half
627     * @param top top panel
628     * @param bottom bottom panel
629     * @param re relation editor
630     *
631     * @return the split panel
632     */
633    protected static JSplitPane buildSplitPane(JPanel top, JPanel bottom, IRelationEditor re) {
634        final JSplitPane pane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
635        pane.setTopComponent(top);
636        pane.setBottomComponent(bottom);
637        pane.setOneTouchExpandable(true);
638        if (re instanceof Window) {
639            ((Window) re).addWindowListener(new WindowAdapter() {
640                @Override
641                public void windowOpened(WindowEvent e) {
642                    // has to be called when the window is visible, otherwise no effect
643                    pane.setDividerLocation(0.3);
644                }
645            });
646        }
647        return pane;
648    }
649
650    /**
651     * The toolbar with the buttons on the left
652     */
653    static class LeftButtonToolbar extends JToolBar {
654        private static final long serialVersionUID = 1L;
655
656        /**
657         * Constructs a new {@code LeftButtonToolbar}.
658         * @param editorAccess relation editor
659         */
660        LeftButtonToolbar(IRelationEditorActionAccess editorAccess) {
661            setOrientation(SwingConstants.VERTICAL);
662            setFloatable(false);
663
664            List<IRelationEditorActionGroup> groups = new ArrayList<>();
665            // Move
666            groups.add(buildNativeGroup(10,
667                    new MoveUpAction(editorAccess, "moveUp"),
668                    new MoveDownAction(editorAccess, "moveDown")
669                    ));
670            // Edit
671            groups.add(buildNativeGroup(20,
672                    new EditAction(editorAccess),
673                    new RemoveAction(editorAccess, "removeSelected")
674                    ));
675            // Sort
676            groups.add(buildNativeGroup(30,
677                    new SortAction(editorAccess),
678                    new SortBelowAction(editorAccess)
679                    ));
680            // Reverse
681            groups.add(buildNativeGroup(40,
682                    new ReverseAction(editorAccess)
683                    ));
684            // Download
685            groups.add(buildNativeGroup(50,
686                    new DownloadIncompleteMembersAction(editorAccess, "downloadIncomplete"),
687                    new DownloadSelectedIncompleteMembersAction(editorAccess)
688                    ));
689            groups.addAll(RelationEditorHooks.getMemberActions());
690
691            IRelationEditorActionGroup.fillToolbar(this, groups, editorAccess);
692
693
694            InputMap inputMap = editorAccess.getMemberTable().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
695            inputMap.put((KeyStroke) new RemoveAction(editorAccess, "removeSelected")
696                    .getValue(Action.ACCELERATOR_KEY), "removeSelected");
697            inputMap.put((KeyStroke) new MoveUpAction(editorAccess, "moveUp")
698                    .getValue(Action.ACCELERATOR_KEY), "moveUp");
699            inputMap.put((KeyStroke) new MoveDownAction(editorAccess, "moveDown")
700                    .getValue(Action.ACCELERATOR_KEY), "moveDown");
701            inputMap.put((KeyStroke) new DownloadIncompleteMembersAction(
702                    editorAccess, "downloadIncomplete").getValue(Action.ACCELERATOR_KEY), "downloadIncomplete");
703        }
704    }
705
706    /**
707     * build the toolbar with the buttons for adding or removing the current selection
708     * @param editorAccess relation editor
709     *
710     * @return control buttons panel for selection/members
711     */
712    protected static JToolBar buildSelectionControlButtonToolbar(IRelationEditorActionAccess editorAccess) {
713        JToolBar tb = new JToolBar(SwingConstants.VERTICAL);
714        tb.setFloatable(false);
715
716        List<IRelationEditorActionGroup> groups = new ArrayList<>();
717        groups.add(buildNativeGroup(10,
718                new AddSelectedAtStartAction(editorAccess),
719                new AddSelectedBeforeSelection(editorAccess),
720                new AddSelectedAfterSelection(editorAccess),
721                new AddSelectedAtEndAction(editorAccess)
722                ));
723        groups.add(buildNativeGroup(20,
724                new SelectedMembersForSelectionAction(editorAccess),
725                new SelectPrimitivesForSelectedMembersAction(editorAccess)
726                ));
727        groups.add(buildNativeGroup(30,
728                new RemoveSelectedAction(editorAccess)
729                ));
730        groups.addAll(RelationEditorHooks.getSelectActions());
731
732        IRelationEditorActionGroup.fillToolbar(tb, groups, editorAccess);
733        return tb;
734    }
735
736    private static IRelationEditorActionGroup buildNativeGroup(int order, AbstractRelationEditorAction... actions) {
737        return new IRelationEditorActionGroup() {
738            @Override
739            public int order() {
740                return order;
741            }
742
743            @Override
744            public List<AbstractRelationEditorAction> getActions(IRelationEditorActionAccess editorAccess) {
745                return Arrays.asList(actions);
746            }
747        };
748    }
749
750    @Override
751    protected Dimension findMaxDialogSize() {
752        return new Dimension(700, 650);
753    }
754
755    @Override
756    public void setVisible(boolean visible) {
757        if (isVisible() == visible) {
758            return;
759        }
760        if (visible) {
761            tagEditorPanel.initAutoCompletion(getLayer());
762        }
763        super.setVisible(visible);
764        Clipboard clipboard = ClipboardUtils.getClipboard();
765        if (visible) {
766            RelationDialogManager.getRelationDialogManager().positionOnScreen(this);
767            if (windowMenuItem == null) {
768                windowMenuItem = addToWindowMenu(this, getLayer().getName());
769            }
770            tagEditorPanel.requestFocusInWindow();
771            for (FlavorListener listener : clipboardListeners) {
772                clipboard.addFlavorListener(listener);
773            }
774        } else {
775            // make sure all registered listeners are unregistered
776            //
777            memberTable.stopHighlighting();
778            selectionTableModel.unregister();
779            memberTableModel.unregister();
780            memberTable.unregisterListeners();
781
782            if (windowMenuItem != null) {
783                MainApplication.getMenu().windowMenu.remove(windowMenuItem);
784                windowMenuItem = null;
785            }
786            for (FlavorListener listener : clipboardListeners) {
787                clipboard.removeFlavorListener(listener);
788            }
789            dispose();
790        }
791    }
792
793    /**
794     * Adds current relation editor to the windows menu (in the "volatile" group)
795     * @param re relation editor
796     * @param layerName layer name
797     * @return created menu item
798     */
799    protected static JMenuItem addToWindowMenu(IRelationEditor re, String layerName) {
800        Relation r = re.getRelation();
801        String name = r == null ? tr("New relation") : r.getLocalName();
802        JosmAction focusAction = new JosmAction(
803                tr("Relation Editor: {0}", name == null && r != null ? r.getId() : name),
804                "dialogs/relationlist",
805                tr("Focus Relation Editor with relation ''{0}'' in layer ''{1}''", name, layerName),
806                null, false, false) {
807            private static final long serialVersionUID = 1L;
808
809            @Override
810            public void actionPerformed(ActionEvent e) {
811                ((RelationEditor) getValue("relationEditor")).setVisible(true);
812            }
813        };
814        focusAction.putValue("relationEditor", re);
815        return MainMenu.add(MainApplication.getMenu().windowMenu, focusAction, MainMenu.WINDOW_MENU_GROUP.VOLATILE);
816    }
817
818    /**
819     * checks whether the current relation has members referring to itself. If so,
820     * warns the users and provides an option for removing these members.
821     * @param memberTableModel member table model
822     * @param relation relation
823     */
824    protected static void cleanSelfReferences(MemberTableModel memberTableModel, Relation relation) {
825        List<OsmPrimitive> toCheck = new ArrayList<>();
826        toCheck.add(relation);
827        if (memberTableModel.hasMembersReferringTo(toCheck)) {
828            int ret = ConditionalOptionPaneUtil.showOptionDialog(
829                    "clean_relation_self_references",
830                    MainApplication.getMainFrame(),
831                    tr("<html>There is at least one member in this relation referring<br>"
832                            + "to the relation itself.<br>"
833                            + "This creates circular dependencies and is discouraged.<br>"
834                            + "How do you want to proceed with circular dependencies?</html>"),
835                            tr("Warning"),
836                            JOptionPane.YES_NO_OPTION,
837                            JOptionPane.WARNING_MESSAGE,
838                            new String[]{tr("Remove them, clean up relation"), tr("Ignore them, leave relation as is")},
839                            tr("Remove them, clean up relation")
840            );
841            switch (ret) {
842            case ConditionalOptionPaneUtil.DIALOG_DISABLED_OPTION:
843            case JOptionPane.CLOSED_OPTION:
844            case JOptionPane.NO_OPTION:
845                return;
846            case JOptionPane.YES_OPTION:
847                memberTableModel.removeMembersReferringTo(toCheck);
848                break;
849            default: // Do nothing
850            }
851        }
852    }
853
854    private void registerCopyPasteAction(AbstractAction action, Object actionName, KeyStroke shortcut,
855            JRootPane rootPane, JTable... tables) {
856        if (shortcut == null) {
857            Logging.warn("No shortcut provided for the Paste action in Relation editor dialog");
858        } else {
859            int mods = shortcut.getModifiers();
860            int code = shortcut.getKeyCode();
861            if (code != KeyEvent.VK_INSERT && (mods == 0 || mods == InputEvent.SHIFT_DOWN_MASK)) {
862                Logging.info(tr("Sorry, shortcut \"{0}\" can not be enabled in Relation editor dialog"), shortcut);
863                return;
864            }
865        }
866        rootPane.getActionMap().put(actionName, action);
867        if (shortcut != null) {
868            rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(shortcut, actionName);
869            // Assign also to JTables because they have their own Copy&Paste implementation
870            // (which is disabled in this case but eats key shortcuts anyway)
871            for (JTable table : tables) {
872                table.getInputMap(JComponent.WHEN_FOCUSED).put(shortcut, actionName);
873                table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(shortcut, actionName);
874                table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(shortcut, actionName);
875            }
876        }
877        if (action instanceof FlavorListener) {
878            clipboardListeners.add((FlavorListener) action);
879        }
880    }
881
882    @Override
883    public void dispose() {
884        refreshAction.destroy();
885        UndoRedoHandler.getInstance().removeCommandQueueListener(this);
886        super.dispose(); // call before setting relation to null, see #20304
887        setRelation(null);
888    }
889
890    /**
891     * Exception thrown when user aborts add operation.
892     */
893    public static class AddAbortException extends Exception {
894    }
895
896    /**
897     * Asks confirmation before adding a primitive.
898     * @param primitive primitive to add
899     * @return {@code true} is user confirms the operation, {@code false} otherwise
900     * @throws AddAbortException if user aborts operation
901     */
902    public static boolean confirmAddingPrimitive(OsmPrimitive primitive) throws AddAbortException {
903        String msg = tr("<html>This relation already has one or more members referring to<br>"
904                + "the object ''{0}''<br>"
905                + "<br>"
906                + "Do you really want to add another relation member?</html>",
907                Utils.escapeReservedCharactersHTML(primitive.getDisplayName(DefaultNameFormatter.getInstance()))
908            );
909        int ret = ConditionalOptionPaneUtil.showOptionDialog(
910                "add_primitive_to_relation",
911                MainApplication.getMainFrame(),
912                msg,
913                tr("Multiple members referring to same object."),
914                JOptionPane.YES_NO_CANCEL_OPTION,
915                JOptionPane.WARNING_MESSAGE,
916                null,
917                null
918        );
919        switch (ret) {
920        case ConditionalOptionPaneUtil.DIALOG_DISABLED_OPTION:
921        case JOptionPane.YES_OPTION:
922            return true;
923        case JOptionPane.NO_OPTION:
924        case JOptionPane.CLOSED_OPTION:
925            return false;
926        case JOptionPane.CANCEL_OPTION:
927        default:
928            throw new AddAbortException();
929        }
930    }
931
932    /**
933     * Warn about circular references.
934     * @param primitive the concerned primitive
935     */
936    public static void warnOfCircularReferences(OsmPrimitive primitive) {
937        warnOfCircularReferences(primitive, Collections.emptyList());
938    }
939
940    /**
941     * Warn about circular references.
942     * @param primitive the concerned primitive
943     * @param loop list of relation that form the circular dependencies.
944     *   Only used to report the loop if more than one relation is involved.
945     * @since 16651
946     */
947    public static void warnOfCircularReferences(OsmPrimitive primitive, List<Relation> loop) {
948        final String msg;
949        DefaultNameFormatter df = DefaultNameFormatter.getInstance();
950        if (loop.size() <= 2) {
951            msg = tr("<html>You are trying to add a relation to itself.<br>"
952                    + "<br>"
953                    + "This generates a circular dependency of parent/child elements and is therefore discouraged.<br>"
954                    + "Skipping relation ''{0}''.</html>",
955                    Utils.escapeReservedCharactersHTML(primitive.getDisplayName(df)));
956        } else {
957            msg = tr("<html>You are trying to add a child relation which refers to the parent relation.<br>"
958                    + "<br>"
959                    + "This generates a circular dependency of parent/child elements and is therefore discouraged.<br>"
960                    + "Skipping relation ''{0}''." + "<br>"
961                    + "Relations that would generate the circular dependency:<br>{1}</html>",
962                    Utils.escapeReservedCharactersHTML(primitive.getDisplayName(df)),
963                    loop.stream().map(p -> Utils.escapeReservedCharactersHTML(p.getDisplayName(df)))
964                            .collect(Collectors.joining(" -> <br>")));
965        }
966        JOptionPane.showMessageDialog(
967                MainApplication.getMainFrame(),
968                msg,
969                tr("Warning"),
970                JOptionPane.WARNING_MESSAGE);
971    }
972
973    /**
974     * Adds primitives to a given relation.
975     * @param orig The relation to modify
976     * @param primitivesToAdd The primitives to add as relation members
977     * @return The resulting command
978     * @throws IllegalArgumentException if orig is null
979     */
980    public static Command addPrimitivesToRelation(final Relation orig, Collection<? extends OsmPrimitive> primitivesToAdd) {
981        CheckParameterUtil.ensureParameterNotNull(orig, "orig");
982        try {
983            final Collection<TaggingPreset> presets = TaggingPresets.getMatchingPresets(
984                    EnumSet.of(TaggingPresetType.forPrimitive(orig)), orig.getKeys(), false);
985            Relation target = new Relation(orig);
986            boolean modified = false;
987            for (OsmPrimitive p : primitivesToAdd) {
988                if (p instanceof Relation) {
989                    List<Relation> loop = RelationChecker.checkAddMember(target, (Relation) p);
990                    if (!loop.isEmpty() && loop.get(0).equals(loop.get(loop.size() - 1))) {
991                        warnOfCircularReferences(p, loop);
992                        continue;
993                    }
994                } else if (MemberTableModel.hasMembersReferringTo(target.getMembers(), Collections.singleton(p))
995                        && !confirmAddingPrimitive(p)) {
996                    continue;
997                }
998                final Set<String> roles = findSuggestedRoles(presets, p);
999                target.addMember(new RelationMember(roles.size() == 1 ? roles.iterator().next() : "", p));
1000                modified = true;
1001            }
1002            List<RelationMember> members = new ArrayList<>(target.getMembers());
1003            target.setMembers(null); // see #19885
1004            return modified ? new ChangeMembersCommand(orig, members) : null;
1005        } catch (AddAbortException ign) {
1006            Logging.trace(ign);
1007            return null;
1008        }
1009    }
1010
1011    protected static Set<String> findSuggestedRoles(final Collection<TaggingPreset> presets, OsmPrimitive p) {
1012        return presets.stream()
1013                .map(preset -> preset.suggestRoleForOsmPrimitive(p))
1014                .filter(role -> !Utils.isEmpty(role))
1015                .collect(Collectors.toSet());
1016    }
1017
1018    class MemberTableDblClickAdapter extends MouseAdapter {
1019        @Override
1020        public void mouseClicked(MouseEvent e) {
1021            if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
1022                new EditAction(actionAccess).actionPerformed(null);
1023            }
1024        }
1025    }
1026
1027    private final class RelationEditorActionAccess implements IRelationEditorActionAccess {
1028
1029        @Override
1030        public MemberTable getMemberTable() {
1031            return memberTable;
1032        }
1033
1034        @Override
1035        public MemberTableModel getMemberTableModel() {
1036            return memberTableModel;
1037        }
1038
1039        @Override
1040        public SelectionTable getSelectionTable() {
1041            return selectionTable;
1042        }
1043
1044        @Override
1045        public SelectionTableModel getSelectionTableModel() {
1046            return selectionTableModel;
1047        }
1048
1049        @Override
1050        public IRelationEditor getEditor() {
1051            return GenericRelationEditor.this;
1052        }
1053
1054        @Override
1055        public TagEditorModel getTagModel() {
1056            return tagEditorPanel.getModel();
1057        }
1058
1059        @Override
1060        public AutoCompletingTextField getTextFieldRole() {
1061            return tfRole;
1062        }
1063
1064    }
1065
1066    @Override
1067    public void commandChanged(int queueSize, int redoSize) {
1068        Relation r = getRelation();
1069        if (r != null) {
1070            if (r.getDataSet() == null) {
1071                // see #19915
1072                setRelation(null);
1073                applyAction.updateEnabledState();
1074            } else if (isDirtyRelation()) {
1075                if (!isDirtyEditor()) {
1076                    reloadDataFromRelation();
1077                } else if (!isSaving) {
1078                    new Notification(tr("Relation modified outside of relation editor with pending changes. Conflict resolution required."))
1079                    .setIcon(JOptionPane.WARNING_MESSAGE).show();
1080                }
1081            }
1082        }
1083    }
1084
1085    @Override
1086    public boolean isDirtyEditor() {
1087        Relation snapshot = getRelationSnapshot();
1088        Relation relation = getRelation();
1089        return (snapshot != null && !memberTableModel.hasSameMembersAs(snapshot)) ||
1090                tagEditorPanel.getModel().isDirty() || relation == null || relation.getDataSet() == null;
1091    }
1092
1093    @Override
1094    public void setIsSaving(boolean b) {
1095        isSaving = b;
1096    }
1097}