-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathCommander.java
2408 lines (2178 loc) · 73.7 KB
/
Commander.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* IJ BAR: https://github.com/tferr/Scripts
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation
* (http://www.gnu.org/licenses/gpl.txt).
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
package bar.plugin;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.prefs.Preferences;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.event.TableModelEvent;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import bar.FileDrop;
import bar.Utils;
import fiji.Debug;
import fiji.util.gui.GenericDialogPlus;
import ij.IJ;
//import ij.Menus;
import ij.WindowManager;
import ij.gui.DialogListener;
import ij.gui.GenericDialog;
import ij.gui.ImageWindow;
import ij.io.OpenDialog;
import ij.plugin.PlugIn;
import ij.text.TextPanel;
import ij.text.TextWindow;
/**
* Implements a light-weight and fast keyboard-based file browser for ImageJ
* (<i>BAR>BAR Commander...</i> command). . A summary of features is listed on
* the BAR <a href="http://imagej.net/BAR#Commander">documentation page</a>.
* <p>
* Commander is modeled after <a href=
* "https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/plugin/CommandFinder.java"
* >CommandFinder</a> by Mark Longair and <a href=
* "https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/macro/FunctionFinder.java"
* >FunctionFinder</a> by Jerome Mutterer. It is also influenced by Johannes
* Schindelin's <a href=
* "https://github.com/fiji/Fiji_Plugins/blob/master/src/main/java/fiji/util/Recent_Commands.java"
* >Recent_Commands plugin</a> and a bit of DOS nostalgia. Drag and drop support
* is implemented by {@link bar.FileDrop FileDrop} (<a
* href="http://www.iharder.net/current/java/filedrop/">website</a>).
*/
public class Commander implements PlugIn, ActionListener, DocumentListener,
KeyListener, ListSelectionListener, MouseListener, WindowListener {
/** Default path to be listed at startup */
private static final String DEF_PATH = System.getProperty("user.home");
/** Default query to be displayed at startup */
private static final String PROMPT_PLACEHOLDER = "search or press ! for console";
/** Character that triggers Console mode */
private static final String CONSOLE_TRIGGER = "!";
/** Flag that monitors if file list reached maximum size */
private boolean truncatedList = false;
/** Flag that toggles changes to status bar messages */
private boolean freezeStatusBar = false;
/** Defaults */
private static final boolean DEF_CLOSE_ON_OPEN = false;
private static final boolean DEF_IJM_LEGACY = false;
private static final int DEF_MAX_SIZE = 200;
private static final int DEF_FRAME_WIDTH = 250;
private static final int DEF_FRAME_HEIGHT = 450;
private static final int DEF_FRAME_X = 30;
private static final int DEF_FRAME_Y = 0;
/** Parameters **/
private static int frameX, frameY, frameWidth, frameHeight, maxSize;
private boolean closeOnOpen, ijmLegacy, caseSensitive, regex, wholeWord;
private String path;
private String matchingString = "";
private JFrame frame;
private JTextField prompt;
private JCheckBox regexCheckBox, caseSensitiveCheckBox, wholeWordCheckBox;
private JScrollPane listPane;
private JLabel statusBar;
private JButton historyButton, optionsButton, openButton, closeButton;
private JPopupMenu optionsMenu;
private JMenu bookmarksMenu, recentMenu;
private ArrayList<String> filenames, bookmarks, recentPaths;
private ArrayList<SavedSearch> prevSearches;
private String selectedItem;
private JTable table;
private static TableModel tableModel;
private JTableHeader tableHeader;
private final Preferences prefs = Preferences.userNodeForPackage(getClass());
/**
* Calls {@link fiji.Debug#runFilter(String, String, String)
* fiji.Debug.runFilter()} so that the plugin can be debugged from an IDE
*/
public static void main(final String[] args) { Debug.run("BAR Commander...",""); }
/* (non-Javadoc)
* @see ij.plugin.PlugIn#run(java.lang.String)
*/
public void run(final String arg) {
// Check if Commander is already running
if (WindowManager.getWindow("BAR Commander") != null) {
if (arg != null && !arg.isEmpty())
IJ.showStatus("In Commander, type <" + arg + "> to start browsing...");
IJ.selectWindow("BAR Commander");
return;
}
Utils.shiftClickWarning();
if (IJ.altKeyDown())
clearPreferences();
// Initialize file list, favorites and history. Set defaults
filenames = new ArrayList<String>();
bookmarks = new ArrayList<String>();
recentPaths = new ArrayList<String>();
prevSearches = new ArrayList<SavedSearch>();
loadPreferences();
// Check if a path has been specified in plugins.config
if ("!lib".equals(arg))
path = Utils.getLibDir();
else if ("!snip".equals(arg))
path = Utils.getSnippetsDir();
// Try to retrieve a new directory if specified path is not valid
if (!Utils.fileExists(path)) {
path = IJ.getDirectory("Choose new directory");
// Exit if user canceled prompt
if (path == null) {
IJ.showStatus("Commander requires a valid directory at startup...");
return;
}
}
// Start Commander
new Thread() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
} catch (final Exception ignored) {
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
runInteractively();
}
});
}
}.start();
}
void clearPreferences() {
try {
if (IJ.showMessageWithCancel("Reset all options to defaults?", "Reset Commander preferences?\n"
+ "Bookmarks and previously saved searches will be forgotten.\n \n"
+ "(Preferences can be reset by holding \"Alt\" when starting Commander)")) {
prefs.clear();
if (frame != null) {
frame.setLocation(DEF_FRAME_X, DEF_FRAME_Y);
frame.setSize(DEF_FRAME_WIDTH, DEF_FRAME_HEIGHT);
maxSize = DEF_MAX_SIZE;
closeOnOpen = DEF_CLOSE_ON_OPEN;
ijmLegacy = DEF_IJM_LEGACY;
caseSensitive = wholeWord = regex = false;
path = DEF_PATH;
clearBookmarks();
clearRecentPaths();
clearSearches();
resetFileList();
}
}
} catch (final Exception e) {
IJ.handleException(e);
}
}
void loadPreferences() {
try {
frameX = prefs.getInt("cmder.frameX", DEF_FRAME_X);
frameY = prefs.getInt("cmder.frameY", DEF_FRAME_Y);
frameWidth = prefs.getInt("cmder.frameWidth", DEF_FRAME_WIDTH);
frameHeight = prefs.getInt("cmder.frameHeight", DEF_FRAME_HEIGHT);
maxSize = prefs.getInt("cmder.maxSize", DEF_MAX_SIZE);
closeOnOpen = prefs.getBoolean("cmder.closeOnOpen", DEF_CLOSE_ON_OPEN);
ijmLegacy = prefs.getBoolean("cmder.ijmLegacy", DEF_IJM_LEGACY);
caseSensitive = prefs.getBoolean("cmder.caseSensitive", false);
wholeWord = prefs.getBoolean("cmder.wholeWord", false);
regex = prefs.getBoolean("cmder.regex", false);
path = prefs.get("cmder.path", DEF_PATH);
// Bookmarks Recent paths and Saved Searches
final String favs[] = prefs.get("cmder.bookmarks", "").split(",");
for (final String f : favs)
if (!f.isEmpty())
bookmarks.add(f);
final String recent[] = prefs.get("cmder.recentPaths", "").split(",");
for (final String r : recent)
if (!r.isEmpty())
recentPaths.add(r);
final int nQueries = prefs.getInt("cmder.nQueries", 2);
for (int i = 0; i < nQueries; i++) {
final SavedSearch srch = new SavedSearch(prefs.get("cmder.prevSearch" + i, ""));
if (srch.valid())
prevSearches.add(srch);
}
} catch (final Exception e) {
IJ.handleException(e);
}
}
void savePreferences() {
try {
prefs.putInt("cmder.frameX", frame.getX());
prefs.putInt("cmder.frameY", frame.getY());
prefs.putInt("cmder.frameWidth", frame.getWidth());
prefs.putInt("cmder.frameHeight", frame.getHeight());
prefs.putInt("cmder.maxSize", maxSize);
prefs.putBoolean("cmder.closeOnOpen", closeOnOpen);
prefs.putBoolean("cmder.ijmLegacy", ijmLegacy);
prefs.putBoolean("cmder.caseSensitive", caseSensitive);
prefs.putBoolean("cmder.regex", regex);
prefs.putBoolean("cmder.wholeWord", wholeWord);
prefs.put("cmder.path", path);
// Bookmarks, Recent paths and Saved Searches
String favs = "";
for (final String b : bookmarks)
favs += b + ",";
prefs.put("cmder.bookmarks", favs);
String recent = "";
for (final String r : recentPaths)
recent += r + ",";
prefs.put("cmder.recentPaths", recent);
prefs.putInt("cmder.nQueries", prevSearches.size());
for (int i = 0; i < prevSearches.size(); i++) {
prefs.put("cmder.prevSearch" + i, prevSearches.get(i).toPrefsString());
}
} catch (final Exception e) {
IJ.handleException(e);
}
}
/** Initializes lists, builds and displays prompt */
void runInteractively() {
// Create search prompt
prompt = new JTextField(PROMPT_PLACEHOLDER);
prompt.selectAll();
prompt.getDocument().addDocumentListener(this);
prompt.addActionListener(this);
prompt.addKeyListener(this);
// Created search options
caseSensitiveCheckBox = new JCheckBox("Aa", caseSensitive);
final Font cboxFont = caseSensitiveCheckBox.getFont();
final int cboxHeight = cboxFont.getSize();
final int cboxGap = caseSensitiveCheckBox.getIconTextGap();
caseSensitiveCheckBox.putClientProperty("JComponent.sizeVariant", "small");
caseSensitiveCheckBox.setIconTextGap(cboxGap-1);
caseSensitiveCheckBox.setEnabled(!regex);
caseSensitiveCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(final ItemEvent ie) {
caseSensitive = caseSensitiveCheckBox.isSelected();
setMatchingString(prompt.getText());
updateList();
}
});
wholeWordCheckBox = new JCheckBox("Whole word", wholeWord);
wholeWordCheckBox.putClientProperty("JComponent.sizeVariant", "small");
wholeWordCheckBox.setIconTextGap(cboxGap-1);
wholeWordCheckBox.setEnabled(!regex);
wholeWordCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(final ItemEvent ie) {
wholeWord = wholeWordCheckBox.isSelected();
setMatchingString(prompt.getText());
updateList();
}
});
regexCheckBox = new JCheckBox("Regex", regex);
regexCheckBox.putClientProperty("JComponent.sizeVariant", "small");
regexCheckBox.setIconTextGap(cboxGap-1);
regexCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(final ItemEvent ie) {
regex = regexCheckBox.isSelected();
wholeWordCheckBox.setEnabled(!regex);
caseSensitiveCheckBox.setEnabled(!regex);
setMatchingString(prompt.getText());
updateList();
}
});
// Create the 'search options' panel
final JPanel cboxPanel = new JPanel(new GridBagLayout());
final GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(0, 0, cboxHeight / 2, 0);
c.gridx = 0; c.gridy = 0;
cboxPanel.add(caseSensitiveCheckBox, c);
c.gridx++;
cboxPanel.add(wholeWordCheckBox, c);
c.gridx++;
cboxPanel.add(regexCheckBox, c);
// Create the 'history' button and blend it with prompt
//final Icon icon = UIManager.getIcon("Table.descendingSortIcon");
prompt.setBorder(new EmptyBorder(4, 4, 4, 4));
prompt.setFont(prompt.getFont().deriveFont(15f));
historyButton = new JButton("<html>…</html>");
historyButton.setBackground(prompt.getBackground());
historyButton.setFont(prompt.getFont());
historyButton.setBorder(new EmptyBorder(0, 0, 0, 2));
historyButton.setContentAreaFilled(false);
historyButton.addActionListener(this);
// Create search panel: a unified component looking like a JTextField
final JPanel promptPanel = new JPanel(new BorderLayout());
promptPanel.add(prompt, BorderLayout.CENTER);
promptPanel.add(historyButton, BorderLayout.LINE_END);
promptPanel.setBackground(prompt.getBackground());
promptPanel.setBorder(prompt.getBorder() );
// Place all search-related components into a final container
final JPanel searchPanel = new JPanel(new BorderLayout());
promptPanel.validate();
searchPanel.add(promptPanel, BorderLayout.CENTER);
searchPanel.add(cboxPanel, BorderLayout.PAGE_END);
searchPanel.setFocusable(true);
// Create table holding file list. Format it so it mimics a JList
tableModel = new TableModel();
table = new ScrollableTable();
table.setModel(tableModel);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(false);
//table.setAutoCreateRowSorter(true);
table.setShowGrid(false);
table.setShowHorizontalLines(false);
table.setShowVerticalLines(false);
table.setRowMargin(0);
table.setIntercellSpacing(new Dimension(0, 0));
table.addKeyListener(this);
table.addMouseListener(this);
table.getSelectionModel().addListSelectionListener(this);
// Auto-scroll table using keystrokes
table.addKeyListener(new KeyAdapter() {
public void keyTyped(final KeyEvent evt) {
if (evt.isControlDown() || evt.isMetaDown())
return;
final int nRows = tableModel.getRowCount();
final char ch = Character.toLowerCase(evt.getKeyChar());
if (!Character.isLetterOrDigit(ch)) {
return; // Ignore searches for non alpha-numeric characters
}
final int sRow = table.getSelectedRow();
for (int row = (sRow+1) % nRows; row != sRow; row = (row+1) % nRows) {
final String rowData = tableModel.getValueAt(row, 0).toString();
final char rowCh = Character.toLowerCase(rowData.charAt(0));
if (ch == rowCh) {
table.setRowSelectionInterval(row, row);
table.scrollRectToVisible(table.getCellRect(row, 0, true));
break;
}
}
}
});
// Use Column header as a path bar
tableHeader = table.getTableHeader();
tableHeader.setDefaultRenderer(new HeaderRenderer(table));
tableHeader.addMouseListener(this);
// Allow folders to be dropped in file list. Consider only first item dropped
listPane = new JScrollPane(table);
listPane.getViewport().setBackground(Color.WHITE); // http://stackoverflow.com/a/18362310
new FileDrop(listPane, new FileDrop.Listener() {
public void filesDropped(final java.io.File[] files) {
try {
final String dir = (files[0].isDirectory()) ? files[0]
.getCanonicalPath() : files[0].getParent();
if (dir == null) {
error("Drag and Drop failed...");
return;
}
setPath(dir);
updateList();
} catch (final java.io.IOException e) {
error("Drag and Drop failed...");
}
}
});
// Create status bar
statusBar = new JLabel();
statusBar.addMouseListener(this);
updateBrowserStatus();
// Create popup menu and buttons
optionsMenu = createOptionsMenu();
final JPanel buttonPanel = new JPanel();
closeButton = new JButton("Quit");
closeButton.addActionListener(this);
buttonPanel.add(closeButton);
optionsButton = new JButton(". . .");
optionsButton.setFont(optionsButton.getFont().deriveFont(Font.BOLD));
optionsButton.addActionListener(this);
buttonPanel.add(optionsButton);
openButton = new JButton("Open");
openButton.addActionListener(this);
buttonPanel.add(openButton);
final JPanel contained = new JPanel(new BorderLayout());
final JPanel container = new JPanel(new BorderLayout());
container.setFocusable(true);
contained.add(statusBar, BorderLayout.CENTER);
contained.add(buttonPanel, BorderLayout.PAGE_END);
container.add(searchPanel, BorderLayout.PAGE_START);
container.add(listPane, BorderLayout.CENTER);
container.add(contained, BorderLayout.PAGE_END);
// Set mnemonics
regexCheckBox.setMnemonic(KeyEvent.VK_R);
wholeWordCheckBox.setMnemonic(KeyEvent.VK_W);
caseSensitiveCheckBox.setMnemonic(KeyEvent.VK_A);
optionsButton.setMnemonic(KeyEvent.VK_PERIOD);
closeButton.setMnemonic(KeyEvent.VK_Q);
openButton.setMnemonic(KeyEvent.VK_O);
// Populate file list. Update status and path bar
setPath(path);
updateList();
// Display commander
frame = new JFrame("BAR Commander");
setDefaultTooltips();
frame.add(container);
frame.addWindowListener(this);
frame.pack();
frame.setSize(frameWidth, frameHeight);
frame.setLocation(frameX, frameY);
frame.setVisible(true);
//openButton.getRootPane().setDefaultButton(openButton);
prompt.requestFocusInWindow();
WindowManager.addWindow(frame);
}
/** Adds current path to "Favorites" menu */
void addBookmark() {
if (!bookmarks.contains(path)) {
bookmarks.add(path);
updateBookmarksMenu();
log("New bookmark: "+ path);
} else
error("Already bookmarked "+ path);
}
/** Adds current path to "Recent" menu */
void addRecentPath(final String path, final int maxListSize) {
recentPaths.remove(path);
recentPaths.add(0, path);
if (recentPaths.size() > maxListSize)
recentPaths.remove(recentPaths.size() - 1);
updateRecentMenu();
}
/** Prompts for a new path (requires fiji.util.gui.GenericDialogPlus) */
void cdToDirectory(final String defaultpath) {
try {
log("Changing directory...");
Class.forName("fiji.util.gui.GenericDialogPlus");
final GenericDialogPlus gd = new GenericDialogPlus("Change directory", frame);
gd.addDirectoryField("cd to..", defaultpath, 50);
gd.setOKLabel(" Set Path ");
gd.addDialogListener(new DialogListener() {
@Override
public boolean dialogItemChanged(final GenericDialog gd, final AWTEvent e) {
final TextField tf = (TextField) gd.getStringFields().elementAt(0);
final Button[] buttons = gd.getButtons();
if (new File(gd.getNextString()).isDirectory()) {
tf.setForeground(Color.BLACK);
buttons[0].setLabel(" Set Path ");
return true;
} else {
tf.setForeground(Color.RED);
buttons[0].setLabel("Invalid Path");
return false;
}
}
});
gd.showDialog();
final String newPath = gd.getNextString();
if (!gd.wasCanceled() && !newPath.isEmpty()) {
changeDirectory(newPath);
} else {
error("cd to... not executed");
return;
}
} catch (final ClassNotFoundException e) {
error("cd to... not executed");
error("Dependencies Missing", "Error: This command requires fiji-lib.");
}
}
/**
* Changes path to the specified directory path (if valid). Displays and IJ
* error if directory does not exist. If specified directory is empty, user
* is prompted to choose a new directory.
*/
void changeDirectory(String newDir) {
if (newDir.isEmpty())
newDir = IJ.getDirectory("Choose new directory");
if (newDir == null)
return;
if (Utils.fileExists(newDir))
setPath(newDir);
else
error("Path unavailable: "+ newDir);
resetFileList();
}
/** Clears all bookmarks in "Favorites" (optionsMenu) */
void clearBookmarks() {
try {
bookmarks.clear();
prefs.put("cmder.bookmarks", "");
} catch (final Exception e) {
IJ.handleException(e);
}
updateBookmarksMenu();
}
/** Clears recent paths in "Recent folders" (optionsMenu) */
void clearRecentPaths() {
try {
recentPaths.clear();
prefs.put("cmder.recentPaths", "");
} catch (final Exception e) {
IJ.handleException(e);
}
updateRecentMenu();
}
/** Clears previous searches in "History" dropdown menu */
void clearSearches() {
prevSearches.clear();
try {
final int nQueries = prefs.getInt("cmder.nQueries", 2);
prefs.putInt("cmder.nQueries", 0);
for (int i = 0; i < nQueries; i++)
prefs.remove("cmder.prevSearch" + i);
} catch (final Exception e) {
IJ.handleException(e);
}
}
/** Creates the "Copy Path" menu */
JMenu copyPathMenu() {
final JMenu cm = new JMenu("Copy Path");
JMenuItem mi = new JMenuItem("Default Path");
mi.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
pathToClipboard("");
}
});
cm.add(mi);
mi = new JMenuItem("Short Path");
mi.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
pathToClipboard("short");
}
});
cm.add(mi);
mi = new JMenuItem("URL");
mi.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
pathToClipboard("url");
}
});
cm.add(mi);
return cm;
}
/**
* Copies current path to the system clipboard.
*
* @param type
* if "url", the path URL is copied. If "short", an abbreviated
* path is copied. This means short filenames in 8.3 format for
* Windows and relative paths with escaped whitespaces in Unix.
* The default path is copied if <code>type</code> has any other
* value.
*/
void pathToClipboard(final String type) {
String path = this.path;
if (!isConsoleMode() && table.getSelectedRow() > -1
&& !selectedItem.startsWith(".."))
path += selectedItem;
try {
if (type.equals("url")) {
path = new File(path).toURI().toURL().toString();
} else if (type.equals("short")) {
if (path.length() > 1 && path.endsWith(File.separator))
path = path.substring(0, path.length() - 1);
if (IJ.isWindows()) {
final Runtime rt = Runtime.getRuntime();
final Process process = rt.exec("cmd /c for %I in (\""
+ path + "\") do @echo %~fsI");
process.waitFor();
final java.io.InputStream is = process.getInputStream();
final java.util.Scanner s = new java.util.Scanner(is);
s.useDelimiter("\\A");
if (s.hasNext())
path = s.next();
s.close();
} else {
path = path.replace(System.getProperty("user.home"), "~");
path = path.replace(" ", "\\ ");
}
}
final StringSelection stringSelection = new StringSelection(path);
final Clipboard cb = Toolkit.getDefaultToolkit()
.getSystemClipboard();
cb.setContents(stringSelection, null);
} catch (final Exception e) {
IJ.handleException(e);
}
log("Path copied to clipboard...", 500);
//if(IJ.debugMode) IJ.log(path);
}
/** Creates optionsMenu */
JPopupMenu createOptionsMenu() {
final JPopupMenu popup = new JPopupMenu();
final OptionsActionListener al = new OptionsActionListener();
final int modifierA = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
final int modifierB = (java.awt.event.InputEvent.SHIFT_MASK | modifierA);
bookmarksMenu = new JMenu("Favorites");
updateBookmarksMenu();
popup.add(bookmarksMenu);
recentMenu = new JMenu("Recent Folders");
updateRecentMenu();
popup.add(recentMenu);
popup.addSeparator();
JMenuItem mi = new JMenuItem("Print Current List");
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, modifierA));
mi.addActionListener(al);
popup.add(mi);
mi = new JMenuItem("Refresh File List");
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, modifierA));
mi.addActionListener(al);
popup.add(mi);
popup.addSeparator();
mi = new JMenuItem("Enter Console Mode");
mi.addActionListener(al);
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, modifierB));
popup.add(mi);
mi = new JMenuItem("Go To...");
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, modifierB));
mi.addActionListener(al);
popup.add(mi);
mi = new JMenuItem("Reveal Path");
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, modifierB));
mi.addActionListener(al);
popup.add(mi);
popup.addSeparator();
popup.add(copyPathMenu());
popup.addSeparator();
mi = new JMenuItem("Preferences...");
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, modifierA));
mi.addActionListener(al);
popup.add(mi);
return popup;
}
/** Creates the "Favorites" (bookmarks) menu */
void updateBookmarksMenu() {
final OptionsActionListener al = new OptionsActionListener();
final int modifierA = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
bookmarksMenu.removeAll();
JMenuItem mi = new JMenuItem("Add to Favorites");
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, modifierA));
mi.addActionListener(al);
bookmarksMenu.add(mi);
if (bookmarks.size() > 0) {
mi = new JMenuItem("Clear favorites");
mi.addActionListener(al);
bookmarksMenu.add(mi);
bookmarksMenu.addSeparator();
}
for (final String bookmark : bookmarks) {
mi = new JMenuItem();
final int lgth = 50;
if (bookmark.length() > lgth) {
mi.setText("..." + bookmark.substring(bookmark.length() - lgth));
mi.setToolTipText(bookmark);
} else {
mi.setText(bookmark);
}
mi.setActionCommand(bookmark);
mi.addActionListener(al);
bookmarksMenu.add(mi);
}
}
/** Creates the "Recent Folders" menu */
void updateRecentMenu() {
if (recentPaths.size() == 0) {
recentMenu.setEnabled(false);
return;
} else {
recentMenu.setEnabled(true);
recentMenu.removeAll();
final RecentActionListener al = new RecentActionListener();
JMenuItem mi;
for (final String r : recentPaths) {
final String entry = new File(r).getName();
mi = new JMenuItem(entry.isEmpty() ? File.separator : entry);
mi.setActionCommand(r);
mi.addActionListener(al);
recentMenu.add(mi);
}
recentMenu.addSeparator();
mi = new JMenuItem("Clear Menu");
mi.addActionListener(al);
recentMenu.add(mi);
}
}
/** Displays History Menu */
void showHistoryMenu() {
final JPopupMenu popup = new JPopupMenu();
final HistoryActionListener al = new HistoryActionListener();
final int modifierA = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
JMenuItem mi;
mi = new JMenuItem("Save search");
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, modifierA));
mi.addActionListener(al);
popup.add(mi);
if (prevSearches.size() > 0) {
mi = new JMenuItem("Clear searches");
mi.addActionListener(al);
popup.add(mi);
popup.addSeparator();
}
for (final SavedSearch search : prevSearches) {
mi = new JMenuItem(search.query);
mi.addActionListener(al);
popup.add(mi);
}
popup.show(historyButton, 0, 0);
}
/**
* Displays a message in the status bar.
*
* @param msecs
* Duration (in milliseconds). Message will remain visible for at
* least the specified duration . This is achieved through a
* TimerTask that keeps the freezeStatusBar flag set to true for
* the specified time.
* @param restore
* If true, the previous message displayed in the status bar is
* reinstated after the specified duration.
* @see log
* @see error
*/
void showStatus(final String msg, final long msecs, final boolean restore) {
//final FontMetrics fm = statusBar.getFontMetrics(statusBar.getFont());
//final int maxLength = msg.length() * FRAME_WIDTH / fm.stringWidth(msg);
//if (msg.length() > maxLength)
// msg = msg.substring(0, maxLength - 3) + "...";
final String previousMsg = statusBar.getText();
statusBar.setText(msg);
if (msecs == 0)
return;
freezeStatusBar = true;
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
@Override
public void run() {
freezeStatusBar = false;
if (restore)
statusBar.setText(previousMsg);
timer.cancel();
}
};
try {
timer.schedule(task, msecs);
} catch (final Exception e) {
timer.cancel();
}
}
/**
* Displays an error message. When triggered in console mode the message is
* displayed for at least 4s. This is achieved through a timerTask that
* keeps the freezeStatusBar flag set to true for five seconds.
*
* @see log
* @see showStatus
*/
void error(final String errorMsg) {
error(errorMsg, isConsoleMode());
}
/**
* Displays an error message.
*
* @param persistent
* If true, the message is displayed for at least 4s. This is
* achieved through a timerTask that keeps the freezeStatusBar
* flag set to true for five seconds.
*
* @see log
* @see showStatus
*/
void error(final String errorMsg, final boolean persistent) {
statusBar.setForeground(Color.RED);
showStatus(errorMsg, (persistent) ? 4000 : 0, false);
}
/** Displays an ImageJ error message ensuring focus of main window */
void error(final String title, final String msg) {
IJ.error(title, msg);
frame.toFront();
}
/**
* Displays an informational message if status bar is not "frozen"
* (freezeStatusBar is false). Does nothing if freezeStatusBar is true
* (an error is being displayed).
*
* @see error
* @see showStatus
*/
void log(final String msg) {
if (!freezeStatusBar)
showStatus(msg, 0, false);
}
/**
* Displays a temporary informational message (visible only for the
* specified amount of time) if status bar is not "frozen" (freezeStatusBar
* is false). Does nothing if freezeStatusBar is true (an error is being
* displayed).
*
* @param msecs
* Duration (in milliseconds).
* @see error
* @see showStatus
*/
void log(final String msg, final long msecs) {
if (!freezeStatusBar)
showStatus(msg, msecs, true);
}
/**
* Interprets console commands upon receiving the exit status from
* execCommand
*
* @see execCommand
*/
void interpretCommand(final String cmd) {
if (cmd.isEmpty()) // just a spacer in command list
return;
final String result = execCommand(cmd);
// Case null: cmd encoded a path and encoded directory was not found
if (result == null) {
if (cmd.startsWith("imp")) {
error("Image directory unknown");
error("Unknown path", "Could not determine path of active image.");
} else if (cmd.startsWith("pwd")) {
error("Working directory unknown");
error("Unknown path", "Working directory is set upon a valid I/O operation.");
} else if (!cmd.startsWith("goto")) {
error("Directory not found");
error("Error", "The requested directory could not be found.");
}
resetCommandList();
return;
}
// Case 0: cmd encoded a non-verbose self-contained instruction
if (result.equals(String.valueOf(0))) {
resetFileList(CONSOLE_TRIGGER + cmd + " executed...");
prompt.requestFocusInWindow();
return;
}
// Remaining cases: cmd encodes a new path
changeDirectory(result);
prompt.requestFocusInWindow();
}
/**
* Executes console commands. Outputs one of the following exit status:
* <p>
* "0": Executed a a self-contained command that need no follow-up.
* null: Failed to retrieve a path.
* non-null string: A successfully retrieved path
*
* @see interpretCommand
*/
String execCommand(final String cmd) {
// Case "0": Self-contained commands that need no follow-up
String exitStatus = String.valueOf(0);