1 /*******************************************************************************
2 * Copyright (c) 2014, 2015 Ericsson
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
10 * Matthew Khouzam - Initial API and implementation
11 *******************************************************************************/
13 package org
.eclipse
.tracecompass
.tmf
.ui
.swtbot
.tests
.shared
;
15 import static org
.junit
.Assert
.assertNotNull
;
16 import static org
.junit
.Assert
.assertTrue
;
17 import static org
.junit
.Assert
.fail
;
19 import java
.util
.List
;
20 import java
.util
.TimeZone
;
22 import org
.eclipse
.core
.resources
.IFolder
;
23 import org
.eclipse
.core
.resources
.IProject
;
24 import org
.eclipse
.core
.resources
.IResource
;
25 import org
.eclipse
.core
.resources
.IResourceVisitor
;
26 import org
.eclipse
.core
.resources
.ResourcesPlugin
;
27 import org
.eclipse
.core
.runtime
.CoreException
;
28 import org
.eclipse
.core
.runtime
.IPath
;
29 import org
.eclipse
.core
.runtime
.NullProgressMonitor
;
30 import org
.eclipse
.core
.runtime
.jobs
.Job
;
31 import org
.eclipse
.jface
.bindings
.keys
.IKeyLookup
;
32 import org
.eclipse
.jface
.bindings
.keys
.KeyStroke
;
33 import org
.eclipse
.jface
.bindings
.keys
.ParseException
;
34 import org
.eclipse
.swt
.graphics
.Point
;
35 import org
.eclipse
.swt
.graphics
.Rectangle
;
36 import org
.eclipse
.swt
.widgets
.Display
;
37 import org
.eclipse
.swt
.widgets
.Shell
;
38 import org
.eclipse
.swt
.widgets
.Table
;
39 import org
.eclipse
.swt
.widgets
.TableItem
;
40 import org
.eclipse
.swtbot
.eclipse
.finder
.SWTWorkbenchBot
;
41 import org
.eclipse
.swtbot
.eclipse
.finder
.matchers
.WidgetMatcherFactory
;
42 import org
.eclipse
.swtbot
.eclipse
.finder
.widgets
.SWTBotEditor
;
43 import org
.eclipse
.swtbot
.eclipse
.finder
.widgets
.SWTBotView
;
44 import org
.eclipse
.swtbot
.swt
.finder
.SWTBot
;
45 import org
.eclipse
.swtbot
.swt
.finder
.finders
.UIThreadRunnable
;
46 import org
.eclipse
.swtbot
.swt
.finder
.results
.Result
;
47 import org
.eclipse
.swtbot
.swt
.finder
.results
.VoidResult
;
48 import org
.eclipse
.swtbot
.swt
.finder
.utils
.SWTUtils
;
49 import org
.eclipse
.swtbot
.swt
.finder
.waits
.Conditions
;
50 import org
.eclipse
.swtbot
.swt
.finder
.waits
.DefaultCondition
;
51 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotButton
;
52 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotCheckBox
;
53 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotMenu
;
54 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotShell
;
55 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotTable
;
56 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotTree
;
57 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotTreeItem
;
58 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.TimeoutException
;
59 import org
.eclipse
.tracecompass
.tmf
.ui
.editors
.TmfEventsEditor
;
60 import org
.eclipse
.tracecompass
.tmf
.ui
.project
.model
.TmfOpenTraceHelper
;
61 import org
.eclipse
.tracecompass
.tmf
.ui
.project
.model
.TmfProjectElement
;
62 import org
.eclipse
.tracecompass
.tmf
.ui
.project
.model
.TmfProjectRegistry
;
63 import org
.eclipse
.tracecompass
.tmf
.ui
.project
.model
.TmfTraceElement
;
64 import org
.eclipse
.tracecompass
.tmf
.ui
.project
.model
.TmfTraceFolder
;
65 import org
.eclipse
.tracecompass
.tmf
.ui
.project
.model
.TmfTracesFolder
;
66 import org
.eclipse
.tracecompass
.tmf
.ui
.swtbot
.tests
.shared
.ConditionHelpers
.ProjectElementHasChild
;
67 import org
.eclipse
.tracecompass
.tmf
.ui
.views
.TracingPerspectiveFactory
;
68 import org
.eclipse
.ui
.IEditorPart
;
69 import org
.eclipse
.ui
.IEditorReference
;
70 import org
.eclipse
.ui
.IPageLayout
;
71 import org
.eclipse
.ui
.PartInitException
;
72 import org
.eclipse
.ui
.PlatformUI
;
73 import org
.eclipse
.ui
.WorkbenchException
;
74 import org
.hamcrest
.Matcher
;
77 * SWTBot Helper functions
79 * @author Matthew Khouzam
81 public final class SWTBotUtils
{
83 private static final String WINDOW_MENU
= "Window";
84 private static final String PREFERENCES_MENU_ITEM
= "Preferences";
85 private static boolean fPrintedEnvironment
= false;
87 private SWTBotUtils() {
90 private static final String TRACING_PERSPECTIVE_ID
= TracingPerspectiveFactory
.ID
;
93 * Waits for all Eclipse jobs to finish
95 public static void waitForJobs() {
96 while (!Job
.getJobManager().isIdle()) {
102 * Sleeps current thread for a given time.
104 * @param waitTimeMillis
105 * time in milliseconds to wait
107 public static void delay(final long waitTimeMillis
) {
109 Thread
.sleep(waitTimeMillis
);
110 } catch (final InterruptedException e
) {
116 * Create a tracing project
119 * the name of the tracing project
121 public static void createProject(final String projectName
) {
125 UIThreadRunnable
.syncExec(new VoidResult() {
128 IProject project
= TmfProjectRegistry
.createProject(projectName
, null, new NullProgressMonitor());
129 assertNotNull(project
);
133 SWTBotUtils
.waitForJobs();
140 * the name of the tracing project
141 * @param deleteResources
142 * whether or not to deleted resources under the project
146 public static void deleteProject(final String projectName
, boolean deleteResources
, SWTWorkbenchBot bot
) {
147 // Wait for any analysis to complete because it might create
148 // supplementary files
149 SWTBotUtils
.waitForJobs();
151 ResourcesPlugin
.getWorkspace().getRoot().getProject(projectName
).refreshLocal(IResource
.DEPTH_INFINITE
, null);
152 } catch (CoreException e
) {
155 SWTBotUtils
.waitForJobs();
157 final SWTBotView projectViewBot
= bot
.viewById(IPageLayout
.ID_PROJECT_EXPLORER
);
158 projectViewBot
.setFocus();
160 SWTBotTree treeBot
= projectViewBot
.bot().tree();
161 SWTBotTreeItem treeItem
= treeBot
.getTreeItem(projectName
);
162 SWTBotMenu contextMenu
= treeItem
.contextMenu("Delete");
165 if (deleteResources
) {
166 bot
.shell("Delete Resources").setFocus();
167 final SWTBotCheckBox checkBox
= bot
.checkBox();
168 bot
.waitUntil(Conditions
.widgetIsEnabled(checkBox
));
172 final SWTBotButton okButton
= bot
.button("OK");
173 bot
.waitUntil(Conditions
.widgetIsEnabled(okButton
));
176 SWTBotUtils
.waitForJobs();
180 * Deletes a project and its resources
183 * the name of the tracing project
187 public static void deleteProject(String projectName
, SWTWorkbenchBot bot
) {
188 deleteProject(projectName
, true, bot
);
192 * Focus on the main window
195 * swtbotshells for all the shells
197 public static void focusMainWindow(SWTBotShell
[] shellBots
) {
198 for (SWTBotShell shellBot
: shellBots
) {
199 if (shellBot
.getText().toLowerCase().contains("eclipse")) {
206 * Close a view with a title
209 * the title, like "welcome"
213 public static void closeView(String title
, SWTWorkbenchBot bot
) {
214 final List
<SWTBotView
> openViews
= bot
.views();
215 for (SWTBotView view
: openViews
) {
216 if (view
.getTitle().equalsIgnoreCase(title
)) {
218 bot
.waitUntil(ConditionHelpers
.ViewIsClosed(view
));
224 * Close a view with an id
227 * the view id, like "org.eclipse.linuxtools.tmf.ui.views.histogram"
231 public static void closeViewById(String viewId
, SWTWorkbenchBot bot
) {
232 final SWTBotView view
= bot
.viewById(viewId
);
234 bot
.waitUntil(ConditionHelpers
.ViewIsClosed(view
));
238 * Switch to the tracing perspective
240 public static void switchToTracingPerspective() {
241 switchToPerspective(TRACING_PERSPECTIVE_ID
);
245 * Switch to a given perspective
248 * the perspective id (like
249 * "org.eclipse.linuxtools.tmf.ui.perspective"
251 public static void switchToPerspective(final String id
) {
252 UIThreadRunnable
.syncExec(new VoidResult() {
256 PlatformUI
.getWorkbench().showPerspective(id
, PlatformUI
.getWorkbench().getActiveWorkbenchWindow());
257 } catch (WorkbenchException e
) {
258 fail(e
.getMessage());
265 * Initialize the environment for SWTBot
267 public static void initialize() {
270 SWTWorkbenchBot bot
= new SWTWorkbenchBot();
271 UIThreadRunnable
.syncExec(() -> {
274 // There seems to be problems on some system where the main shell is
275 // not in focus initially. This was seen using Xvfb and Xephyr on some occasions.
276 focusMainWindow(bot
.shells());
278 Shell shell
= bot
.activeShell().widget
;
280 // Only adjust shell if it appears to be the top-most
281 if (shell
.getParent() == null) {
282 makeShellFullyVisible(shell
);
287 private static void printEnvironment() {
288 if (fPrintedEnvironment
) {
292 // Print some information about the environment that could affect test outcome
293 Rectangle bounds
= Display
.getDefault().getBounds();
294 System
.out
.println("Display size: " + bounds
.width
+ "x" + bounds
.height
);
296 String osVersion
= System
.getProperty("os.version");
297 if (osVersion
!= null) {
298 System
.out
.println("OS version=" + osVersion
);
300 String gtkVersion
= System
.getProperty("org.eclipse.swt.internal.gtk.version");
301 if (gtkVersion
!= null) {
302 System
.out
.println("GTK version=" + gtkVersion
);
303 String overlayScrollbar
= System
.getenv("LIBOVERLAY_SCROLLBAR");
304 if (overlayScrollbar
!= null) {
305 System
.out
.println("LIBOVERLAY_SCROLLBAR=" + overlayScrollbar
);
307 String ubuntuMenuProxy
= System
.getenv("UBUNTU_MENUPROXY");
308 if (ubuntuMenuProxy
!= null) {
309 System
.out
.println("UBUNTU_MENUPROXY=" + ubuntuMenuProxy
);
313 System
.out
.println("Time zone: " + TimeZone
.getDefault().getDisplayName());
315 fPrintedEnvironment
= true;
319 * If the test is running in the UI thread then fail
321 private static void failIfUIThread() {
322 if (Display
.getCurrent() != null && Display
.getCurrent().getThread() == Thread
.currentThread()) {
323 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"
324 + " that useUIThread is set to false in the pom.xml");
329 * Try to make the shell fully visible in the display. If the shell cannot
330 * fit the display, it will be positioned so that top-left corner is at
331 * <code>(0, 0)</code> in display-relative coordinates.
334 * the shell to make fully visible
336 private static void makeShellFullyVisible(Shell shell
) {
337 Rectangle displayBounds
= shell
.getDisplay().getBounds();
338 Point absCoord
= shell
.toDisplay(0, 0);
339 Point shellSize
= shell
.getSize();
341 Point newLocation
= new Point(absCoord
.x
, absCoord
.y
);
342 newLocation
.x
= Math
.max(0, Math
.min(absCoord
.x
, displayBounds
.width
- shellSize
.x
));
343 newLocation
.y
= Math
.max(0, Math
.min(absCoord
.y
, displayBounds
.height
- shellSize
.y
));
344 if (!newLocation
.equals(absCoord
)) {
345 shell
.setLocation(newLocation
);
350 * Open a trace, this does not perform any validation though
355 * the path of the trace file (absolute or relative)
357 * the trace type id (eg: org.eclipse.linuxtools.btf.trace)
359 public static void openTrace(final String projectName
, final String tracePath
, final String traceType
) {
360 openTrace(projectName
, tracePath
, traceType
, true);
364 * Open a trace, this does not perform any validation though
369 * the path of the trace file (absolute or relative)
371 * the trace type id (eg: org.eclipse.linuxtools.btf.trace)
373 * delay and wait for jobs
375 public static void openTrace(final String projectName
, final String tracePath
, final String traceType
, boolean delay
) {
376 final Exception exception
[] = new Exception
[1];
378 UIThreadRunnable
.syncExec(new VoidResult() {
382 IProject project
= ResourcesPlugin
.getWorkspace().getRoot().getProject(projectName
);
383 TmfTraceFolder destinationFolder
= TmfProjectRegistry
.getProject(project
, true).getTracesFolder();
384 TmfOpenTraceHelper
.openTraceFromPath(destinationFolder
, tracePath
, PlatformUI
.getWorkbench().getActiveWorkbenchWindow().getShell(), traceType
);
385 } catch (CoreException e
) {
390 if (exception
[0] != null) {
391 fail(exception
[0].getMessage());
401 * Finds an editor and sets focus to the editor
407 * @return the corresponding SWTBotEditor
409 public static SWTBotEditor
activateEditor(SWTWorkbenchBot bot
, String editorName
) {
410 Matcher
<IEditorReference
> matcher
= WidgetMatcherFactory
.withPartName(editorName
);
411 final SWTBotEditor editorBot
= bot
.editor(matcher
);
412 IEditorPart iep
= editorBot
.getReference().getEditor(true);
413 final TmfEventsEditor tmfEd
= (TmfEventsEditor
) iep
;
415 UIThreadRunnable
.syncExec(new VoidResult() {
422 SWTBotUtils
.waitForJobs();
423 SWTBotUtils
.delay(1000);
424 assertNotNull(tmfEd
);
429 * Opens a trace in an editor and get the TmfEventsEditor
434 * the name of the project that contains the trace
436 * the trace element path (relative to Traces folder)
437 * @return TmfEventsEditor the opened editor
439 public static TmfEventsEditor
openEditor(SWTWorkbenchBot bot
, String projectName
, IPath elementPath
) {
440 final SWTBotView projectExplorerView
= bot
.viewById(IPageLayout
.ID_PROJECT_EXPLORER
);
441 projectExplorerView
.setFocus();
442 SWTBot projectExplorerBot
= projectExplorerView
.bot();
444 final SWTBotTree tree
= projectExplorerBot
.tree();
445 projectExplorerBot
.waitUntil(ConditionHelpers
.IsTreeNodeAvailable(projectName
, tree
));
446 final SWTBotTreeItem treeItem
= tree
.getTreeItem(projectName
);
449 SWTBotTreeItem tracesNode
= getTraceProjectItem(projectExplorerBot
, treeItem
, TmfTracesFolder
.TRACES_FOLDER_NAME
);
452 SWTBotTreeItem currentItem
= tracesNode
;
453 for (String segment
: elementPath
.segments()) {
454 currentItem
= getTraceProjectItem(projectExplorerBot
, currentItem
, segment
);
455 currentItem
.select();
456 currentItem
.doubleClick();
459 SWTBotEditor editor
= bot
.editorByTitle(elementPath
.toString());
460 IEditorPart editorPart
= editor
.getReference().getEditor(false);
461 assertTrue(editorPart
instanceof TmfEventsEditor
);
462 return (TmfEventsEditor
) editorPart
;
466 * Returns the child tree item of the specified item with the given name.
467 * The project element label may have a count suffix in the format ' [n]'.
470 * a given workbench bot
472 * the parent tree item
474 * the desired child element name (without suffix)
475 * @return the a {@link SWTBotTreeItem} with the specified name
477 public static SWTBotTreeItem
getTraceProjectItem(SWTBot bot
, final SWTBotTreeItem parentItem
, final String name
) {
478 ProjectElementHasChild condition
= new ProjectElementHasChild(parentItem
, name
);
479 bot
.waitUntil(condition
);
480 return condition
.getItem();
484 * Select the traces folder
487 * a given workbench bot
489 * the name of the project (it needs to exist or else it would
491 * @return a {@link SWTBotTreeItem} of the "Traces" folder
493 public static SWTBotTreeItem
selectTracesFolder(SWTWorkbenchBot bot
, String projectName
) {
494 SWTBotTreeItem projectTreeItem
= selectProject(bot
, projectName
);
495 projectTreeItem
.select();
496 SWTBotTreeItem tracesFolderItem
= getTraceProjectItem(bot
, projectTreeItem
, TmfTracesFolder
.TRACES_FOLDER_NAME
);
497 tracesFolderItem
.select();
498 return tracesFolderItem
;
502 * Clear the traces folder
505 * a given workbench bot
507 * the name of the project (needs to exist)
509 public static void clearTracesFolder(SWTWorkbenchBot bot
, String projectName
) {
510 IProject project
= ResourcesPlugin
.getWorkspace().getRoot().getProject(projectName
);
511 TmfProjectElement tmfProject
= TmfProjectRegistry
.getProject(project
, false);
512 TmfTraceFolder tracesFolder
= tmfProject
.getTracesFolder();
514 for (TmfTraceElement traceElement
: tracesFolder
.getTraces()) {
515 traceElement
.delete(null);
518 final IFolder resource
= tracesFolder
.getResource();
519 resource
.accept(new IResourceVisitor() {
521 public boolean visit(IResource visitedResource
) throws CoreException
{
522 if (visitedResource
!= resource
) {
523 visitedResource
.delete(true, null);
527 }, IResource
.DEPTH_ONE
, 0);
528 } catch (CoreException e
) {
529 fail(e
.getMessage());
532 bot
.waitUntil(new DefaultCondition() {
533 private int fTraceNb
= 0;
536 public boolean test() throws Exception
{
537 List
<TmfTraceElement
> traces
= tracesFolder
.getTraces();
538 fTraceNb
= traces
.size();
539 return fTraceNb
== 0;
543 public String
getFailureMessage() {
544 return "Traces Folder not empty (" + fTraceNb
+ ")";
551 * Select the project in Project Explorer
554 * a given workbench bot
556 * the name of the project (it needs to exist or else it would time out)
557 * @return a {@link SWTBotTreeItem} of the project
559 public static SWTBotTreeItem
selectProject(SWTWorkbenchBot bot
, String projectName
) {
560 SWTBotView projectExplorerBot
= bot
.viewByTitle("Project Explorer");
561 projectExplorerBot
.show();
562 SWTBotTreeItem treeItem
= projectExplorerBot
.bot().tree().getTreeItem(projectName
);
573 public static void openView(final String id
) {
574 final PartInitException res
[] = new PartInitException
[1];
575 UIThreadRunnable
.syncExec(new VoidResult() {
579 PlatformUI
.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(id
);
580 } catch (PartInitException e
) {
585 if (res
[0] != null) {
586 fail(res
[0].getMessage());
595 * the {@link SWTBotTable} table
597 public static void maximizeTable(SWTBotTable tableBot
) {
599 tableBot
.pressShortcut(KeyStroke
.getInstance(IKeyLookup
.CTRL_NAME
+ "+"), KeyStroke
.getInstance("M"));
600 } catch (ParseException e
) {
606 * Get the bounds of a cell (SWT.Rectangle) for the specified row and column
612 * the row of the table to look up
614 * the column of the table to look up
615 * @return the bounds in display relative coordinates
617 public static Rectangle
getCellBounds(final Table table
, final int row
, final int col
) {
618 return UIThreadRunnable
.syncExec(new Result
<Rectangle
>() {
620 public Rectangle
run() {
621 TableItem item
= table
.getItem(row
);
622 Rectangle bounds
= item
.getBounds(col
);
623 Point p
= table
.toDisplay(bounds
.x
, bounds
.y
);
624 Rectangle rect
= new Rectangle(p
.x
, p
.y
, bounds
.width
, bounds
.height
);
631 * Get the tree item from a tree at the specified location
636 * the tree to find the tree item in
638 * the path to the tree item, in the form of node names (from
640 * @return the tree item
642 public static SWTBotTreeItem
getTreeItem(SWTBot bot
, SWTBotTree tree
, String
... nodeNames
) {
643 if (nodeNames
.length
== 0) {
647 bot
.waitUntil(ConditionHelpers
.IsTreeNodeAvailable(nodeNames
[0], tree
));
648 SWTBotTreeItem currentNode
= tree
.getTreeItem(nodeNames
[0]);
649 for (int i
= 1; i
< nodeNames
.length
; i
++) {
650 currentNode
.expand();
652 String nodeName
= nodeNames
[i
];
654 bot
.waitUntil(ConditionHelpers
.IsTreeChildNodeAvailable(nodeName
, currentNode
));
655 } catch (TimeoutException e
) {
656 //FIXME: Sometimes in a JFace TreeViewer, it expands to nothing. Need to find out why.
657 currentNode
.collapse();
658 currentNode
.expand();
659 bot
.waitUntil(ConditionHelpers
.IsTreeChildNodeAvailable(nodeName
, currentNode
));
662 SWTBotTreeItem newNode
= currentNode
.getNode(nodeName
);
663 currentNode
= newNode
;
670 * Get the active events editor. Note that this will wait until such editor
673 * @param workbenchBot
674 * a given workbench bot
675 * @return the active events editor
677 public static SWTBotEditor
activeEventsEditor(final SWTWorkbenchBot workbenchBot
) {
678 final SWTBotEditor editor
[] = new SWTBotEditor
[1];
679 workbenchBot
.waitUntil(new DefaultCondition() {
681 public boolean test() throws Exception
{
682 List
<SWTBotEditor
> editors
= workbenchBot
.editors(WidgetMatcherFactory
.withPartId(TmfEventsEditor
.ID
));
683 for (SWTBotEditor e
: editors
) {
684 if (e
.isActive() && !e
.getWidget().isDisposed()) {
693 public String
getFailureMessage() {
694 return "Active events editor not found";
701 * Open the preferences dialog and return the corresponding shell.
704 * a given workbench bot
705 * @return the preferences shell
707 public static SWTBotShell
openPreferences(SWTBot bot
) {
708 if (SWTUtils
.isMac()) {
709 // On Mac, the Preferences menu item is under the application name.
710 // For some reason, we can't access the application menu anymore so
711 // we use the keyboard shortcut.
713 bot
.activeShell().pressShortcut(KeyStroke
.getInstance(IKeyLookup
.COMMAND_NAME
+ "+"), KeyStroke
.getInstance(","));
714 } catch (ParseException e
) {
718 bot
.menu(WINDOW_MENU
).menu(PREFERENCES_MENU_ITEM
).click();
721 bot
.waitUntil(Conditions
.shellIsActive(PREFERENCES_MENU_ITEM
));
722 return bot
.activeShell();