-
Notifications
You must be signed in to change notification settings - Fork 1
/
TabbedCustomDialog.java
1153 lines (1057 loc) · 45.5 KB
/
TabbedCustomDialog.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
/******************************************
Copyright 2018 Nuix
http://www.apache.org/licenses/LICENSE-2.0
*******************************************/
package com.nuix.nx.dialogs;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import javax.swing.*;
import com.nuix.nx.controls.models.DoubleBoundedRangeModel;
import org.apache.log4j.Logger;
import org.jdesktop.swingx.JXDatePicker;
import com.google.common.base.Joiner;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.nuix.nx.NuixConnection;
import com.nuix.nx.controls.BatchExporterLoadFileSettings;
import com.nuix.nx.controls.BatchExporterNativeSettings;
import com.nuix.nx.controls.BatchExporterPdfSettings;
import com.nuix.nx.controls.BatchExporterTextSettings;
import com.nuix.nx.controls.BatchExporterTraversalSettings;
import com.nuix.nx.controls.ChoiceTableControl;
import com.nuix.nx.controls.ComboItemBox;
import com.nuix.nx.controls.CsvTable;
import com.nuix.nx.controls.DynamicTableControl;
import com.nuix.nx.controls.LocalWorkerSettings;
import com.nuix.nx.controls.MultipleChoiceComboBox;
import com.nuix.nx.controls.OcrSettings;
import com.nuix.nx.controls.PathList;
import com.nuix.nx.controls.PathSelectionControl;
import com.nuix.nx.controls.StringList;
import com.nuix.nx.controls.models.Choice;
import com.nuix.nx.controls.models.ControlDeserializationHandler;
import com.nuix.nx.controls.models.ControlSerializationHandler;
/***
* Allows you to build a settings dialog with multiple tabs. Each tab is a {@link com.nuix.nx.dialogs.CustomTabPanel} which
* suports easily adding various controls such as check boxes, text field, radio buttons and so on.
* @author Jason Wells
*
*/
@SuppressWarnings("serial")
public class TabbedCustomDialog extends JDialog {
private static Logger logger = Logger.getLogger(TabbedCustomDialog.class);
private Map<String,CustomTabPanel> tabs = new LinkedHashMap<String,CustomTabPanel>();
Map<String,Component> controls;
private boolean dialogResult = false;
private ValidationCallback validationCallback;
private boolean stickySettingsEnabled = false;
private String stickySettingsFilePath = "";
private File helpFile = null;
private String helpUrl = null;
private String dateSerializationFormat = "yyyy-MM-dd HH:mm:ss";
private SimpleDateFormat sdf = new SimpleDateFormat(dateSerializationFormat);
private Map<String,ControlSerializationHandler> serializationHandlers = new HashMap<String,ControlSerializationHandler>();
private Map<String,ControlDeserializationHandler> deserializationHandlers = new HashMap<String,ControlDeserializationHandler>();
private JTabbedPane tabbedPane;
private JButton btnOk;
private JButton btnCancel;
private JMenuBar menuBar;
private JMenu mnFile;
private JMenuItem mntmSaveSettings;
private JMenuItem mntmLoadSettings;
private JMenu mnHelp;
private JMenuItem mntmViewHelp;
private Runnable jsonFileLoadedCallback;
/***
* Create a new instance.
*/
public TabbedCustomDialog() {
this("Script");
}
/***
* Create a new instance with the specified title.
* @param title The inital title of the dialog.
*/
public TabbedCustomDialog(String title) {
super((JDialog)null);
setTitle(title);
setIconImage(Toolkit.getDefaultToolkit().getImage(TabbedCustomDialog.class.getResource("/com/nuix/nx/dialogs/nuix_icon.png")));
controls = new HashMap<String,Component>();
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.setModal(true);
setSize(new Dimension(1024,768));
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{432, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
getContentPane().setLayout(gridBagLayout);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
GridBagConstraints gbc_tabbedPane = new GridBagConstraints();
gbc_tabbedPane.insets = new Insets(0, 0, 5, 0);
gbc_tabbedPane.fill = GridBagConstraints.BOTH;
gbc_tabbedPane.gridx = 0;
gbc_tabbedPane.gridy = 0;
getContentPane().add(tabbedPane, gbc_tabbedPane);
JPanel buttonsPanel = new JPanel();
GridBagConstraints gbc_buttonsPanel = new GridBagConstraints();
gbc_buttonsPanel.anchor = GridBagConstraints.EAST;
gbc_buttonsPanel.gridx = 0;
gbc_buttonsPanel.gridy = 1;
getContentPane().add(buttonsPanel, gbc_buttonsPanel);
btnOk = new JButton("Ok");
btnOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(TabbedCustomDialog.this.validationCallback != null){
try{
if(validationCallback.validate(TabbedCustomDialog.this.toMap()) == false){
return;
}
}
catch(Exception exc){
System.out.println("Validation callback on TabbedCustomDialog threw an exception!");
exc.printStackTrace();
}
}
TabbedCustomDialog.this.dialogResult = true;
if(stickySettingsEnabled){
try {
saveJsonFile(stickySettingsFilePath);
} catch (Exception e) {
}
}
TabbedCustomDialog.this.dispose();
}
});
buttonsPanel.add(btnOk);
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogResult = false;
TabbedCustomDialog.this.dispose();
}
});
buttonsPanel.add(btnCancel);
menuBar = new JMenuBar();
setJMenuBar(menuBar);
mnFile = new JMenu("File");
mnFile.setIcon(new ImageIcon(TabbedCustomDialog.class.getResource("/com/nuix/nx/dialogs/page_white_text.png")));
menuBar.add(mnFile);
mntmSaveSettings = new JMenuItem("Save Settings...");
mntmSaveSettings.setIcon(new ImageIcon(TabbedCustomDialog.class.getResource("/com/nuix/nx/dialogs/page_white_put.png")));
mntmSaveSettings.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
File saveLocation = CommonDialogs.saveFileDialog("", "Settings JSON File", "json", "Save Settings to File");
if(saveLocation != null){
try {
saveJsonFile(saveLocation.getPath());
} catch (Exception e) {
CommonDialogs.showError("Error while saving settings: "+e.getMessage());
e.printStackTrace();
}
}
}
});
mnFile.add(mntmSaveSettings);
mntmLoadSettings = new JMenuItem("Load Settings...");
mntmLoadSettings.setIcon(new ImageIcon(TabbedCustomDialog.class.getResource("/com/nuix/nx/dialogs/page_white_get.png")));
mntmLoadSettings.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
File loadLocation = CommonDialogs.openFileDialog("", "Settings JSON File", "json", "Load Settings to File");
if(loadLocation != null){
try {
loadJsonFile(loadLocation.getPath());
} catch (IOException e1) {
CommonDialogs.showError("Error while loading settings: " + e1.getMessage());
}
}
}
});
mnFile.add(mntmLoadSettings);
mnHelp = new JMenu("Help");
mnHelp.setIcon(new ImageIcon(TabbedCustomDialog.class.getResource("/com/nuix/nx/dialogs/help.png")));
mnHelp.setVisible(false);
menuBar.add(mnHelp);
mntmViewHelp = new JMenuItem("View Help");
mntmViewHelp.setVisible(false);
mntmViewHelp.setIcon(new ImageIcon(TabbedCustomDialog.class.getResource("/com/nuix/nx/dialogs/help.png")));
mntmViewHelp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(helpFile != null){
if(helpFile.exists()){
try {
Desktop.getDesktop().open(helpFile);
} catch (IOException e) {
e.printStackTrace();
}
} else {
CommonDialogs.showWarning("Could not find help file at: "+helpFile.getPath());
}
}
}
});
mnHelp.add(mntmViewHelp);
mntmViewOnlineHelp = new JMenuItem("View Online Help");
mntmViewOnlineHelp.setVisible(false);
mntmViewOnlineHelp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(helpUrl));
} catch (IOException e1) {
CommonDialogs.showError("Unable to open help page at "+helpUrl+"\n\n"+e1.getMessage());
}
}
});
mntmViewOnlineHelp.setIcon(new ImageIcon(TabbedCustomDialog.class.getResource("/com/nuix/nx/dialogs/help.png")));
mnHelp.add(mntmViewOnlineHelp);
}
/***
* Displays this custom dialog. Dialog is modal so this call will block caller until dialog is closed. To determine
* whether user clicked "Ok", "Cancel" or closed the dialog, call {@link #getDialogResult()} afterwards.
*/
public void display(){
dialogResult = false;
if(stickySettingsEnabled){
try{
loadJsonFile(stickySettingsFilePath);
}catch(Exception exc){
String message = String.format("Error while loading sticky settings JSON file '%s'", stickySettingsFilePath);
logger.error(message,exc);
}
}
if(helpFile != null && helpFile.exists()) {
mnHelp.setVisible(true);
mntmViewHelp.setVisible(true);
}
if(helpUrl != null && !helpUrl.trim().isEmpty()) {
mnHelp.setVisible(true);
mntmViewOnlineHelp.setVisible(true);
}
for(CustomTabPanel tab : tabs.values()){
tab.addVerticalFillerAsNeeded();
tabbedPane.addTab(tab.getLabel(), tab);
}
//pack();
setLocationRelativeTo(null);
setVisible(true);
}
/***
* Similar to {@link #display()} except that the dialog will be displayed non-modal and will invoke the provided callback
* when the dialog is closed and the result of {@link #getDialogResult()} returns true. Note that invoking this from a
* script essentially behaves as asynchronous call from the script's perspective!
* @param callback The callback to invoke when the dialog is closed.
*/
public void displayNonModal(Consumer<Boolean> callback){
dialogResult = false;
if(stickySettingsEnabled){
try{
loadJsonFile(stickySettingsFilePath);
}catch(Exception exc){
String message = String.format("Error while loading sticky settings JSON file '%s'", stickySettingsFilePath);
logger.error(message,exc);
}
}
if(helpFile != null && helpFile.exists()) {
mnHelp.setVisible(true);
mntmViewHelp.setVisible(true);
}
if(helpUrl != null && !helpUrl.trim().isEmpty()) {
mnHelp.setVisible(true);
mntmViewOnlineHelp.setVisible(true);
}
for(CustomTabPanel tab : tabs.values()){
tab.addVerticalFillerAsNeeded();
tabbedPane.addTab(tab.getLabel(), tab);
}
//Call users callback on successful close
this.addWindowListener(new WindowListener(){
@Override
public void windowOpened(WindowEvent e) { /*ignored for this use*/ }
@Override
public void windowClosing(WindowEvent e) { /*ignored for this use*/ }
@Override
public void windowClosed(WindowEvent e) {
if(getDialogResult() == true){
callback.accept(getDialogResult());
}
}
@Override
public void windowIconified(WindowEvent e) { /*ignored for this use*/ }
@Override
public void windowDeiconified(WindowEvent e) { /*ignored for this use*/ }
@Override
public void windowActivated(WindowEvent e) { /*ignored for this use*/ }
@Override
public void windowDeactivated(WindowEvent e) { /*ignored for this use*/ }
});
setModal(false);
setLocationRelativeTo(null);
setVisible(true);
}
/***
* Resizes the dialog to fill the screen, less the specified margin on all sides.
* @param margins The margin size on all sides
*/
public void fillScreen(int margins){
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension fillSize = new Dimension((int) screenSize.getWidth() - (margins * 2),
(int) screenSize.getHeight() - (margins * 2));
setSize(fillSize);
}
/***
* Gets the tab with the specified ID
* @param id The ID specified when the tab was created
* @return The tab associated with the specified ID
*/
public CustomTabPanel getTab(String id) {
return tabs.get(id);
}
/***
* Adds a new tab to the dialog.
* @param id The case sensitive unique identifier used to reference this tab
* @param label The label for the tab
* @return A newly created tab associated to this dialog
*/
public CustomTabPanel addTab(String id, String label) {
if(tabs.containsKey(id))
throw new RuntimeException("Dialog already contains a tab with the ID: "+id);
CustomTabPanel newTab = new CustomTabPanel(label,this);
tabs.put(id,newTab);
controls.put(id, newTab);
return newTab;
}
public ScrollableCustomTabPanel addScrollableTab(String id, String label) {
if(tabs.containsKey(id))
throw new RuntimeException("Dialog already contains a tab with the ID: "+id);
ScrollableCustomTabPanel newTab = new ScrollableCustomTabPanel(label,this);
tabs.put(id,newTab);
controls.put(id, newTab);
return newTab;
}
/***
* Updates the label for given tab to a new value
* @param tabId Id assigned to the tab when it was added
* @param label The new label value for the tab
*/
public void setTabLabel(String tabId, String label){
tabbedPane.setTitleAt(tabbedPane.indexOfComponent(getTab(tabId)), label);
}
/***
* Allows you to change the orientation of the tabs in the dialog by providing one of the
* JTabbedPane alignment constants
* @param tabPlacement A JTabbedPane alignment constant, such as JTabbedPane.LEFT
*/
public void setTabPlacement(int tabPlacement){
tabbedPane.setTabPlacement(tabPlacement);
}
/***
* Changes the orientation of the dialogs tabs to be along the left side of the dialog
*/
public void setTabPlacementLeft(){
setTabPlacement(JTabbedPane.LEFT);
}
/***
* Gets the result of showing the dialog.
* @return True if the user clicked the 'Ok' button. False if otherwise ('Cancel' button or closed the dialog).
*/
public boolean getDialogResult() {
return dialogResult;
}
/***
* Returns a Map of the control values.
* @return Map where the assigned identifier is the key and the control's value is the value.
*/
public Map<String,Object> toMap(){
return toMap(false);
}
/***
* Returns a Map of the control values.
* @param forJsonCreation Set to true if the output is intended to be serialized to JSON. Some
* of the values in the map may be generated differently to better cooperate with what JSON
* is capable of storing.
* @return Map where the assigned identifier is the key and the control's value is the value.
*/
public Map<String,Object> toMap(boolean forJsonCreation){
Map<String,Object> result = new HashMap<String,Object>();
for(CustomTabPanel tab : tabs.values()){
result.putAll(tab.toMap(forJsonCreation));
}
return result;
}
/***
* Registers an event handle such that a given control is only enabled when another checkable control is checked.
* @param dependentControlIdentifier The identifier of the already added control for which the enabled state depends on another checkable control.
* @param targetCheckableIdentifier The identifier of the already added checkable control which will determine the enabled state of the dependent control.
* @throws Exception This could be caused by various things such as invalid identifiers or the identifier provided in targetCheckableIdentifier
* does not point to a checkable control (CheckBox or RadioButton).
*/
public void enabledOnlyWhenChecked(String dependentControlIdentifier, String targetCheckableIdentifier) throws Exception{
Component dependentComponent = controls.get(dependentControlIdentifier);
Component targetComponent = controls.get(targetCheckableIdentifier);
boolean currentCheckedState = isChecked(targetCheckableIdentifier);
dependentComponent.setEnabled(currentCheckedState);
((java.awt.ItemSelectable)targetComponent).addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent arg0) {
try {
controls.get(dependentControlIdentifier).setEnabled(isChecked(targetCheckableIdentifier));
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/***
* Similar to {@link #enabledOnlyWhenChecked(String, String)}, this method registers event handlers on one or more checkable controls
* such that a given dependent control is only enabled when all of the specified target checkable controls are checked.
* @param dependentControlIdentifier The identifier of the already added control for which the enabled state depends on another checkable control.
* @param targetCheckableIdentifiers The identifier of the one or more already added checkable controls which will determine the enabled state
* of the dependent control.
* @throws Exception This could be caused by various things such as invalid identifiers or the identifier provided in targetCheckableIdentifier
* does not point to a checkable control (CheckBox or RadioButton).
*/
public void enabledOnlyWhenAllChecked(String dependentControlIdentifier, String... targetCheckableIdentifiers) throws Exception {
Component dependentComponent = controls.get(dependentControlIdentifier);
for (int i = 0; i < targetCheckableIdentifiers.length; i++) {
Component targetComponent = controls.get(targetCheckableIdentifiers[i]);
if(targetComponent instanceof java.awt.ItemSelectable) {
((java.awt.ItemSelectable)targetComponent).addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent arg0) {
try {
boolean currentCheckedState = allAreChecked(targetCheckableIdentifiers);
dependentComponent.setEnabled(currentCheckedState);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
// Set initial state
boolean currentCheckedState = allAreChecked(targetCheckableIdentifiers);
dependentComponent.setEnabled(currentCheckedState);
}
/***
* Similar to {@link #enabledOnlyWhenChecked(String, String)}, this method registers event handlers on one or more checkable controls
* such that a given dependent control is only enabled when none of the specified target checkable controls are checked.
* @param dependentControlIdentifier The identifier of the already added control for which the enabled state depends on another checkable control.
* @param targetCheckableIdentifiers The identifier of the one or more already added checkable controls which will determine the enabled state
* of the dependent control.
* @throws Exception This could be caused by various things such as invalid identifiers or the identifier provided in targetCheckableIdentifier
* does not point to a checkable control (CheckBox or RadioButton).
*/
public void enabledOnlyWhenNoneChecked(String dependentControlIdentifier, String... targetCheckableIdentifiers) throws Exception {
Component dependentComponent = controls.get(dependentControlIdentifier);
for (int i = 0; i < targetCheckableIdentifiers.length; i++) {
Component targetComponent = controls.get(targetCheckableIdentifiers[i]);
if(targetComponent instanceof java.awt.ItemSelectable) {
((java.awt.ItemSelectable)targetComponent).addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent arg0) {
try {
boolean currentCheckedState = noneAreChecked(targetCheckableIdentifiers);
dependentComponent.setEnabled(currentCheckedState);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
// Set initial state
boolean currentCheckedState = noneAreChecked(targetCheckableIdentifiers);
dependentComponent.setEnabled(currentCheckedState);
}
/***
* Similar to {@link #enabledOnlyWhenChecked(String, String)}, this method registers event handlers on one or more checkable controls
* such that a given dependent control is only enabled when at least one of the specified target checkable controls are checked.
* @param dependentControlIdentifier The identifier of the already added control for which the enabled state depends on another checkable control.
* @param targetCheckableIdentifiers The identifier of the one or more already added checkable controls which will determine the enabled state
* of the dependent control.
* @throws Exception This could be caused by various things such as invalid identifiers or the identifier provided in targetCheckableIdentifier
* does not point to a checkable control (CheckBox or RadioButton).
*/
public void enabledIfAnyChecked(String dependentControlIdentifier, String... targetCheckableIdentifiers) throws Exception {
Component dependentComponent = controls.get(dependentControlIdentifier);
for (int i = 0; i < targetCheckableIdentifiers.length; i++) {
Component targetComponent = controls.get(targetCheckableIdentifiers[i]);
if(targetComponent instanceof java.awt.ItemSelectable) {
((java.awt.ItemSelectable)targetComponent).addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent arg0) {
try {
boolean currentCheckedState = anyAreChecked(targetCheckableIdentifiers);
dependentComponent.setEnabled(currentCheckedState);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
// Set initial state
boolean currentCheckedState = anyAreChecked(targetCheckableIdentifiers);
dependentComponent.setEnabled(currentCheckedState);
}
/***
* Registers an event handle such that a given control is only enabled when another checkable control is not checked.
* @param dependentControlIdentifier The identifier of the already added control for which the enabled state depends on another checkable control.
* @param targetCheckableIdentifier The identifier of the already added checkable control which will determine the enabled state of the dependent control.
* @throws Exception This could be caused by various things such as invalid identifiers or the identifier provided in targetCheckableIdentifier
* does not point to a checkable control (CheckBox or RadioButton).
*/
public void enabledOnlyWhenNotChecked(String dependentControlIdentifier, String targetCheckableIdentifier) throws Exception{
Component dependentComponent = controls.get(dependentControlIdentifier);
Component targetComponent = controls.get(targetCheckableIdentifier);
boolean currentCheckedState = isChecked(targetCheckableIdentifier);
dependentComponent.setEnabled(!currentCheckedState);
((java.awt.ItemSelectable)targetComponent).addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent arg0) {
try {
controls.get(dependentControlIdentifier).setEnabled(!isChecked(targetCheckableIdentifier));
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/***
* Gets whether a particular Checkbox or RadioButton is checked.
* @param identifier The unique identifier assigned to the control when it was appended to this dialog.
* @return True if the control is checked, false otherwise.
* @throws Exception Thrown if identifier is invalid or identifier does not refer to a Checkbox or RadioButton.
*/
public boolean isChecked(String identifier) throws Exception{
Component component = controls.get(identifier);
if(component instanceof JCheckBox){
return ((JCheckBox)controls.get(identifier)).isSelected();
}
else if(component instanceof JRadioButton){
return ((JRadioButton)controls.get(identifier)).isSelected();
}
else
throw new Exception("Control for identifier '"+identifier+"' is not a JCheckbox or JRadioButton");
}
public boolean allAreChecked(String... identifiers) throws Exception {
for (int i = 0; i < identifiers.length; i++) {
if(!isChecked(identifiers[i])) { return false; }
}
return true;
}
public boolean noneAreChecked(String... identifiers) throws Exception {
for (int i = 0; i < identifiers.length; i++) {
if(isChecked(identifiers[i])) { return false; }
}
return true;
}
public boolean anyAreChecked(String... identifiers) throws Exception {
for (int i = 0; i < identifiers.length; i++) {
if(isChecked(identifiers[i])) { return true; }
}
return false;
}
/***
* Sets whether a particular Checkbox or RadioButton is checked.
* @param identifier The unique identifier assigned to the control when it was appended to this dialog.
* @param isChecked True to check the control, false to uncheck the control.
* @throws Exception Thrown if identifier is invalid or identifier does not refer to a Checkbox or RadioButton.
*/
public void setChecked(String identifier, boolean isChecked) throws Exception{
Component component = controls.get(identifier);
if(component instanceof JCheckBox){
((JCheckBox)controls.get(identifier)).setSelected(isChecked);
}
else if(component instanceof JRadioButton){
((JRadioButton)controls.get(identifier)).setSelected(isChecked);
}
else
throw new Exception("Control for identifier '"+identifier+"' is not a JCheckbox or JRadioButton");
}
/***
* Gets the text present in a TextField or PasswordField.
* @param identifier The unique identifier assigned to the control when it was appended to this dialog.
* @return The text present in the control.
* @throws Exception Thrown if identifier is invalid or identifier does not refer to a TextField or PasswordField.
*/
public String getText(String identifier) throws Exception{
Component component = controls.get(identifier);
if(component instanceof JPasswordField){
return new String(((JPasswordField)component).getPassword());
}
else if (component instanceof JTextField){
return ((JTextField)component).getText();
}
else if(component instanceof PathSelectionControl){
return ((PathSelectionControl)component).getPath();
}
else if(component instanceof JComboBox<?>){
return (String)((JComboBox<?>)component).getSelectedItem();
}
else if(component instanceof JTextArea){
return ((JTextArea)component).getText();
}
else
throw new Exception("Control for identifier '"+identifier+"' is not a supported control type: JPasswordField, JTextField, PathSelectionControl, JTextArea");
}
/***
* Sets the text present in a TextField or PasswordField.
* @param identifier The unique identifier assigned to the control when it was appended to this dialog.
* @param text The text value to set.
* @throws Exception Thrown if identifier is invalid or identifier does not refer to a TextField or PasswordField.
*/
public void setText(String identifier, String text) throws Exception{
Component component = controls.get(identifier);
if(component instanceof JPasswordField){
((JPasswordField)component).setText(text);
}
else if (component instanceof JTextField){
((JTextField)component).setText(text);
}
else if(component instanceof PathSelectionControl){
((PathSelectionControl)component).setPath(text);
}
else if(component instanceof ComboItemBox){
((ComboItemBox)component).setSelectedValue(text);
}
else if(component instanceof JComboBox<?>){
((JComboBox<?>)component).setSelectedItem(text);
}
else if (component instanceof JTextArea){
((JTextArea)component).setText(text);
}
else
throw new Exception("Control for identifier '"+identifier+"' is not a supported control type: JPasswordField, JTextField, PathSelectionControl, JTextArea");
}
/***
* Allows you to get the actual Java Swing control. You will likely need to cast it to the appropriate type before use.
* @param identifier The unique identifier assigned to the control when it was appended to this dialog.
* @return The control as base class Component. See documentation for various append methods for control types.
*/
public Component getControl(String identifier){
return controls.get(identifier);
}
/***
* This enables "sticky settings" where the dialog will save a JSON file of settings when 'Okay' is clicked and will attempt to
* load previously saved settings when the dialog is displayed. This currently only works with controls added to the dialog which
* support {@link setText} and {@link setChecked}. See {@link #toJson} and {@link #loadJson}.
* @param filePath The full file path where you expect the settings JSON file to be located. Likely you will generate a path relative to your script at runtime.
*/
public void enableStickySettings(String filePath){
stickySettingsEnabled = true;
stickySettingsFilePath = filePath;
}
/***
* Allows code to implement and provide a callback which can validate whether things are okay.
* @param callback Callback should return false if things are not satisfactory, true otherwise.
*/
public void validateBeforeClosing(ValidationCallback callback){
validationCallback = callback;
}
/***
* Gets a JSON String equivalent of the dialog values. This is a convenience method for calling
* {@link #toMap} and then converting that Map to a JSON string.
* @return A JSON string representation of the dialogs values (based on the Map returned by {@link toMap}).
*/
public String toJson(){
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
builder.setDateFormat(dateSerializationFormat);
Gson gson = builder.create();
String jsonString = gson.toJson(toMap(true));
// https://github.com/google/gson/issues/388#issuecomment-83704872
StringBuilder result = new StringBuilder();
for(char c : jsonString.toCharArray()) {
if (c <= 0x7F) {
result.append(c);
} else {
// Escape
result.append(String.format("\\u%04x", (int) c));
}
}
return result.toString();
}
/***
* Attempts to set control values based on entries in JSON file. Entries which are unknown or cause errors are ignored.
* Loads JSON onto any controls in any tabs contained by this TabbedCustomDialog instance.
* @param json A JSON string to attempt to load.
*/
public void loadJson(String json){
loadJson(json,controls);
}
/***
* Loads JSON but only to the controls contained within the specified tab.
* @param json A JSON string to attempt to load
* @param tabIdentifier Identifier of existing tab to which you would like to load the JSON into.
*/
public void loadJson(String json, String tabIdentifier){
loadJson(json,tabs.get(tabIdentifier).controls);
}
/***
* Attempts to set control values based on entries in JSON file. Entries which are unknown or cause errors are ignored.
* @param json A JSON string to attempt to load.
* @param controlMap A map of components to load the JSON onto.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public void loadJson(String json, Map<String,Component> controlMap){
Gson gson = new Gson();
System.out.println("Parsing JSON...");
Map<String,Object> fieldValues = gson.fromJson(json,new TypeToken<Map<String,Object>>(){}.getType());
System.out.println("Assigning values to controls...");
for(Map.Entry<String,Object> entry : fieldValues.entrySet()){
String controlIdentifier = entry.getKey();
Component control = controlMap.get(controlIdentifier);
try{
if(deserializationHandlers.containsKey(controlIdentifier)){
//Dynamic table needs to have filter cleared before being meddled with
if (control instanceof DynamicTableControl){
((DynamicTableControl)control).setFilter("");
}
deserializationHandlers.get(controlIdentifier).deserializeControlData(entry.getValue(), control);
}
else if (entry.getValue() instanceof Boolean){
// Call general purpose set checked method
setChecked(controlIdentifier,(Boolean)entry.getValue());
}
else if(control instanceof JSpinner){
((JSpinner)control).setValue(entry.getValue());
}
else if(control instanceof JSlider) {
BoundedRangeModel model = ((JSlider) control).getModel();
if(model instanceof DoubleBoundedRangeModel) {
((DoubleBoundedRangeModel)model).setValue(((Number)entry.getValue()).doubleValue());
} else {
model.setValue(((Number)entry.getValue()).intValue());
}
}
// These require a bit more logic to deserialize
else if(control instanceof ChoiceTableControl){
ChoiceTableControl choiceTable = (ChoiceTableControl) control;
choiceTable.getTableModel().uncheckAllChoices();
List<String> selectedLabels = new ArrayList<String>();
for(String value : (Iterable<String>)entry.getValue()){
selectedLabels.add(value);
}
choiceTable.getTableModel().setCheckedByLabels(selectedLabels, true);
choiceTable.getTableModel().sortCheckedToTop();
} else if(control instanceof PathList){
PathList pathList = (PathList) control;
List<String> values = new ArrayList<String>();
for(String value : (Iterable<String>)entry.getValue()){
values.add(value);
}
pathList.setPaths(values);
}
else if(control instanceof StringList){
StringList stringList = (StringList) control;
List<String> values = new ArrayList<String>();
for(String value : (Iterable<String>)entry.getValue()){
values.add(value);
}
stringList.setValues(values);
}
else if(control instanceof MultipleChoiceComboBox) {
MultipleChoiceComboBox mccb = (MultipleChoiceComboBox) control;
List<String> values = (ArrayList<String>) entry.getValue();
mccb.setCheckedChoices(values);
}
else if(control instanceof LocalWorkerSettings){
LocalWorkerSettings lws = (LocalWorkerSettings) control;
Map<String,Object> settings = (Map<String,Object>)entry.getValue();
//System.out.println(settings);
lws.setWorkerCount(((Double) settings.get("workerCount")).intValue());
lws.setMemoryPerWorker(((Double) settings.get("workerMemory")).intValue());
lws.setWorkerTempDirectory((String) settings.get("workerTemp"));
}
else if(control instanceof BatchExporterTraversalSettings){
BatchExporterTraversalSettings bets = (BatchExporterTraversalSettings) control;
Map<String,Object> settings = (Map<String,Object>)entry.getValue();
bets.getComboTraversal().setSelectedValue((String)settings.get("strategy"));
bets.getComboDedupe().setSelectedValue((String)settings.get("deduplication"));
bets.getComboSortOrder().setSelectedValue((String)settings.get("sortOrder"));
}
else if(control instanceof BatchExporterNativeSettings){
BatchExporterNativeSettings bens = (BatchExporterNativeSettings) control;
Map<String,Object> settings = (Map<String,Object>)entry.getValue();
bens.getComboNaming().setSelectedValue((String)settings.get("naming"));
bens.getTxtPath().setText((String)settings.get("path"));
bens.getTxtSuffix().setText((String)settings.get("suffix"));
bens.getComboMailFormat().setSelectedValue((String)settings.get("mailFormat"));
bens.getChckbxIncludeAttachments().setSelected((Boolean)settings.get("includeAttachments"));
bens.getChckbxRegenerateStored().setSelected((Boolean)settings.get("regenerateStored"));
}
else if(control instanceof BatchExporterTextSettings){
BatchExporterTextSettings bets = (BatchExporterTextSettings) control;
Map<String,Object> settings = (Map<String,Object>)entry.getValue();
bets.getComboNaming().setSelectedValue((String)settings.get("naming"));
bets.getTxtPath().setText((String)settings.get("path"));
bets.getTxtSuffix().setText((String)settings.get("suffix"));
bets.getChckbxWrapLines().setSelected((Boolean)settings.get("wrapLinesChecked"));
bets.getSpinnerWrapLength().setValue(((Double)settings.get("wrapLines")).intValue());
bets.getComboLineSeparator().setSelectedValue((String)settings.get("lineSeparator"));
bets.getComboEncoding().setSelectedValue((String)settings.get("encoding"));
}
else if(control instanceof BatchExporterPdfSettings){
BatchExporterPdfSettings beps = (BatchExporterPdfSettings) control;
Map<String,Object> settings = (Map<String,Object>)entry.getValue();
beps.getComboNaming().setSelectedValue((String)settings.get("naming"));
beps.getTxtPath().setText((String)settings.get("path"));
beps.getTxtSuffix().setText((String)settings.get("suffix"));
beps.getChckbxRegenerateStored().setSelected((Boolean)settings.get("regenerateStored"));
}
else if(control instanceof BatchExporterLoadFileSettings){
BatchExporterLoadFileSettings belfs = (BatchExporterLoadFileSettings) control;
Map<String,Object> settings = (Map<String,Object>)entry.getValue();
belfs.getComboLoadFileType().setSelectedValue((String)settings.get("type"));
belfs.getComboProfile().setSelectedValue((String)settings.get("metadataProfile"));
belfs.getComboEncoding().setSelectedValue((String)settings.get("encoding"));
belfs.getComboLineSeparator().setSelectedValue((String)settings.get("lineSeparator"));
}
else if(control instanceof OcrSettings){
OcrSettings os = (OcrSettings) control;
Map<String,Object> settings = (Map<String,Object>)entry.getValue();
os.getChckbxRegeneratePdfs().setSelected((Boolean)settings.get("regeneratePdfs"));
os.getChckbxUpdatePdfText().setSelected((Boolean)settings.get("updatePdf"));
os.getChckbxUpdateItemText().setSelected((Boolean)settings.get("updateText"));
os.getComboTextModification().setSelectedValue((String)settings.get("textModification"));
os.getComboQuality().setSelectedValue((String)settings.get("quality"));
os.getComboRotation().setSelectedValue((String)settings.get("rotation"));
os.getChckbxDeskew().setSelected((Boolean)settings.get("deskew"));
os.getOutputDirectory().setPath((String)settings.get("outputDirectory"));
if(NuixConnection.getCurrentNuixVersion().isAtLeast("7.2.0") && settings.containsKey("updateDuplicates")){
os.setUpdateDuplicates((Boolean)settings.get("updateDuplicates"));
}
if(NuixConnection.getCurrentNuixVersion().isAtLeast("7.2.0") && settings.containsKey("timeout")){
os.setTimeoutMinutes(((Double)settings.get("timeout")).intValue());
}
ChoiceTableControl choiceTable = os.getLanguageChoices();
// Should clear check state before loading in new check state
choiceTable.getTableModel().uncheckAllChoices();
List<Choice> loadedChoices = new ArrayList<Choice>();
for(String value : (Iterable<String>)settings.get("languages")){
Choice choice = choiceTable.getTableModel().getFirstChoiceByLabel(value);
if(choice != null){
choiceTable.getTableModel().setChoiceSelection(choice, true);
loadedChoices.add(choice);
}
else {
System.out.println("Unable to resolve choice for "+entry.getKey()+" => "+value);
}
}
choiceTable.getTableModel().sortChoicesToTop(loadedChoices);
}
else if (control instanceof DynamicTableControl){
((DynamicTableControl)control).setFilter("");
List<String> values = new ArrayList<String>();
for(String value : (Iterable<String>)entry.getValue()){
values.add(value);
}
((DynamicTableControl)control).getTableModel().setCheckedRecordsFromHashes(values);
}
else if (control instanceof CsvTable){
CsvTable table = (CsvTable)control;
List<Map<String,String>> records = (List<Map<String,String>>)entry.getValue();
for (Map<String, String> record : records) {
table.addRecord(record);
}
}
else if(entry.getValue() instanceof String){
if(control instanceof JXDatePicker){
((JXDatePicker)control).setDate(sdf.parse((String)entry.getValue()));
} else {
// Call general purpose set text method
setText(controlIdentifier,(String)entry.getValue());
}
}
}catch(Exception exc){
System.out.println("Error while deserializing JSON field '"+controlIdentifier+"':");
System.out.println(exc.toString());
exc.printStackTrace();
}
}
}
/***
* Saves the settings of this dialog to a JSON file
* @param filePath Path to the JSON file settings will be saved to
* @throws Exception Thrown if there are exceptions while saving the file
*/
public void saveJsonFile(String filePath) throws Exception{
FileWriter fw = null;
PrintWriter pw = null;
try{
fw = new FileWriter(filePath);
pw = new PrintWriter(fw);
pw.print(toJson());
}catch(Exception exc){
throw exc;
}
finally{
try {
if(fw != null) { fw.close(); }
if(pw != null) { pw.close(); }
} catch (Exception e) {
e.printStackTrace();