Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 73aa1f1373d4900aae66ecf17ae2e9c0a1b695b0 (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
/*******************************************************************************
 * Copyright (c) 2016 Red Hat Inc. 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:
 *     Red Hat Inc. - initial API and implementation
 *******************************************************************************/
package org.eclipse.linuxtools.internal.docker.ui.testutils.swt;

import static org.assertj.core.api.Assertions.fail;

import java.util.List;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
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.linuxtools.internal.docker.ui.views.DockerExplorerView;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.eclipse.swtbot.eclipse.finder.waits.Conditions;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView;
import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable;
import org.eclipse.swtbot.swt.finder.results.Result;
import org.eclipse.swtbot.swt.finder.results.VoidResult;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotToolbarButton;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
import org.eclipse.ui.console.IConsoleConstants;
import org.eclipse.ui.progress.UIJob;
import org.junit.Assert;
import org.junit.ComparisonFailure;

/**
 * Utility class for SWT
 */
public class SWTUtils {

	/**
	 * Calls <strong>synchronously</strong> the given {@link Supplier} in the
	 * default Display and returns the result
	 *
	 * @param supplier
	 *            the Supplier to call
	 * @return the supplier's result
	 */
	public static <V> V syncExec(final Supplier<V> supplier) {
		final Queue<V> result = new ArrayBlockingQueue<>(1);
		Display.getDefault().syncExec(() -> result.add(supplier.get()));
		return result.poll();
	}

	/**
	 * Executes <strong>synchronously</strong> the given {@link Runnable} in the
	 * default Display
	 *
	 * @param runnable
	 *            the {@link Runnable} to execute
	 */
	public static void syncExec(final Runnable runnable) {
		Display.getDefault().syncExec(runnable);
	}

	/**
	 * Executes <strong>synchronously</strong> the given {@link Runnable} in the
	 * default Display. The given {@link Runnable} is ran into a rapping
	 * {@link Runnable} that will catch the {@link ComparisonFailure} that may
	 * be raised during an assertion.
	 *
	 * @param runnable
	 *            the {@link Runnable} to execute
	 * @throws ComparisonFailure
	 *             if an assertion failed.
	 * @throws SWTException
	 *             if an {@link SWTException} occurred
	 */
	@Deprecated
	public static void syncAssert(final Runnable runnable) throws SWTException, ComparisonFailure {
		final Queue<ComparisonFailure> failure = new ArrayBlockingQueue<>(1);
		final Queue<SWTException> swtException = new ArrayBlockingQueue<>(1);
		Display.getDefault().syncExec(() -> {
			try {
				runnable.run();
			} catch (ComparisonFailure e1) {
				failure.add(e1);
			} catch (SWTException e2) {
				swtException.add(e2);
			}
		});
		if (!failure.isEmpty()) {
			throw failure.poll();
		}
		if (!swtException.isEmpty()) {
			throw swtException.poll();
		}
	}

	/**
	 * Executes the given {@link Runnable} <strong>asynchronously</strong> in
	 * the default {@link Display} and waits until all jobs are done before
	 * completing.
	 *
	 * @param runnable
	 * @throws InterruptedException
	 */
	public static void asyncExec(final Runnable runnable) {
		asyncExec(runnable, true);
	}

	/**
	 * Executes the given {@link Runnable} <strong>asynchronously</strong> in
	 * the default {@link Display} and waits until all jobs are done before
	 * completing.
	 *
	 * @param runnable
	 *            the {@link Runnable} to execute
	 * @param waitForJobsToComplete
	 *            boolean flag to indicate if the method should wait for all
	 *            jobs to complete before finishing
	 * @throws InterruptedException
	 */
	public static void asyncExec(final Runnable runnable, final boolean waitForJobsToComplete) {
		final Queue<ComparisonFailure> failure = new ArrayBlockingQueue<>(1);
		final Queue<SWTException> swtException = new ArrayBlockingQueue<>(1);
		Display.getDefault().asyncExec(() -> {
			try {
				runnable.run();
			} catch (ComparisonFailure e1) {
				failure.add(e1);
			} catch (SWTException e2) {
				swtException.add(e2);
			}
		});
		if (waitForJobsToComplete) {
			waitForJobsToComplete();
		}
		if (!failure.isEmpty()) {
			throw failure.poll();
		}
		if (!swtException.isEmpty()) {
			throw swtException.poll();
		}
	}

	/**
	 * Waits for all {@link Job} to complete.
	 *
	 * @throws InterruptedException
	 */
	public static void waitForJobsToComplete() {
		wait(1, TimeUnit.SECONDS);
		while (!Job.getJobManager().isIdle()) {
			wait(1, TimeUnit.SECONDS);
		}
	}

	/**
	 * Waits for all {@link Job} to complete.
	 *
	 * @throws InterruptedException
	 */
	public static void waitForJobsToComplete(Object familly) {
		// while (Job.getJobManager().find(familly).length > 0) {
		// wait(1, TimeUnit.SECONDS);
		// }
		Conditions.waitForJobs(DockerExplorerView.class, "Docker Explorer View jobs");
	}

	/**
	 * @param viewBot
	 *            the {@link SWTBotView} containing the {@link Tree} to traverse
	 * @param paths
	 *            the node path in the {@link SWTBotTree} associated with the
	 *            given {@link SWTBotView}
	 * @return the first {@link SWTBotTreeItem} matching the given node names
	 */
	public static SWTBotTreeItem getTreeItem(final SWTBotView viewBot, final String... paths) {
		final SWTBotTree tree = viewBot.bot().tree();
		return getTreeItem(tree.getAllItems(), paths);
	}

	/**
	 *
	 * @param parentTreeItem
	 *            the parent tree item from which to start
	 * @param paths
	 *            the relative path to the item to return
	 * @return the {@link SWTBotTreeItem} that matches the given path from the
	 *         given parent tree item
	 */
	public static SWTBotTreeItem getTreeItem(final SWTBotTreeItem parentTreeItem, final String... paths) {
		if (paths.length == 1) {
			return getTreeItem(parentTreeItem, paths[0]);
		}
		final String[] remainingPaths = new String[paths.length - 1];
		System.arraycopy(paths, 1, remainingPaths, 0, paths.length - 1);
		return getTreeItem(getTreeItem(parentTreeItem, paths[0]), remainingPaths);
	}

	/**
	 * Returns the first child node in the given parent tree item whose text
	 * matches (ie, begins with) the given path argument.
	 *
	 * @param parentTree
	 *            the parent tree item
	 * @param path
	 *            the text of the node that should match
	 * @return the first matching node or <code>null</code> if none could be
	 *         found
	 */
	public static SWTBotTreeItem getTreeItem(final SWTBotTree parentTree, final String path) {
		for (SWTBotTreeItem child : parentTree.getAllItems()) {
			if (child.getText().startsWith(path)) {
				return child;
			}
		}
		return null;
	}

	/**
	 * Returns the first child node in the given parent tree item whose text
	 * matches (ie, begins with) the given path argument.
	 *
	 * @param parentTreeItem
	 *            the parent tree item
	 * @param path
	 *            the text of the node that should match
	 * @return the first matching node or <code>null</code> if none could be
	 *         found
	 */
	public static SWTBotTreeItem getTreeItem(final SWTBotTreeItem parentTreeItem, final String path) {
		for (SWTBotTreeItem child : parentTreeItem.getItems()) {
			if (child.getText().startsWith(path)) {
				return child;
			}
		}
		return null;
	}

	private static SWTBotTreeItem getTreeItem(final SWTBotTreeItem[] treeItems, final String[] paths) {
		final SWTBotTreeItem swtBotTreeItem = Stream.of(treeItems).filter(item -> item.getText().startsWith(paths[0]))
				.findFirst().orElseThrow(() -> new RuntimeException("Available items: "
						+ Stream.of(treeItems).map(item -> item.getText()).collect(Collectors.joining(", "))));
		if (paths.length > 1) {
			syncExec(() -> swtBotTreeItem.expand());
			final String[] remainingPath = new String[paths.length - 1];
			System.arraycopy(paths, 1, remainingPath, 0, remainingPath.length);
			return getTreeItem(swtBotTreeItem.getItems(), remainingPath);
		}
		return swtBotTreeItem;
	}

	/**
	 * Waits for the given duration
	 *
	 * @param duration
	 *            the duration
	 * @param unit
	 *            the duration unit
	 */
	public static void wait(final int duration, final TimeUnit unit) {
		try {
			Thread.sleep(unit.toMillis(duration));
		} catch (InterruptedException e) {
			fail("Failed to wait for a " + unit.toMillis(duration) + "ms", e);
		}
	}

	/**
	 * Selects <strong> all child items</strong> in the given
	 * <code>parentTreeItem</code> whose labels match the given
	 * <code>items</code>.
	 *
	 * @param parentTreeItem
	 *            the parent tree item
	 * @param matchItems
	 *            the items to select
	 * @return
	 */
	public static SWTBotTreeItem select(final SWTBotTreeItem parentTreeItem, final String... matchItems) {
		final List<String> fullyQualifiedItems = Stream.of(parentTreeItem.getItems()).filter(
				treeItem -> Stream.of(matchItems).anyMatch(matchItem -> treeItem.getText().startsWith(matchItem)))
				.map(item -> item.getText()).collect(Collectors.toList());
		return parentTreeItem.select(fullyQualifiedItems.toArray(new String[0]));
	}

	/**
	 * Selects the given <code>treeItem</code> whose labels match the given
	 * <code>items</code>.
	 *
	 * @param treeItem
	 *            the parent tree item
	 * @param matchItems
	 *            the items to select
	 */
	public static void select(SWTBotTreeItem treeItem) {
		treeItem.select();
	}

	/**
	 * @param tree
	 *            the root {@link SWTBotTree}
	 * @param path
	 *            the path for the menu
	 * @return the child {@link SWTBotMenu} named with the first item in the
	 *         given <code>path</code> from the given {@link SWTBotTree}
	 */
	public static SWTBotMenu getContextMenu(final SWTBotTree tree, String... path) {
		final SWTBotMenu contextMenu = tree.contextMenu(path[0]);
		if (contextMenu == null) {
			Assert.fail("Failed to find context menu '" + path[0] + "'.");
		}
		if (path.length == 1) {
			return contextMenu;
		}
		final String[] remainingPath = new String[path.length - 1];
		System.arraycopy(path, 1, remainingPath, 0, remainingPath.length);
		return getSubMenu(contextMenu, remainingPath);
	}

	/**
	 * Hides the menu for the given <code>tree</code>
	 *
	 * @param tree
	 *            the tree whose {@link Menu} should be hidden
	 */
	public static void hideMenu(final SWTBotTree tree) {
		final Menu menu = UIThreadRunnable.syncExec((Result<Menu>) () -> tree.widget.getMenu());
		UIThreadRunnable.syncExec(new VoidResult() {

			@Override
			public void run() {
				hide(menu);
			}

			private void hide(final Menu menu) {
				menu.notifyListeners(SWT.Hide, new Event());
				if (menu.getParentMenu() != null) {
					hide(menu.getParentMenu());
				}
			}
		});
	}

	/**
	 * @param menu
	 *            the parent menu
	 * @param path
	 *            the path for the menu
	 * @return the child {@link SWTBotMenu} named with the first item in the
	 *         given <code>path</code> from the given {@link SWTBotMenu}
	 */
	public static SWTBotMenu getSubMenu(final SWTBotMenu menu, String... path) {
		final SWTBotMenu subMenu = menu.menu(path[0]);
		if (subMenu == null) {
			Assert.fail("Failed to find submenu '" + path[0] + "'.");
		}
		if (path.length == 1) {
			return subMenu;
		}
		final String[] remainingPath = new String[path.length - 1];
		System.arraycopy(path, 1, remainingPath, 0, remainingPath.length);
		return getSubMenu(subMenu, remainingPath);
	}

	public static SWTBotTreeItem expand(final SWTBotTree tree, final String... paths) {
		final SWTBotTreeItem rootItem = getTreeItem(tree, paths[0]);
		expandTreeItem(rootItem);
		if (paths.length > 1) {
			final String[] remainingPath = new String[paths.length - 1];
			System.arraycopy(paths, 1, remainingPath, 0, remainingPath.length);
			return expand(rootItem, remainingPath);
		}
		return rootItem;
	}

	public static SWTBotTreeItem expand(final SWTBotTreeItem treeItem, final String... paths) {
		final SWTBotTreeItem childItem = getTreeItem(treeItem, paths[0]);
		expandTreeItem(childItem);
		if (paths.length > 1) {
			final String[] remainingPath = new String[paths.length - 1];
			System.arraycopy(paths, 1, remainingPath, 0, remainingPath.length);
			return expand(childItem, remainingPath);
		}
		return getTreeItem(treeItem, paths[0]);
	}

	private static SWTBotTreeItem expandTreeItem(final SWTBotTreeItem treeItem) {
		final UIJob expandJob = new UIJob("expanding tree") {

			@Override
			public IStatus runInUIThread(IProgressMonitor monitor) {
				treeItem.expand();
				return Status.OK_STATUS;
			}
		};
		expandJob.addJobChangeListener(new JobChangeAdapter() {
			@Override
			public void done(IJobChangeEvent event) {
				final int maxAttempts = 30;
				int currentAttempt = 0;
				while (currentAttempt < maxAttempts && treeItem.getItems().length == 1
						&& treeItem.getItems()[0].getText().isEmpty()) {
					SWTUtils.wait(1, TimeUnit.SECONDS);
					currentAttempt++;
				}

			}
		});
		expandJob.schedule();
		SWTUtils.wait(1, TimeUnit.SECONDS);
		return treeItem;
	}

	@SuppressWarnings("unchecked")
	public static SWTBotView getSWTBotView(final SWTWorkbenchBot bot, final String viewId) {
		return bot.views().stream().filter(v -> v.getViewReference().getId().equals(viewId)).findFirst().orElse(null);
	}

	@SuppressWarnings("unchecked")
	public static <T> T getView(final SWTWorkbenchBot bot, final String viewId) {
		return (T) bot.views().stream().filter(v -> v.getViewReference().getId().equals(viewId)).findFirst()
				.map(v -> v.getReference().getView(false)).orElse(null);
	}

	/**
	 * @return <code>true</code> if the Console view is visible in the active
	 *         page, <code>false</code> otherwise.
	 * @throws InterruptedException
	 */
	public static boolean isConsoleViewVisible(final SWTWorkbenchBot bot) {
		return SWTUtils.getView(bot, IConsoleConstants.ID_CONSOLE_VIEW) != null;
	}

	public static SWTBotToolbarButton getConsoleToolbarButtonWithTooltipText(final SWTWorkbenchBot bot, final String tooltipText) {
		return bot.viewById(IConsoleConstants.ID_CONSOLE_VIEW).getToolbarButtons().stream()
				.filter(button -> button.getToolTipText().equals(tooltipText)).findFirst().get();
	}

}

Back to the top