source: josm/trunk/src/org/openstreetmap/josm/gui/preferences/ToolbarPreferences.java@ 8342

Last change on this file since 8342 was 8342, checked in by Don-vip, 9 years ago

code style - Close curly brace and the next "else", "catch" and "finally" keywords should be located on the same line

  • Property svn:eol-style set to native
File size: 45.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.preferences;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Component;
7import java.awt.Container;
8import java.awt.Dimension;
9import java.awt.GridBagLayout;
10import java.awt.GridLayout;
11import java.awt.LayoutManager;
12import java.awt.Rectangle;
13import java.awt.datatransfer.DataFlavor;
14import java.awt.datatransfer.Transferable;
15import java.awt.datatransfer.UnsupportedFlavorException;
16import java.awt.event.ActionEvent;
17import java.awt.event.ActionListener;
18import java.awt.event.InputEvent;
19import java.awt.event.KeyEvent;
20import java.beans.PropertyChangeEvent;
21import java.beans.PropertyChangeListener;
22import java.io.IOException;
23import java.util.ArrayList;
24import java.util.Arrays;
25import java.util.Collection;
26import java.util.Collections;
27import java.util.HashMap;
28import java.util.LinkedList;
29import java.util.List;
30import java.util.Map;
31
32import javax.swing.AbstractAction;
33import javax.swing.Action;
34import javax.swing.DefaultListCellRenderer;
35import javax.swing.DefaultListModel;
36import javax.swing.Icon;
37import javax.swing.ImageIcon;
38import javax.swing.JButton;
39import javax.swing.JCheckBoxMenuItem;
40import javax.swing.JComponent;
41import javax.swing.JLabel;
42import javax.swing.JList;
43import javax.swing.JMenuItem;
44import javax.swing.JPanel;
45import javax.swing.JPopupMenu;
46import javax.swing.JScrollPane;
47import javax.swing.JTable;
48import javax.swing.JToolBar;
49import javax.swing.JTree;
50import javax.swing.ListCellRenderer;
51import javax.swing.MenuElement;
52import javax.swing.TransferHandler;
53import javax.swing.event.ListSelectionEvent;
54import javax.swing.event.ListSelectionListener;
55import javax.swing.event.PopupMenuEvent;
56import javax.swing.event.PopupMenuListener;
57import javax.swing.event.TreeSelectionEvent;
58import javax.swing.event.TreeSelectionListener;
59import javax.swing.table.AbstractTableModel;
60import javax.swing.tree.DefaultMutableTreeNode;
61import javax.swing.tree.DefaultTreeCellRenderer;
62import javax.swing.tree.DefaultTreeModel;
63import javax.swing.tree.TreePath;
64
65import org.openstreetmap.josm.Main;
66import org.openstreetmap.josm.actions.ActionParameter;
67import org.openstreetmap.josm.actions.AdaptableAction;
68import org.openstreetmap.josm.actions.JosmAction;
69import org.openstreetmap.josm.actions.ParameterizedAction;
70import org.openstreetmap.josm.actions.ParameterizedActionDecorator;
71import org.openstreetmap.josm.gui.tagging.TaggingPreset;
72import org.openstreetmap.josm.tools.GBC;
73import org.openstreetmap.josm.tools.ImageProvider;
74import org.openstreetmap.josm.tools.Shortcut;
75
76public class ToolbarPreferences implements PreferenceSettingFactory {
77
78 private static final String EMPTY_TOOLBAR_MARKER = "<!-empty-!>";
79
80 public static class ActionDefinition {
81 private final Action action;
82 private String name = "";
83 private String icon = "";
84 private ImageIcon ico = null;
85 private final Map<String, Object> parameters = new HashMap<>();
86
87 public ActionDefinition(Action action) {
88 this.action = action;
89 }
90
91 public Map<String, Object> getParameters() {
92 return parameters;
93 }
94
95 public Action getParametrizedAction() {
96 if (getAction() instanceof ParameterizedAction)
97 return new ParameterizedActionDecorator((ParameterizedAction) getAction(), parameters);
98 else
99 return getAction();
100 }
101
102 public Action getAction() {
103 return action;
104 }
105
106 public String getName() {
107 return name;
108 }
109
110 public String getDisplayName() {
111 return name.isEmpty() ? (String) action.getValue(Action.NAME) : name;
112 }
113
114 public String getDisplayTooltip() {
115 if(!name.isEmpty())
116 return name;
117
118 Object tt = action.getValue(TaggingPreset.OPTIONAL_TOOLTIP_TEXT);
119 if (tt != null)
120 return (String) tt;
121
122 return (String) action.getValue(Action.SHORT_DESCRIPTION);
123 }
124
125 public Icon getDisplayIcon() {
126 if(ico != null)
127 return ico;
128 Object o = action.getValue(Action.LARGE_ICON_KEY);
129 if(o == null)
130 o = action.getValue(Action.SMALL_ICON);
131 return (Icon) o;
132 }
133
134 public void setName(String name) {
135 this.name = name;
136 }
137
138 public String getIcon() {
139 return icon;
140 }
141
142 public void setIcon(String icon) {
143 this.icon = icon;
144 ico = ImageProvider.getIfAvailable("", icon);
145 }
146
147 public boolean isSeparator() {
148 return action == null;
149 }
150
151 public static ActionDefinition getSeparator() {
152 return new ActionDefinition(null);
153 }
154
155 public boolean hasParameters() {
156 if (!(getAction() instanceof ParameterizedAction)) return false;
157 for (Object o: parameters.values()) {
158 if (o!=null) return true;
159 }
160 return false;
161 }
162 }
163
164 public static class ActionParser {
165 private final Map<String, Action> actions;
166 private final StringBuilder result = new StringBuilder();
167 private int index;
168 private char[] s;
169
170 public ActionParser(Map<String, Action> actions) {
171 this.actions = actions;
172 }
173
174 private String readTillChar(char ch1, char ch2) {
175 result.setLength(0);
176 while (index < s.length && s[index] != ch1 && s[index] != ch2) {
177 if (s[index] == '\\') {
178 index++;
179 if (index >= s.length) {
180 break;
181 }
182 }
183 result.append(s[index]);
184 index++;
185 }
186 return result.toString();
187 }
188
189 private void skip(char ch) {
190 if (index < s.length && s[index] == ch) {
191 index++;
192 }
193 }
194
195 public ActionDefinition loadAction(String actionName) {
196 index = 0;
197 this.s = actionName.toCharArray();
198
199 String name = readTillChar('(', '{');
200 Action action = actions.get(name);
201
202 if (action == null)
203 return null;
204
205 ActionDefinition result = new ActionDefinition(action);
206
207 if (action instanceof ParameterizedAction) {
208 skip('(');
209
210 ParameterizedAction parametrizedAction = (ParameterizedAction)action;
211 Map<String, ActionParameter<?>> actionParams = new HashMap<>();
212 for (ActionParameter<?> param: parametrizedAction.getActionParameters()) {
213 actionParams.put(param.getName(), param);
214 }
215
216 while (index < s.length && s[index] != ')') {
217 String paramName = readTillChar('=', '=');
218 skip('=');
219 String paramValue = readTillChar(',',')');
220 if (paramName.length() > 0) {
221 ActionParameter<?> actionParam = actionParams.get(paramName);
222 if (actionParam != null) {
223 result.getParameters().put(paramName, actionParam.readFromString(paramValue));
224 }
225 }
226 skip(',');
227 }
228 skip(')');
229 }
230 if (action instanceof AdaptableAction) {
231 skip('{');
232
233 while (index < s.length && s[index] != '}') {
234 String paramName = readTillChar('=', '=');
235 skip('=');
236 String paramValue = readTillChar(',','}');
237 if ("icon".equals(paramName) && paramValue.length() > 0) {
238 result.setIcon(paramValue);
239 } else if("name".equals(paramName) && paramValue.length() > 0) {
240 result.setName(paramValue);
241 }
242 skip(',');
243 }
244 skip('}');
245 }
246
247 return result;
248 }
249
250 private void escape(String s) {
251 for (int i=0; i<s.length(); i++) {
252 char ch = s.charAt(i);
253 if (ch == '\\' || ch == '(' || ch == '{' || ch == ',' || ch == ')' || ch == '}' || ch == '=') {
254 result.append('\\');
255 result.append(ch);
256 } else {
257 result.append(ch);
258 }
259 }
260 }
261
262 @SuppressWarnings("unchecked")
263 public String saveAction(ActionDefinition action) {
264 result.setLength(0);
265
266 String val = (String) action.getAction().getValue("toolbar");
267 if(val == null)
268 return null;
269 escape(val);
270 if (action.getAction() instanceof ParameterizedAction) {
271 result.append('(');
272 List<ActionParameter<?>> params = ((ParameterizedAction)action.getAction()).getActionParameters();
273 for (int i=0; i<params.size(); i++) {
274 ActionParameter<Object> param = (ActionParameter<Object>)params.get(i);
275 escape(param.getName());
276 result.append('=');
277 Object value = action.getParameters().get(param.getName());
278 if (value != null) {
279 escape(param.writeToString(value));
280 }
281 if (i < params.size() - 1) {
282 result.append(',');
283 } else {
284 result.append(')');
285 }
286 }
287 }
288 if (action.getAction() instanceof AdaptableAction) {
289 boolean first = true;
290 String tmp = action.getName();
291 if(tmp.length() != 0) {
292 result.append(first ? "{" : ",");
293 result.append("name=");
294 escape(tmp);
295 first = false;
296 }
297 tmp = action.getIcon();
298 if(tmp.length() != 0) {
299 result.append(first ? "{" : ",");
300 result.append("icon=");
301 escape(tmp);
302 first = false;
303 }
304 if(!first) {
305 result.append('}');
306 }
307 }
308
309 return result.toString();
310 }
311 }
312
313 private static class ActionParametersTableModel extends AbstractTableModel {
314
315 private transient ActionDefinition currentAction = ActionDefinition.getSeparator();
316
317 @Override
318 public int getColumnCount() {
319 return 2;
320 }
321
322 @Override
323 public int getRowCount() {
324 int adaptable = ((currentAction.getAction() instanceof AdaptableAction) ? 2 : 0);
325 if (currentAction.isSeparator() || !(currentAction.getAction() instanceof ParameterizedAction))
326 return adaptable;
327 ParameterizedAction pa = (ParameterizedAction)currentAction.getAction();
328 return pa.getActionParameters().size() + adaptable;
329 }
330
331 @SuppressWarnings("unchecked")
332 private ActionParameter<Object> getParam(int index) {
333 ParameterizedAction pa = (ParameterizedAction)currentAction.getAction();
334 return (ActionParameter<Object>) pa.getActionParameters().get(index);
335 }
336
337 @Override
338 public Object getValueAt(int rowIndex, int columnIndex) {
339 if(currentAction.getAction() instanceof AdaptableAction)
340 {
341 if (rowIndex < 2) {
342 switch (columnIndex) {
343 case 0:
344 return rowIndex == 0 ? tr("Tooltip") : tr("Icon");
345 case 1:
346 return rowIndex == 0 ? currentAction.getName() : currentAction.getIcon();
347 default:
348 return null;
349 }
350 } else {
351 rowIndex -= 2;
352 }
353 }
354 ActionParameter<Object> param = getParam(rowIndex);
355 switch (columnIndex) {
356 case 0:
357 return param.getName();
358 case 1:
359 return param.writeToString(currentAction.getParameters().get(param.getName()));
360 default:
361 return null;
362 }
363 }
364
365 @Override
366 public boolean isCellEditable(int row, int column) {
367 return column == 1;
368 }
369
370 @Override
371 public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
372 if(currentAction.getAction() instanceof AdaptableAction)
373 {
374 if (rowIndex == 0) {
375 currentAction.setName((String)aValue);
376 return;
377 } else if (rowIndex == 1) {
378 currentAction.setIcon((String)aValue);
379 return;
380 } else {
381 rowIndex -= 2;
382 }
383 }
384 ActionParameter<Object> param = getParam(rowIndex);
385 currentAction.getParameters().put(param.getName(), param.readFromString((String)aValue));
386 }
387
388 public void setCurrentAction(ActionDefinition currentAction) {
389 this.currentAction = currentAction;
390 fireTableDataChanged();
391 }
392 }
393
394 private class ToolbarPopupMenu extends JPopupMenu {
395 private transient ActionDefinition act;
396
397 private void setActionAndAdapt(ActionDefinition action) {
398 this.act = action;
399 doNotHide.setSelected(Main.pref.getBoolean("toolbar.always-visible", true));
400 remove.setVisible(act!=null);
401 shortcutEdit.setVisible(act!=null);
402 }
403
404 private JMenuItem remove = new JMenuItem(new AbstractAction(tr("Remove from toolbar")) {
405 @Override
406 public void actionPerformed(ActionEvent e) {
407 Collection<String> t = new LinkedList<>(getToolString());
408 ActionParser parser = new ActionParser(null);
409 // get text definition of current action
410 String res = parser.saveAction(act);
411 // remove the button from toolbar preferences
412 t.remove( res );
413 Main.pref.putCollection("toolbar", t);
414 Main.toolbar.refreshToolbarControl();
415 }
416 });
417
418 private JMenuItem configure = new JMenuItem(new AbstractAction(tr("Configure toolbar")) {
419 @Override
420 public void actionPerformed(ActionEvent e) {
421 final PreferenceDialog p =new PreferenceDialog(Main.parent);
422 p.selectPreferencesTabByName("toolbar");
423 p.setVisible(true);
424 }
425 });
426
427 private JMenuItem shortcutEdit = new JMenuItem(new AbstractAction(tr("Edit shortcut")) {
428 @Override
429 public void actionPerformed(ActionEvent e) {
430 final PreferenceDialog p =new PreferenceDialog(Main.parent);
431 p.getTabbedPane().getShortcutPreference().setDefaultFilter(act.getDisplayName());
432 p.selectPreferencesTabByName("shortcuts");
433 p.setVisible(true);
434 // refresh toolbar to try using changed shortcuts without restart
435 Main.toolbar.refreshToolbarControl();
436 }
437 });
438
439 private JCheckBoxMenuItem doNotHide = new JCheckBoxMenuItem(new AbstractAction(tr("Do not hide toolbar and menu")) {
440 @Override
441 public void actionPerformed(ActionEvent e) {
442 boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState();
443 Main.pref.put("toolbar.always-visible", sel);
444 Main.pref.put("menu.always-visible", sel);
445 }
446 });
447 {
448 addPopupMenuListener(new PopupMenuListener() {
449 @Override
450 public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
451 setActionAndAdapt(buttonActions.get(
452 ((JPopupMenu)e.getSource()).getInvoker()
453 ));
454 }
455 @Override
456 public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
457
458 @Override
459 public void popupMenuCanceled(PopupMenuEvent e) {}
460 });
461 add(remove);
462 add(configure);
463 add(shortcutEdit);
464 add(doNotHide);
465 }
466 }
467
468 private ToolbarPopupMenu popupMenu = new ToolbarPopupMenu();
469
470 /**
471 * Key: Registered name (property "toolbar" of action).
472 * Value: The action to execute.
473 */
474 private final Map<String, Action> actions = new HashMap<>();
475 private final Map<String, Action> regactions = new HashMap<>();
476
477 private final DefaultMutableTreeNode rootActionsNode = new DefaultMutableTreeNode(tr("Actions"));
478
479 public JToolBar control = new JToolBar();
480 private final Map<Object, ActionDefinition> buttonActions = new HashMap<>(30);
481
482 @Override
483 public PreferenceSetting createPreferenceSetting() {
484 return new Settings(rootActionsNode);
485 }
486
487 public class Settings extends DefaultTabPreferenceSetting {
488
489 private final class Move implements ActionListener {
490 @Override
491 public void actionPerformed(ActionEvent e) {
492 if ("<".equals(e.getActionCommand()) && actionsTree.getSelectionCount() > 0) {
493
494 int leadItem = selected.getSize();
495 if (selectedList.getSelectedIndex() != -1) {
496 int[] indices = selectedList.getSelectedIndices();
497 leadItem = indices[indices.length - 1];
498 }
499 for (TreePath selectedAction : actionsTree.getSelectionPaths()) {
500 DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedAction.getLastPathComponent();
501 if (node.getUserObject() == null) {
502 selected.add(leadItem++, ActionDefinition.getSeparator());
503 } else if (node.getUserObject() instanceof Action) {
504 selected.add(leadItem++, new ActionDefinition((Action)node.getUserObject()));
505 }
506 }
507 } else if (">".equals(e.getActionCommand()) && selectedList.getSelectedIndex() != -1) {
508 while (selectedList.getSelectedIndex() != -1) {
509 selected.remove(selectedList.getSelectedIndex());
510 }
511 } else if ("up".equals(e.getActionCommand())) {
512 int i = selectedList.getSelectedIndex();
513 ActionDefinition o = selected.get(i);
514 if (i != 0) {
515 selected.remove(i);
516 selected.add(i-1, o);
517 selectedList.setSelectedIndex(i-1);
518 }
519 } else if ("down".equals(e.getActionCommand())) {
520 int i = selectedList.getSelectedIndex();
521 ActionDefinition o = selected.get(i);
522 if (i != selected.size()-1) {
523 selected.remove(i);
524 selected.add(i+1, o);
525 selectedList.setSelectedIndex(i+1);
526 }
527 }
528 }
529 }
530
531 private class ActionTransferable implements Transferable {
532
533 private final DataFlavor[] flavors = new DataFlavor[] { ACTION_FLAVOR };
534
535 private final List<ActionDefinition> actions;
536
537 public ActionTransferable(List<ActionDefinition> actions) {
538 this.actions = actions;
539 }
540
541 @Override
542 public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
543 return actions;
544 }
545
546 @Override
547 public DataFlavor[] getTransferDataFlavors() {
548 return flavors;
549 }
550
551 @Override
552 public boolean isDataFlavorSupported(DataFlavor flavor) {
553 return flavors[0] == flavor;
554 }
555 }
556
557 private final Move moveAction = new Move();
558
559 private final DefaultListModel<ActionDefinition> selected = new DefaultListModel<>();
560 private final JList<ActionDefinition> selectedList = new JList<>(selected);
561
562 private final DefaultTreeModel actionsTreeModel;
563 private final JTree actionsTree;
564
565 private final ActionParametersTableModel actionParametersModel = new ActionParametersTableModel();
566 private final JTable actionParametersTable = new JTable(actionParametersModel);
567 private JPanel actionParametersPanel;
568
569 private JButton upButton;
570 private JButton downButton;
571 private JButton removeButton;
572 private JButton addButton;
573
574 private String movingComponent;
575
576 public Settings(DefaultMutableTreeNode rootActionsNode) {
577 super(/* ICON(preferences/) */ "toolbar", tr("Toolbar customization"), tr("Customize the elements on the toolbar."));
578 actionsTreeModel = new DefaultTreeModel(rootActionsNode);
579 actionsTree = new JTree(actionsTreeModel);
580 }
581
582 private JButton createButton(String name) {
583 JButton b = new JButton();
584 if ("up".equals(name)) {
585 b.setIcon(ImageProvider.get("dialogs", "up"));
586 } else if ("down".equals(name)) {
587 b.setIcon(ImageProvider.get("dialogs", "down"));
588 } else {
589 b.setText(name);
590 }
591 b.addActionListener(moveAction);
592 b.setActionCommand(name);
593 return b;
594 }
595
596 private void updateEnabledState() {
597 int index = selectedList.getSelectedIndex();
598 upButton.setEnabled(index > 0);
599 downButton.setEnabled(index != -1 && index < selectedList.getModel().getSize() - 1);
600 removeButton.setEnabled(index != -1);
601 addButton.setEnabled(actionsTree.getSelectionCount() > 0);
602 }
603
604 @Override
605 public void addGui(PreferenceTabbedPane gui) {
606 actionsTree.setCellRenderer(new DefaultTreeCellRenderer() {
607 @Override
608 public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
609 boolean leaf, int row, boolean hasFocus) {
610 DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
611 JLabel comp = (JLabel) super.getTreeCellRendererComponent(
612 tree, value, sel, expanded, leaf, row, hasFocus);
613 if (node.getUserObject() == null) {
614 comp.setText(tr("Separator"));
615 comp.setIcon(ImageProvider.get("preferences/separator"));
616 } else if (node.getUserObject() instanceof Action) {
617 Action action = (Action) node.getUserObject();
618 comp.setText((String) action.getValue(Action.NAME));
619 comp.setIcon((Icon) action.getValue(Action.SMALL_ICON));
620 }
621 return comp;
622 }
623 });
624
625 ListCellRenderer<ActionDefinition> renderer = new ListCellRenderer<ActionDefinition>() {
626 private final DefaultListCellRenderer def = new DefaultListCellRenderer();
627 @Override
628 public Component getListCellRendererComponent(JList<? extends ActionDefinition> list,
629 ActionDefinition action, int index, boolean isSelected, boolean cellHasFocus) {
630 String s;
631 Icon i;
632 if (!action.isSeparator()) {
633 s = action.getDisplayName();
634 i = action.getDisplayIcon();
635 } else {
636 i = ImageProvider.get("preferences/separator");
637 s = tr("Separator");
638 }
639 JLabel l = (JLabel)def.getListCellRendererComponent(list, s, index, isSelected, cellHasFocus);
640 l.setIcon(i);
641 return l;
642 }
643 };
644 selectedList.setCellRenderer(renderer);
645 selectedList.addListSelectionListener(new ListSelectionListener(){
646 @Override
647 public void valueChanged(ListSelectionEvent e) {
648 boolean sel = selectedList.getSelectedIndex() != -1;
649 if (sel) {
650 actionsTree.clearSelection();
651 ActionDefinition action = selected.get(selectedList.getSelectedIndex());
652 actionParametersModel.setCurrentAction(action);
653 actionParametersPanel.setVisible(actionParametersModel.getRowCount() > 0);
654 }
655 updateEnabledState();
656 }
657 });
658
659 selectedList.setDragEnabled(true);
660 selectedList.setTransferHandler(new TransferHandler() {
661 @Override
662 @SuppressWarnings("unchecked")
663 protected Transferable createTransferable(JComponent c) {
664 List<ActionDefinition> actions = new ArrayList<>();
665 for (ActionDefinition o: ((JList<ActionDefinition>)c).getSelectedValuesList()) {
666 actions.add(o);
667 }
668 return new ActionTransferable(actions);
669 }
670
671 @Override
672 public int getSourceActions(JComponent c) {
673 return TransferHandler.MOVE;
674 }
675
676 @Override
677 public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
678 for (DataFlavor f : transferFlavors) {
679 if (ACTION_FLAVOR.equals(f))
680 return true;
681 }
682 return false;
683 }
684
685 @Override
686 public void exportAsDrag(JComponent comp, InputEvent e, int action) {
687 super.exportAsDrag(comp, e, action);
688 movingComponent = "list";
689 }
690
691 @Override
692 public boolean importData(JComponent comp, Transferable t) {
693 try {
694 int dropIndex = selectedList.locationToIndex(selectedList.getMousePosition(true));
695 @SuppressWarnings("unchecked")
696 List<ActionDefinition> draggedData = (List<ActionDefinition>) t.getTransferData(ACTION_FLAVOR);
697
698 Object leadItem = dropIndex >= 0 ? selected.elementAt(dropIndex) : null;
699 int dataLength = draggedData.size();
700
701 if (leadItem != null) {
702 for (Object o: draggedData) {
703 if (leadItem.equals(o))
704 return false;
705 }
706 }
707
708 int dragLeadIndex = -1;
709 boolean localDrop = "list".equals(movingComponent);
710
711 if (localDrop) {
712 dragLeadIndex = selected.indexOf(draggedData.get(0));
713 for (Object o: draggedData) {
714 selected.removeElement(o);
715 }
716 }
717 int[] indices = new int[dataLength];
718
719 if (localDrop) {
720 int adjustedLeadIndex = selected.indexOf(leadItem);
721 int insertionAdjustment = dragLeadIndex <= adjustedLeadIndex ? 1 : 0;
722 for (int i = 0; i < dataLength; i++) {
723 selected.insertElementAt(draggedData.get(i), adjustedLeadIndex + insertionAdjustment + i);
724 indices[i] = adjustedLeadIndex + insertionAdjustment + i;
725 }
726 } else {
727 for (int i = 0; i < dataLength; i++) {
728 selected.add(dropIndex, draggedData.get(i));
729 indices[i] = dropIndex + i;
730 }
731 }
732 selectedList.clearSelection();
733 selectedList.setSelectedIndices(indices);
734 movingComponent = "";
735 return true;
736 } catch (Exception e) {
737 Main.error(e);
738 }
739 return false;
740 }
741
742 @Override
743 protected void exportDone(JComponent source, Transferable data, int action) {
744 if ("list".equals(movingComponent)) {
745 try {
746 List<?> draggedData = (List<?>) data.getTransferData(ACTION_FLAVOR);
747 boolean localDrop = selected.contains(draggedData.get(0));
748 if (localDrop) {
749 int[] indices = selectedList.getSelectedIndices();
750 Arrays.sort(indices);
751 for (int i = indices.length - 1; i >= 0; i--) {
752 selected.remove(indices[i]);
753 }
754 }
755 } catch (Exception e) {
756 Main.error(e);
757 }
758 movingComponent = "";
759 }
760 }
761 });
762
763 actionsTree.setTransferHandler(new TransferHandler() {
764 private static final long serialVersionUID = 1L;
765
766 @Override
767 public int getSourceActions( JComponent c ){
768 return TransferHandler.MOVE;
769 }
770
771 @Override
772 protected void exportDone(JComponent source, Transferable data, int action) {
773 }
774
775 @Override
776 protected Transferable createTransferable(JComponent c) {
777 TreePath[] paths = actionsTree.getSelectionPaths();
778 List<ActionDefinition> dragActions = new ArrayList<>();
779 for (TreePath path : paths) {
780 DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
781 Object obj = node.getUserObject();
782 if (obj == null) {
783 dragActions.add(ActionDefinition.getSeparator());
784 } else if (obj instanceof Action) {
785 dragActions.add(new ActionDefinition((Action) obj));
786 }
787 }
788 return new ActionTransferable(dragActions);
789 }
790 });
791 actionsTree.setDragEnabled(true);
792 actionsTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
793 @Override public void valueChanged(TreeSelectionEvent e) {
794 updateEnabledState();
795 }
796 });
797
798 final JPanel left = new JPanel(new GridBagLayout());
799 left.add(new JLabel(tr("Toolbar")), GBC.eol());
800 left.add(new JScrollPane(selectedList), GBC.std().fill(GBC.BOTH));
801
802 final JPanel right = new JPanel(new GridBagLayout());
803 right.add(new JLabel(tr("Available")), GBC.eol());
804 right.add(new JScrollPane(actionsTree), GBC.eol().fill(GBC.BOTH));
805
806 final JPanel buttons = new JPanel(new GridLayout(6,1));
807 buttons.add(upButton = createButton("up"));
808 buttons.add(addButton = createButton("<"));
809 buttons.add(removeButton = createButton(">"));
810 buttons.add(downButton = createButton("down"));
811 updateEnabledState();
812
813 final JPanel p = new JPanel();
814 p.setLayout(new LayoutManager(){
815 @Override
816 public void addLayoutComponent(String name, Component comp) {}
817 @Override
818 public void removeLayoutComponent(Component comp) {}
819 @Override
820 public Dimension minimumLayoutSize(Container parent) {
821 Dimension l = left.getMinimumSize();
822 Dimension r = right.getMinimumSize();
823 Dimension b = buttons.getMinimumSize();
824 return new Dimension(l.width+b.width+10+r.width,l.height+b.height+10+r.height);
825 }
826 @Override
827 public Dimension preferredLayoutSize(Container parent) {
828 Dimension l = new Dimension(200, 200);
829 Dimension r = new Dimension(200, 200);
830 return new Dimension(l.width+r.width+10+buttons.getPreferredSize().width,Math.max(l.height, r.height));
831 }
832 @Override
833 public void layoutContainer(Container parent) {
834 Dimension d = p.getSize();
835 Dimension b = buttons.getPreferredSize();
836 int width = (d.width-10-b.width)/2;
837 left.setBounds(new Rectangle(0,0,width,d.height));
838 right.setBounds(new Rectangle(width+10+b.width,0,width,d.height));
839 buttons.setBounds(new Rectangle(width+5, d.height/2-b.height/2, b.width, b.height));
840 }
841 });
842 p.add(left);
843 p.add(buttons);
844 p.add(right);
845
846 actionParametersPanel = new JPanel(new GridBagLayout());
847 actionParametersPanel.add(new JLabel(tr("Action parameters")), GBC.eol().insets(0, 10, 0, 20));
848 actionParametersTable.getColumnModel().getColumn(0).setHeaderValue(tr("Parameter name"));
849 actionParametersTable.getColumnModel().getColumn(1).setHeaderValue(tr("Parameter value"));
850 actionParametersPanel.add(actionParametersTable.getTableHeader(), GBC.eol().fill(GBC.HORIZONTAL));
851 actionParametersPanel.add(actionParametersTable, GBC.eol().fill(GBC.BOTH).insets(0, 0, 0, 10));
852 actionParametersPanel.setVisible(false);
853
854 JPanel panel = gui.createPreferenceTab(this);
855 panel.add(p, GBC.eol().fill(GBC.BOTH));
856 panel.add(actionParametersPanel, GBC.eol().fill(GBC.HORIZONTAL));
857 selected.removeAllElements();
858 for (ActionDefinition actionDefinition: getDefinedActions()) {
859 selected.addElement(actionDefinition);
860 }
861 }
862
863 @Override
864 public boolean ok() {
865 Collection<String> t = new LinkedList<>();
866 ActionParser parser = new ActionParser(null);
867 for (int i = 0; i < selected.size(); ++i) {
868 ActionDefinition action = selected.get(i);
869 if (action.isSeparator()) {
870 t.add("|");
871 } else {
872 String res = parser.saveAction(action);
873 if(res != null) {
874 t.add(res);
875 }
876 }
877 }
878 if (t.isEmpty()) {
879 t = Collections.singletonList(EMPTY_TOOLBAR_MARKER);
880 }
881 Main.pref.putCollection("toolbar", t);
882 Main.toolbar.refreshToolbarControl();
883 return false;
884 }
885
886 }
887
888 /**
889 * Constructs a new {@code ToolbarPreferences}.
890 */
891 public ToolbarPreferences() {
892 control.setFloatable(false);
893 control.setComponentPopupMenu(popupMenu);
894 }
895
896 private void loadAction(DefaultMutableTreeNode node, MenuElement menu) {
897 Object userObject = null;
898 MenuElement menuElement = menu;
899 if (menu.getSubElements().length > 0 &&
900 menu.getSubElements()[0] instanceof JPopupMenu) {
901 menuElement = menu.getSubElements()[0];
902 }
903 for (MenuElement item : menuElement.getSubElements()) {
904 if (item instanceof JMenuItem) {
905 JMenuItem menuItem = ((JMenuItem)item);
906 if (menuItem.getAction() != null) {
907 Action action = menuItem.getAction();
908 userObject = action;
909 Object tb = action.getValue("toolbar");
910 if(tb == null) {
911 Main.info(tr("Toolbar action without name: {0}",
912 action.getClass().getName()));
913 continue;
914 } else if (!(tb instanceof String)) {
915 if(!(tb instanceof Boolean) || (Boolean)tb) {
916 Main.info(tr("Strange toolbar value: {0}",
917 action.getClass().getName()));
918 }
919 continue;
920 } else {
921 String toolbar = (String) tb;
922 Action r = actions.get(toolbar);
923 if(r != null && r != action && !toolbar.startsWith("imagery_")) {
924 Main.info(tr("Toolbar action {0} overwritten: {1} gets {2}",
925 toolbar, r.getClass().getName(), action.getClass().getName()));
926 }
927 actions.put(toolbar, action);
928 }
929 } else {
930 userObject = menuItem.getText();
931 }
932 }
933 DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(userObject);
934 node.add(newNode);
935 loadAction(newNode, item);
936 }
937 }
938
939 public Action getAction(String s) {
940 Action e = actions.get(s);
941 if(e == null) {
942 e = regactions.get(s);
943 }
944 return e;
945 }
946
947 private void loadActions() {
948 rootActionsNode.removeAllChildren();
949 loadAction(rootActionsNode, Main.main.menu);
950 for(Map.Entry<String, Action> a : regactions.entrySet())
951 {
952 if(actions.get(a.getKey()) == null) {
953 rootActionsNode.add(new DefaultMutableTreeNode(a.getValue()));
954 }
955 }
956 rootActionsNode.add(new DefaultMutableTreeNode(null));
957 }
958
959 private static final String[] deftoolbar = {"open", "save", "download", "upload", "|",
960 "undo", "redo", "|", "dialogs/search", "preference", "|", "splitway", "combineway",
961 "wayflip", "|", "imagery-offset", "|", "tagginggroup_Highways/Streets",
962 "tagginggroup_Highways/Ways", "tagginggroup_Highways/Waypoints",
963 "tagginggroup_Highways/Barriers", "|", "tagginggroup_Transport/Car",
964 "tagginggroup_Transport/Public Transport", "|", "tagginggroup_Facilities/Tourism",
965 "tagginggroup_Facilities/Food+Drinks", "|", "tagginggroup_Man Made/Historic Places", "|",
966 "tagginggroup_Man Made/Man Made"};
967
968 public static Collection<String> getToolString() {
969
970 Collection<String> toolStr = Main.pref.getCollection("toolbar", Arrays.asList(deftoolbar));
971 if (toolStr == null || toolStr.isEmpty()) {
972 toolStr = Arrays.asList(deftoolbar);
973 }
974 return toolStr;
975 }
976
977 private Collection<ActionDefinition> getDefinedActions() {
978 loadActions();
979
980 Map<String, Action> allActions = new HashMap<>(regactions);
981 allActions.putAll(actions);
982 ActionParser actionParser = new ActionParser(allActions);
983
984 Collection<ActionDefinition> result = new ArrayList<>();
985
986 for (String s : getToolString()) {
987 if ("|".equals(s)) {
988 result.add(ActionDefinition.getSeparator());
989 } else {
990 ActionDefinition a = actionParser.loadAction(s);
991 if(a != null) {
992 result.add(a);
993 } else {
994 Main.info("Could not load tool definition "+s);
995 }
996 }
997 }
998
999 return result;
1000 }
1001
1002 /**
1003 * @return The parameter (for better chaining)
1004 */
1005 public Action register(Action action) {
1006 String toolbar = (String) action.getValue("toolbar");
1007 if (toolbar == null) {
1008 Main.info(tr("Registered toolbar action without name: {0}",
1009 action.getClass().getName()));
1010 } else {
1011 Action r = regactions.get(toolbar);
1012 if (r != null) {
1013 Main.info(tr("Registered toolbar action {0} overwritten: {1} gets {2}",
1014 toolbar, r.getClass().getName(), action.getClass().getName()));
1015 }
1016 }
1017 regactions.put(toolbar, action);
1018 return action;
1019 }
1020
1021 /**
1022 * Parse the toolbar preference setting and construct the toolbar GUI control.
1023 *
1024 * Call this, if anything has changed in the toolbar settings and you want to refresh
1025 * the toolbar content (e.g. after registering actions in a plugin)
1026 */
1027 public void refreshToolbarControl() {
1028 control.removeAll();
1029 buttonActions.clear();
1030 boolean unregisterTab = Shortcut.findShortcut(KeyEvent.VK_TAB, 0)!=null;
1031
1032 for (ActionDefinition action : getDefinedActions()) {
1033 if (action.isSeparator()) {
1034 control.addSeparator();
1035 } else {
1036 final JButton b = addButtonAndShortcut(action);
1037 buttonActions.put(b, action);
1038
1039 Icon i = action.getDisplayIcon();
1040 if (i != null) {
1041 b.setIcon(i);
1042 } else {
1043 // hide action text if an icon is set later (necessary for delayed/background image loading)
1044 action.getParametrizedAction().addPropertyChangeListener(new PropertyChangeListener() {
1045
1046 @Override
1047 public void propertyChange(PropertyChangeEvent evt) {
1048 if (Action.SMALL_ICON.equals(evt.getPropertyName())) {
1049 b.setHideActionText(evt.getNewValue() != null);
1050 }
1051 }
1052 });
1053 }
1054 b.setInheritsPopupMenu(true);
1055 b.setFocusTraversalKeysEnabled(!unregisterTab);
1056 }
1057 }
1058 control.setFocusTraversalKeysEnabled(!unregisterTab);
1059 control.setVisible(control.getComponentCount() != 0);
1060 control.repaint();
1061 }
1062
1063 /**
1064 * The method to add custom button on toolbar like search or preset buttons
1065 * @param definitionText toolbar definition text to describe the new button,
1066 * must be carefully generated by using {@link ActionParser}
1067 * @param preferredIndex place to put the new button, give -1 for the end of toolbar
1068 * @param removeIfExists if true and the button already exists, remove it
1069 */
1070 public void addCustomButton(String definitionText, int preferredIndex, boolean removeIfExists) {
1071 List<String> t = new LinkedList<>(getToolString());
1072 if (t.contains(definitionText)) {
1073 if (!removeIfExists) return; // do nothing
1074 t.remove(definitionText);
1075 } else {
1076 if (preferredIndex>=0 && preferredIndex < t.size()) {
1077 t.add(preferredIndex, definitionText); // add to specified place
1078 } else {
1079 t.add(definitionText); // add to the end
1080 }
1081 }
1082 Main.pref.putCollection("toolbar", t);
1083 Main.toolbar.refreshToolbarControl();
1084 }
1085
1086 private JButton addButtonAndShortcut(ActionDefinition action) {
1087 Action act = action.getParametrizedAction();
1088 JButton b = control.add(act);
1089
1090 Shortcut sc = null;
1091 if (action.getAction() instanceof JosmAction) {
1092 sc = ((JosmAction) action.getAction()).getShortcut();
1093 if (sc.getAssignedKey() == KeyEvent.CHAR_UNDEFINED) {
1094 sc = null;
1095 }
1096 }
1097
1098 long paramCode = 0;
1099 if (action.hasParameters()) {
1100 paramCode = action.parameters.hashCode();
1101 }
1102
1103 String tt = action.getDisplayTooltip();
1104 if (tt==null) {
1105 tt="";
1106 }
1107
1108 if (sc == null || paramCode != 0) {
1109 String name = (String) action.getAction().getValue("toolbar");
1110 if (name==null) {
1111 name=action.getDisplayName();
1112 }
1113 if (paramCode!=0) {
1114 name = name+paramCode;
1115 }
1116 String desc = action.getDisplayName() + ((paramCode==0)?"":action.parameters.toString());
1117 sc = Shortcut.registerShortcut("toolbar:"+name, tr("Toolbar: {0}", desc),
1118 KeyEvent.CHAR_UNDEFINED, Shortcut.NONE);
1119 Main.unregisterShortcut(sc);
1120 Main.registerActionShortcut(act, sc);
1121
1122 // add shortcut info to the tooltip if needed
1123 if (sc.getAssignedUser()) {
1124 if (tt.startsWith("<html>") && tt.endsWith("</html>")) {
1125 tt = tt.substring(6,tt.length()-6);
1126 }
1127 tt = Main.platform.makeTooltip(tt, sc);
1128 }
1129 }
1130
1131 if (!tt.isEmpty()) {
1132 b.setToolTipText(tt);
1133 }
1134 return b;
1135 }
1136
1137 private static final DataFlavor ACTION_FLAVOR = new DataFlavor(ActionDefinition.class, "ActionItem");
1138}
Note: See TracBrowser for help on using the repository browser.