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
|
/*
* Copyright 2000-2014 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.progress.impl;
import com.intellij.concurrency.JobScheduler;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.*;
import com.intellij.openapi.progress.util.ProgressWindow;
import com.intellij.openapi.progress.util.SmoothProgressAdapter;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.ex.ProgressIndicatorEx;
import com.intellij.psi.PsiLock;
import com.intellij.ui.SystemNotifications;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class ProgressManagerImpl extends ProgressManager implements Disposable {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.progress.impl.ProgressManagerImpl");
public static final int CHECK_CANCELED_DELAY_MILLIS = 10;
private final AtomicInteger myCurrentUnsafeProgressCount = new AtomicInteger(0);
private final AtomicInteger myCurrentModalProgressCount = new AtomicInteger(0);
private static volatile int ourLockedCheckCounter = 0;
private static final boolean DISABLED = "disabled".equals(System.getProperty("idea.ProcessCanceledException"));
private final ScheduledFuture<?> myCheckCancelledFuture;
public ProgressManagerImpl() {
if (DISABLED) {
myCheckCancelledFuture = null;
}
else {
myCheckCancelledFuture = JobScheduler.getScheduler().scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
ourNeedToCheckCancel = true;
}
}, 0, CHECK_CANCELED_DELAY_MILLIS, TimeUnit.MILLISECONDS);
}
}
@Override
protected void doCheckCanceled() throws ProcessCanceledException {
final ProgressIndicator progress = getProgressIndicator();
if (progress != null) {
try {
progress.checkCanceled();
}
catch (ProcessCanceledException e) {
if (DISABLED) {
return;
}
if (Thread.holdsLock(PsiLock.LOCK)) {
ourLockedCheckCounter++;
if (ourLockedCheckCounter > 10) {
ourLockedCheckCounter = 0;
canceled();
}
}
else {
ourLockedCheckCounter = 0;
throw e;
}
}
}
}
private static class NonCancelableIndicator extends EmptyProgressIndicator implements NonCancelableSection {
private final ProgressIndicator myOld;
private NonCancelableIndicator() {
myOld = myThreadIndicator.get();
}
@Override
public void done() {
ProgressIndicator currentIndicator = myThreadIndicator.get();
if (currentIndicator != this) {
throw new AssertionError("Trying do .done() NonCancelableSection, which is already done");
}
myThreadIndicator.set(myOld);
}
@Override
public void checkCanceled() {
}
}
@NotNull
@Override
public final NonCancelableSection startNonCancelableSection() {
NonCancelableIndicator nonCancelor = new NonCancelableIndicator();
myThreadIndicator.set(nonCancelor);
return nonCancelor;
}
@Override
public void executeNonCancelableSection(@NotNull Runnable runnable) {
executeProcessUnderProgress(runnable, new NonCancelableIndicator());
}
@Override
public void setCancelButtonText(String cancelButtonText) {
ProgressIndicator progressIndicator = getProgressIndicator();
if (progressIndicator != null) {
if (progressIndicator instanceof SmoothProgressAdapter && cancelButtonText != null) {
ProgressIndicator original = ((SmoothProgressAdapter)progressIndicator).getOriginal();
if (original instanceof ProgressWindow) {
((ProgressWindow)original).setCancelButtonText(cancelButtonText);
}
}
}
}
@Override
public boolean hasProgressIndicator() {
return getProgressIndicator() != null;
}
@Override
public boolean hasUnsafeProgressIndicator() {
return myCurrentUnsafeProgressCount.get() > 0;
}
@Override
public boolean hasModalProgressIndicator() {
return myCurrentModalProgressCount.get() > 0;
}
@Override
public void runProcess(@NotNull final Runnable process, final ProgressIndicator progress) {
executeProcessUnderProgress(new Runnable(){
@Override
public void run() {
try {
try {
if (progress != null && !progress.isRunning()) {
progress.start();
}
}
catch (Throwable e) {
LOG.info("Unexpected error when starting progress: ", e);
throw new RuntimeException(e);
}
process.run();
maybeSleep();
}
finally {
if (progress != null && progress.isRunning()) {
progress.stop();
if (progress instanceof ProgressIndicatorEx) {
((ProgressIndicatorEx)progress).processFinish();
}
}
}
}
},progress);
}
@Override
public <T> T runProcess(@NotNull final Computable<T> process, ProgressIndicator progress) throws ProcessCanceledException {
final Ref<T> ref = new Ref<T>();
runProcess(new Runnable() {
@Override
public void run() {
ref.set(process.compute());
}
}, progress);
return ref.get();
}
@Override
public void executeProcessUnderProgress(@NotNull Runnable process, ProgressIndicator progress) throws ProcessCanceledException {
boolean modal = progress != null && progress.isModal();
if (modal) myCurrentModalProgressCount.incrementAndGet();
if (progress == null || progress instanceof ProgressWindow) myCurrentUnsafeProgressCount.incrementAndGet();
try {
super.executeProcessUnderProgress(process, progress);
}
finally {
if (progress == null || progress instanceof ProgressWindow) myCurrentUnsafeProgressCount.decrementAndGet();
if (modal) myCurrentModalProgressCount.decrementAndGet();
}
}
@Override
public boolean runProcessWithProgressSynchronously(@NotNull final Runnable process,
@NotNull String progressTitle,
boolean canBeCanceled,
@Nullable Project project) {
return runProcessWithProgressSynchronously(process, progressTitle, canBeCanceled, project, null);
}
@Override
public <T, E extends Exception> T runProcessWithProgressSynchronously(@NotNull final ThrowableComputable<T, E> process,
@NotNull @Nls String progressTitle,
boolean canBeCanceled,
@Nullable Project project) throws E {
final Ref<T> result = new Ref<T>();
final Ref<Throwable> exception = new Ref<Throwable>();
runProcessWithProgressSynchronously(new Task.Modal(project, progressTitle, canBeCanceled) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
try {
T compute = process.compute();
result.set(compute);
}
catch (Throwable t) {
exception.set(t);
}
}
}, null);
if (!exception.isNull()) {
Throwable t = exception.get();
if (t instanceof Error) throw (Error)t;
if (t instanceof RuntimeException) throw (RuntimeException)t;
@SuppressWarnings("unchecked") E e = (E)t;
throw e;
}
return result.get();
}
@Override
public boolean runProcessWithProgressSynchronously(@NotNull final Runnable process,
@NotNull String progressTitle,
boolean canBeCanceled,
@Nullable Project project,
@Nullable JComponent parentComponent) {
Task.Modal task = new Task.Modal(project, progressTitle, canBeCanceled) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
process.run();
}
};
return runProcessWithProgressSynchronously(task, parentComponent);
}
private static boolean runProcessWithProgressSynchronously(@NotNull final Task task, @Nullable final JComponent parentComponent) {
final long start = System.currentTimeMillis();
final boolean result = ((ApplicationEx)ApplicationManager.getApplication())
.runProcessWithProgressSynchronously(new TaskContainer(task) {
@Override
public void run() {
new TaskRunnable(task, ProgressManager.getInstance().getProgressIndicator()).run();
}
}, task.getTitle(), task.isCancellable(), task.getProject(), parentComponent, task.getCancelText());
if (result) {
final long end = System.currentTimeMillis();
final Task.NotificationInfo notificationInfo = task.notifyFinished();
long time = end - start;
if (notificationInfo != null && time > 5000) { // show notification only if process took more than 5 secs
final JFrame frame = WindowManager.getInstance().getFrame(task.getProject());
if (frame != null && !frame.hasFocus()) {
systemNotify(notificationInfo);
}
}
task.onSuccess();
}
else {
task.onCancel();
}
return result;
}
private static void systemNotify(final Task.NotificationInfo notificationInfo) {
SystemNotifications.getInstance().notify(notificationInfo.getNotificationName(),
notificationInfo.getNotificationTitle(),
notificationInfo.getNotificationText());
}
@Override
public void runProcessWithProgressAsynchronously(@NotNull Project project,
@NotNull String progressTitle,
@NotNull final Runnable process,
@Nullable final Runnable successRunnable,
@Nullable final Runnable canceledRunnable) {
runProcessWithProgressAsynchronously(project, progressTitle, process, successRunnable, canceledRunnable, PerformInBackgroundOption.DEAF);
}
@Override
public void runProcessWithProgressAsynchronously(@NotNull final Project project,
@Nls @NotNull final String progressTitle,
@NotNull final Runnable process,
@Nullable final Runnable successRunnable,
@Nullable final Runnable canceledRunnable,
@NotNull final PerformInBackgroundOption option) {
runProcessWithProgressAsynchronously(new Task.Backgroundable(project, progressTitle, true, option) {
@Override
public void run(@NotNull final ProgressIndicator indicator) {
process.run();
}
@Override
public void onCancel() {
if (canceledRunnable != null) {
canceledRunnable.run();
}
}
@Override
public void onSuccess() {
if (successRunnable != null) {
successRunnable.run();
}
}
});
}
public static void runProcessWithProgressAsynchronously(@NotNull Task.Backgroundable task) {
final ProgressIndicator progressIndicator;
if (ApplicationManager.getApplication().isHeadlessEnvironment()) {
progressIndicator = new EmptyProgressIndicator();
}
else {
progressIndicator = new BackgroundableProcessIndicator(task);
}
runProcessWithProgressAsynchronously(task, progressIndicator, null);
}
@Override
public void runProcessWithProgressAsynchronously(@NotNull Task.Backgroundable task, @NotNull ProgressIndicator progressIndicator) {
runProcessWithProgressAsynchronously(task, progressIndicator, null);
}
@NotNull
public static Future<?> runProcessWithProgressAsynchronously(@NotNull final Task.Backgroundable task,
@NotNull final ProgressIndicator progressIndicator,
@Nullable final Runnable continuation) {
return runProcessWithProgressAsynchronously(task, progressIndicator, continuation, ModalityState.NON_MODAL);
}
@NotNull
public static Future<?> runProcessWithProgressAsynchronously(@NotNull final Task.Backgroundable task,
@NotNull final ProgressIndicator progressIndicator,
@Nullable final Runnable continuation,
@NotNull final ModalityState modalityState) {
if (progressIndicator instanceof Disposable) {
Disposer.register(ApplicationManager.getApplication(), (Disposable)progressIndicator);
}
final Runnable process = new TaskRunnable(task, progressIndicator, continuation);
TaskContainer action = new TaskContainer(task) {
@Override
public void run() {
boolean canceled = false;
final long start = System.currentTimeMillis();
try {
ProgressManager.getInstance().runProcess(process, progressIndicator);
}
catch (ProcessCanceledException e) {
canceled = true;
}
final long end = System.currentTimeMillis();
final long time = end - start;
if (canceled || progressIndicator.isCanceled()) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
task.onCancel();
}
}, modalityState);
}
else {
final Task.NotificationInfo notificationInfo = task.notifyFinished();
if (notificationInfo != null && time > 5000) { // snow notification if process took more than 5 secs
final Component window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
if (window == null || notificationInfo.isShowWhenFocused()) {
systemNotify(notificationInfo);
}
}
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
task.onSuccess();
}
}, modalityState);
}
}
};
return ApplicationManager.getApplication().executeOnPooledThread(action);
}
@Override
public void run(@NotNull final Task task) {
if (task.isHeadless()) {
if (ApplicationManager.getApplication().isDispatchThread()) {
runProcessWithProgressSynchronously(task, null);
}
else {
new TaskRunnable(task, new EmptyProgressIndicator()).run();
}
}
else if (task.isModal()) {
runProcessWithProgressSynchronously(task.asModal(), null);
}
else {
final Task.Backgroundable backgroundable = task.asBackgroundable();
if (backgroundable.isConditionalModal() && !backgroundable.shouldStartInBackground()) {
runProcessWithProgressSynchronously(task, null);
}
else {
runProcessWithProgressAsynchronously(backgroundable);
}
}
}
private abstract static class TaskContainer implements Runnable {
private final Task myTask;
protected TaskContainer(@NotNull Task task) {
myTask = task;
}
@NotNull
public Task getTask() {
return myTask;
}
}
private static class TaskRunnable extends TaskContainer {
private final ProgressIndicator myIndicator;
private final Runnable myContinuation;
private TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator) {
this(task, indicator, null);
}
private TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator, @Nullable Runnable continuation) {
super(task);
myIndicator = indicator;
myContinuation = continuation;
}
@Override
public void run() {
try {
getTask().run(myIndicator);
}
finally {
try {
if (myIndicator instanceof ProgressIndicatorEx) {
((ProgressIndicatorEx)myIndicator).finish(getTask());
}
}
finally {
if (myContinuation != null) {
myContinuation.run();
}
}
}
}
}
@Override
public void dispose() {
if (myCheckCancelledFuture != null) myCheckCancelledFuture.cancel(false);
}
private static void maybeSleep() {
final int debugProgressTime = Registry.intValue("ide.debug.minProgressTime");
if (debugProgressTime > 0) {
try {
Thread.sleep(debugProgressTime);
}
catch (InterruptedException e) {
//ignore
}
}
}
}
|