-
Notifications
You must be signed in to change notification settings - Fork 0
/
JWFileChooserViewController.java
938 lines (816 loc) · 26.5 KB
/
JWFileChooserViewController.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
/*
* Copyright © 2020 Mark Raynsford <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jwheatsheaf.ui.internal;
import com.io7m.jaffirm.core.Preconditions;
import com.io7m.jwheatsheaf.api.JWDirectoryCreationFailed;
import com.io7m.jwheatsheaf.api.JWFileChooserConfiguration;
import com.io7m.jwheatsheaf.api.JWFileChooserEventType;
import com.io7m.jwheatsheaf.api.JWFileChooserFilterType;
import com.io7m.jwheatsheaf.api.JWFileImageSetType;
import com.io7m.jwheatsheaf.api.JWFileListingFailed;
import com.io7m.jwheatsheaf.ui.JWFileChoosers;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TextInputDialog;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.util.Callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* The file chooser view controller.
*
* The {@code setConfiguration} method must be called after creation.
*/
public final class JWFileChooserViewController
{
private static final Logger LOG =
LoggerFactory.getLogger(JWFileChooserViewController.class);
private final AtomicReference<Consumer<JWFileChooserEventType>> eventReceiver;
private final BlockingDeque<String> initialFilename;
private final ChangeListener<Path> listener;
@FXML private Button homeDirectoryButton;
@FXML private Button newDirectoryButton;
@FXML private Button okButton;
@FXML private Button selectDirectButton;
@FXML private Button upDirectoryButton;
@FXML private ChoiceBox<Path> pathMenu;
@FXML private ComboBox<JWFileChooserFilterType> fileTypeMenu;
@FXML private ListView<JWFileSourceEntryType> sourcesList;
@FXML private Pane mainContent;
@FXML private ProgressIndicator progressIndicator;
@FXML private TableView<JWFileItem> directoryTable;
@FXML private TextField fileName;
@FXML private TextField searchField;
private ExecutorService ioExecutor;
private JWFileChooserConfiguration configuration;
private JWFileChooserFilterType filterAll;
private JWFileChooserFilterType filterOnlyDirectories;
private JWFileChoosers choosers;
private JWFileChoosersTesting testing;
private JWFileImageSetType imageSet;
private JWFileList fileListing;
private JWStrings strings;
private JWToolTips toolTips;
private List<Node> lockableViews;
private List<Path> result;
private TableView.TableViewSelectionModel<JWFileItem> directoryTableSelectionModel;
private volatile Path currentDirectory;
/**
* Construct a view controller.
*/
public JWFileChooserViewController()
{
this.listener = this::onPathMenuItemSelected;
this.result = List.of();
this.initialFilename = new LinkedBlockingDeque<>();
this.eventReceiver = new AtomicReference<>(event -> {
});
}
private static List<Path> allParentsOf(
final Path startDirectory)
{
final var parents = new ArrayList<Path>(startDirectory.getNameCount());
parents.add(startDirectory);
var currentDirectory = startDirectory.getParent();
while (currentDirectory != null) {
parents.add(currentDirectory);
currentDirectory = currentDirectory.getParent();
}
return parents;
}
private String formatSize(
final long size)
{
return this.configuration.fileSizeFormatter().formatSize(size);
}
public void setEventReceiver(
final Consumer<JWFileChooserEventType> newEventReceiver)
{
this.eventReceiver.set(
Objects.requireNonNullElse(newEventReceiver, event -> {
}));
}
/**
* Set the file chooser provider and configuration.
*
* @param inChoosers The provider
* @param inIoExecutor An executor for background I/O operations
* @param inTesting An internal testing interface
* @param inStrings UI strings
* @param inDefaultImageSet The default image set
* @param inConfiguration The configuration
*/
public void setConfiguration(
final JWFileChoosers inChoosers,
final ExecutorService inIoExecutor,
final JWFileChoosersTesting inTesting,
final JWStrings inStrings,
final JWFileImageSetType inDefaultImageSet,
final JWFileChooserConfiguration inConfiguration)
{
this.choosers =
Objects.requireNonNull(inChoosers, "inChoosers");
this.configuration =
Objects.requireNonNull(inConfiguration, "configuration");
this.testing =
Objects.requireNonNull(inTesting, "inTesting");
this.strings =
Objects.requireNonNull(inStrings, "inStrings");
this.ioExecutor =
Objects.requireNonNull(inIoExecutor, "inIoExecutor");
Objects.requireNonNull(inDefaultImageSet, "inDefaultImageSet");
this.directoryTableSelectionModel =
this.directoryTable.getSelectionModel();
this.toolTips =
new JWToolTips(this.strings);
this.filterAll =
JWFileChooserFilterAllFiles.create(this.strings);
this.filterOnlyDirectories =
JWFileChooserFilterOnlyDirectories.create(this.strings);
this.fileListing =
new JWFileList(this.filterAll);
this.imageSet =
this.configuration.fileImageSet()
.orElse(inDefaultImageSet);
this.newDirectoryButton.setGraphic(
JWImages.imageView16x16Of(this.imageSet.forDirectoryCreate())
);
this.upDirectoryButton.setGraphic(
JWImages.imageView16x16Of(this.imageSet.forDirectoryUp())
);
this.selectDirectButton.setGraphic(
JWImages.imageView16x16Of(this.imageSet.forSelectDirect())
);
this.homeDirectoryButton.setGraphic(
JWImages.imageView16x16Of(this.imageSet.forHome())
);
final var fileSystem =
this.configuration.fileSystem();
final var startDirectory =
this.configuration.initialDirectory()
.orElse(fileSystem.getPath("").toAbsolutePath());
this.configureButtons();
this.configureSearch();
this.configureFileField();
this.configureTableView();
this.configureFileTypeMenu();
this.configureSourceList(fileSystem);
/*
* The list of views that will be "locked" when an I/O operation is
* happening.
*/
this.lockableViews = List.of(
this.directoryTable,
this.homeDirectoryButton,
this.newDirectoryButton,
this.okButton,
this.pathMenu,
this.searchField,
this.selectDirectButton,
this.sourcesList,
this.upDirectoryButton
);
this.setCurrentDirectory(startDirectory);
}
private void configureSearch()
{
this.searchField.textProperty()
.addListener(observable -> this.onSearchFieldChanged());
}
private void configureFileField()
{
this.fileName.textProperty()
.addListener(observable -> this.onNameFieldChanged());
this.configuration.initialFileName()
.ifPresent(this.initialFilename::push);
}
private void configureSourceList(
final FileSystem fileSystem)
{
/*
* Add a set of source entries. The list begins with the
* recent items source, and then contains one entry per filesystem
* root.
*/
final var sources = new ArrayList<JWFileSourceEntryType>();
sources.add(new JWFileSourceEntryRecentItems(this.configuration));
for (final var root : fileSystem.getRootDirectories()) {
sources.add(new JWFileSourceEntryFilesystemRoot(
this.configuration.showParentDirectory(), root)
);
}
this.sourcesList.setItems(FXCollections.observableList(sources));
this.sourcesList.setCellFactory(new SourceListCellFactory());
}
private void configureFileTypeMenu()
{
final Callback<ListView<JWFileChooserFilterType>, ListCell<JWFileChooserFilterType>> cellFactory =
param -> {
final ListCell<JWFileChooserFilterType> cell = new ListCell<>()
{
@Override
protected void updateItem(
final JWFileChooserFilterType item,
final boolean empty)
{
super.updateItem(item, empty);
if (empty || item == null) {
this.setGraphic(null);
this.setText(null);
return;
}
this.setText(item.description());
this.setGraphic(null);
}
};
return cell;
};
this.fileTypeMenu.setCellFactory(cellFactory);
this.fileTypeMenu.setButtonCell(cellFactory.call(null));
final var filters = new ArrayList<JWFileChooserFilterType>();
filters.add(this.filterAll);
filters.add(this.filterOnlyDirectories);
filters.addAll(this.configuration.fileFilters());
this.fileTypeMenu.setItems(FXCollections.observableList(filters));
/*
* Select the default filter. If there isn't one, select the first
* filter.
*/
final var selectionModel =
this.fileTypeMenu.getSelectionModel();
this.configuration.fileFilterDefault()
.ifPresentOrElse(
selectionModel::select,
() -> selectionModel.select(0)
);
this.onFileFilterSelected();
}
/**
* Set the current directory. This has the effect of rebuilding the
* path menu at the top of the file chooser, and populating the directory
* table.
*
* @param path The new directory
*/
private void setCurrentDirectory(
final Path path)
{
this.currentDirectory = Objects.requireNonNull(path, "path");
this.rebuildPathMenu(path);
this.populateDirectoryTable(path);
}
private void rebuildPathMenu(
final Path startDirectory)
{
final var directories = allParentsOf(startDirectory);
final var selectionModel = this.pathMenu.getSelectionModel();
selectionModel.selectedItemProperty().removeListener(this.listener);
this.pathMenu.setItems(FXCollections.observableList(directories));
selectionModel.select(0);
selectionModel.selectedItemProperty().addListener(this.listener);
}
private void populateDirectoryTable(
final Path directory)
{
this.populateDirectoryTableWith(
() -> JWFileItems.listDirectory(
directory,
this.configuration.showParentDirectory())
);
}
private void populateDirectoryTableWith(
final JWFileListingRetrieverType itemRetriever)
{
this.directoryTable.setItems(this.fileListing.items());
this.ioLockUI();
this.ioExecutor.execute(() -> {
try {
final var items = itemRetriever.onFileItemsRequested();
this.applyTestingIODelayIfRequested();
Platform.runLater(() -> {
this.ioUnlockUI();
this.fileListing.setItems(items);
try {
final var name = this.initialFilename.pop();
this.trySelectDirectoryItem(items, name);
this.fileName.setText(name);
} catch (final NoSuchElementException e) {
// Most of the time, there's no initial filename.
}
});
} catch (final Exception e) {
LOG.error("exception during directory listing: ", e);
Platform.runLater(() -> {
this.ioUnlockUI();
this.fileListing.setItems(List.of());
try {
this.eventReceiver.get()
.accept(JWFileListingFailed.of(this.currentDirectory, e));
} catch (final Exception ex) {
LOG.error("exception raised by event receiver: ", ex);
}
});
}
});
}
/**
* Select the item in the list of file items that has the given name and
* return it. If none of them have the given name, do nothing and return
* nothing.
*/
private Optional<JWFileItem> trySelectDirectoryItem(
final List<JWFileItem> items,
final String name)
{
for (final var item : items) {
/*
* Check to see if the given name matches the display name of the file.
* Some file items have artificial display names (such as "." and "..").
*/
final var itemDisplayOpt = item.displayName();
if (itemDisplayOpt.isPresent()) {
final var itemDisplay = itemDisplayOpt.get();
if (Objects.equals(itemDisplay, name)) {
this.directoryTableSelectionModel.select(item);
return Optional.of(item);
}
}
/*
* Check to see if the given name matches the filename component
* of the file item path.
*/
final var itemFile =
Optional.ofNullable(item.path().getFileName())
.map(Path::toString)
.orElse(null);
if (Objects.equals(itemFile, name)) {
this.directoryTableSelectionModel.select(item);
return Optional.of(item);
}
}
return Optional.empty();
}
/**
* Select the item in the list of file items that has the given name and
* return it. If none of them have the given name, do nothing and clear
* the directory table selection.
*/
private Optional<JWFileItem> trySelectDirectoryItemOrDeselect(
final TableView<JWFileItem> tableView,
final String name)
{
final var selected =
this.trySelectDirectoryItem(tableView.getItems(), name);
if (selected.isEmpty()) {
this.directoryTableSelectionModel.clearSelection();
}
return selected;
}
private void ioUnlockUI()
{
Preconditions.checkPreconditionV(
Platform.isFxApplicationThread(),
"Must be the FX application thread");
for (final var view : this.lockableViews) {
view.setDisable(false);
}
this.progressIndicator.setVisible(false);
this.reconfigureOKButton();
}
private void ioLockUI()
{
Preconditions.checkPreconditionV(
Platform.isFxApplicationThread(),
"Must be the FX application thread");
for (final var view : this.lockableViews) {
view.setDisable(true);
}
this.progressIndicator.setVisible(true);
}
private void applyTestingIODelayIfRequested()
{
this.testing
.ioDelay()
.ifPresent(duration -> {
try {
Thread.sleep(duration.toMillis());
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
private void onPathMenuItemSelected(
final ObservableValue<? extends Path> observable,
final Path oldValue,
final Path newValue)
{
this.setCurrentDirectory(newValue);
}
@FXML
private void onFileFilterSelected()
{
this.fileListing.setFilter(this.fileTypeMenu.getValue());
}
@FXML
private void onSearchFieldChanged()
{
this.fileListing.setSearch(this.searchField.getText().trim());
}
@FXML
private void onSelectDirectButton()
{
final var dialog = new TextInputDialog();
dialog.setTitle(this.strings.enterPathTitle());
dialog.setHeaderText(null);
dialog.setContentText(this.strings.enterPath());
this.configuration.cssStylesheet().ifPresent(css -> {
dialog.getDialogPane()
.getStylesheets()
.add(css.toExternalForm());
});
final var nameOpt = dialog.showAndWait();
if (nameOpt.isPresent()) {
final var name = nameOpt.get();
final var path = this.configuration.fileSystem().getPath(name);
final var parent = path.getParent();
if (parent != null) {
this.setCurrentDirectory(parent);
}
this.fileName.setText(path.getFileName().toString());
}
}
@FXML
private void onUpDirectoryButton()
{
final var parent = this.currentDirectory.getParent();
if (parent != null) {
this.setCurrentDirectory(parent);
}
}
@FXML
private void onCreateDirectoryButton()
{
final var dialog = new TextInputDialog();
dialog.setTitle(this.strings.createDirectoryTitle());
dialog.setHeaderText(null);
dialog.setContentText(this.strings.enterDirectoryName());
this.configuration.cssStylesheet().ifPresent(css -> {
dialog.getDialogPane()
.getStylesheets()
.add(css.toExternalForm());
});
final var nameOpt = dialog.showAndWait();
if (nameOpt.isPresent()) {
final var name = nameOpt.get();
final var newDirectory = this.currentDirectory.resolve(name);
try {
Files.createDirectories(newDirectory);
} catch (final IOException e) {
LOG.error("error creating directory: ", e);
try {
this.eventReceiver.get()
.accept(JWDirectoryCreationFailed.of(newDirectory, e));
} catch (final Exception ex) {
LOG.error("exception raised by event receiver: ", ex);
}
}
this.setCurrentDirectory(this.currentDirectory);
}
}
@FXML
private void onOKSelected()
{
this.result = List.of();
switch (this.configuration.action()) {
case OPEN_EXISTING_MULTIPLE:
case OPEN_EXISTING_SINGLE:
this.result =
this.directoryTableSelectionModel
.getSelectedItems()
.stream()
.map(JWFileItem::path)
.collect(Collectors.toList());
break;
case CREATE:
this.result =
List.of(this.currentDirectory.resolve(this.fileName.getText()));
break;
}
this.result =
this.result.stream()
.filter(this::filterSelectionMode)
.collect(Collectors.toList());
if (!this.result().isEmpty()) {
final var window = this.mainContent.getScene().getWindow();
window.hide();
}
}
@FXML
private void onCancelSelected()
{
this.result = List.of();
final var window = this.mainContent.getScene().getWindow();
window.hide();
}
@FXML
private void onHomeSelected()
{
final var homeDirectoryOpt = this.configuration.homeDirectory();
homeDirectoryOpt.ifPresent(this::setCurrentDirectory);
}
@FXML
private void onNameFieldAction()
{
this.trySelectDirectoryItemOrDeselect(
this.directoryTable,
this.fileName.getText()
);
this.reconfigureOKButton();
this.okButton.requestFocus();
}
@FXML
private void onNameFieldChanged()
{
this.trySelectDirectoryItemOrDeselect(
this.directoryTable,
this.fileName.getText()
);
this.reconfigureOKButton();
}
private void configureButtons()
{
this.configureButtonHome();
switch (this.configuration.action()) {
case OPEN_EXISTING_MULTIPLE:
case OPEN_EXISTING_SINGLE:
this.okButton.setText(this.strings.open());
break;
case CREATE:
this.okButton.setText(this.strings.save());
break;
}
this.okButton.setDisable(true);
this.newDirectoryButton.setDisable(
!this.configuration.allowDirectoryCreation());
this.directoryTableSelectionModel.selectedItemProperty()
.addListener(item -> this.reconfigureOKButton());
}
private void configureButtonHome()
{
final var homeParent =
this.homeDirectoryButton.getParent();
final var homeDirectoryOpt =
this.configuration.homeDirectory();
if (homeDirectoryOpt.isEmpty()) {
homeParent.setVisible(false);
homeParent.setManaged(false);
}
}
private void configureTableView()
{
switch (this.configuration.action()) {
case OPEN_EXISTING_SINGLE:
case CREATE:
this.directoryTableSelectionModel
.setSelectionMode(SelectionMode.SINGLE);
break;
case OPEN_EXISTING_MULTIPLE:
this.directoryTableSelectionModel
.setSelectionMode(SelectionMode.MULTIPLE);
break;
}
this.directoryTable.setPlaceholder(new Label(""));
final var tableColumns =
this.directoryTable.getColumns();
final var tableTypeColumn =
(TableColumn<JWFileItem, JWFileItem>) tableColumns.get(0);
final var tableNameColumn =
(TableColumn<JWFileItem, JWFileItem>) tableColumns.get(1);
final var tableSizeColumn =
(TableColumn<JWFileItem, Long>) tableColumns.get(2);
final var tableTimeColumn =
(TableColumn<JWFileItem, FileTime>) tableColumns.get(3);
tableTypeColumn.setSortable(true);
tableTypeColumn.setReorderable(false);
tableTypeColumn.setCellFactory(column -> {
final TableCell<JWFileItem, JWFileItem> cell =
new JWFileItemTableTypeCell(this.imageSet, this.toolTips);
cell.setOnMouseClicked(this::onTableRowClicked);
return cell;
});
tableNameColumn.setSortable(true);
tableNameColumn.setReorderable(false);
tableNameColumn.setCellFactory(column -> {
final TableCell<JWFileItem, JWFileItem> cell =
new JWFileItemTableNameCell(this.toolTips);
cell.setOnMouseClicked(this::onTableRowClicked);
return cell;
});
tableSizeColumn.setSortable(true);
tableSizeColumn.setReorderable(false);
tableSizeColumn.setCellFactory(column -> {
final TableCell<JWFileItem, Long> cell =
new JWFileItemTableSizeCell(this::formatSize);
cell.setOnMouseClicked(this::onTableRowClicked);
return cell;
});
tableTimeColumn.setSortable(true);
tableTimeColumn.setReorderable(false);
tableTimeColumn.setCellFactory(column -> {
final TableCell<JWFileItem, FileTime> cell =
new JWFileItemTableTimeCell(this.configuration.fileTimeFormatter());
cell.setOnMouseClicked(this::onTableRowClicked);
return cell;
});
tableTypeColumn.setCellValueFactory(
param -> new ReadOnlyObjectWrapper<>(param.getValue()));
tableNameColumn.setCellValueFactory(
param -> new ReadOnlyObjectWrapper<>(param.getValue()));
tableSizeColumn.setCellValueFactory(
param -> new ReadOnlyObjectWrapper<>(Long.valueOf(param.getValue().size())));
tableTimeColumn.setCellValueFactory(
param -> new ReadOnlyObjectWrapper<>(param.getValue().modifiedTime()));
this.fileListing.comparator()
.bind(this.directoryTable.comparatorProperty());
}
private void reconfigureOKButton()
{
var enabled = false;
switch (this.configuration.action()) {
case OPEN_EXISTING_MULTIPLE:
case OPEN_EXISTING_SINGLE: {
enabled = this.atLeastOneItemSelected();
break;
}
case CREATE: {
enabled = this.atLeastOneItemSelected() || this.fileNameNotEmpty();
break;
}
}
this.okButton.setDisable(!enabled);
}
private boolean fileNameNotEmpty()
{
return !this.fileName.getText().isEmpty();
}
/**
* Answers whether the given {@link Path} may be returned to the client.
*
* @param path A file selected in the user interface.
*
* @return {@code true} if the given {@link Path} is an acceptable selection.
*/
private boolean filterSelectionMode(final Path path)
{
return this.configuration.fileSelectionMode().apply(path);
}
private boolean atLeastOneItemSelected()
{
final var selectedItems =
this.directoryTableSelectionModel
.getSelectedItems();
for (final var selectedItem : selectedItems) {
final var itemPath = selectedItem.path();
if (this.filterSelectionMode(itemPath)) {
return true;
}
}
return false;
}
private void onTableRowClicked(
final MouseEvent event)
{
if (event.getClickCount() == 1) {
final var selectionModel = this.directoryTableSelectionModel;
final var item = selectionModel.getSelectedItem();
if (item != null) {
this.fileName.setText(item.name());
}
return;
}
if (event.getClickCount() == 2) {
final var selectionModel = this.directoryTableSelectionModel;
final var item = selectionModel.getSelectedItem();
if (item != null) {
final var directory = item.path();
if (Files.isDirectory(directory)) {
this.setCurrentDirectory(directory);
}
}
}
}
private void onSourceItemDoubleClicked(
final MouseEvent event)
{
if (event.getClickCount() == 2) {
final var item = this.sourcesList.getSelectionModel().getSelectedItem();
item.path().ifPresent(this::setCurrentDirectory);
this.populateDirectoryTableWith(item);
}
}
/**
* @return The list of selected files, if any
*/
public List<Path> result()
{
return this.result;
}
/**
* Cancel and hide the file selection.
*/
public void cancel()
{
this.result = List.of();
this.mainContent.getScene()
.getWindow()
.hide();
}
private final class SourceListCellFactory
implements Callback<ListView<JWFileSourceEntryType>, ListCell<JWFileSourceEntryType>>
{
SourceListCellFactory()
{
}
@Override
public ListCell<JWFileSourceEntryType> call(
final ListView<JWFileSourceEntryType> param)
{
final ListCell<JWFileSourceEntryType> cell =
new JWFileSourceEntryTypeListCell();
cell.setOnMouseClicked(
JWFileChooserViewController.this::onSourceItemDoubleClicked);
return cell;
}
}
private final class JWFileSourceEntryTypeListCell
extends ListCell<JWFileSourceEntryType>
{
JWFileSourceEntryTypeListCell()
{
}
@Override
protected void updateItem(
final JWFileSourceEntryType item,
final boolean empty)
{
super.updateItem(item, empty);
if (empty || item == null) {
this.setGraphic(null);
this.setText(null);
return;
}
item.onListCell(
JWFileChooserViewController.this.imageSet,
JWFileChooserViewController.this.strings,
this
);
}
}
}