summaryrefslogtreecommitdiff
path: root/platform/platform-impl/src/com/intellij/ide/impl/ProjectUtil.java
blob: de431fd548a30655e53243dec53ff184d40a2719 (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
858
859
// 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.ide.impl;

import com.intellij.CommonBundle;
import com.intellij.configurationStore.StoreUtil;
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector;
import com.intellij.ide.GeneralSettings;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.IdeCoreBundle;
import com.intellij.ide.RecentProjectsManager;
import com.intellij.ide.actions.OpenFileAction;
import com.intellij.ide.highlighter.ProjectFileType;
import com.intellij.openapi.application.*;
import com.intellij.openapi.components.StorageScheme;
import com.intellij.openapi.components.impl.stores.IProjectStore;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.ui.MessageDialogBuilder;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.text.Strings;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.*;
import com.intellij.platform.CommandLineProjectOpenProcessor;
import com.intellij.platform.PlatformProjectOpenProcessor;
import com.intellij.project.ProjectKt;
import com.intellij.projectImport.ProjectOpenProcessor;
import com.intellij.ui.AppIcon;
import com.intellij.ui.ComponentUtil;
import com.intellij.util.*;
import com.intellij.util.io.PathKt;
import org.jetbrains.annotations.*;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;

import static com.intellij.openapi.util.NullableLazyValue.lazyNullable;

public final class ProjectUtil extends ProjectUtilCore {
  private static final Logger LOG = Logger.getInstance(ProjectUtil.class);

  public static final String DEFAULT_PROJECT_NAME = "default";
  public static final String PROJECTS_DIR = "projects";
  public static final String PROPERTY_PROJECT_PATH = "%s.project.path";

  @ApiStatus.Internal
  public static final Key<Boolean> FORCE_CHECK_DIRECTORY_KEY = Key.create("project.util.processor.chooser");

  @ApiStatus.Internal
  public static final Key<Function<List<? extends ProjectOpenProcessor>, ProjectOpenProcessor>> PROCESSOR_CHOOSER_KEY =
    Key.create("project.util.processor.chooser");

  private static String ourProjectsPath;

  private ProjectUtil() { }

  /** @deprecated Use {@link #updateLastProjectLocation(Path)} */
  @Deprecated(forRemoval = true)
  public static void updateLastProjectLocation(@NotNull String projectFilePath) {
    updateLastProjectLocation(Path.of(projectFilePath));
  }

  public static void updateLastProjectLocation(@NotNull Path lastProjectLocation) {
    if (Files.isRegularFile(lastProjectLocation)) {
      // for directory-based project storage
      lastProjectLocation = lastProjectLocation.getParent();
    }

    if (lastProjectLocation == null) {
      // the immediate parent of the ipr file
      return;
    }

    // the candidate directory to be saved
    lastProjectLocation = lastProjectLocation.getParent();
    if (lastProjectLocation == null) {
      return;
    }

    String path = lastProjectLocation.toString();
    try {
      path = FileUtil.resolveShortWindowsName(path);
    }
    catch (IOException e) {
      LOG.info(e);
      return;
    }
    RecentProjectsManager.getInstance().setLastProjectCreationLocation(PathUtil.toSystemIndependentName(path));
  }

  /** @deprecated Use {@link ProjectManager#closeAndDispose(Project)} */
  @Deprecated
  public static boolean closeAndDispose(@NotNull Project project) {
    return ProjectManager.getInstance().closeAndDispose(project);
  }

  public static Project openOrImport(@NotNull Path path, Project projectToClose, boolean forceOpenInNewFrame) {
    return openOrImport(path, OpenProjectTask.build().withProjectToClose(projectToClose).withForceOpenInNewFrame(forceOpenInNewFrame));
  }

  public static Project openOrImport(@NotNull Path path) {
    return openOrImport(path, new OpenProjectTask());
  }

  /**
   * @param path                project file path
   * @param projectToClose      currently active project
   * @param forceOpenInNewFrame forces opening in new frame
   * @return project by path if the path was recognized as IDEA project file or one of the project formats supported by
   * installed importers (regardless of opening/import result)
   * null otherwise
   */
  public static @Nullable Project openOrImport(@NotNull String path, @Nullable Project projectToClose, boolean forceOpenInNewFrame) {
    return openOrImport(Path.of(path), OpenProjectTask.build().withProjectToClose(projectToClose).withForceOpenInNewFrame(forceOpenInNewFrame));
  }

  public static @Nullable Project openOrImport(@NotNull Path file, @NotNull OpenProjectTask options) {
    OpenResult openResult = tryOpenOrImport(file, options);
    if (openResult instanceof OpenResult.Success) {
      return ((OpenResult.Success)openResult).getProject();
    }
    return null;
  }

  @ApiStatus.Experimental
  public static @NotNull OpenResult tryOpenOrImport(@NotNull Path file, @NotNull OpenProjectTask options) {
    if (!options.getForceOpenInNewFrame()) {
      Project existing = findAndFocusExistingProjectForPath(file);
      if (existing != null) {
        return new OpenResult.Success(existing);
      }
    }

    NullableLazyValue<VirtualFile> lazyVirtualFile = lazyNullable(() -> getFileAndRefresh(file));

    if (!TrustedProjects.confirmOpeningAndSetProjectTrustedStateIfNeeded(file)) {
      return OpenResult.cancel();
    }

    for (ProjectOpenProcessor provider : ProjectOpenProcessor.EXTENSION_POINT_NAME.getIterable()) {
      if (!provider.isStrongProjectInfoHolder()) {
        continue;
      }

      // `PlatformProjectOpenProcessor` is not a strong project info holder, so there is no need to optimize (VFS not required)
      VirtualFile virtualFile = lazyVirtualFile.getValue();
      if (virtualFile == null) {
        return OpenResult.failure();
      }

      if (provider.canOpenProject(virtualFile)) {
        Project project = chooseProcessorAndOpen(Collections.singletonList(provider), virtualFile, options);
        return openResult(project, OpenResult.cancel());
      }
    }

    if (isValidProjectPath(file)) {
      // see OpenProjectTest.`open valid existing project dir with inability to attach using OpenFileAction` test about why `runConfigurators = true` is specified here
      Project project = ProjectManagerEx.getInstanceEx().openProject(file, options.withRunConfigurators());
      return openResult(project, OpenResult.failure());
    }

    if (FORCE_CHECK_DIRECTORY_KEY.get(options) == Boolean.TRUE && Files.isDirectory(file)) {
      try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(file)) {
        for (Path child : directoryStream) {
          String childPath = child.toString();
          if (childPath.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) {
            Project project = openProject(Path.of(childPath), options);
            return openResult(project, OpenResult.failure());
          }
        }
      }
      catch (IOException ignore) { }
    }

    List<ProjectOpenProcessor> processors = computeProcessors(file, lazyVirtualFile);
    if (processors.isEmpty()) {
      return OpenResult.failure();
    }

    Project project;
    if (processors.size() == 1 && processors.get(0) instanceof PlatformProjectOpenProcessor) {
      project = ProjectManagerEx.getInstanceEx().openProject(file, options.asNewProject().withRunConfigurators().withBeforeOpenCallback(p -> {
        p.putUserData(PlatformProjectOpenProcessor.PROJECT_OPENED_BY_PLATFORM_PROCESSOR, Boolean.TRUE);
        return true;
      }));
    }
    else {
      VirtualFile virtualFile = lazyVirtualFile.getValue();
      if (virtualFile == null) {
        return OpenResult.failure();
      }

      project = chooseProcessorAndOpen(processors, virtualFile, options);
    }

    if (project == null) {
      return OpenResult.failure();
    }

    postProcess(project);
    return new OpenResult.Success(project);
  }

  private static @NotNull OpenResult openResult(@Nullable Project project, @NotNull OpenResult alternative) {
    return project != null ? new OpenResult.Success(project) : alternative;
  }

  public static @NotNull CompletableFuture<@Nullable Project> openOrImportAsync(@NotNull Path file, @NotNull OpenProjectTask options) {
    if (!options.getForceOpenInNewFrame()) {
      Project existing = findAndFocusExistingProjectForPath(file);
      if (existing != null) {
        return CompletableFuture.completedFuture(existing);
      }
    }

    NullableLazyValue<VirtualFile> lazyVirtualFile = lazyNullable(() -> getFileAndRefresh(file));

    for (ProjectOpenProcessor provider : ProjectOpenProcessor.EXTENSION_POINT_NAME.getIterable()) {
      if (!provider.isStrongProjectInfoHolder()) {
        continue;
      }

      // `PlatformProjectOpenProcessor` is not a strong project info holder, so there is no need to optimize (VFS not required)
      VirtualFile virtualFile = lazyVirtualFile.getValue();
      if (virtualFile == null) {
        return CompletableFuture.completedFuture(null);
      }

      if (provider.canOpenProject(virtualFile)) {
        return chooseProcessorAndOpenAsync(Collections.singletonList(provider), virtualFile, options);
      }
    }

    if (isValidProjectPath(file)) {
      // see OpenProjectTest.`open valid existing project dir with inability to attach using OpenFileAction` test about why `runConfigurators = true` is specified here
      return ProjectManagerEx.getInstanceEx().openProjectAsync(file, options.withRunConfigurators());
    }

    if (FORCE_CHECK_DIRECTORY_KEY.get(options) == Boolean.TRUE && Files.isDirectory(file)) {
      try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(file)) {
        for (Path child : directoryStream) {
          String childPath = child.toString();
          if (childPath.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) {
            return CompletableFuture.completedFuture(openProject(Path.of(childPath), options));
          }
        }
      }
      catch (IOException ignore) { }
    }

    List<ProjectOpenProcessor> processors = computeProcessors(file, lazyVirtualFile);
    if (processors.isEmpty()) {
      return CompletableFuture.completedFuture(null);
    }

    CompletableFuture<Project> projectFuture;
    if (processors.size() == 1 && processors.get(0) instanceof PlatformProjectOpenProcessor) {
      projectFuture = ProjectManagerEx.getInstanceEx().openProjectAsync(file, options.asNewProject().withRunConfigurators().withBeforeOpenCallback(p -> {
        p.putUserData(PlatformProjectOpenProcessor.PROJECT_OPENED_BY_PLATFORM_PROCESSOR, Boolean.TRUE);
        return true;
      }));
    }
    else {
      VirtualFile virtualFile = lazyVirtualFile.getValue();
      if (virtualFile == null) {
        return CompletableFuture.completedFuture(null);
      }

      projectFuture = chooseProcessorAndOpenAsync(processors, virtualFile, options);
    }

    return projectFuture.thenApply(ProjectUtil::postProcess);
  }

  private static @NotNull List<ProjectOpenProcessor> computeProcessors(@NotNull Path file, @NotNull NullableLazyValue<? extends VirtualFile> lazyVirtualFile) {
    List<ProjectOpenProcessor> processors = new SmartList<>();
    ProjectOpenProcessor.EXTENSION_POINT_NAME.forEachExtensionSafe(processor -> {
      if (processor instanceof PlatformProjectOpenProcessor) {
        if (Files.isDirectory(file)) {
          processors.add(processor);
        }
      }
      else {
        VirtualFile virtualFile = lazyVirtualFile.getValue();
        if (virtualFile != null && processor.canOpenProject(virtualFile)) {
          processors.add(processor);
        }
      }
    });
    return processors;
  }

  private static @Nullable Project postProcess(@Nullable Project project) {
    if (project == null) {
      return null;
    }

    StartupManager.getInstance(project).runAfterOpened(() -> {
      ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, project.getDisposed(), () -> {
        ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.PROJECT_VIEW);
        if (toolWindow != null) {
          toolWindow.activate(null);
        }
      });
    });
    return project;
  }

  private static @Nullable Project chooseProcessorAndOpen(@NotNull List<? extends ProjectOpenProcessor> processors,
                                                          @NotNull VirtualFile virtualFile,
                                                          @NotNull OpenProjectTask options) {
    ProjectOpenProcessor processor;
    if (processors.size() == 1) {
      processor = processors.get(0);
    }
    else {
      processors.removeIf(it -> it instanceof PlatformProjectOpenProcessor);
      Function<List<? extends ProjectOpenProcessor>, ProjectOpenProcessor> chooser;
      if (processors.size() == 1) {
        processor = processors.get(0);
      }
      else if ((chooser = PROCESSOR_CHOOSER_KEY.get(options)) != null) {
        LOG.info("options.openProcessorChooser will handle the open processor dilemma");
        processor = chooser.apply(processors);
      }
      else {
        Ref<ProjectOpenProcessor> ref = new Ref<>();
        ApplicationManager.getApplication().invokeAndWait(() -> {
          ref.set(SelectProjectOpenProcessorDialog.showAndGetChoice(processors, virtualFile));
        });
        processor = ref.get();
        if (processor == null) {
          return null;
        }
      }
    }

    Ref<Project> result = new Ref<>();
    ApplicationManager.getApplication().invokeAndWait(() -> {
      result.set(processor.doOpenProject(virtualFile, options.getProjectToClose(), options.getForceOpenInNewFrame()));
    });
    return result.get();
  }

  private static @NotNull CompletableFuture<@Nullable Project> chooseProcessorAndOpenAsync(@NotNull List<ProjectOpenProcessor> processors,
                                                                                           @NotNull VirtualFile virtualFile,
                                                                                           @NotNull OpenProjectTask options) {
    CompletableFuture<ProjectOpenProcessor> processorFuture;
    if (processors.size() == 1) {
      processorFuture = CompletableFuture.completedFuture(processors.get(0));
    }
    else {
      processors.removeIf(it -> it instanceof PlatformProjectOpenProcessor);
      Function<List<? extends ProjectOpenProcessor>, ProjectOpenProcessor> chooser;
      if (processors.size() == 1) {
        processorFuture = CompletableFuture.completedFuture(processors.get(0));
      }
      else if ((chooser = PROCESSOR_CHOOSER_KEY.get(options)) != null) {
        LOG.info("options.openProcessorChooser will handle the open processor dilemma");
        processorFuture = CompletableFuture.completedFuture(chooser.apply(processors));
      }
      else {
        processorFuture = CompletableFuture.supplyAsync(() -> {
          return SelectProjectOpenProcessorDialog.showAndGetChoice(processors, virtualFile);
        }, ApplicationManager.getApplication()::invokeLater);
      }
    }

    return processorFuture.thenCompose(processor -> {
      if (processor == null) {
        return CompletableFuture.completedFuture(null);
      }

      CompletableFuture<Project> future =
        processor.openProjectAsync(virtualFile, options.getProjectToClose(), options.getForceOpenInNewFrame());
      if (future != null) {
        return future;
      }

      return CompletableFuture.supplyAsync(() -> {
        return processor.doOpenProject(virtualFile, options.getProjectToClose(), options.getForceOpenInNewFrame());
      }, ApplicationManager.getApplication()::invokeLater);
    });
  }

  public static @Nullable Project openProject(@NotNull String path, @Nullable Project projectToClose, boolean forceOpenInNewFrame) {
    return openProject(Path.of(path), OpenProjectTask.build().withProjectToClose(projectToClose).withForceOpenInNewFrame(forceOpenInNewFrame));
  }

  public static @Nullable Project openProject(@NotNull Path file, @NotNull OpenProjectTask options) {
    BasicFileAttributes fileAttributes = PathKt.basicAttributesIfExists(file);
    if (fileAttributes == null) {
      Messages.showErrorDialog(IdeBundle.message("error.project.file.does.not.exist", file.toString()), CommonBundle.getErrorTitle());
      return null;
    }

    Project existing = findAndFocusExistingProjectForPath(file);
    if (existing != null) {
      return existing;
    }

    if (isRemotePath(file.toString()) && !RecentProjectsManager.getInstance().hasPath(FileUtil.toSystemIndependentName(file.toString()))) {
      if (!confirmLoadingFromRemotePath(file.toString(), "warning.load.project.from.share", "title.load.project.from.share")) {
        return null;
      }
    }

    if (fileAttributes.isDirectory()) {
      Path dir = file.resolve(Project.DIRECTORY_STORE_FOLDER);
      if (!Files.isDirectory(dir)) {
        Messages.showErrorDialog(IdeBundle.message("error.project.file.does.not.exist", dir.toString()), CommonBundle.getErrorTitle());
        return null;
      }
    }

    try {
      return ProjectManagerEx.getInstanceEx().openProject(file, options);
    }
    catch (Exception e) {
      Messages.showMessageDialog(IdeBundle.message("error.cannot.load.project", e.getMessage()),
                                 IdeBundle.message("title.cannot.load.project"), Messages.getErrorIcon());
    }
    return null;
  }

  public static boolean confirmLoadingFromRemotePath(@NotNull String path,
                                                     @NotNull @PropertyKey(resourceBundle = IdeBundle.BUNDLE) String msgKey,
                                                     @NotNull @PropertyKey(resourceBundle = IdeBundle.BUNDLE) String titleKey) {
    return showYesNoDialog(IdeBundle.message(msgKey, path), titleKey);
  }

  public static boolean showYesNoDialog(@NotNull @Nls String message, @NotNull @PropertyKey(resourceBundle = IdeBundle.BUNDLE) String titleKey) {
    return MessageDialogBuilder.yesNo(IdeBundle.message(titleKey), message)
      .icon(Messages.getWarningIcon())
      .ask(getActiveFrameOrWelcomeScreen());
  }

  public static Window getActiveFrameOrWelcomeScreen() {
    Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
    if (window != null) {
      return window;
    }

    for (Frame frame : Frame.getFrames()) {
      if (frame instanceof IdeFrame && frame.isVisible()) {
        return frame;
      }
    }
    return null;
  }

  public static boolean isRemotePath(@NotNull String path) {
    return path.contains("://") || path.contains("\\\\");
  }

  public static @Nullable Project findProject(@NotNull Path file) {
    Project[] openProjects = getOpenProjects();
    if (openProjects.length == 0) {
      return null;
    }

    for (Project project : openProjects) {
      if (isSameProject(file, project)) {
        return project;
      }
    }
    return null;
  }

  public static @Nullable Project findAndFocusExistingProjectForPath(@NotNull Path file) {
    var project = findProject(file);
    if (project != null) {
      focusProjectWindow(project, false);
    }
    return project;
  }

  /**
   * @return {@link GeneralSettings#OPEN_PROJECT_SAME_WINDOW} or
   *         {@link GeneralSettings#OPEN_PROJECT_NEW_WINDOW} or
   *         {@link Messages#CANCEL} (when a user cancels the dialog)
   */
  public static int confirmOpenNewProject(boolean isNewProject) {
    return confirmOpenNewProject(isNewProject, null);
  }

  /**
   * @param isNewProject true if the project is just created
   * @param projectName name of the project to open (can be displayed to the user)
   * @return {@link GeneralSettings#OPEN_PROJECT_SAME_WINDOW} or
   *         {@link GeneralSettings#OPEN_PROJECT_NEW_WINDOW} or
   *         {@link Messages#CANCEL} (when a user cancels the dialog)
   */
  public static int confirmOpenNewProject(boolean isNewProject, @Nullable String projectName) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      return GeneralSettings.OPEN_PROJECT_NEW_WINDOW;
    }

    int mode = GeneralSettings.getInstance().getConfirmOpenNewProject();
    if (mode == GeneralSettings.OPEN_PROJECT_ASK) {
      String message = projectName == null ? 
                       IdeBundle.message("prompt.open.project.in.new.frame") :
                       IdeBundle.message("prompt.open.project.with.name.in.new.frame", projectName);
      if (isNewProject) {
        boolean openInExistingFrame =
          MessageDialogBuilder.yesNo(IdeCoreBundle.message("title.new.project"), message)
            .yesText(IdeBundle.message("button.existing.frame"))
            .noText(IdeBundle.message("button.new.frame"))
            .doNotAsk(new ProjectNewWindowDoNotAskOption())
            .guessWindowAndAsk();
        mode = openInExistingFrame ? GeneralSettings.OPEN_PROJECT_SAME_WINDOW : GeneralSettings.OPEN_PROJECT_NEW_WINDOW;
      }
      else {
        int exitCode =
          MessageDialogBuilder.yesNoCancel(IdeBundle.message("title.open.project"), message)
            .yesText(IdeBundle.message("button.existing.frame"))
            .noText(IdeBundle.message("button.new.frame"))
            .doNotAsk(new ProjectNewWindowDoNotAskOption())
            .guessWindowAndAsk();
        mode = exitCode == Messages.YES ? GeneralSettings.OPEN_PROJECT_SAME_WINDOW :
               exitCode == Messages.NO ? GeneralSettings.OPEN_PROJECT_NEW_WINDOW :
               Messages.CANCEL;
      }
      if (mode != Messages.CANCEL) {
        LifecycleUsageTriggerCollector.onProjectFrameSelected(mode);
      }
    }
    return mode;
  }

  /**
   * @return {@link GeneralSettings#OPEN_PROJECT_SAME_WINDOW} or
   *         {@link GeneralSettings#OPEN_PROJECT_NEW_WINDOW} or
   *         {@link GeneralSettings#OPEN_PROJECT_SAME_WINDOW_ATTACH} or
   *         {@code -1} (when a user cancels the dialog)
   */
  public static int confirmOpenOrAttachProject() {
    int mode = GeneralSettings.getInstance().getConfirmOpenNewProject();
    if (mode == GeneralSettings.OPEN_PROJECT_ASK) {
      int exitCode = Messages.showDialog(
        IdeBundle.message("prompt.open.project.or.attach"),
        IdeBundle.message("prompt.open.project.or.attach.title"),
        new String[]{
          IdeBundle.message("prompt.open.project.or.attach.button.this.window"),
          IdeBundle.message("prompt.open.project.or.attach.button.new.window"),
          IdeBundle.message("prompt.open.project.or.attach.button.attach"),
          CommonBundle.getCancelButtonText()
        },
        0,
        Messages.getQuestionIcon(),
        new ProjectNewWindowDoNotAskOption());
      mode = exitCode == 0 ? GeneralSettings.OPEN_PROJECT_SAME_WINDOW :
             exitCode == 1 ? GeneralSettings.OPEN_PROJECT_NEW_WINDOW :
             exitCode == 2 ? GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH :
             -1;
      if (mode != -1) {
        LifecycleUsageTriggerCollector.onProjectFrameSelected(mode);
      }
    }
    return mode;
  }

  /** @deprecated Use {@link #isSameProject(Path, Project)} */
  @Deprecated
  public static boolean isSameProject(@Nullable String projectFilePath, @NotNull Project project) {
    return projectFilePath != null && isSameProject(Path.of(projectFilePath), project);
  }

  public static boolean isSameProject(@NotNull Path projectFile, @NotNull Project project) {
    IProjectStore projectStore = ProjectKt.getStateStore(project);
    Path existingBaseDirPath = projectStore.getProjectBasePath();

    if (existingBaseDirPath.getFileSystem() != projectFile.getFileSystem()) {
      return false;
    }

    if (Files.isDirectory(projectFile)) {
      try {
        return Files.isSameFile(projectFile, existingBaseDirPath);
      }
      catch (IOException ignore) {
        return false;
      }
    }

    if (projectStore.getStorageScheme() == StorageScheme.DEFAULT) {
      try {
        return Files.isSameFile(projectFile, projectStore.getProjectFilePath());
      }
      catch (IOException ignore) {
        return false;
      }
    }

    Path parent = projectFile.getParent();
    if (parent == null) {
      return false;
    }

    Path parentFileName = parent.getFileName();
    if (parentFileName != null && parentFileName.toString().equals(Project.DIRECTORY_STORE_FOLDER)) {
      parent = parent.getParent();
      return parent != null && FileUtil.pathsEqual(parent.toString(), existingBaseDirPath.toString());
    }

    return projectFile.getFileName().toString().endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION) &&
           FileUtil.pathsEqual(parent.toString(), existingBaseDirPath.toString());
  }

  /**
   * Focuses the specified project's window. If {@code stealFocusIfAppInactive} is {@code true} and corresponding logic is supported by OS
   * (making it work on Windows requires enabling focus stealing system-wise, see {@link com.intellij.ui.WinFocusStealer}), the window will
   * get the focus even if other application is currently active. Otherwise, there will be some indication that the target window requires
   * user attention. Focus stealing behaviour (enabled by {@code stealFocusIfAppInactive}) is generally not considered a proper application
   * behaviour, and should only be used in special cases, when we know that user definitely expects it.
   */
  public static void focusProjectWindow(@Nullable Project project, boolean stealFocusIfAppInactive) {
    JFrame frame = WindowManager.getInstance().getFrame(project);
    if (frame == null) {
      return;
    }

    boolean appIsActive = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow() != null;

    // On macOS, `j.a.Window#toFront` restores the frame if needed.
    // On X Window, restoring minimized frame can steal focus from an active application, so we do it only when the IDE is active.
    if (SystemInfo.isWindows || SystemInfo.isXWindow && appIsActive) {
      int state = frame.getExtendedState();
      if ((state & Frame.ICONIFIED) != 0) {
        frame.setExtendedState(state & ~Frame.ICONIFIED);
      }
    }

    if (stealFocusIfAppInactive) {
      AppIcon.getInstance().requestFocus((IdeFrame)frame);
    }
    else {
      if (!SystemInfo.isXWindow || appIsActive) {
        // some Linux window managers allow `j.a.Window#toFront` to steal focus, so we don't call it on Linux when the IDE is inactive
        frame.toFront();
      }
      if (!SystemInfo.isWindows) {
        // on Windows, `j.a.Window#toFront` will request attention if needed
        AppIcon.getInstance().requestAttention(project, true);
      }
    }
  }

  public static @NotNull String getBaseDir() {
    String defaultDirectory = GeneralSettings.getInstance().getDefaultProjectDirectory();
    if (Strings.isNotEmpty(defaultDirectory)) {
      return defaultDirectory.replace('/', File.separatorChar);
    }
    final String lastProjectLocation = RecentProjectsManager.getInstance().getLastProjectCreationLocation();
    if (lastProjectLocation != null) {
      return lastProjectLocation.replace('/', File.separatorChar);
    }
    return getUserHomeProjectDir();
  }

  public static String getUserHomeProjectDir() {
    String productName;
    if (PlatformUtils.isCLion() || PlatformUtils.isAppCode() || PlatformUtils.isDataGrip()) {
      productName = ApplicationNamesInfo.getInstance().getProductName();
    }
    else {
      productName = ApplicationNamesInfo.getInstance().getLowercaseProductName();
    }
    return SystemProperties.getUserHome().replace('/', File.separatorChar) + File.separator + productName + "Projects";
  }

  public static @Nullable Project tryOpenFiles(@Nullable Project project, @NotNull List<? extends Path> list, String location) {
    try {
      for (Path file : list) {
        OpenProjectTask options = OpenProjectTask.build().withProjectToClose(project).withForceOpenInNewFrame(true);
        OpenResult openResult = tryOpenOrImport(file.toAbsolutePath(), options);
        if (openResult instanceof OpenResult.Success) {
          LOG.debug(location + ": load project from ", file);
          return ((OpenResult.Success)openResult).getProject();
        }
        else if (openResult instanceof OpenResult.Cancel) {
          LOG.debug(location + ": canceled project opening");
          return null;
        }
      }
    }
    catch (ProcessCanceledException ex) {
      LOG.debug(location + ": skip project opening");
      return null;
    }

    Project result = null;
    for (Path file : list) {
      if (!Files.exists(file)) {
        continue;
      }

      LOG.debug(location + ": open file ", file);
      if (project != null) {
        VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(FileUtilRt.toSystemIndependentName(file.toString()));
        if (virtualFile != null && virtualFile.isValid()) {
          OpenFileAction.openFile(virtualFile, project);
        }
        result = project;
      }
      else {
        CommandLineProjectOpenProcessor processor = CommandLineProjectOpenProcessor.getInstanceIfExists();
        if (processor != null) {
          Project opened = processor.openProjectAndFile(file, -1, -1, false);
          if (opened != null && result == null) {
            result = opened;
          }
        }
      }
    }

    return result;
  }

  @NotNull
  @SystemDependent
  public static String getProjectsPath() { //todo: merge somehow with getBaseDir
    Application application = ApplicationManager.getApplication();
    String fromSettings = application == null || application.isHeadlessEnvironment() ? null :
                          GeneralSettings.getInstance().getDefaultProjectDirectory();
    if (StringUtil.isNotEmpty(fromSettings)) {
      return PathManager.getAbsolutePath(fromSettings);
    }
    if (ourProjectsPath == null) {
      String produceName = ApplicationNamesInfo.getInstance().getProductName().toLowerCase(Locale.ENGLISH);
      String propertyName = String.format(PROPERTY_PROJECT_PATH, produceName);
      String propertyValue = System.getProperty(propertyName);
      ourProjectsPath = propertyValue != null
                        ? PathManager.getAbsolutePath(StringUtil.unquoteString(propertyValue, '\"'))
                        : getProjectsDirDefault();
    }
    return ourProjectsPath;
  }

  private static @NotNull String getProjectsDirDefault() {
    if (PlatformUtils.isDataGrip()) return getUserHomeProjectDir();
    return PathManager.getConfigPath() + File.separator + PROJECTS_DIR;
  }

  public static @NotNull Path getProjectPath(@NotNull String name) {
    return Path.of(getProjectsPath(), name);
  }

  public static @Nullable Path getProjectFile(@NotNull String name) {
    Path projectDir = getProjectPath(name);
    return Files.isDirectory(projectDir.resolve(Project.DIRECTORY_STORE_FOLDER)) ? projectDir : null;
  }

  public static @Nullable Project openOrCreateProject(@NotNull String name) {
    return openOrCreateProject(name, null);
  }

  public static @Nullable Project openOrCreateProject(@NotNull String name, @Nullable ProjectCreatedCallback  projectCreatedCallback) {
    return ProgressManager.getInstance().computeInNonCancelableSection(() -> openOrCreateProjectInner(name, projectCreatedCallback));
  }

  public interface ProjectCreatedCallback {
    void projectCreated(Project project);
  }

  public static @NotNull Set<String> getExistingProjectNames() {
    Set<String> result = new LinkedHashSet<>();
    File file = new File(getProjectsPath());
    for (String name : ObjectUtils.notNull(file.list(), ArrayUtilRt.EMPTY_STRING_ARRAY)) {
      if (getProjectFile(name) != null) {
        result.add(name);
      }
    }
    return result;
  }

  private static @Nullable Project openOrCreateProjectInner(@NotNull String name, @Nullable ProjectCreatedCallback projectCreatedCallback) {
    Path existingFile = getProjectFile(name);
    if (existingFile != null) {
      Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
      for (Project p : openProjects) {
        if (!p.isDefault() && isSameProject(existingFile, p)) {
          focusProjectWindow(p, false);
          return p;
        }
      }
      return ProjectManagerEx.getInstanceEx().openProject(existingFile, new OpenProjectTask().withRunConfigurators());
    }

    Path file = getProjectPath(name);
    boolean created;
    try {
      created = (!Files.exists(file) && Files.createDirectories(file) != null) || Files.isDirectory(file);
    }
    catch (IOException e) {
      created = false;
    }

    Path projectFile = null;
    if (created) {
      OpenProjectTask options = OpenProjectTask.build().asNewProject().withRunConfigurators().withProjectName(name);
      Project project = ProjectManagerEx.getInstanceEx().newProject(file, options);
      if (project != null) {
        if (projectCreatedCallback != null) {
          projectCreatedCallback.projectCreated(project);
        }
        saveAndDisposeProject(project);
        projectFile = getProjectFile(name);
      }
    }
    if (projectFile == null) return null;

    OpenProjectTask options = OpenProjectTask.build().withRunConfigurators().withCreatedByWizard().withoutVfsRefresh();
    return ProjectManagerEx.getInstanceEx().openProject(projectFile, options);
  }

  private static void saveAndDisposeProject(@NotNull Project project) {
    StoreUtil.saveSettings(project, true);
    ApplicationManager.getApplication().invokeAndWait(() -> {
      WriteAction.run(() -> Disposer.dispose(project));
    });
  }

  public static @Nullable Project getProjectForWindow(@Nullable Window window) {
    if (window != null) {
      while (window.getOwner() != null) {
        window = window.getOwner();
      }
      if (window instanceof IdeFrame) {
        return ((IdeFrame)window).getProject();
      }
    }
    return null;
  }

  public static @Nullable Project getProjectForComponent(@Nullable Component component) {
    return getProjectForWindow(ComponentUtil.getWindow(component));
  }
}