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