Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 575b4401eb4e28f5cdf1729eacf9a981823407ac (plain) (blame)
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
/*******************************************************************************
 * Copyright (C) 2017, Thomas Wolf <thomas.wolf@paranor.ch>
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *******************************************************************************/
package org.eclipse.egit.ui.internal.dialogs;

import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.LinkedList;
import java.util.Queue;

import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IProgressMonitorWithBlocking;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.ProgressMonitorWrapper;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.internal.UIText;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.ProgressMonitorPart;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

/**
 * A special-purpose {@link MinimumSizeWizardDialog} whose
 * {@link #run(boolean, boolean, IRunnableWithProgress) run()} method really
 * runs the job in the background. Use this mechanism with care!
 */
public class NonBlockingWizardDialog extends MinimumSizeWizardDialog {

	private Queue<BackgroundJob> jobs = new LinkedList<>();

	/**
	 * Creates a new {@link NonBlockingWizardDialog} that prevents the dialog
	 * from being made too small to show the starting page.
	 *
	 * @param parentShell
	 *            for the dialog
	 * @param newWizard
	 *            to show in the dialog
	 */
	public NonBlockingWizardDialog(Shell parentShell, IWizard newWizard) {
		this(parentShell, newWizard, true);
	}

	/**
	 * Creates a new {@link NonBlockingWizardDialog}.
	 *
	 * @param parentShell
	 *            for the dialog
	 * @param newWizard
	 *            to show in the dialog
	 * @param restrictResize
	 *            {@code true} if the dialog should prevent being resized
	 *            smaller than necessary to show the starting page;
	 *            {@code false} if resizing to any size should be allowed
	 */
	public NonBlockingWizardDialog(Shell parentShell, IWizard newWizard,
			boolean restrictResize) {
		super(parentShell, newWizard, restrictResize);
	}

	@Override
	protected Control createContents(Composite parent) {
		parent.addDisposeListener(e -> cancelJobs());
		addPageChangedListener(e -> cancelJobs());
		return super.createContents(parent);
	}

	/**
	 * Runs the given {@code runnable} in a background job, reporting progress
	 * through the dialog's progress monitor, if any, and invoking
	 * {@code onCancel} if the job is canceled.
	 * <p>
	 * The dialog is <em>not</em> made inactive while the job runs.
	 * </p>
	 * <p>
	 * Such background jobs are queued and will execute one after another. They
	 * are canceled when the current wizard page changes, or when the dialog
	 * closes.
	 * </p>
	 *
	 * @param runnable
	 *            to run
	 * @param onCancel
	 *            to run when the job is canceled; may be {@code null}
	 */
	public void run(IRunnableWithProgress runnable, Runnable onCancel) {
		Assert.isNotNull(runnable);
		synchronized (jobs) {
			BackgroundJob newJob = new BackgroundJob(runnable, onCancel,
					getCurrentPage());
			jobs.add(newJob);
			if (jobs.size() == 1) {
				newJob.schedule();
			}
		}
	}

	/**
	 * Cancels any currently scheduled background jobs.
	 */
	public void cancelJobs() {
		Job currentJob;
		synchronized (jobs) {
			currentJob = jobs.peek();
			jobs.clear();
		}
		if (currentJob != null) {
			currentJob.cancel();
		}
	}

	@Override
	public void showPage(IWizardPage page) {
		// Need to synchronize to avoid race condition with a background job
		// terminating.
		synchronized (jobs) {
			super.showPage(page);
		}
	}

	@Override
	public IWizardPage getCurrentPage() {
		synchronized (jobs) {
			return super.getCurrentPage();
		}
	}

	@Override
	protected final ProgressMonitorPart createProgressMonitorPart(
			Composite composite, GridLayout pmlayout) {
		return new BackgroundProgressMonitorPart(composite, pmlayout);
	}

	private void restoreFocus(Control focusControl) {
		if (focusControl != null && !focusControl.isDisposed()) {
			Shell shell = getShell();
			if (shell != null && !shell.isDisposed()
					&& focusControl.getShell() == shell) {
				focusControl.setFocus();
			}
		}
	}

	private class BackgroundProgressMonitorPart extends ProgressMonitorPart {

		private Job job;

		public BackgroundProgressMonitorPart(Composite parent, Layout layout) {
			super(parent, layout, true);
		}

		public void setJob(Job job) {
			this.job = job;
		}

		@Override
		public void beginTask(String name, int totalWork) {
			// Super implementation steals the focus and sets it to the
			// monitor part's stop button.
			Display display = this.getDisplay();
			Control focusControl = display.isDisposed() ? null
					: display.getFocusControl();
			super.beginTask(name, totalWork);
			restoreFocus(focusControl);
		}

		@Override
		public void setCanceled(boolean cancel) {
			super.setCanceled(cancel);
			if (cancel) {
				if (job != null) {
					job.cancel();
				}
			}
		}

		@Override
		public void done() {
			job = null;
			super.done();
		}
	}

	/**
	 * Copied from org.eclipse.jface.operation.AccumulatingProgressMonitor and
	 * made {@link #isCanceled()} also consider the progress monitor provided by
	 * the Job framework. Also handle disposal in {@link #done()}.
	 * <p>
	 * The resulting monitor can be used from any thread; progress reporting to
	 * the wrapped monitor will occur asynchronously in the UI thread.
	 */
	private static class ForwardingProgressMonitor
			extends ProgressMonitorWrapper {
		private Display display;

		private Collector collector;

		private IProgressMonitor jobMonitor;

		private String currentTask = ""; //$NON-NLS-1$

		private class Collector implements Runnable {
			private String taskName;

			private String subTask;

			private double worked;

			private IProgressMonitor monitor;

			public Collector(String taskName, String subTask, double work,
					IProgressMonitor monitor) {
				this.taskName = taskName;
				this.subTask = subTask;
				this.worked = work;
				this.monitor = monitor;
			}

			public void setTaskName(String name) {
				this.taskName = name;
			}

			public void worked(double workedIncrement) {
				this.worked = this.worked + workedIncrement;
			}

			public void subTask(String subTaskName) {
				this.subTask = subTaskName;
			}

			@Override
			public void run() {
				clearCollector(this);
				if (taskName != null) {
					monitor.setTaskName(taskName);
				}
				if (subTask != null) {
					monitor.subTask(subTask);
				}
				if (worked > 0) {
					monitor.internalWorked(worked);
				}
			}
		}

		/**
		 * Creates a progress monitor wrapping the given one that uses the given
		 * display.
		 *
		 * @param monitor
		 *            the actual progress monitor to be wrapped
		 * @param jobMonitor
		 *            auxiliary monitor to consider for isCanceled()
		 * @param display
		 *            the SWT display used to forward the calls to the wrapped
		 *            progress monitor
		 */
		public ForwardingProgressMonitor(IProgressMonitor monitor,
				IProgressMonitor jobMonitor, Display display) {
			super(monitor);
			Assert.isNotNull(display);
			this.display = display;
			this.jobMonitor = jobMonitor;
		}

		@Override
		public boolean isCanceled() {
			return jobMonitor.isCanceled() || super.isCanceled();
		}

		@Override
		public void beginTask(final String name, final int totalWork) {
			synchronized (this) {
				collector = null;
			}
			display.asyncExec(() -> {
				currentTask = name;
				getWrappedProgressMonitor().beginTask(name, totalWork);
			});
		}

		/**
		 * Clears the collector object used to accumulate work and subtask calls
		 * if it matches the given one.
		 *
		 * @param collectorToClear
		 */
		private synchronized void clearCollector(Collector collectorToClear) {
			// Check if the accumulator is still using the given collector.
			// If not, don't clear it.
			if (this.collector == collectorToClear) {
				this.collector = null;
			}
		}

		/**
		 * Creates a collector object to accumulate work and subtask calls.
		 *
		 * @param taskName
		 *            initial task name
		 * @param subTask
		 *            initial sub-task name
		 * @param work
		 *            initial work of the collector
		 */
		private void createCollector(String taskName, String subTask,
				double work) {
			collector = new Collector(taskName, subTask, work,
					getWrappedProgressMonitor());
			display.asyncExec(collector);
		}

		@Override
		public void done() {
			synchronized (this) {
				collector = null;
			}
			if (!display.isDisposed()) {
				display.asyncExec(() -> {
					try {
						getWrappedProgressMonitor().done();
					} catch (SWTException e) {
						// May occur if the wrapped monitor is some already
						// disposed control. ProgressMonitorPart is otherwise
						// careful not to do anything when it has been disposed,
						// but neglects to check in done(). Just ignore it.
					}
				});
			}
		}

		@Override
		public synchronized void internalWorked(final double work) {
			if (collector == null) {
				createCollector(null, null, work);
			} else {
				collector.worked(work);
			}
		}

		@Override
		public synchronized void setTaskName(final String name) {
			currentTask = name;
			if (collector == null) {
				createCollector(name, null, 0);
			} else {
				collector.setTaskName(name);
			}
		}

		@Override
		public synchronized void subTask(final String name) {
			if (collector == null) {
				createCollector(null, name, 0);
			} else {
				collector.subTask(name);
			}
		}

		@Override
		public void worked(int work) {
			internalWorked(work);
		}

		@Override
		public void clearBlocked() {
			// If this is a monitor that can report blocking do so.
			// Don't bother with a collector as this should only ever
			// happen once.
			IProgressMonitor wrapped = getWrappedProgressMonitor();
			if (!(wrapped instanceof IProgressMonitorWithBlocking)) {
				return;
			}

			display.asyncExec(() -> {
				((IProgressMonitorWithBlocking) wrapped).clearBlocked();
				Dialog.getBlockedHandler().clearBlocked();
			});
		}

		@Override
		public void setBlocked(final IStatus reason) {
			// If this is a monitor that can report blocking do so.
			// Don't bother with a collector as this should only ever
			// happen once and prevent any more progress.
			IProgressMonitor wrapped = getWrappedProgressMonitor();
			if (!(wrapped instanceof IProgressMonitorWithBlocking)) {
				return;
			}

			display.asyncExec(() -> {
				((IProgressMonitorWithBlocking) wrapped).setBlocked(reason);
				// Do not give a shell as we want it to block until it opens.
				Dialog.getBlockedHandler().showBlocked(wrapped, reason,
						currentTask);
			});
		}

	}

	private class BackgroundJob extends Job {

		private IRunnableWithProgress runnable;

		private Runnable onCancel;

		private IWizardPage page;

		public BackgroundJob(IRunnableWithProgress runnable, Runnable onCancel,
				IWizardPage page) {
			super(MessageFormat.format(
					UIText.NonBlockingWizardDialog_BackgroundJobName,
					page.getName()));
			this.runnable = runnable;
			this.onCancel = onCancel;
			this.page = page;
			this.addJobChangeListener(new JobChangeAdapter() {

				@Override
				public void done(IJobChangeEvent event) {
					if (!PlatformUI.isWorkbenchRunning()) {
						return;
					}
					Display display = PlatformUI.getWorkbench().getDisplay();
					if (display == null || display.isDisposed()) {
						return;
					}
					display.syncExec(() -> {
						boolean hideProgress = false;
						synchronized (jobs) {
							Job currentJob = jobs.peek();
							if (currentJob == BackgroundJob.this) {
								jobs.poll();
								Job nextJob = jobs.peek();
								if (nextJob != null) {
									nextJob.schedule();
								} else {
									hideProgress = true;
								}
							} else if (currentJob == null) {
								hideProgress = true;
							}
							if (hideProgress) {
								IProgressMonitor uiMonitor = getProgressMonitor();
								if (uiMonitor instanceof ProgressMonitorPart) {
									ProgressMonitorPart part = ((ProgressMonitorPart) uiMonitor);
									if (!part.isDisposed()) {
										part.setVisible(false);
										part.removeFromCancelComponent(null);
									}
								}
							}
						}
					});
				}
			});
			this.setUser(false);
			this.setSystem(true);
		}

		@Override
		public boolean shouldRun() {
			synchronized (jobs) {
				return page == getCurrentPage() && jobs.peek() == this;
			}
		}

		@Override
		protected void canceling() {
			try {
				if (onCancel != null) {
					onCancel.run();
				}
			} finally {
				super.canceling();
			}
		}

		@Override
		protected IStatus run(IProgressMonitor monitor) {
			if (!shouldRun()) {
				// Should actually not occur. Just to be on the safe side.
				return Status.CANCEL_STATUS;
			}
			// Hook up monitors so that we can report progress in the UI.
			IProgressMonitor uiMonitor = getProgressMonitor();
			IProgressMonitor combinedMonitor;
			if (uiMonitor instanceof ProgressMonitorPart) {
				ProgressMonitorPart part = ((ProgressMonitorPart) uiMonitor);
				IProgressMonitor[] newMonitor = { null };
				Display display = PlatformUI.getWorkbench().getDisplay();
				if (display == null || display.isDisposed()) {
					return Status.CANCEL_STATUS;
				}
				display.syncExec(() -> {
					if (((ProgressMonitorPart) uiMonitor).isDisposed()) {
						return;
					}
					try {
						Control focusControl = display.getFocusControl();
						part.setVisible(true);
						part.attachToCancelComponent(null);
						// Attaching sets the focus to the stop button...
						restoreFocus(focusControl);
						if (part instanceof BackgroundProgressMonitorPart) {
							((BackgroundProgressMonitorPart) part)
									.setJob(BackgroundJob.this);
						}
						newMonitor[0] = new ForwardingProgressMonitor(uiMonitor,
								monitor, part.getDisplay());
					} catch (SWTException e) {
						return;
					}
				});
				combinedMonitor = newMonitor[0];
				if (combinedMonitor == null) {
					return Status.CANCEL_STATUS;
				}
			} else {
				combinedMonitor = monitor;
			}
			try {
				runnable.run(combinedMonitor);
			} catch (InvocationTargetException e) {
				return Activator.createErrorStatus(e.getLocalizedMessage(), e);
			} catch (InterruptedException e) {
				return Status.CANCEL_STATUS;
			} finally {
				monitor.done();
				if (combinedMonitor != monitor) {
					combinedMonitor.done();
				}
			}
			return Status.OK_STATUS;
		}

	}
}

Back to the top