summaryrefslogtreecommitdiff
path: root/platform/platform-impl/src/com/intellij/openapi/fileChooser/impl/FileChooserPanelImpl.java
blob: 6dc5ac196e047fa3e039d3323d1f0eee5435f51f (plain)
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
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.fileChooser.impl;

import com.intellij.execution.process.ProcessIOExecutorService;
import com.intellij.execution.wsl.WSLDistribution;
import com.intellij.execution.wsl.WSLUtil;
import com.intellij.execution.wsl.WslDistributionManager;
import com.intellij.icons.AllIcons;
import com.intellij.ide.highlighter.ArchiveFileType;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.application.Experiments;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserPanel;
import com.intellij.openapi.fileChooser.ex.FileLookup;
import com.intellij.openapi.fileChooser.ex.FileTextFieldImpl;
import com.intellij.openapi.fileChooser.ex.LocalFsFinder;
import com.intellij.openapi.fileTypes.FileTypeRegistry;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.NioFiles;
import com.intellij.openapi.util.text.NaturalComparator;
import com.intellij.openapi.util.text.Strings;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.local.CoreLocalFileSystem;
import com.intellij.openapi.vfs.local.CoreLocalVirtualFile;
import com.intellij.ui.*;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBPanel;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.JBInsets;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.StatusText;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.List;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.intellij.openapi.fileChooser.ex.FileChooserDialogImpl.FILE_CHOOSER_SHOW_PATH_PROPERTY;
import static com.intellij.openapi.util.Pair.pair;
import static java.awt.GridBagConstraints.*;
import static java.util.Objects.requireNonNull;

final class FileChooserPanelImpl extends JBPanel<FileChooserPanelImpl> implements FileChooserPanel, Disposable {
  private static final Logger LOG = Logger.getInstance(FileChooserPanelImpl.class);
  private static final String SEPARATOR = "!/";
  private static final CoreLocalFileSystem FS = new CoreLocalFileSystem();

  private final FileTypeRegistry myRegistry;
  private final FileChooserDescriptor myDescriptor;
  private final Runnable myCallback;
  private final @Nullable WatchService myWatcher;
  private final Map<Path, FileSystem> myOpenFileSystems;

  private final ComboBox<PathWrapper> myPath;
  private final SortedListModel<FsItem> myModel;
  private final JBList<FsItem> myList;
  private boolean myShowPathBar;
  private boolean myPathBarActive;
  private volatile boolean myShowHiddenFiles;

  private final Object myLock = new String("file.chooser.panel.lock");
  private int myCounter = 0;
  private Pair<Integer, Future<?>> myCurrentTask = pair(-1, CompletableFuture.completedFuture(null));
  // guarded by `myLock` via `update()` callback, which the inspection doesn't detect
  @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") private @Nullable Path myCurrentDirectory;
  @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") private final List<FsItem> myCurrentContent = new ArrayList<>();
  @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") private @Nullable WatchKey myWatchKey;

  FileChooserPanelImpl(@NotNull FileChooserDescriptor descriptor, @NotNull Runnable callback, Path @NotNull [] recentPaths) {
    super(new GridBagLayout());

    myRegistry = FileTypeRegistry.getInstance();
    myDescriptor = descriptor;
    myCallback = callback;
    myWatcher = startWatchService();
    myOpenFileSystems = new ConcurrentHashMap<>();

    myShowHiddenFiles = descriptor.isShowHiddenFiles();
    myShowPathBar = PropertiesComponent.getInstance().getBoolean(FILE_CHOOSER_SHOW_PATH_PROPERTY, true);

    var label = new JLabel(descriptor.getDescription());

    var group = (DefaultActionGroup)ActionManager.getInstance().getAction("FileChooserToolbar");
    var toolBar = ActionManager.getInstance().createActionToolbar("FileChooserDialog", group, true);
    toolBar.setTargetComponent(this);

    myPath = new ComboBox<>(Stream.of(recentPaths).map(PathWrapper::new).toArray(PathWrapper[]::new));
    myPath.setVisible(myShowPathBar);
    myPath.setEditable(true);
    myPath.addFocusListener(new FocusAdapter() {
      @Override
      public void focusGained(FocusEvent e) {
        myPathBarActive = true;
      }
    });
    var pathEditor = (JTextField)myPath.getEditor().getEditorComponent();
    var finder = new LocalFsFinder(false).withBaseDir(null);
    FileLookup.LookupFilter filter =
      f -> myDescriptor.isFileVisible(new CoreLocalVirtualFile(FS, ((LocalFsFinder.IoFile)f).getFile()), myShowHiddenFiles);
    new FileTextFieldImpl(pathEditor, finder, filter, FileChooserFactoryImpl.getMacroMap(), this);

    myModel = new SortedListModel<>(FsItem.COMPARATOR);
    myList = new JBList<>(myModel);
    myList.setCellRenderer(new MyListCellRenderer());
    myList.setSelectionMode(descriptor.isChooseMultiple() ? ListSelectionModel.MULTIPLE_INTERVAL_SELECTION : ListSelectionModel.SINGLE_SELECTION);
    myList.addFocusListener(new FocusAdapter() {
      @Override
      public void focusGained(FocusEvent e) {
        myPathBarActive = false;
      }
    });
    myList.addMouseListener(new MouseAdapter() {
      @Override
      public void mouseClicked(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
          var idx = myList.locationToIndex(e.getPoint());
          if (idx >= 0) {
            openItemAtIndex(idx, e);
          }
        }
      }
    });
    myList.addKeyListener(new KeyAdapter() {
      @Override
      public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER && e.getModifiersEx() == 0) {
          int[] selection = myList.getSelectedIndices();
          if (selection.length == 1) {
            openItemAtIndex(selection[0], e);
          }
        }
      }
    });
    new ListSpeedSearch<>(myList);
    myList.getActionMap().put(ListActions.Left.ID, myList.getActionMap().get(ListActions.Home.ID));
    myList.getActionMap().put(ListActions.Right.ID, myList.getActionMap().get(ListActions.End.ID));
    myList.getActionMap().put(FileChooserPanelActions.Root.ID, new AbstractAction() {
      @Override
      public void actionPerformed(ActionEvent e) {
        load(null, myCurrentDirectory, 0);
      }
    });
    myList.getActionMap().put(FileChooserPanelActions.LevelUp.ID, new AbstractAction() {
      @Override
      public void actionPerformed(ActionEvent e) {
        if (myCurrentDirectory != null) {
          load(parent(myCurrentDirectory), null, UPPER_LEVEL);
        }
      }
    });

    var scrollPane = ScrollPaneFactory.createScrollPane(myList);
    var pathInsets = myPath.getInsets();
    @SuppressWarnings("UseDPIAwareInsets") var scrollInsets = new Insets(JBUI.scale(5) - pathInsets.bottom, pathInsets.left, 0, pathInsets.right);
    scrollPane.setBorder(BorderFactory.createLineBorder(UIUtil.getBoundsColor()));

    add(label, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.01, CENTER, HORIZONTAL, JBInsets.emptyInsets(), 0, 0));
    add(toolBar.getComponent(), new GridBagConstraints(0, 1, 1, 1, 1.0, 0.01, CENTER, HORIZONTAL, JBInsets.emptyInsets(), 0, 0));
    add(myPath, new GridBagConstraints(0, 2, 1, 1, 1.0, 0.01, CENTER, HORIZONTAL, JBInsets.emptyInsets(), 0, 0));
    add(scrollPane, new GridBagConstraints(0, 3, 1, 1, 1.0, 0.98, CENTER, BOTH, scrollInsets, 0, 0));
  }

  private @Nullable WatchService startWatchService() {
    try {
      var watcher = FileSystems.getDefault().newWatchService();
      execute(() -> {
        while (true) {
          try {
            var key = watcher.take();
            var events = key.pollEvents();
            key.reset();
            if (!events.isEmpty()) {
              UIUtil.invokeLaterIfNeeded(() -> {
                synchronized (myLock) {
                  if (key == myWatchKey && myCurrentDirectory != null) {
                    reload(null);
                  }
                }
              });
            }
          }
          catch (InterruptedException ignored) { }
          catch (ClosedWatchServiceException e) {
            break;
          }
        }
      });
      return watcher;
    }
    catch (Exception e) {
      LOG.warn(e);
      return null;
    }
  }

  private void openItemAtIndex(int idx, InputEvent e) {
    FsItem item = myModel.get(idx);
    if (item.directory) {
      load(item.path, null, FsItem.UPLINK.equals(item.name) ? UPPER_LEVEL : 0);
    }
    else if (myDescriptor.isChooseJarContents() && myRegistry.getFileTypeByFileName(item.name) == ArchiveFileType.INSTANCE) {
      load(item.path, null, INTO_ARCHIVE);
    }
    else {
      myCallback.run();
    }
    e.consume();
  }

  JComponent getPreferredFocusedComponent() {
    return myShowPathBar ? myPath : myList;
  }

  @NotNull List<@NotNull Path> chosenPaths() {
    if (myShowPathBar && myPathBarActive) {
      var object = myPath.getEditor().getItem();
      if (object instanceof PathWrapper) {
        return List.of(((PathWrapper)object).path);
      }
      if (object instanceof String && !((String)object).isBlank()) {
        var path = findByPath(FileUtil.expandUserHome(((String)object).trim()));
        if (path != null && path.isAbsolute()) {
          return List.of(path);
        }
      }
      return List.of();
    }
    else {
      var items = myList.getSelectedValuesList();
      if (items.size() == 1 && FsItem.UPLINK.equals(items.get(0).name)) {
        items = List.of(myCurrentContent.get(0));  // substituting selected uplink with `.`
      }
      return items.stream()
        .filter(r -> r.selectable)
        .map(r -> requireNonNull(r.path))
        .collect(Collectors.toList());
    }
  }

  @Override
  public @NotNull JComponent getComponent() {
    return this;
  }

  @Override
  public void load(@Nullable Path path) {
    if (path == null || path.isAbsolute()) {
      load(path, null, 0);
    }
    else {
      throw new IllegalArgumentException("Not absolute: " + path);
    }
  }

  @Override
  public void reload(@Nullable Path focusOn) {
    if (focusOn == null) {
      FsItem value = myList.getSelectedValue();
      if (value != null) {
        focusOn = value.path;
      }
    }
    synchronized (myLock) {
      load(myCurrentDirectory, focusOn, 0);
    }
  }

  @Override
  public boolean showPathBar() {
    return myShowPathBar;
  }

  @Override
  public void showPathBar(boolean show) {
    myShowPathBar = show;
    PropertiesComponent.getInstance().setValue(FILE_CHOOSER_SHOW_PATH_PROPERTY, Boolean.toString(show));
    myPath.setVisible(show);
    (show ? myPath : myList).requestFocusInWindow();
  }

  @Override
  public boolean showHiddenFiles() {
    return myShowHiddenFiles;
  }

  @Override
  public void showHiddenFiles(boolean show) {
    myShowHiddenFiles = show;
    synchronized (myLock) {
      if (myCurrentDirectory != null) {
        var selection = myList.getSelectedValue();
        myModel.clear();
        for (var i = 1; i < myCurrentContent.size(); i++) {  // excluding `.`
          FsItem item = myCurrentContent.get(i);
          if (show || item.visible) myModel.add(item);
        }
        myList.setSelectedValue(selection, true);
      }
    }
  }

  @Override
  public @Nullable Path currentDirectory() {
    return myCurrentDirectory;
  }

  @Override
  public @NotNull List<Path> selectedPaths() {
    return KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == myList
           ? myList.getSelectedValuesList().stream()
             .filter(r -> !FsItem.UPLINK.equals(r.name) && r.path != null && r.path.getParent() != null)
             .map(r -> r.path)
             .collect(Collectors.toList())
           : List.of();
  }

  @Override
  public void dispose() {
    synchronized (myLock) {
      cancelCurrentTask();
    }
    if (myWatcher != null) {
      try {
        myWatcher.close();
      }
      catch (IOException e) {
        LOG.warn(e);
      }
    }
    myOpenFileSystems.forEach((p, fs) -> {
      try {
        fs.close();
      }
      catch (IOException e) {
        LOG.warn(e);
      }
    });
  }

  private static final int UPPER_LEVEL = 1;
  private static final int INTO_ARCHIVE = 2;

  private void load(@Nullable Path path, @Nullable Path focusOn, int direction) {
    synchronized (myLock) {
      myPath.setItem(path != null ? new PathWrapper(path) : null);
      myModel.clear();
      myList.clearSelection();
      myList.setPaintBusy(true);
      myList.setEmptyText(StatusText.getDefaultEmptyText());

      var childDir = direction == UPPER_LEVEL ? myCurrentDirectory : null;
      myCurrentDirectory = null;
      myCurrentContent.clear();
      cancelCurrentTask();
      var id = myCounter++;
      if (LOG.isTraceEnabled()) LOG.trace("starting: " + id + ", " + path);
      myCurrentTask = pair(id, execute(() -> {
        var directory = directoryToLoad(path, direction == INTO_ARCHIVE);
        if (directory != null) {
          var pathToSelect = focusOn != null ? focusOn :
                             childDir != null && childDir.getParent() == null && isJar(childDir.toUri()) ? parent(childDir) :
                             childDir;
          loadDirectory(directory, pathToSelect, id);
        }
        else {
          loadRoots(id, childDir);
        }
      }));
    }
  }

  private void cancelCurrentTask() {
    myCurrentTask.second.cancel(true);
    if (myWatchKey != null) {
      myWatchKey.cancel();
      myWatchKey = null;
    }
  }

  private @Nullable Path directoryToLoad(@Nullable Path path, boolean asZip) {
    if (path != null && asZip) {
      try {
        @SuppressWarnings("resource") var fs = myOpenFileSystems.computeIfAbsent(path, k -> {
          try {
            return FileSystems.newFileSystem(path, null);
          }
          catch (IOException e) {
            throw new UncheckedIOException(e);
          }
        });
        return fs.getRootDirectories().iterator().next();
      }
      catch (Exception e) {
        LOG.warn(e);
        return path.getParent();
      }
    }

    for (var current = path; current != null; current = parent(current)) {
      try {
        var attributes = Files.readAttributes(current, BasicFileAttributes.class);
        return attributes.isDirectory() ? current : current.getParent();
      }
      catch (Exception e) {
        LOG.trace(e);
      }
    }

    return null;
  }

  private void loadDirectory(Path directory, @Nullable Path pathToSelect, int id) {
    var cancelled = new AtomicBoolean(false);

    var vfsDirectory = new PreloadedDirectory(directory);
    var dot = new FsItem(directory, ".", true, false, myDescriptor.isFileSelectable(vfsDirectory), null);
    var uplink = new FsItem(parent(directory), FsItem.UPLINK, true, true, false, AllIcons.Nodes.UpFolder);
    update(id, cancelled, () -> {
      myCurrentDirectory = directory;
      myPath.setItem(new PathWrapper(directory));
      myCurrentContent.add(dot);
      myCurrentContent.add(uplink);
      myModel.add(uplink);
    });

    var selection = new AtomicReference<>(uplink);
    try {
      var isSymlink = Files.isSymbolicLink(directory);
      var options = isSymlink ? EnumSet.of(FileVisitOption.FOLLOW_LINKS) : EnumSet.noneOf(FileVisitOption.class);

      Files.walkFileTree(directory, options, 1, new SimpleFileVisitor<>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
          if (attrs.isSymbolicLink()) {
            try {
              attrs = new DelegatingFileAttributes(Files.readAttributes(file, BasicFileAttributes.class));
            }
            catch (IOException e) {
              LOG.debug(e);
            }
          }

          var virtualFile = new LazyDirectoryOrFile(vfsDirectory, file, attrs);
          if (!myDescriptor.isFileVisible(virtualFile, true)) {
            return FileVisitResult.CONTINUE;  // not hidden, just ignored
          }
          var visible = myDescriptor.isFileVisible(virtualFile, false);
          var selectable = myDescriptor.isFileSelectable(virtualFile);
          var icon = myDescriptor.getIcon(virtualFile);
          var item = new FsItem(file, file.getFileName().toString(), attrs.isDirectory(), visible, selectable, icon);
          update(id, cancelled, () -> {
            myCurrentContent.add(item);
            if (visible || myShowHiddenFiles) {
              myModel.add(item);
            }
          });

          if (pathToSelect != null && file.equals(pathToSelect)) {
            selection.set(item);
          }

          return cancelled.get() ? FileVisitResult.TERMINATE : FileVisitResult.CONTINUE;
        }
      });
    }
    catch (Exception e) {
      LOG.warn(directory.toString(), e);
    }

    if (!cancelled.get()) {
      WatchKey watchKey = null;
      if (myWatcher != null && isLocalFs(directory)) {
        try {
          watchKey = directory.register(myWatcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
        }
        catch (Exception e) {
          if (LOG.isDebugEnabled()) LOG.debug("cannot watch " + directory, e);
        }
      }

      var _watchKey = watchKey;
      update(
        id,
        () -> {
          myList.setPaintBusy(false);
          myList.setSelectedValue(selection.get(), true);
          myWatchKey = _watchKey;
        },
        () -> { if (_watchKey != null) _watchKey.cancel(); });
    }
  }

  private void loadRoots(int id, @Nullable Path pathToSelect) {
    var cancelled = new AtomicBoolean(false);

    update(id, cancelled, () -> {
      myCurrentDirectory = null;
      myPath.setItem(null);
    });

    var roots = new ArrayList<Path>();
    for (var root : FileSystems.getDefault().getRootDirectories()) roots.add(root);
    if (WSLUtil.isSystemCompatible() && Experiments.getInstance().isFeatureEnabled("wsl.p9.show.roots.in.file.chooser")) {
      try {
        List<WSLDistribution> distributions = WslDistributionManager.getInstance().getInstalledDistributionsFuture().get(200, TimeUnit.MILLISECONDS);
        for (var distribution : distributions) roots.add(distribution.getUNCRootPath());
      }
      catch (Exception e) {
        LOG.warn(e);
      }
    }

    var selection = new AtomicReference<FsItem>();
    for (var root : roots) {
      if (cancelled.get()) break;
      try {
        var attrs = Files.readAttributes(root, BasicFileAttributes.class);
        var virtualFile = new LazyDirectoryOrFile(null, root, attrs);
        var name = NioFiles.getFileName(root);
        if (name.length() > 1 && name.endsWith(File.separator)) {
          name = name.substring(0, name.length() - 1);
        }
        if (SystemInfo.isWindows) {
          var store = Files.getFileStore(root).name();
          if (!store.isBlank()) {
            name += " [" + store + ']';
          }
        }
        var item = new FsItem(root, name, true, true, myDescriptor.isFileSelectable(virtualFile), AllIcons.Nodes.Folder);
        update(id, cancelled, () -> myModel.add(item));
        if (pathToSelect != null && root.equals(pathToSelect)) {
          selection.set(item);
        }
      }
      catch (Exception e) {
        LOG.warn(root.toString(), e);
      }
    }

    if (!cancelled.get()) {
      update(id, cancelled, () -> {
        myList.setPaintBusy(false);
        if (myModel.getSize() == 0) {
          myList.setEmptyText(UIBundle.message("file.chooser.cannot.load.roots"));
        }
        else {
          FsItem selectedItem = selection.get();
          if (selectedItem != null) {
            myList.setSelectedValue(selectedItem, true);
          }
          else {
            myList.setSelectedIndex(0);
          }
        }
      });
    }
  }

  private static @Nullable Path parent(Path path) {
    var parent = path.getParent();
    if (parent == null) {
      var uri = path.toUri();
      if (isJar(uri)) {
        var fileUri = Strings.trimEnd(uri.getRawSchemeSpecificPart(), SEPARATOR);
        try {
          return Path.of(new URI(fileUri));
        }
        catch (Exception e) {
          LOG.warn(e);
        }
      }
    }
    return parent;
  }

  private @Nullable Path findByPath(String text) {
    var p = text.lastIndexOf(SEPARATOR);
    if (p > 0 && myDescriptor.isChooseJarContents()) {
      var archive = NioFiles.toPath(text.substring(0, p));
      if (archive != null && myRegistry.getFileTypeByFileName(archive.getFileName().toString()) == ArchiveFileType.INSTANCE) {
        @SuppressWarnings("resource") var fs = myOpenFileSystems.computeIfAbsent(archive, k -> {
          try {
            return FileSystems.newFileSystem(archive, null);
          }
          catch (IOException e) {
            LOG.warn(e);
            return null;
          }
        });
        if (fs != null) {
          return fs.getRootDirectories().iterator().next().resolve(text.substring(p + 2));
        }
      }
    }

    return NioFiles.toPath(text);
  }

  private static boolean isJar(URI uri) {
    return "jar".equals(uri.getScheme());
  }

  private static boolean isLocalFs(Path file) {
    return file.getFileSystem() == FileSystems.getDefault();
  }

  private static Future<Void> execute(Runnable operation) {
    return CompletableFuture
      .runAsync(operation, ProcessIOExecutorService.INSTANCE)
      .exceptionally(t -> { LOG.error(t); return null; });
  }

  private void update(int id, AtomicBoolean cancelled, Runnable operation) {
    update(id, operation, () -> cancelled.set(true));
  }

  private void update(int id, Runnable whenActive, Runnable whenCancelled) {
    UIUtil.invokeLaterIfNeeded(() -> {
      synchronized (myLock) {
        boolean active = myCurrentTask.first == id && !myCurrentTask.second.isCancelled();
        (active ? whenActive : whenCancelled).run();
      }
    });
  }

  private static final class PathWrapper {
    private final Path path;

    private PathWrapper(Path path) {
      this.path = path;
    }

    @Override
    public boolean equals(Object o) {
      return this == o || o instanceof FsItem && path.equals(((FsItem)o).path);
    }

    @Override
    public int hashCode() {
      return path.hashCode();
    }

    @Override
    public String toString() {
      var uri = path.toUri();
      if (isJar(uri)) {
        var raw = uri.getRawSchemeSpecificPart();
        var p = raw.lastIndexOf(SEPARATOR);
        if (p > 0) {
          try {
            return Path.of(new URI(raw.substring(0, p))) + raw.substring(p);
          }
          catch (Exception e) {
            LOG.warn(e);
          }
        }
      }
      return path.toString();
    }
  }

  private static final class FsItem {
    private static final String UPLINK = "..";

    private final Path path;
    private final @NlsSafe String name;
    private final boolean directory;
    private final boolean visible;
    private final boolean selectable;
    private final @Nullable Icon icon;

    private FsItem(Path path, String name, boolean directory, boolean visible, boolean selectable, @Nullable Icon icon) {
      this.path = path;
      this.name = name;
      this.directory = directory;
      this.visible = visible;
      this.selectable = selectable;
      this.icon = icon;
    }

    @Override
    public String toString() {
      return name;  // called by `JBList#doCopyToClipboardAction` and `ListSpeedSearch`
    }

    private static final Comparator<FsItem> COMPARATOR = (o1, o2) -> {
      if (UPLINK.equals(o1.name)) return -1;
      if (UPLINK.equals(o2.name)) return 1;
      var byType = Boolean.compare(o2.directory, o1.directory);
      if (byType != 0) return byType;
      byType = Boolean.compare(o1.name.startsWith("\\\\"), o2.name.startsWith("\\\\"));
      if (byType != 0) return byType;
      return NaturalComparator.INSTANCE.compare(o1.name, o2.name);
    };
  }

  private static final class MyListCellRenderer extends SimpleListCellRenderer<FsItem> {
    private final Border myPadding = JBUI.Borders.empty(UIUtil.getListCellVPadding(), 3);  // a constant from `DarculaComboBoxUI`

    @Override
    public void customize(@NotNull JList<? extends FsItem> list, FsItem value, int index, boolean selected, boolean focused) {
      setBorder(myPadding);
      setIcon(value.icon);
      setText(value.name);
      setForeground(selected ? UIUtil.getListSelectionForeground(true) : UIUtil.getListForeground());
      setEnabled(value.selectable || FsItem.UPLINK.equals(value.name));
    }
  }

  private static final class PreloadedDirectory extends CoreLocalVirtualFile {
    private final List<LazyDirectoryOrFile> myChildren = new ArrayList<>();

    private PreloadedDirectory(Path file) {
      super(FS, file, true);
    }

    @Override
    public @Nullable VirtualFile getParent() {
      return null;
    }

    @Override
    public @Nullable VirtualFile findChild(@NotNull String name) {
      if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) throw new IllegalArgumentException(name);
      return ContainerUtil.find(myChildren, f -> name.equals(f.getName()));
    }

    @Override
    public VirtualFile[] getChildren() {
      return VfsUtilCore.toVirtualFileArray(myChildren);
    }
  }

  private static final class LazyDirectoryOrFile extends CoreLocalVirtualFile {
    private final @Nullable VirtualFile myParent;
    private final @Nullable Map<String, Optional<LazyDirectoryOrFile>> myChildren;

    private LazyDirectoryOrFile(@Nullable VirtualFile parent, Path file, BasicFileAttributes attrs) {
      super(FS, file, attrs);
      myParent = parent;
      myChildren = attrs.isDirectory() ? new HashMap<>() : null;
      if (parent instanceof PreloadedDirectory) {
        ((PreloadedDirectory)parent).myChildren.add(this);
      }
    }

    @Override
    public @Nullable VirtualFile getParent() {
      return myParent;
    }

    @Override
    public @Nullable VirtualFile findChild(@NotNull String name) {
      if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) throw new IllegalArgumentException(name);
      return myChildren == null ? null : myChildren.computeIfAbsent(name, k -> {
        try {
          var childFile = getFile().resolve(name);
          var attrs = Files.readAttributes(childFile, BasicFileAttributes.class);
          return Optional.of(new LazyDirectoryOrFile(this, childFile, attrs));
        }
        catch (Exception e) {
          LOG.trace(e);
          return Optional.empty();
        }
      }).orElse(null);
    }

    @Override
    public VirtualFile[] getChildren() {
      return myChildren == null
             ? VirtualFile.EMPTY_ARRAY
             : myChildren.values().stream().map(o -> o.orElse(null)).filter(Objects::nonNull).toArray(VirtualFile[]::new);
    }
  }

  private static final class DelegatingFileAttributes implements BasicFileAttributes {
    private final BasicFileAttributes myDelegate;

    private DelegatingFileAttributes(BasicFileAttributes delegate) {
      myDelegate = delegate;
    }

    @Override
    public FileTime lastModifiedTime() {
      return myDelegate.lastModifiedTime();
    }

    @Override
    public FileTime lastAccessTime() {
      return myDelegate.lastAccessTime();
    }

    @Override
    public FileTime creationTime() {
      return myDelegate.creationTime();
    }

    @Override
    public boolean isRegularFile() {
      return myDelegate.isRegularFile();
    }

    @Override
    public boolean isDirectory() {
      return myDelegate.isDirectory();
    }

    @Override
    public boolean isSymbolicLink() {
      return true;
    }

    @Override
    public boolean isOther() {
      return myDelegate.isOther();
    }

    @Override
    public long size() {
      return myDelegate.size();
    }

    @Override
    public Object fileKey() {
      return myDelegate.fileKey();
    }
  }
}