-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
ProjectManagerImpl.java
806 lines (704 loc) · 27.3 KB
/
ProjectManagerImpl.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
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.project.impl;
import com.intellij.configurationStore.StorageUtilKt;
import com.intellij.conversion.ConversionResult;
import com.intellij.conversion.ConversionService;
import com.intellij.ide.AppLifecycleListener;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.startup.StartupManagerEx;
import com.intellij.ide.startup.impl.StartupManagerImpl;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.NotificationsManager;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.*;
import com.intellij.openapi.application.impl.LaterInvocator;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.*;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.startup.StartupManager;
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.vfs.VirtualFile;
import com.intellij.openapi.vfs.impl.ZipHandler;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame;
import com.intellij.ui.GuiUtils;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.UnsafeWeakList;
import com.intellij.util.ref.GCUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ProjectManagerImpl extends ProjectManagerEx implements Disposable {
private static final Logger LOG = Logger.getInstance(ProjectManagerImpl.class);
private static final Key<List<ProjectManagerListener>> LISTENERS_IN_PROJECT_KEY = Key.create("LISTENERS_IN_PROJECT_KEY");
@SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized")
private ProjectImpl myDefaultProject; // Only used asynchronously in save and dispose, which itself are synchronized.
private Project[] myOpenProjects = {}; // guarded by lock
private final Map<String, Project> myOpenProjectByHash = ContainerUtil.newConcurrentMap();
private final Object lock = new Object();
private final List<ProjectManagerListener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private final ProgressManager myProgressManager;
private volatile boolean myDefaultProjectWasDisposed;
@NotNull
private static List<ProjectManagerListener> getListeners(@NotNull Project project) {
List<ProjectManagerListener> array = project.getUserData(LISTENERS_IN_PROJECT_KEY);
if (array == null) return Collections.emptyList();
return array;
}
public ProjectManagerImpl(ProgressManager progressManager) {
myProgressManager = progressManager;
final ProjectManagerListener busPublisher = ApplicationManager.getApplication().getMessageBus().syncPublisher(TOPIC);
addProjectManagerListener(
new ProjectManagerListener() {
@Override
public void projectOpened(final Project project) {
busPublisher.projectOpened(project);
for (ProjectManagerListener listener : getListeners(project)) {
listener.projectOpened(project);
}
}
@Override
public void projectClosed(Project project) {
busPublisher.projectClosed(project);
for (ProjectManagerListener listener : getListeners(project)) {
listener.projectClosed(project);
}
ZipHandler.clearFileAccessorCache();
LaterInvocator.purgeExpiredItems();
}
@Override
public boolean canCloseProject(Project project) {
for (ProjectManagerListener listener : getListeners(project)) {
if (!listener.canCloseProject(project)) {
return false;
}
}
return true;
}
@Override
public void projectClosing(Project project) {
busPublisher.projectClosing(project);
for (ProjectManagerListener listener : getListeners(project)) {
listener.projectClosing(project);
}
}
}
);
}
@Override
public void dispose() {
ApplicationManager.getApplication().assertWriteAccessAllowed();
if (myDefaultProject != null) {
Disposer.dispose(myDefaultProject);
myDefaultProject = null;
myDefaultProjectWasDisposed = true;
}
}
@SuppressWarnings("StaticNonFinalField") public static int TEST_PROJECTS_CREATED;
private static final boolean LOG_PROJECT_LEAKAGE_IN_TESTS = Boolean.parseBoolean(System.getProperty("idea.log.leaked.projects.in.tests", "true"));
private static final int MAX_LEAKY_PROJECTS = 5;
@SuppressWarnings("FieldCanBeLocal") private final Map<Project, String> myProjects = new WeakHashMap<>();
@Override
@Nullable
public Project newProject(@Nullable String projectName, @NotNull String filePath, boolean useDefaultProjectSettings, boolean isDummy) {
filePath = toCanonicalName(filePath);
if (ApplicationManager.getApplication().isUnitTestMode()) {
//noinspection AssignmentToStaticFieldFromInstanceMethod
TEST_PROJECTS_CREATED++;
//noinspection TestOnlyProblems
checkProjectLeaksInTests();
}
File projectFile = new File(filePath);
if (projectFile.isFile()) {
FileUtil.delete(projectFile);
}
else {
File[] files = new File(projectFile, Project.DIRECTORY_STORE_FOLDER).listFiles();
if (files != null) {
for (File file : files) {
FileUtil.delete(file);
}
}
}
ProjectImpl project = createProject(projectName, filePath, false);
try {
initProject(project, useDefaultProjectSettings ? getDefaultProject() : null);
if (LOG_PROJECT_LEAKAGE_IN_TESTS) {
myProjects.put(project, null);
}
return project;
}
catch (Throwable t) {
LOG.info(t);
Messages.showErrorDialog(message(t), ProjectBundle.message("project.load.default.error"));
return null;
}
}
@NonNls
@NotNull
private static String message(@NotNull Throwable e) {
String message = e.getMessage();
if (message != null) return message;
message = e.getLocalizedMessage();
//noinspection ConstantConditions
if (message != null) return message;
message = e.toString();
Throwable cause = e.getCause();
if (cause != null) {
String causeMessage = message(cause);
return message + " (cause: " + causeMessage + ")";
}
return message;
}
@TestOnly
private void checkProjectLeaksInTests() {
if (!LOG_PROJECT_LEAKAGE_IN_TESTS || getLeakedProjects().count() < MAX_LEAKY_PROJECTS) {
return;
}
if (Math.random() >= 0.05) {
return; // Check for leaked projects ~ every 20 tests
}
for (int i = 0; i < 3 && getLeakedProjects().count() >= MAX_LEAKY_PROJECTS; i++) {
GCUtil.tryGcSoftlyReachableObjects();
}
System.gc();
if (getLeakedProjects().count() >= MAX_LEAKY_PROJECTS) {
List<Project> copy = getLeakedProjects().collect(Collectors.toCollection(UnsafeWeakList::new));
myProjects.clear();
if (ContainerUtil.collect(copy.iterator()).size() >= MAX_LEAKY_PROJECTS) {
throw new TooManyProjectLeakedException(copy);
}
}
}
@TestOnly
private Stream<Project> getLeakedProjects() {
return myProjects.keySet().stream().filter(project -> project.isDisposed() && !((ProjectImpl)project).isTemporarilyDisposed());
}
private void initProject(@NotNull ProjectImpl project, @Nullable Project template) {
ProgressIndicator indicator = myProgressManager.getProgressIndicator();
if (indicator != null && !project.isDefault()) {
indicator.setText(ProjectBundle.message("loading.components.for", project.getName()));
}
ApplicationManager.getApplication().getMessageBus().syncPublisher(ProjectLifecycleListener.TOPIC).beforeProjectLoaded(project);
boolean succeed = false;
try {
if (template != null) {
project.getStateStore().loadProjectFromTemplate(template);
}
project.init();
succeed = true;
}
finally {
if (!succeed && !project.isDefault()) {
TransactionGuard.submitTransaction(project, () -> WriteAction.run(() -> Disposer.dispose(project)));
}
}
}
private ProjectImpl createProject(@Nullable String projectName, @NotNull String filePath, boolean isDefault) {
if (isDefault) {
return new DefaultProject(this, "");
}
return new ProjectImpl(this, FileUtilRt.toSystemIndependentName(filePath), projectName);
}
@Override
@Nullable
public Project loadProject(@NotNull String filePath) throws IOException {
return loadProject(filePath, null);
}
@Override
@Nullable
public Project loadProject(@NotNull String filePath, @Nullable String projectName) throws IOException {
try {
ProjectImpl project = createProject(projectName, new File(filePath).getAbsolutePath(), false);
initProject(project, null);
return project;
}
catch (Throwable t) {
LOG.info(t);
throw new IOException(t);
}
}
@NotNull
private static String toCanonicalName(@NotNull final String filePath) {
try {
return FileUtil.resolveShortWindowsName(filePath);
}
catch (IOException e) {
// OK. File does not yet exist so it's canonical path will be equal to its original path.
}
return filePath;
}
@TestOnly
public synchronized boolean isDefaultProjectInitialized() {
return myDefaultProject != null;
}
@Override
@NotNull
public synchronized Project getDefaultProject() {
LOG.assertTrue(!myDefaultProjectWasDisposed, "Default project has been already disposed!");
if (myDefaultProject == null) {
ProgressManager.getInstance().executeNonCancelableSection(() -> {
try {
myDefaultProject = createProject(null, "", true);
initProject(myDefaultProject, null);
}
catch (Throwable t) {
PluginManager.processException(t);
}
});
}
return myDefaultProject;
}
@Override
@NotNull
public Project[] getOpenProjects() {
synchronized (lock) {
return myOpenProjects;
}
}
@Override
public boolean isProjectOpened(Project project) {
synchronized (lock) {
return ArrayUtil.contains(project, myOpenProjects);
}
}
@Override
public boolean openProject(@NotNull final Project project) {
if (isLight(project)) {
((ProjectImpl)project).setTemporarilyDisposed(false);
boolean isInitialized = StartupManagerEx.getInstanceEx(project).startupActivityPassed();
if (isInitialized) {
addToOpened(project);
// events already fired
return true;
}
}
for (Project p : getOpenProjects()) {
if (ProjectUtil.isSameProject(project.getProjectFilePath(), p)) {
GuiUtils.invokeLaterIfNeeded(() -> ProjectUtil.focusProjectWindow(p, false), ModalityState.NON_MODAL);
return false;
}
}
if (!addToOpened(project)) {
return false;
}
Runnable process = () -> {
TransactionGuard.getInstance().submitTransactionAndWait(() -> fireProjectOpened(project));
StartupManagerImpl startupManager = (StartupManagerImpl)StartupManager.getInstance(project);
startupManager.runStartupActivities();
// Startup activities (e.g. the one in FileBasedIndexProjectHandler) have scheduled dumb mode to begin "later"
// Now we schedule-and-wait to the same event queue to guarantee that the dumb mode really begins now:
// Post-startup activities should not ever see unindexed and at the same time non-dumb state
TransactionGuard.getInstance().submitTransactionAndWait(startupManager::startCacheUpdate);
startupManager.runPostStartupActivitiesFromExtensions();
GuiUtils.invokeLaterIfNeeded(() -> {
if (!project.isDisposed()) {
startupManager.runPostStartupActivities();
Application application = ApplicationManager.getApplication();
if (!(application.isHeadlessEnvironment() || application.isUnitTestMode())) {
StorageUtilKt.checkUnknownMacros(project, true);
}
}
if (ApplicationManager.getApplication().isActive()) {
JFrame projectFrame = WindowManager.getInstance().getFrame(project);
if (projectFrame != null) {
IdeFocusManager.getInstance(project).requestFocus(projectFrame, true);
}
}
}, ModalityState.NON_MODAL);
};
ProgressIndicator indicator = myProgressManager.getProgressIndicator();
if (indicator != null) {
indicator.setText("Preparing workspace...");
process.run();
return true;
}
boolean ok = myProgressManager.runProcessWithProgressSynchronously(process, ProjectBundle.message("project.load.progress"), canCancelProjectLoading(), project);
if (!ok) {
closeProject(project, false, false, true);
notifyProjectOpenFailed();
return false;
}
return true;
}
private boolean addToOpened(@NotNull Project project) {
assert !project.isDisposed() : "Must not open already disposed project";
synchronized (lock) {
if (isProjectOpened(project)) {
return false;
}
myOpenProjects = ArrayUtil.append(myOpenProjects, project);
ProjectCoreUtil.theProject = myOpenProjects.length == 1 ? project : null;
myOpenProjectByHash.put(project.getLocationHash(), project);
}
return true;
}
private void removeFromOpened(@NotNull Project project) {
synchronized (lock) {
myOpenProjects = ArrayUtil.remove(myOpenProjects, project);
ProjectCoreUtil.theProject = myOpenProjects.length == 1 ? myOpenProjects[0] : null;
myOpenProjectByHash.values().remove(project); // remove by value and not by key!
}
}
@Nullable
public Project findOpenProjectByHash(@Nullable String locationHash) {
return myOpenProjectByHash.get(locationHash);
}
private static boolean canCancelProjectLoading() {
return !ProgressManager.getInstance().isInNonCancelableSection();
}
@Override
public Project loadAndOpenProject(@NotNull final String originalFilePath) throws IOException {
final String filePath = toCanonicalName(originalFilePath);
final ConversionResult conversionResult = ConversionService.getInstance().convert(filePath);
ProjectImpl project;
if (conversionResult.openingIsCanceled()) {
project = null;
}
else {
project = createProject(null, toCanonicalName(filePath), false);
myProgressManager.run(new Task.WithResult<Project, IOException>(project, ProjectBundle.message("project.load.progress"), true) {
@Override
protected Project compute(@NotNull ProgressIndicator indicator) throws IOException {
if (!loadProjectWithProgress(project)) {
return null;
}
if (!conversionResult.conversionNotNeeded()) {
StartupManager.getInstance(project).registerPostStartupActivity(() -> conversionResult.postStartupActivity(project));
}
openProject(project);
return project;
}
});
}
if (project == null) {
WelcomeFrame.showIfNoProjectOpened();
return null;
}
if (!project.isOpen()) {
WelcomeFrame.showIfNoProjectOpened();
ApplicationManager.getApplication().runWriteAction(() -> {
if (!project.isDisposed()) {
Disposer.dispose(project);
}
});
}
return project;
}
/**
* Converts and loads the project at the specified path.
*
* @param filePath the path to open the project.
* @return the project, or null if the user has cancelled opening the project.
*/
@Override
@Nullable
public Project convertAndLoadProject(@NotNull String filePath) throws IOException {
final String canonicalFilePath = toCanonicalName(filePath);
final ConversionResult conversionResult = ConversionService.getInstance().convert(canonicalFilePath);
if (conversionResult.openingIsCanceled()) {
return null;
}
ProjectImpl project = createProject(null, canonicalFilePath, false);
if (!loadProjectWithProgress(project)) return null;
if (!conversionResult.conversionNotNeeded()) {
StartupManager.getInstance(project).registerPostStartupActivity(() -> conversionResult.postStartupActivity(project));
}
return project;
}
private boolean loadProjectWithProgress(ProjectImpl project) throws IOException {
try {
if (myProgressManager.getProgressIndicator() != null) {
initProject(project, null);
return true;
}
myProgressManager.runProcessWithProgressSynchronously((ThrowableComputable<Object, RuntimeException>)() -> {
initProject(project, null);
return project;
}, ProjectBundle.message("project.load.progress"), canCancelProjectLoading(), project);
return true;
}
catch (ProcessCanceledException e) {
return false;
}
catch (Throwable t) {
LOG.info(t);
throw new IOException(t);
}
}
private static void notifyProjectOpenFailed() {
Application application = ApplicationManager.getApplication();
application.getMessageBus().syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed();
if (application.isUnitTestMode()) return;
WelcomeFrame.showIfNoProjectOpened();
}
@Override
@TestOnly
public void openTestProject(@NotNull final Project project) {
assert ApplicationManager.getApplication().isUnitTestMode();
openProject(project);
UIUtil.dispatchAllInvocationEvents(); // post init activities are invokeLatered
}
@NotNull
@Override
@TestOnly
public Collection<Project> closeTestProject(@NotNull final Project project) {
assert ApplicationManager.getApplication().isUnitTestMode();
closeProject(project, false, false, false);
Project[] projects = getOpenProjects();
return projects.length == 0 ? Collections.emptyList() : Arrays.asList(projects);
}
@Override
public void reloadProject(@NotNull Project project) {
doReloadProject(project);
}
public static void doReloadProject(@NotNull Project project) {
final Ref<Project> projectRef = Ref.create(project);
ProjectReloadState.getInstance(project).onBeforeAutomaticProjectReload();
ApplicationManager.getApplication().invokeLater(() -> {
LOG.debug("Reloading project.");
Project project1 = projectRef.get();
// Let it go
projectRef.set(null);
if (project1.isDisposed()) {
return;
}
// must compute here, before project dispose
String presentableUrl = project1.getPresentableUrl();
if (!ProjectUtil.closeAndDispose(project1)) {
return;
}
ProjectUtil.openProject(presentableUrl, null, true);
}, ModalityState.NON_MODAL);
}
@Override
public boolean closeProject(@NotNull final Project project) {
return closeProject(project, true, false, true);
}
public boolean closeProject(@NotNull final Project project, final boolean save, final boolean dispose, boolean checkCanClose) {
if (ApplicationManager.getApplication().isWriteAccessAllowed()) {
throw new IllegalStateException("Must not call closeProject() from under write action because fireProjectClosing() listeners must have a chance to do something useful");
}
ApplicationManager.getApplication().assertIsDispatchThread();
if (isLight(project)) {
// if we close project at the end of the test, just mark it closed; if we are shutting down the entire test framework, proceed to full dispose
if (!((ProjectImpl)project).isTemporarilyDisposed()) {
((ProjectImpl)project).setTemporarilyDisposed(true);
removeFromOpened(project);
return true;
}
((ProjectImpl)project).setTemporarilyDisposed(false);
}
else {
if (!isProjectOpened(project)) return true;
}
if (checkCanClose && !canClose(project)) return false;
final ShutDownTracker shutDownTracker = ShutDownTracker.getInstance();
shutDownTracker.registerStopperThread(Thread.currentThread());
try {
if (save) {
FileDocumentManager.getInstance().saveAllDocuments();
project.save();
}
if (checkCanClose && !ensureCouldCloseIfUnableToSave(project)) {
return false;
}
fireProjectClosing(project); // somebody can start progress here, do not wrap in write action
ApplicationManager.getApplication().runWriteAction(() -> {
removeFromOpened(project);
fireProjectClosed(project);
if (dispose) {
Disposer.dispose(project);
}
});
}
finally {
shutDownTracker.unregisterStopperThread(Thread.currentThread());
}
return true;
}
@TestOnly
public static boolean isLight(@NotNull Project project) {
return project instanceof ProjectImpl && ((ProjectImpl)project).isLight();
}
@Override
public boolean closeAndDispose(@NotNull final Project project) {
return closeProject(project, true, true, true);
}
private void fireProjectClosing(@NotNull Project project) {
if (LOG.isDebugEnabled()) {
LOG.debug("enter: fireProjectClosing()");
}
for (ProjectManagerListener listener : myListeners) {
try {
listener.projectClosing(project);
}
catch (Exception e) {
LOG.error("From listener "+listener+" ("+listener.getClass()+")", e);
}
}
}
@Override
public void addProjectManagerListener(@NotNull ProjectManagerListener listener) {
myListeners.add(listener);
}
@Override
public void addProjectManagerListener(@NotNull final ProjectManagerListener listener, @NotNull Disposable parentDisposable) {
addProjectManagerListener(listener);
Disposer.register(parentDisposable, () -> removeProjectManagerListener(listener));
}
@Override
public void removeProjectManagerListener(@NotNull ProjectManagerListener listener) {
boolean removed = myListeners.remove(listener);
LOG.assertTrue(removed);
}
@Override
public void addProjectManagerListener(@NotNull Project project, @NotNull ProjectManagerListener listener) {
List<ProjectManagerListener> listeners = project.getUserData(LISTENERS_IN_PROJECT_KEY);
if (listeners == null) {
listeners = ((UserDataHolderEx)project)
.putUserDataIfAbsent(LISTENERS_IN_PROJECT_KEY, ContainerUtil.createLockFreeCopyOnWriteList());
}
listeners.add(listener);
}
@Override
public void removeProjectManagerListener(@NotNull Project project, @NotNull ProjectManagerListener listener) {
List<ProjectManagerListener> listeners = project.getUserData(LISTENERS_IN_PROJECT_KEY);
LOG.assertTrue(listeners != null);
boolean removed = listeners.remove(listener);
LOG.assertTrue(removed);
}
private void fireProjectOpened(@NotNull Project project) {
if (LOG.isDebugEnabled()) {
LOG.debug("projectOpened");
}
for (ProjectManagerListener listener : myListeners) {
try {
listener.projectOpened(project);
}
catch (Exception e) {
LOG.error(e);
}
}
}
private void fireProjectClosed(@NotNull Project project) {
if (LOG.isDebugEnabled()) {
LOG.debug("projectClosed");
}
for (ProjectManagerListener listener : myListeners) {
try {
listener.projectClosed(project);
}
catch (Exception e) {
LOG.error(e);
}
}
}
@Override
public boolean canClose(@NotNull Project project) {
if (LOG.isDebugEnabled()) {
LOG.debug("enter: canClose()");
}
for (ProjectManagerListener listener : myListeners) {
try {
if (!listener.canCloseProject(project)) {
LOG.debug("close canceled by " + listener);
return false;
}
}
catch (Throwable e) {
LOG.warn(e); // DO NOT LET ANY PLUGIN to prevent closing due to exception
}
}
return true;
}
private static boolean ensureCouldCloseIfUnableToSave(@NotNull Project project) {
UnableToSaveProjectNotification[] notifications =
NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification.class, project);
if (notifications.length == 0) {
return true;
}
StringBuilder message = new StringBuilder();
message.append(String.format("%s was unable to save some project files,\nare you sure you want to close this project anyway?",
ApplicationNamesInfo.getInstance().getProductName()));
message.append("\n\nRead-only files:\n");
int count = 0;
VirtualFile[] files = notifications[0].myFiles;
for (VirtualFile file : files) {
if (count == 10) {
message.append('\n').append("and ").append(files.length - count).append(" more").append('\n');
}
else {
message.append(file.getPath()).append('\n');
count++;
}
}
return Messages.showYesNoDialog(project, message.toString(), "Unsaved Project", Messages.getWarningIcon()) == Messages.YES;
}
public static class UnableToSaveProjectNotification extends Notification {
private Project myProject;
public VirtualFile[] myFiles;
public UnableToSaveProjectNotification(@NotNull final Project project, @NotNull VirtualFile[] readOnlyFiles) {
super("Project Settings", "Could not save project", "Unable to save project files. Please ensure project files are writable and you have permissions to modify them." +
" <a href=\"\">Try to save project again</a>.", NotificationType.ERROR,
(notification, event) -> {
final UnableToSaveProjectNotification unableToSaveProjectNotification = (UnableToSaveProjectNotification)notification;
final Project _project = unableToSaveProjectNotification.myProject;
notification.expire();
if (_project != null && !_project.isDisposed()) {
_project.save();
}
});
myProject = project;
myFiles = readOnlyFiles;
}
@Override
public void expire() {
myProject = null;
super.expire();
}
}
@Override
public void saveChangedProjectFile(@NotNull VirtualFile file, @NotNull Project project) {
}
@Override
public void blockReloadingProjectOnExternalChanges() {
}
@Override
public void unblockReloadingProjectOnExternalChanges() {
}
}