Fix main shell not active using Xvfb
[deliverable/tracecompass.git] / tmf / org.eclipse.tracecompass.tmf.ui.swtbot.tests / shared / org / eclipse / tracecompass / tmf / ui / swtbot / tests / shared / SWTBotUtils.java
1 /*******************************************************************************
2 * Copyright (c) 2014, 2015 Ericsson
3 *
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 *
9 * Contributors:
10 * Matthew Khouzam - Initial API and implementation
11 *******************************************************************************/
12
13 package org.eclipse.tracecompass.tmf.ui.swtbot.tests.shared;
14
15 import static org.junit.Assert.assertNotNull;
16 import static org.junit.Assert.assertTrue;
17 import static org.junit.Assert.fail;
18
19 import java.util.List;
20
21 import org.eclipse.core.resources.IProject;
22 import org.eclipse.core.resources.IResource;
23 import org.eclipse.core.resources.ResourcesPlugin;
24 import org.eclipse.core.runtime.CoreException;
25 import org.eclipse.core.runtime.IPath;
26 import org.eclipse.core.runtime.NullProgressMonitor;
27 import org.eclipse.core.runtime.jobs.Job;
28 import org.eclipse.jface.bindings.keys.IKeyLookup;
29 import org.eclipse.jface.bindings.keys.KeyStroke;
30 import org.eclipse.jface.bindings.keys.ParseException;
31 import org.eclipse.swt.graphics.Point;
32 import org.eclipse.swt.graphics.Rectangle;
33 import org.eclipse.swt.widgets.Display;
34 import org.eclipse.swt.widgets.Shell;
35 import org.eclipse.swt.widgets.Table;
36 import org.eclipse.swt.widgets.TableItem;
37 import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
38 import org.eclipse.swtbot.eclipse.finder.matchers.WidgetMatcherFactory;
39 import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor;
40 import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView;
41 import org.eclipse.swtbot.swt.finder.SWTBot;
42 import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable;
43 import org.eclipse.swtbot.swt.finder.results.Result;
44 import org.eclipse.swtbot.swt.finder.results.VoidResult;
45 import org.eclipse.swtbot.swt.finder.utils.SWTUtils;
46 import org.eclipse.swtbot.swt.finder.waits.Conditions;
47 import org.eclipse.swtbot.swt.finder.waits.DefaultCondition;
48 import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton;
49 import org.eclipse.swtbot.swt.finder.widgets.SWTBotCheckBox;
50 import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu;
51 import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
52 import org.eclipse.swtbot.swt.finder.widgets.SWTBotTable;
53 import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
54 import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
55 import org.eclipse.tracecompass.tmf.ui.editors.TmfEventsEditor;
56 import org.eclipse.tracecompass.tmf.ui.project.model.TmfOpenTraceHelper;
57 import org.eclipse.tracecompass.tmf.ui.project.model.TmfProjectRegistry;
58 import org.eclipse.tracecompass.tmf.ui.project.model.TmfTraceFolder;
59 import org.eclipse.tracecompass.tmf.ui.project.model.TmfTracesFolder;
60 import org.eclipse.tracecompass.tmf.ui.swtbot.tests.shared.ConditionHelpers.ProjectElementHasChild;
61 import org.eclipse.tracecompass.tmf.ui.views.TracingPerspectiveFactory;
62 import org.eclipse.ui.IEditorPart;
63 import org.eclipse.ui.IEditorReference;
64 import org.eclipse.ui.IPageLayout;
65 import org.eclipse.ui.PartInitException;
66 import org.eclipse.ui.PlatformUI;
67 import org.eclipse.ui.WorkbenchException;
68 import org.hamcrest.Matcher;
69
70 /**
71 * SWTBot Helper functions
72 *
73 * @author Matthew Khouzam
74 */
75 public final class SWTBotUtils {
76
77 private static final String WINDOW_MENU = "Window";
78 private static final String PREFERENCES_MENU_ITEM = "Preferences";
79
80 private SWTBotUtils() {
81 }
82
83 private static final String TRACING_PERSPECTIVE_ID = TracingPerspectiveFactory.ID;
84
85 /**
86 * Waits for all Eclipse jobs to finish
87 */
88 public static void waitForJobs() {
89 while (!Job.getJobManager().isIdle()) {
90 delay(100);
91 }
92 }
93
94 /**
95 * Sleeps current thread for a given time.
96 *
97 * @param waitTimeMillis
98 * time in milliseconds to wait
99 */
100 public static void delay(final long waitTimeMillis) {
101 try {
102 Thread.sleep(waitTimeMillis);
103 } catch (final InterruptedException e) {
104 // Ignored
105 }
106 }
107
108 /**
109 * Create a tracing project
110 *
111 * @param projectName
112 * the name of the tracing project
113 */
114 public static void createProject(final String projectName) {
115 /*
116 * Make a new test
117 */
118 UIThreadRunnable.syncExec(new VoidResult() {
119 @Override
120 public void run() {
121 IProject project = TmfProjectRegistry.createProject(projectName, null, new NullProgressMonitor());
122 assertNotNull(project);
123 }
124 });
125
126 SWTBotUtils.waitForJobs();
127 }
128
129 /**
130 * Deletes a project
131 *
132 * @param projectName
133 * the name of the tracing project
134 * @param deleteResources
135 * whether or not to deleted resources under the project
136 * @param bot
137 * the workbench bot
138 */
139 public static void deleteProject(final String projectName, boolean deleteResources, SWTWorkbenchBot bot) {
140 // Wait for any analysis to complete because it might create
141 // supplementary files
142 SWTBotUtils.waitForJobs();
143 try {
144 ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).refreshLocal(IResource.DEPTH_INFINITE, null);
145 } catch (CoreException e) {
146 }
147
148 SWTBotUtils.waitForJobs();
149
150 final SWTBotView projectViewBot = bot.viewById(IPageLayout.ID_PROJECT_EXPLORER);
151 projectViewBot.setFocus();
152
153 SWTBotTree treeBot = projectViewBot.bot().tree();
154 SWTBotTreeItem treeItem = treeBot.getTreeItem(projectName);
155 SWTBotMenu contextMenu = treeItem.contextMenu("Delete");
156 contextMenu.click();
157
158 if (deleteResources) {
159 bot.shell("Delete Resources").setFocus();
160 final SWTBotCheckBox checkBox = bot.checkBox();
161 bot.waitUntil(Conditions.widgetIsEnabled(checkBox));
162 checkBox.click();
163 }
164
165 final SWTBotButton okButton = bot.button("OK");
166 bot.waitUntil(Conditions.widgetIsEnabled(okButton));
167 okButton.click();
168
169 SWTBotUtils.waitForJobs();
170 }
171
172 /**
173 * Deletes a project and its resources
174 *
175 * @param projectName
176 * the name of the tracing project
177 * @param bot
178 * the workbench bot
179 */
180 public static void deleteProject(String projectName, SWTWorkbenchBot bot) {
181 deleteProject(projectName, true, bot);
182 }
183
184 /**
185 * Focus on the main window
186 *
187 * @param shellBots
188 * swtbotshells for all the shells
189 */
190 public static void focusMainWindow(SWTBotShell[] shellBots) {
191 for (SWTBotShell shellBot : shellBots) {
192 if (shellBot.getText().toLowerCase().contains("eclipse")) {
193 shellBot.activate();
194 }
195 }
196 }
197
198 /**
199 * Close a view with a title
200 *
201 * @param title
202 * the title, like "welcome"
203 * @param bot
204 * the workbench bot
205 */
206 public static void closeView(String title, SWTWorkbenchBot bot) {
207 final List<SWTBotView> openViews = bot.views();
208 for (SWTBotView view : openViews) {
209 if (view.getTitle().equalsIgnoreCase(title)) {
210 view.close();
211 bot.waitUntil(ConditionHelpers.ViewIsClosed(view));
212 }
213 }
214 }
215
216 /**
217 * Close a view with an id
218 *
219 * @param viewId
220 * the view id, like "org.eclipse.linuxtools.tmf.ui.views.histogram"
221 * @param bot
222 * the workbench bot
223 */
224 public static void closeViewById(String viewId, SWTWorkbenchBot bot) {
225 final SWTBotView view = bot.viewById(viewId);
226 view.close();
227 bot.waitUntil(ConditionHelpers.ViewIsClosed(view));
228 }
229
230 /**
231 * Switch to the tracing perspective
232 */
233 public static void switchToTracingPerspective() {
234 switchToPerspective(TRACING_PERSPECTIVE_ID);
235 }
236
237 /**
238 * Switch to a given perspective
239 *
240 * @param id
241 * the perspective id (like
242 * "org.eclipse.linuxtools.tmf.ui.perspective"
243 */
244 public static void switchToPerspective(final String id) {
245 UIThreadRunnable.syncExec(new VoidResult() {
246 @Override
247 public void run() {
248 try {
249 PlatformUI.getWorkbench().showPerspective(id, PlatformUI.getWorkbench().getActiveWorkbenchWindow());
250 } catch (WorkbenchException e) {
251 fail(e.getMessage());
252 }
253 }
254 });
255 }
256
257 /**
258 * Initialize the environment for SWTBot
259 */
260 public static void initialize() {
261 failIfUIThread();
262
263 SWTWorkbenchBot bot = new SWTWorkbenchBot();
264 UIThreadRunnable.syncExec(() -> {
265
266 // There seems to be problems on some system where the main shell is
267 // not in focus initially. This was seen using Xvfb and Xephyr on some occasions.
268 focusMainWindow(bot.shells());
269
270 Shell shell = bot.activeShell().widget;
271
272 // Only adjust shell if it appears to be the top-most
273 if (shell.getParent() == null) {
274 makeShellFullyVisible(shell);
275 }
276 });
277 }
278
279 /**
280 * If the test is running in the UI thread then fail
281 */
282 private static void failIfUIThread() {
283 if (Display.getCurrent() != null && Display.getCurrent().getThread() == Thread.currentThread()) {
284 fail("SWTBot test needs to run in a non-UI thread. Make sure that \"Run in UI thread\" is unchecked in your launch configuration or"
285 + " that useUIThread is set to false in the pom.xml");
286 }
287 }
288
289 /**
290 * Try to make the shell fully visible in the display. If the shell cannot
291 * fit the display, it will be positioned so that top-left corner is at
292 * <code>(0, 0)</code> in display-relative coordinates.
293 *
294 * @param shell
295 * the shell to make fully visible
296 */
297 private static void makeShellFullyVisible(Shell shell) {
298 Rectangle displayBounds = shell.getDisplay().getBounds();
299 Point absCoord = shell.toDisplay(0, 0);
300 Point shellSize = shell.getSize();
301
302 Point newLocation = new Point(absCoord.x, absCoord.y);
303 newLocation.x = Math.max(0, Math.min(absCoord.x, displayBounds.width - shellSize.x));
304 newLocation.y = Math.max(0, Math.min(absCoord.y, displayBounds.height - shellSize.y));
305 if (!newLocation.equals(absCoord)) {
306 shell.setLocation(newLocation);
307 }
308 }
309
310 /**
311 * Open a trace, this does not perform any validation though
312 *
313 * @param projectName
314 * The project name
315 * @param tracePath
316 * the path of the trace file (absolute or relative)
317 * @param traceType
318 * the trace type id (eg: org.eclipse.linuxtools.btf.trace)
319 */
320 public static void openTrace(final String projectName, final String tracePath, final String traceType) {
321 openTrace(projectName, tracePath, traceType, true);
322 }
323
324 /**
325 * Open a trace, this does not perform any validation though
326 *
327 * @param projectName
328 * The project name
329 * @param tracePath
330 * the path of the trace file (absolute or relative)
331 * @param traceType
332 * the trace type id (eg: org.eclipse.linuxtools.btf.trace)
333 * @param delay
334 * delay and wait for jobs
335 */
336 public static void openTrace(final String projectName, final String tracePath, final String traceType, boolean delay) {
337 final Exception exception[] = new Exception[1];
338 exception[0] = null;
339 UIThreadRunnable.syncExec(new VoidResult() {
340 @Override
341 public void run() {
342 try {
343 IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
344 TmfTraceFolder destinationFolder = TmfProjectRegistry.getProject(project, true).getTracesFolder();
345 TmfOpenTraceHelper.openTraceFromPath(destinationFolder, tracePath, PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), traceType);
346 } catch (CoreException e) {
347 exception[0] = e;
348 }
349 }
350 });
351 if (exception[0] != null) {
352 fail(exception[0].getMessage());
353 }
354
355 if (delay) {
356 delay(1000);
357 waitForJobs();
358 }
359 }
360
361 /**
362 * Finds an editor and sets focus to the editor
363 *
364 * @param bot
365 * the workbench bot
366 * @param editorName
367 * the editor name
368 * @return the corresponding SWTBotEditor
369 */
370 public static SWTBotEditor activateEditor(SWTWorkbenchBot bot, String editorName) {
371 Matcher<IEditorReference> matcher = WidgetMatcherFactory.withPartName(editorName);
372 final SWTBotEditor editorBot = bot.editor(matcher);
373 IEditorPart iep = editorBot.getReference().getEditor(true);
374 final TmfEventsEditor tmfEd = (TmfEventsEditor) iep;
375 editorBot.show();
376 UIThreadRunnable.syncExec(new VoidResult() {
377 @Override
378 public void run() {
379 tmfEd.setFocus();
380 }
381 });
382
383 SWTBotUtils.waitForJobs();
384 SWTBotUtils.delay(1000);
385 assertNotNull(tmfEd);
386 return editorBot;
387 }
388
389 /**
390 * Opens a trace in an editor and get the TmfEventsEditor
391 *
392 * @param bot
393 * the workbench bot
394 * @param projectName
395 * the name of the project that contains the trace
396 * @param elementPath
397 * the trace element path (relative to Traces folder)
398 * @return TmfEventsEditor the opened editor
399 */
400 public static TmfEventsEditor openEditor(SWTWorkbenchBot bot, String projectName, IPath elementPath) {
401 final SWTBotView projectExplorerView = bot.viewById(IPageLayout.ID_PROJECT_EXPLORER);
402 projectExplorerView.setFocus();
403 SWTBot projectExplorerBot = projectExplorerView.bot();
404
405 final SWTBotTree tree = projectExplorerBot.tree();
406 projectExplorerBot.waitUntil(ConditionHelpers.IsTreeNodeAvailable(projectName, tree));
407 final SWTBotTreeItem treeItem = tree.getTreeItem(projectName);
408 treeItem.expand();
409
410 SWTBotTreeItem tracesNode = getTraceProjectItem(projectExplorerBot, treeItem, TmfTracesFolder.TRACES_FOLDER_NAME);
411 tracesNode.expand();
412
413 SWTBotTreeItem currentItem = tracesNode;
414 for (String segment : elementPath.segments()) {
415 currentItem = getTraceProjectItem(projectExplorerBot, currentItem, segment);
416 currentItem.select();
417 currentItem.doubleClick();
418 }
419
420 SWTBotEditor editor = bot.editorByTitle(elementPath.toString());
421 IEditorPart editorPart = editor.getReference().getEditor(false);
422 assertTrue(editorPart instanceof TmfEventsEditor);
423 return (TmfEventsEditor) editorPart;
424 }
425
426 /**
427 * Returns the child tree item of the specified item with the given name.
428 * The project element label may have a count suffix in the format ' [n]'.
429 *
430 * @param bot
431 * a given workbench bot
432 * @param parentItem
433 * the parent tree item
434 * @param name
435 * the desired child element name (without suffix)
436 * @return the a {@link SWTBotTreeItem} with the specified name
437 */
438 public static SWTBotTreeItem getTraceProjectItem(SWTBot bot, final SWTBotTreeItem parentItem, final String name) {
439 ProjectElementHasChild condition = new ProjectElementHasChild(parentItem, name);
440 bot.waitUntil(condition);
441 return condition.getItem();
442 }
443
444 /**
445 * Select the traces folder
446 *
447 * @param bot
448 * a given workbench bot
449 * @param projectName
450 * the name of the project (it needs to exist or else it would
451 * time out)
452 * @return a {@link SWTBotTreeItem} of the "Traces" folder
453 */
454 public static SWTBotTreeItem selectTracesFolder(SWTWorkbenchBot bot, String projectName) {
455 SWTBotTreeItem projectTreeItem = selectProject(bot, projectName);
456 projectTreeItem.select();
457 SWTBotTreeItem tracesFolderItem = getTraceProjectItem(bot, projectTreeItem, TmfTracesFolder.TRACES_FOLDER_NAME);
458 tracesFolderItem.select();
459 return tracesFolderItem;
460 }
461
462 /**
463 * Select the project in Project Explorer
464 *
465 * @param bot
466 * a given workbench bot
467 * @param projectName
468 * the name of the project (it needs to exist or else it would time out)
469 * @return a {@link SWTBotTreeItem} of the project
470 */
471 public static SWTBotTreeItem selectProject(SWTWorkbenchBot bot, String projectName) {
472 SWTBotView projectExplorerBot = bot.viewByTitle("Project Explorer");
473 projectExplorerBot.show();
474 SWTBotTreeItem treeItem = projectExplorerBot.bot().tree().getTreeItem(projectName);
475 treeItem.select();
476 return treeItem;
477 }
478
479 /**
480 * Open a view by id.
481 *
482 * @param id
483 * view id.
484 */
485 public static void openView(final String id) {
486 final PartInitException res[] = new PartInitException[1];
487 UIThreadRunnable.syncExec(new VoidResult() {
488 @Override
489 public void run() {
490 try {
491 PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(id);
492 } catch (PartInitException e) {
493 res[0] = e;
494 }
495 }
496 });
497 if (res[0] != null) {
498 fail(res[0].getMessage());
499 }
500 waitForJobs();
501 }
502
503 /**
504 * Maximize a table
505 *
506 * @param tableBot
507 * the {@link SWTBotTable} table
508 */
509 public static void maximizeTable(SWTBotTable tableBot) {
510 try {
511 tableBot.pressShortcut(KeyStroke.getInstance(IKeyLookup.CTRL_NAME + "+"), KeyStroke.getInstance("M"));
512 } catch (ParseException e) {
513 fail();
514 }
515 }
516
517 /**
518 * Get the bounds of a cell (SWT.Rectangle) for the specified row and column
519 * index in a table
520 *
521 * @param table
522 * the table
523 * @param row
524 * the row of the table to look up
525 * @param col
526 * the column of the table to look up
527 * @return the bounds in display relative coordinates
528 */
529 public static Rectangle getCellBounds(final Table table, final int row, final int col) {
530 return UIThreadRunnable.syncExec(new Result<Rectangle>() {
531 @Override
532 public Rectangle run() {
533 TableItem item = table.getItem(row);
534 Rectangle bounds = item.getBounds(col);
535 Point p = table.toDisplay(bounds.x, bounds.y);
536 Rectangle rect = new Rectangle(p.x, p.y, bounds.width, bounds.height);
537 return rect;
538 }
539 });
540 }
541
542 /**
543 * Get the tree item from a tree at the specified location
544 *
545 * @param bot
546 * the SWTBot
547 * @param tree
548 * the tree to find the tree item in
549 * @param nodeNames
550 * the path to the tree item, in the form of node names (from
551 * parent to child).
552 * @return the tree item
553 */
554 public static SWTBotTreeItem getTreeItem(SWTBot bot, SWTBotTree tree, String... nodeNames) {
555 if (nodeNames.length == 0) {
556 return null;
557 }
558
559 bot.waitUntil(ConditionHelpers.IsTreeNodeAvailable(nodeNames[0], tree));
560 SWTBotTreeItem currentNode = tree.getTreeItem(nodeNames[0]);
561 for (int i = 1; i < nodeNames.length; i++) {
562 currentNode.expand();
563
564 String nodeName = nodeNames[i];
565 bot.waitUntil(ConditionHelpers.IsTreeChildNodeAvailable(nodeName, currentNode));
566 SWTBotTreeItem newNode = currentNode.getNode(nodeName);
567 currentNode = newNode;
568 }
569
570 return currentNode;
571 }
572
573 /**
574 * Get the active events editor. Note that this will wait until such editor
575 * is available.
576 *
577 * @param workbenchBot
578 * a given workbench bot
579 * @return the active events editor
580 */
581 public static SWTBotEditor activeEventsEditor(final SWTWorkbenchBot workbenchBot) {
582 final SWTBotEditor editor[] = new SWTBotEditor[1];
583 workbenchBot.waitUntil(new DefaultCondition() {
584 @Override
585 public boolean test() throws Exception {
586 List<SWTBotEditor> editors = workbenchBot.editors(WidgetMatcherFactory.withPartId(TmfEventsEditor.ID));
587 for (SWTBotEditor e : editors) {
588 if (e.isActive() && !e.getWidget().isDisposed()) {
589 editor[0] = e;
590 return true;
591 }
592 }
593 return false;
594 }
595
596 @Override
597 public String getFailureMessage() {
598 return "Active events editor not found";
599 }
600 });
601 return editor[0];
602 }
603
604 /**
605 * Open the preferences dialog and return the corresponding shell.
606 *
607 * @param bot
608 * a given workbench bot
609 * @return the preferences shell
610 */
611 public static SWTBotShell openPreferences(SWTBot bot) {
612 if (SWTUtils.isMac()) {
613 // On Mac, the Preferences menu item is under the application name.
614 // For some reason, we can't access the application menu anymore so
615 // we use the keyboard shortcut.
616 try {
617 bot.activeShell().pressShortcut(KeyStroke.getInstance(IKeyLookup.COMMAND_NAME + "+"), KeyStroke.getInstance(","));
618 } catch (ParseException e) {
619 fail();
620 }
621 } else {
622 bot.menu(WINDOW_MENU).menu(PREFERENCES_MENU_ITEM).click();
623 }
624
625 bot.waitUntil(Conditions.shellIsActive(PREFERENCES_MENU_ITEM));
626 return bot.activeShell();
627 }
628 }
This page took 0.084438 seconds and 6 git commands to generate.