Skip to main content
summaryrefslogtreecommitdiffstats
blob: e341bdecaa0e5d5a61fe0284d2568f6374d4cff4 (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
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
/*******************************************************************************
 * Copyright (c) 2004, 2012 Tasktop Technologies and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Tasktop Technologies - initial API and implementation
 *******************************************************************************/

package org.eclipse.mylyn.internal.context.ui.state;

import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SafeRunner;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.util.SafeRunnable;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.context.core.ContextCore;
import org.eclipse.mylyn.context.core.IInteractionElement;
import org.eclipse.mylyn.context.ui.ContextAwareEditorInput;
import org.eclipse.mylyn.context.ui.ContextUi;
import org.eclipse.mylyn.context.ui.IContextAwareEditor;
import org.eclipse.mylyn.internal.context.ui.ContextUiPlugin;
import org.eclipse.mylyn.internal.context.ui.IContextUiPreferenceContstants;
import org.eclipse.mylyn.monitor.ui.MonitorUi;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPathEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.XMLMemento;
import org.eclipse.ui.internal.EditorReference;
import org.eclipse.ui.internal.IPreferenceConstants;
import org.eclipse.ui.internal.IWorkbenchConstants;
import org.eclipse.ui.internal.Workbench;
import org.eclipse.ui.internal.WorkbenchPage;

/**
 * @author Mik Kersten
 * @author Shawn Minto
 */
public class EditorStateParticipant extends ContextStateParticipant {

	public static final String MEMENTO_EDITORS = "org.eclipse.mylyn.context.ui.editors"; //$NON-NLS-1$

	private static final String KEY_MONITORED_WINDOW_OPEN_EDITORS = "MonitoredWindowOpenEditors"; //$NON-NLS-1$

	private static final String ATTRIBUTE_CLASS = "class"; //$NON-NLS-1$

	private static final String ATTRIBUTE_NUMER = "number"; //$NON-NLS-1$

	private static final String ATTRIBUTE_IS_LAUNCHING = "isLaunching"; //$NON-NLS-1$

	private static final String ATTRIBUTE_IS_ACTIVE = "isActive"; //$NON-NLS-1$

	private boolean previousCloseEditorsSetting = Workbench.getInstance()
			.getPreferenceStore()
			.getBoolean(IPreferenceConstants.REUSE_EDITORS_BOOLEAN);

	private boolean enabled;

	private IMemento savedMemento;

	private String savedContextHandle;

	public EditorStateParticipant() {
		this.enabled = true;
	}

	@Override
	public void saveDefaultState(ContextState memento) {
		// save platform preference setting
		Workbench workbench = (Workbench) PlatformUI.getWorkbench();
		previousCloseEditorsSetting = workbench.getPreferenceStore().getBoolean(
				IPreferenceConstants.REUSE_EDITORS_BOOLEAN);
		workbench.getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN, false);
	}

	@Override
	public void restoreState(ContextState state) {
		if (Workbench.getInstance().isStarting()) {
			return;
		}

		boolean wasPaused = ContextCore.getContextManager().isContextCapturePaused();
		try {
			if (!wasPaused) {
				ContextCore.getContextManager().setContextCapturePaused(true);
			}

			// restore editors from memento
			String mementoString = null;
			IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
			try {
				IMemento memento = state.getMemento(MEMENTO_EDITORS);
				savedMemento = memento;
				savedContextHandle = state.getContextHandle();
				if (memento != null) {
					IMemento[] children = memento.getChildren(KEY_MONITORED_WINDOW_OPEN_EDITORS);
					if (children.length > 0) {
						// This code supports restore from multiple windows
						for (IMemento child : children) {
							WorkbenchPage page = getWorkbenchPageForMemento(child, activeWindow);
							if (child != null && page != null) {
								restoreEditors(page, child, page.getWorkbenchWindow() == activeWindow);
							}
						}
					} else {
						// This code is for supporting the old editor management - only the active window
						WorkbenchPage page = (WorkbenchPage) activeWindow.getActivePage();
						if (memento != null) {
							restoreEditors(page, memento, true);
						}
					}
				}
			} catch (Exception e) {
				StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
						"Could not restore all editors, memento: \"" + mementoString + "\"", e)); //$NON-NLS-1$ //$NON-NLS-2$
			}

			// refresh window
			activeWindow.setActivePage(activeWindow.getActivePage());

			// open last active context node, guarantees that something is opened even if no editor memento is available
			IInteractionElement activeNode = state.getContext().getActiveNode();
			if (activeNode != null) {
				ContextUi.getUiBridge(activeNode.getContentType()).open(activeNode);
			}
		} catch (Exception e) {
			StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
					"Failed to open editors on activation", e)); //$NON-NLS-1$
		} finally {
			ContextCore.getContextManager().setContextCapturePaused(false);
		}
	}

	private WorkbenchPage getWorkbenchPageForMemento(IMemento memento, IWorkbenchWindow activeWindow) {
		String windowToRestoreClassName = memento.getString(ATTRIBUTE_CLASS);
		if (windowToRestoreClassName == null) {
			windowToRestoreClassName = ""; //$NON-NLS-1$
		}
		Integer windowToRestorenumber = memento.getInteger(ATTRIBUTE_NUMER);
		if (windowToRestorenumber == null) {
			windowToRestorenumber = 0;
		}

		// try to match the open windows to the one that we want to restore
		Set<IWorkbenchWindow> monitoredWindows = MonitorUi.getMonitoredWindows();
		for (IWorkbenchWindow window : monitoredWindows) {
			int windowNumber = getNumber(window);
			if (window.getClass().getCanonicalName().equals(windowToRestoreClassName)
					&& windowNumber == windowToRestorenumber) {
				return (WorkbenchPage) window.getActivePage();
			}
		}

		// we don't have a good match here, try to make an educated guess
		Boolean isActive = memento.getBoolean(ATTRIBUTE_IS_ACTIVE);
		if (isActive == null) {
			isActive = false;
		}

		// both of these defaulting to true should ensure that all editors are opened even if their previous editor is not around
		boolean shouldRestoreUnknownWindowToActive = true; // TODO could add a preference here
		boolean shouldRestoreActiveWindowToActive = true; // TODO could add a preference here

		if (isActive && shouldRestoreActiveWindowToActive) {
			// if the window that we are trying to restore was the active window, restore it to the active window
			return (WorkbenchPage) activeWindow.getActivePage();
		}

		if (shouldRestoreUnknownWindowToActive) {
			// we can't find a good window, so restore it to the active one
			return (WorkbenchPage) activeWindow.getActivePage();
		}

		if (shouldRestoreActiveWindowToActive && shouldRestoreUnknownWindowToActive) {
			StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
					"Unable to find window to restore memento to.", new Exception())); //$NON-NLS-1$
		}

		// we dont have a window that will work, so don't restore the editors
		// we shouldn't get here if both *WindowToActive booleans are true
		return null;
	}

	@Override
	public void saveState(ContextState state, boolean allowModifications) {
		if (PlatformUI.getWorkbench().isClosing()) {
			return;
		}

		if (allowModifications) {
			closeContextAwareEditors(state.getContextHandle());
		}

		IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
		IWorkbenchWindow launchingWindow = MonitorUi.getLaunchingWorkbenchWindow();
		Set<IWorkbenchWindow> monitoredWindows = MonitorUi.getMonitoredWindows();

		boolean failed = false;
		IMemento newMemento = XMLMemento.createWriteRoot(MEMENTO_EDITORS);
		for (IWorkbenchWindow window : monitoredWindows) {
			IMemento memento = newMemento.createChild(KEY_MONITORED_WINDOW_OPEN_EDITORS);

			memento.putString(ATTRIBUTE_CLASS, window.getClass().getCanonicalName());
			int number = getNumber(window);
			memento.putInteger(ATTRIBUTE_NUMER, number);
			memento.putBoolean(ATTRIBUTE_IS_LAUNCHING, window == launchingWindow);
			memento.putBoolean(ATTRIBUTE_IS_ACTIVE, window == activeWindow);

			try {
				if (is_3_x()) {
					saveEditors_e_3_x((WorkbenchPage) window.getActivePage(), memento);
				} else if (is_3_8_2()) {
					saveEditors_e_8_2(window.getActivePage(), memento);
				} else {
					saveEditors_e_4_legacy((WorkbenchPage) window.getActivePage(), memento);
				}
			} catch (Exception e) {
				StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
						"Saving of editor state failed", e)); //$NON-NLS-1$
				failed = true;
			}
		}

		// retain the state in case editor save/restore fails on e4 
		if (failed && savedMemento != null && savedContextHandle != null
				&& savedContextHandle.equals(state.getContextHandle())) {
			IMemento memento = state.createMemento(MEMENTO_EDITORS);
			memento.putMemento(savedMemento);
		} else {
			IMemento memento = state.createMemento(MEMENTO_EDITORS);
			memento.putMemento(newMemento);
		}
		savedMemento = null;
	}

	private void saveEditors_e_8_2(IWorkbenchPage page, IMemento memento) throws Exception {
		Method getEditorStateMethod = IWorkbenchPage.class.getDeclaredMethod(
				"getEditorState", IEditorReference[].class, boolean.class); //$NON-NLS-1$
		IMemento[] states = (IMemento[]) getEditorStateMethod.invoke(page, page.getEditorReferences(), true);

		for (IMemento state : states) {
			IMemento childMemento = memento.createChild("editor"); //$NON-NLS-1$
			childMemento.putMemento(state);
		}
	}

	@SuppressWarnings("unchecked")
	private void saveEditors_e_4_legacy(final WorkbenchPage page, IMemento memento) throws Exception {
		Method getInternalEditorReferences = WorkbenchPage.class.getDeclaredMethod("getInternalEditorReferences"); //$NON-NLS-1$
		final List<EditorReference> editorReferences = (List<EditorReference>) getInternalEditorReferences.invoke(page);
		SafeRunner.run(new SafeRunnable() {
			public void run() {
				for (EditorReference reference : editorReferences) {
					// realize editor
					IEditorPart editor = reference.getEditor(true);
					if (editor != null) {
						Method method;
						try {
							method = EditorReference.class.getDeclaredMethod("persist"); //$NON-NLS-1$
							method.setAccessible(true);
							method.invoke(reference);
						} catch (Exception e) {
							// ignore
						}
					}
				}
			}
		});

		E4EditorReflector reflector = new E4EditorReflector();
		List<?> editors = reflector.findElements(page);
		for (Object editor : editors) {
			Map<String, String> persistedState = reflector.getPersistedState(editor);
			String state = persistedState.get("memento"); //$NON-NLS-1$
			if (state != null) {
				XMLMemento editorMemento = XMLMemento.createReadRoot(new StringReader(state));
				IMemento childMemento = memento.createChild("editor"); //$NON-NLS-1$
				childMemento.putMemento(editorMemento);
			}
		}
	}

	private void saveEditors_e_3_x(WorkbenchPage page, IMemento memento) throws Exception {
		Method getEditorManagerMethod = WorkbenchPage.class.getDeclaredMethod("getEditorManager"); //$NON-NLS-1$
		Object editorManager = getEditorManagerMethod.invoke(page);

		Method getEditorsMethod = editorManager.getClass().getDeclaredMethod("saveState", IMemento.class); //$NON-NLS-1$
		getEditorsMethod.invoke(editorManager, memento);
	}

	private int getNumber(IWorkbenchWindow window) {
		IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
		for (int i = 0; i < windows.length; i++) {
			if (windows[i] == window) {
				return i;
			}
		}
		return 0;
	}

	@Override
	public void restoreDefaultState(ContextState memento) {
		Workbench.getInstance()
				.getPreferenceStore()
				.setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN, previousCloseEditorsSetting);
		closeAllEditors();
	}

	@Override
	public void clearState(String contextHandle, boolean activeContext) {
//		if (activeContext) {
//			closeContextAwareEditors(contextHandle);
//		}
//		Workbench.getInstance()
//				.getPreferenceStore()
//				.setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN, previousCloseEditorsSetting);
//		if (activeContext) {
//			closeAllEditors();
//		}
		if (activeContext) {
			closeAllEditors();
		}
	}

	/**
	 * HACK: will fail to restore different parts with same name
	 */
	private void restoreEditors(WorkbenchPage page, IMemento memento, boolean isActiveWindow) {
		final ArrayList<?> visibleEditors = new ArrayList<Object>(5);
		final IEditorReference activeEditor[] = new IEditorReference[1];
		final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, "", null); //$NON-NLS-1$

		try {
			IMemento[] editorMementos = memento.getChildren(IWorkbenchConstants.TAG_EDITOR);
			Set<IMemento> editorMementoSet = new LinkedHashSet<IMemento>();
			editorMementoSet.addAll(Arrays.asList(editorMementos));

			if (is_3_x()) {
				restoreEditors_e_3_x(page, visibleEditors, activeEditor, result, editorMementoSet);
			} else if (is_3_8_2()) {
				restoreEditors_e_3_8_2(page, visibleEditors, activeEditor, result, editorMementoSet);
			} else {
				restoreEditors_e_4_legacy(page, visibleEditors, activeEditor, result, editorMementoSet);
			}

			// the 3.8.2 implementation automatically activates the first editor
			if (!is_3_8_2() && activeEditor[0] != null && isActiveWindow) {
				IWorkbenchPart editor = activeEditor[0].getPart(true);
				if (editor != null) {
					page.activate(editor);
				}
			}
		} catch (Exception e) {
			StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
					"Restoring of editor state failed", e)); //$NON-NLS-1$
		}
	}

	/**
	 * Returns true if the environment supports the Eclipse 3.8.2/4.2.2 API for editor save and restore.
	 */
	private boolean is_3_8_2() {
		try {
			IWorkbenchPage.class.getDeclaredMethod(
					"openEditors", IEditorInput[].class, String[].class, IMemento[].class, int.class, int.class); //$NON-NLS-1$
			return true;
		} catch (NoSuchMethodException e) {
			return false;
		}
	}

	/**
	 * Returns true if the environment supports the Eclipse 3.x API for editor save and restore.
	 */
	private boolean is_3_x() {
		try {
			Class<?> editorManager = Class.forName("org.eclipse.ui.internal.EditorManager"); //$NON-NLS-1$
			editorManager.getDeclaredMethod("restoreEditorState", //$NON-NLS-1$
					IMemento.class, ArrayList.class, IEditorReference[].class, MultiStatus.class);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	private void restoreEditors_e_3_8_2(WorkbenchPage page, final ArrayList<?> visibleEditors,
			final IEditorReference[] activeEditor, final MultiStatus result, Set<IMemento> editorMementoSet)
			throws Exception {
		Method openEditorsMethod = IWorkbenchPage.class.getDeclaredMethod(
				"openEditors", IEditorInput[].class, String[].class, IMemento[].class, int.class, int.class); //$NON-NLS-1$
		openEditorsMethod.invoke(page, null, null, editorMementoSet.toArray(new IMemento[0]),
				IWorkbenchPage.MATCH_INPUT, 0);
	}

	private void restoreEditors_e_4_legacy(WorkbenchPage page, ArrayList<?> visibleEditors,
			IEditorReference[] activeEditor, MultiStatus result, Set<IMemento> mementos) throws Exception {
		E4EditorReflector reflector = new E4EditorReflector();
		for (IMemento memento : mementos) {
			StringWriter writer = new StringWriter();
			boolean found = false;
			IMemento inputMememnto = memento.getChild("input"); //$NON-NLS-1$
			if (inputMememnto != null) {
				String pathString = inputMememnto.getString("path"); //$NON-NLS-1$
				if (pathString != null) {
					IPath path = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(pathString)).getLocation();
					for (IEditorReference existingReference : page.getEditorReferences()) {
						if (existingReference.getEditorInput() instanceof IPathEditorInput
								&& (((IPathEditorInput) existingReference.getEditorInput()).getPath().equals(path))) {
							// there is already an editor showing the same file
							found = true;
							break;
						}
					}
				}
			}
			if (!found) {
				// create part
				Object editor = reflector.createPart(page.getWorkbenchWindow());
				// inject persisted editor state
				((XMLMemento) memento).save(writer);
				reflector.getPersistedState(editor).put("memento", writer.toString()); //$NON-NLS-1$
				// create legacy editor control
				reflector.showPart(page, editor);
			}
		}
	}

	private void restoreEditors_e_3_x(WorkbenchPage page, final ArrayList<?> visibleEditors,
			final IEditorReference[] activeEditor, final MultiStatus result, Set<IMemento> editorMementoSet)
			throws Exception {
		Method getEditorManagerMethod = WorkbenchPage.class.getDeclaredMethod("getEditorManager"); //$NON-NLS-1$
		Object editorManager = getEditorManagerMethod.invoke(page);

		Method getEditorsMethod = editorManager.getClass().getDeclaredMethod("getEditors"); //$NON-NLS-1$

		List<IEditorReference> alreadyVisibleEditors = Arrays.asList((IEditorReference[]) getEditorsMethod.invoke(editorManager));
		Set<String> restoredPartNames = new HashSet<String>();
		for (IEditorReference editorReference : alreadyVisibleEditors) {
			restoredPartNames.add(editorReference.getPartName());
		}

		Method restoreEditorStateMethod = editorManager.getClass().getDeclaredMethod("restoreEditorState", //$NON-NLS-1$
				IMemento.class, ArrayList.class, IEditorReference[].class, MultiStatus.class);

		for (IMemento editorMemento : editorMementoSet) {
			String partName = editorMemento.getString(IWorkbenchConstants.TAG_PART_NAME);
			if (!restoredPartNames.contains(partName)) {
				restoreEditorStateMethod.invoke(editorManager, editorMemento, visibleEditors, activeEditor, result);
			} else {
				restoredPartNames.add(partName);
			}
		}

		Method setVisibleEditorMethod = editorManager.getClass().getDeclaredMethod("setVisibleEditor", //$NON-NLS-1$
				IEditorReference.class, boolean.class);
		for (int i = 0; i < visibleEditors.size(); i++) {
			setVisibleEditorMethod.invoke(editorManager, visibleEditors.get(i), false);
		}
	}

	public void closeContextAwareEditors(String contextHandle) {
		try {
			if (PlatformUI.getWorkbench().isClosing()) {
				return;
			}
			for (IWorkbenchWindow window : MonitorUi.getMonitoredWindows()) {
				IWorkbenchPage page = window.getActivePage();
				if (page != null) {
					IEditorReference[] references = page.getEditorReferences();
					List<IEditorReference> toClose = new ArrayList<IEditorReference>();
					for (IEditorReference reference : references) {
						if (canClose(reference)) {
							try {
								IEditorInput input = reference.getEditorInput();
								if (shouldForceClose(input, contextHandle)) {
									toClose.add(reference);
								}
							} catch (PartInitException e) {
								// ignore
							}
						}
					}
					page.closeEditors(toClose.toArray(new IEditorReference[toClose.size()]), true);
				}
			}
		} catch (Throwable t) {
			StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, "Could not auto close editor", t)); //$NON-NLS-1$
		}
	}

	public void closeAllEditors() {
		try {
			if (PlatformUI.getWorkbench().isClosing()) {
				return;
			}
			for (IWorkbenchWindow window : MonitorUi.getMonitoredWindows()) {
				IWorkbenchPage page = window.getActivePage();
				if (page != null) {
					IEditorReference[] references = page.getEditorReferences();
					List<IEditorReference> toClose = new ArrayList<IEditorReference>();
					for (IEditorReference reference : references) {
						if (canClose(reference)) {
							toClose.add(reference);
						}
					}
					page.closeEditors(toClose.toArray(new IEditorReference[toClose.size()]), true);
				}
			}
		} catch (Throwable t) {
			StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, "Could not auto close editor", t)); //$NON-NLS-1$
		}
	}

	private boolean shouldForceClose(final IEditorInput input, final String contextHandle) {
		final AtomicBoolean result = new AtomicBoolean();
		SafeRunnable.run(new ISafeRunnable() {
			public void run() throws Exception {
				ContextAwareEditorInput inputContext = (ContextAwareEditorInput) input.getAdapter(ContextAwareEditorInput.class);
				result.set(inputContext != null && inputContext.forceClose(contextHandle));
			}

			public void handleException(Throwable e) {
				StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
						"Failed to verify editor status", e)); //$NON-NLS-1$
			}
		});
		return result.get();
	}

	private boolean canClose(final IEditorReference editorReference) {
		final IEditorPart editor = editorReference.getEditor(false);
		if (editor != null) {
			final boolean[] result = new boolean[1];
			result[0] = true;
			SafeRunnable.run(new ISafeRunnable() {
				public void run() throws Exception {
					if (editor instanceof IContextAwareEditor) {
						result[0] = ((IContextAwareEditor) editor).canClose();
					} else {
						IContextAwareEditor contextAware = (IContextAwareEditor) editor.getAdapter(IContextAwareEditor.class);
						if (contextAware != null) {
							result[0] = contextAware.canClose();
						}
					}
				}

				public void handleException(Throwable e) {
					StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
							"Failed to verify editor status", e)); //$NON-NLS-1$
				}
			});
			return result[0];
		}
		return true;
	}

	@Override
	public boolean isEnabled() {
		return enabled
				&& ContextUiPlugin.getDefault()
						.getPreferenceStore()
						.getBoolean(IContextUiPreferenceContstants.AUTO_MANAGE_EDITORS);
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

}

Back to the top