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
.eclipse
.swtbot
.swt
.finder
.matchers
.WidgetMatcherFactory
.withMnemonic
;
16 import static org
.eclipse
.tracecompass
.common
.core
.NonNullUtils
.checkNotNull
;
17 import static org
.junit
.Assert
.assertNotNull
;
18 import static org
.junit
.Assert
.assertTrue
;
19 import static org
.junit
.Assert
.fail
;
21 import java
.util
.Arrays
;
22 import java
.util
.List
;
23 import java
.util
.TimeZone
;
24 import java
.util
.concurrent
.atomic
.AtomicBoolean
;
25 import java
.util
.concurrent
.atomic
.AtomicInteger
;
27 import org
.apache
.log4j
.Logger
;
28 import org
.eclipse
.core
.commands
.ExecutionException
;
29 import org
.eclipse
.core
.commands
.NotEnabledException
;
30 import org
.eclipse
.core
.commands
.NotHandledException
;
31 import org
.eclipse
.core
.commands
.common
.NotDefinedException
;
32 import org
.eclipse
.core
.resources
.IFolder
;
33 import org
.eclipse
.core
.resources
.IProject
;
34 import org
.eclipse
.core
.resources
.IResource
;
35 import org
.eclipse
.core
.resources
.IResourceVisitor
;
36 import org
.eclipse
.core
.resources
.ResourcesPlugin
;
37 import org
.eclipse
.core
.runtime
.CoreException
;
38 import org
.eclipse
.core
.runtime
.IPath
;
39 import org
.eclipse
.core
.runtime
.IStatus
;
40 import org
.eclipse
.core
.runtime
.NullProgressMonitor
;
41 import org
.eclipse
.core
.runtime
.Status
;
42 import org
.eclipse
.jdt
.annotation
.NonNull
;
43 import org
.eclipse
.jdt
.annotation
.Nullable
;
44 import org
.eclipse
.jface
.bindings
.keys
.IKeyLookup
;
45 import org
.eclipse
.jface
.bindings
.keys
.KeyStroke
;
46 import org
.eclipse
.jface
.bindings
.keys
.ParseException
;
47 import org
.eclipse
.jface
.dialogs
.MessageDialogWithToggle
;
48 import org
.eclipse
.jface
.preference
.IPreferenceStore
;
49 import org
.eclipse
.swt
.events
.ControlAdapter
;
50 import org
.eclipse
.swt
.events
.ControlEvent
;
51 import org
.eclipse
.swt
.events
.KeyEvent
;
52 import org
.eclipse
.swt
.events
.KeyListener
;
53 import org
.eclipse
.swt
.graphics
.Point
;
54 import org
.eclipse
.swt
.graphics
.Rectangle
;
55 import org
.eclipse
.swt
.widgets
.Control
;
56 import org
.eclipse
.swt
.widgets
.Display
;
57 import org
.eclipse
.swt
.widgets
.Shell
;
58 import org
.eclipse
.swt
.widgets
.Table
;
59 import org
.eclipse
.swt
.widgets
.TableItem
;
60 import org
.eclipse
.swt
.widgets
.TreeItem
;
61 import org
.eclipse
.swtbot
.eclipse
.finder
.SWTWorkbenchBot
;
62 import org
.eclipse
.swtbot
.eclipse
.finder
.matchers
.WidgetMatcherFactory
;
63 import org
.eclipse
.swtbot
.eclipse
.finder
.widgets
.SWTBotEditor
;
64 import org
.eclipse
.swtbot
.eclipse
.finder
.widgets
.SWTBotView
;
65 import org
.eclipse
.swtbot
.swt
.finder
.SWTBot
;
66 import org
.eclipse
.swtbot
.swt
.finder
.finders
.UIThreadRunnable
;
67 import org
.eclipse
.swtbot
.swt
.finder
.keyboard
.Keyboard
;
68 import org
.eclipse
.swtbot
.swt
.finder
.keyboard
.Keystrokes
;
69 import org
.eclipse
.swtbot
.swt
.finder
.results
.IntResult
;
70 import org
.eclipse
.swtbot
.swt
.finder
.results
.Result
;
71 import org
.eclipse
.swtbot
.swt
.finder
.results
.VoidResult
;
72 import org
.eclipse
.swtbot
.swt
.finder
.utils
.MessageFormat
;
73 import org
.eclipse
.swtbot
.swt
.finder
.utils
.SWTUtils
;
74 import org
.eclipse
.swtbot
.swt
.finder
.waits
.Conditions
;
75 import org
.eclipse
.swtbot
.swt
.finder
.waits
.DefaultCondition
;
76 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.AbstractSWTBot
;
77 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.AbstractSWTBotControl
;
78 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotButton
;
79 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotCheckBox
;
80 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotMenu
;
81 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotShell
;
82 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotTable
;
83 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotToolbarButton
;
84 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotTree
;
85 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.SWTBotTreeItem
;
86 import org
.eclipse
.swtbot
.swt
.finder
.widgets
.TimeoutException
;
87 import org
.eclipse
.tracecompass
.internal
.tmf
.ui
.Activator
;
88 import org
.eclipse
.tracecompass
.internal
.tmf
.ui
.ITmfUIPreferences
;
89 import org
.eclipse
.tracecompass
.internal
.tmf
.ui
.project
.operations
.NewExperimentOperation
;
90 import org
.eclipse
.tracecompass
.tmf
.ui
.editors
.TmfEventsEditor
;
91 import org
.eclipse
.tracecompass
.tmf
.ui
.project
.model
.TmfExperimentElement
;
92 import org
.eclipse
.tracecompass
.tmf
.ui
.project
.model
.TmfExperimentFolder
;
93 import org
.eclipse
.tracecompass
.tmf
.ui
.project
.model
.TmfOpenTraceHelper
;
94 import org
.eclipse
.tracecompass
.tmf
.ui
.project
.model
.TmfProjectElement
;
95 import org
.eclipse
.tracecompass
.tmf
.ui
.project
.model
.TmfProjectRegistry
;
96 import org
.eclipse
.tracecompass
.tmf
.ui
.project
.model
.TmfTraceElement
;
97 import org
.eclipse
.tracecompass
.tmf
.ui
.project
.model
.TmfTraceFolder
;
98 import org
.eclipse
.tracecompass
.tmf
.ui
.project
.model
.TmfTracesFolder
;
99 import org
.eclipse
.tracecompass
.tmf
.ui
.swtbot
.tests
.shared
.ConditionHelpers
.ProjectElementHasChild
;
100 import org
.eclipse
.tracecompass
.tmf
.ui
.tests
.shared
.WaitUtils
;
101 import org
.eclipse
.tracecompass
.tmf
.ui
.views
.TracingPerspectiveFactory
;
102 import org
.eclipse
.ui
.IEditorPart
;
103 import org
.eclipse
.ui
.IEditorReference
;
104 import org
.eclipse
.ui
.IPageLayout
;
105 import org
.eclipse
.ui
.IViewPart
;
106 import org
.eclipse
.ui
.IWorkbenchCommandConstants
;
107 import org
.eclipse
.ui
.IWorkbenchPage
;
108 import org
.eclipse
.ui
.IWorkbenchPartSite
;
109 import org
.eclipse
.ui
.PartInitException
;
110 import org
.eclipse
.ui
.PlatformUI
;
111 import org
.eclipse
.ui
.WorkbenchException
;
112 import org
.eclipse
.ui
.handlers
.IHandlerService
;
113 import org
.hamcrest
.Matcher
;
116 * SWTBot Helper functions
118 * @author Matthew Khouzam
120 @SuppressWarnings("restriction")
121 public final class SWTBotUtils
{
123 private static final String WINDOW_MENU
= "Window";
124 private static final String PREFERENCES_MENU_ITEM
= "Preferences";
125 private static boolean fPrintedEnvironment
= false;
126 private static Logger log
= Logger
.getLogger(SWTBotUtils
.class);
128 private SWTBotUtils() {
132 private static final String TRACING_PERSPECTIVE_ID
= TracingPerspectiveFactory
.ID
;
135 * Sleeps current thread for a given time.
137 * @param waitTimeMillis
138 * time in milliseconds to wait
140 public static void delay(final long waitTimeMillis
) {
142 Thread
.sleep(waitTimeMillis
);
143 } catch (final InterruptedException e
) {
149 * Create a tracing project
152 * the name of the tracing project
154 public static void createProject(final String projectName
) {
158 UIThreadRunnable
.syncExec(new VoidResult() {
161 IProject project
= TmfProjectRegistry
.createProject(projectName
, null, new NullProgressMonitor());
162 assertNotNull(project
);
166 WaitUtils
.waitForJobs();
173 * the name of the tracing project
174 * @param deleteResources
175 * whether or not to deleted resources under the project
179 public static void deleteProject(final String projectName
, boolean deleteResources
, SWTWorkbenchBot bot
) {
180 // Wait for any analysis to complete because it might create
181 // supplementary files
182 WaitUtils
.waitForJobs();
184 ResourcesPlugin
.getWorkspace().getRoot().getProject(projectName
).refreshLocal(IResource
.DEPTH_INFINITE
, null);
185 } catch (CoreException e
) {
188 WaitUtils
.waitForJobs();
190 closeSecondaryShells(bot
);
191 WaitUtils
.waitForJobs();
193 if (!ResourcesPlugin
.getWorkspace().getRoot().getProject(projectName
).exists()) {
197 final SWTBotView projectViewBot
= bot
.viewById(IPageLayout
.ID_PROJECT_EXPLORER
);
198 projectViewBot
.setFocus();
200 SWTBotTree treeBot
= projectViewBot
.bot().tree();
201 SWTBotTreeItem treeItem
= treeBot
.getTreeItem(projectName
);
202 SWTBotMenu contextMenu
= treeItem
.contextMenu("Delete");
205 if (deleteResources
) {
206 bot
.shell("Delete Resources").setFocus();
207 final SWTBotCheckBox checkBox
= bot
.checkBox();
208 bot
.waitUntil(Conditions
.widgetIsEnabled(checkBox
));
212 final SWTBotButton okButton
= bot
.button("OK");
213 bot
.waitUntil(Conditions
.widgetIsEnabled(okButton
));
216 WaitUtils
.waitForJobs();
220 * Deletes a project and its resources
223 * the name of the tracing project
227 public static void deleteProject(String projectName
, SWTWorkbenchBot bot
) {
228 deleteProject(projectName
, true, bot
);
232 * Creates an experiment
235 * a given workbench bot
237 * the name of the project, creates the project if needed
239 * the experiment name
241 public static void createExperiment(SWTWorkbenchBot bot
, String projectName
, final @NonNull String expName
) {
242 IProject project
= ResourcesPlugin
.getWorkspace().getRoot().getProject(projectName
);
243 TmfProjectElement tmfProject
= TmfProjectRegistry
.getProject(project
, true);
244 TmfExperimentFolder expFolder
= tmfProject
.getExperimentsFolder();
245 assertNotNull(expFolder
);
246 NewExperimentOperation operation
= new NewExperimentOperation(expFolder
, expName
);
247 operation
.run(new NullProgressMonitor());
249 bot
.waitUntil(new DefaultCondition() {
251 public boolean test() throws Exception
{
252 TmfExperimentElement experiment
= expFolder
.getExperiment(expName
);
253 return experiment
!= null;
257 public String
getFailureMessage() {
258 return "Experiment (" + expName
+ ") couldn't be created";
264 * Focus on the main window
267 * swtbotshells for all the shells
269 public static void focusMainWindow(SWTBotShell
[] shellBots
) {
270 SWTBotShell mainShell
= getMainShell(shellBots
);
271 if (mainShell
!= null) {
272 mainShell
.activate();
276 private static SWTBotShell
getMainShell(SWTBotShell
[] shellBots
) {
277 SWTBotShell mainShell
= null;
278 for (SWTBotShell shellBot
: shellBots
) {
279 if (shellBot
.getText().toLowerCase().contains("eclipse")) {
280 mainShell
= shellBot
;
287 * Close all non-main shells that are visible.
292 public static void closeSecondaryShells(SWTWorkbenchBot bot
) {
293 SWTBotShell
[] shells
= bot
.shells();
294 SWTBotShell mainShell
= getMainShell(shells
);
295 if (mainShell
== null) {
299 // Close all non-main shell but make sure we don't close an invisible
300 // shell such the special "limbo shell" that Eclipse needs to work
301 Arrays
.stream(shells
)
302 .filter(shell
-> shell
!= mainShell
)
303 .filter(s
-> !s
.widget
.isDisposed())
304 .filter(SWTBotShell
::isVisible
)
305 .peek(shell
-> log
.debug(MessageFormat
.format("Closing lingering shell with title {0}", shell
.getText())))
306 .forEach(SWTBotShell
::close
);
310 * Close a view with a title
313 * the title, like "welcome"
317 public static void closeView(String title
, SWTWorkbenchBot bot
) {
318 final List
<SWTBotView
> openViews
= bot
.views();
319 for (SWTBotView view
: openViews
) {
320 if (view
.getTitle().equalsIgnoreCase(title
)) {
322 bot
.waitUntil(ConditionHelpers
.ViewIsClosed(view
));
328 * Close a view with an id
332 * "org.eclipse.linuxtools.tmf.ui.views.histogram"
336 public static void closeViewById(String viewId
, SWTWorkbenchBot bot
) {
337 final SWTBotView view
= bot
.viewById(viewId
);
339 bot
.waitUntil(ConditionHelpers
.ViewIsClosed(view
));
343 * Switch to the tracing perspective
345 public static void switchToTracingPerspective() {
346 switchToPerspective(TRACING_PERSPECTIVE_ID
);
350 * Switch to a given perspective
353 * the perspective id (like
354 * "org.eclipse.linuxtools.tmf.ui.perspective"
356 public static void switchToPerspective(final String id
) {
357 UIThreadRunnable
.syncExec(new VoidResult() {
361 PlatformUI
.getWorkbench().showPerspective(id
, PlatformUI
.getWorkbench().getActiveWorkbenchWindow());
362 } catch (WorkbenchException e
) {
363 fail(e
.getMessage());
370 * Initialize the environment for SWTBot
372 public static void initialize() {
375 SWTWorkbenchBot bot
= new SWTWorkbenchBot();
376 UIThreadRunnable
.syncExec(() -> {
379 // There seems to be problems on some system where the main shell is
380 // not in focus initially. This was seen using Xvfb and Xephyr on
382 focusMainWindow(bot
.shells());
384 Shell shell
= bot
.activeShell().widget
;
386 // Only adjust shell if it appears to be the top-most
387 if (shell
.getParent() == null) {
388 makeShellFullyVisible(shell
);
392 /* Do not switch perspectives on trace open */
393 IPreferenceStore store
= Activator
.getDefault().getPreferenceStore();
394 store
.setValue(ITmfUIPreferences
.SWITCH_TO_PERSPECTIVE
, MessageDialogWithToggle
.NEVER
);
397 private static void printEnvironment() {
398 if (fPrintedEnvironment
) {
402 // Print some information about the environment that could affect test
404 Rectangle bounds
= Display
.getDefault().getBounds();
405 System
.out
.println("Display size: " + bounds
.width
+ "x" + bounds
.height
);
407 String osVersion
= System
.getProperty("os.version");
408 if (osVersion
!= null) {
409 System
.out
.println("OS version=" + osVersion
);
411 String gtkVersion
= System
.getProperty("org.eclipse.swt.internal.gtk.version");
412 if (gtkVersion
!= null) {
413 System
.out
.println("GTK version=" + gtkVersion
);
414 // Try to print the GTK theme information as behavior can change
415 // depending on the theme
416 String gtkTheme
= System
.getProperty("org.eclipse.swt.internal.gtk.theme");
417 System
.out
.println("GTK theme=" + (gtkTheme
== null ?
"unknown" : gtkTheme
));
419 String overlayScrollbar
= System
.getenv("LIBOVERLAY_SCROLLBAR");
420 if (overlayScrollbar
!= null) {
421 System
.out
.println("LIBOVERLAY_SCROLLBAR=" + overlayScrollbar
);
423 String ubuntuMenuProxy
= System
.getenv("UBUNTU_MENUPROXY");
424 if (ubuntuMenuProxy
!= null) {
425 System
.out
.println("UBUNTU_MENUPROXY=" + ubuntuMenuProxy
);
429 System
.out
.println("Time zone: " + TimeZone
.getDefault().getDisplayName());
431 fPrintedEnvironment
= true;
435 * If the test is running in the UI thread then fail
437 private static void failIfUIThread() {
438 if (Display
.getCurrent() != null && Display
.getCurrent().getThread() == Thread
.currentThread()) {
439 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"
440 + " that useUIThread is set to false in the pom.xml");
445 * Try to make the shell fully visible in the display. If the shell cannot
446 * fit the display, it will be positioned so that top-left corner is at
447 * <code>(0, 0)</code> in display-relative coordinates.
450 * the shell to make fully visible
452 private static void makeShellFullyVisible(Shell shell
) {
453 Rectangle displayBounds
= shell
.getDisplay().getBounds();
454 Point absCoord
= shell
.toDisplay(0, 0);
455 Point shellSize
= shell
.getSize();
457 Point newLocation
= new Point(absCoord
.x
, absCoord
.y
);
458 newLocation
.x
= Math
.max(0, Math
.min(absCoord
.x
, displayBounds
.width
- shellSize
.x
));
459 newLocation
.y
= Math
.max(0, Math
.min(absCoord
.y
, displayBounds
.height
- shellSize
.y
));
460 if (!newLocation
.equals(absCoord
)) {
461 shell
.setLocation(newLocation
);
466 * Open a trace, this does not perform any validation though
471 * the path of the trace file (absolute or relative)
473 * the trace type id (eg: org.eclipse.linuxtools.btf.trace)
475 public static void openTrace(final String projectName
, final String tracePath
, final String traceType
) {
476 openTrace(projectName
, tracePath
, traceType
, true);
480 * Open a trace, this does not perform any validation though
485 * the path of the trace file (absolute or relative)
487 * the trace type id (eg: org.eclipse.linuxtools.btf.trace)
489 * delay and wait for jobs
491 public static void openTrace(final String projectName
, final String tracePath
, final String traceType
, boolean delay
) {
492 IStatus status
= UIThreadRunnable
.syncExec(new Result
<IStatus
>() {
494 public IStatus
run() {
496 IProject project
= ResourcesPlugin
.getWorkspace().getRoot().getProject(projectName
);
497 TmfTraceFolder destinationFolder
= TmfProjectRegistry
.getProject(project
, true).getTracesFolder();
498 return TmfOpenTraceHelper
.openTraceFromPath(destinationFolder
, tracePath
, PlatformUI
.getWorkbench().getActiveWorkbenchWindow().getShell(), traceType
);
499 } catch (CoreException e
) {
500 return new Status(IStatus
.ERROR
, "", e
.getMessage(), e
);
504 if (!status
.isOK()) {
505 fail(status
.getMessage());
510 WaitUtils
.waitForJobs();
515 * Finds an editor and sets focus to the editor
521 * @return the corresponding SWTBotEditor
523 public static SWTBotEditor
activateEditor(SWTWorkbenchBot bot
, String editorName
) {
524 Matcher
<IEditorReference
> matcher
= WidgetMatcherFactory
.withPartName(editorName
);
525 final SWTBotEditor editorBot
= bot
.editor(matcher
);
526 IEditorPart iep
= editorBot
.getReference().getEditor(true);
527 final TmfEventsEditor tmfEd
= (TmfEventsEditor
) iep
;
529 UIThreadRunnable
.syncExec(new VoidResult() {
536 WaitUtils
.waitForJobs();
537 SWTBotUtils
.delay(1000);
538 assertNotNull(tmfEd
);
543 * Opens a trace in an editor and get the TmfEventsEditor
548 * the name of the project that contains the trace
550 * the trace element path (relative to Traces folder)
551 * @return TmfEventsEditor the opened editor
553 public static TmfEventsEditor
openEditor(SWTWorkbenchBot bot
, String projectName
, IPath elementPath
) {
554 final SWTBotView projectExplorerView
= bot
.viewById(IPageLayout
.ID_PROJECT_EXPLORER
);
555 projectExplorerView
.setFocus();
556 SWTBot projectExplorerBot
= projectExplorerView
.bot();
558 final SWTBotTree tree
= projectExplorerBot
.tree();
559 projectExplorerBot
.waitUntil(ConditionHelpers
.IsTreeNodeAvailable(projectName
, tree
));
560 final SWTBotTreeItem treeItem
= tree
.getTreeItem(projectName
);
563 SWTBotTreeItem tracesNode
= getTraceProjectItem(projectExplorerBot
, treeItem
, TmfTracesFolder
.TRACES_FOLDER_NAME
);
566 SWTBotTreeItem currentItem
= tracesNode
;
567 for (String segment
: elementPath
.segments()) {
568 currentItem
= getTraceProjectItem(projectExplorerBot
, currentItem
, segment
);
569 currentItem
.doubleClick();
572 SWTBotEditor editor
= bot
.editorByTitle(elementPath
.toString());
573 IEditorPart editorPart
= editor
.getReference().getEditor(false);
574 assertTrue(editorPart
instanceof TmfEventsEditor
);
575 return (TmfEventsEditor
) editorPart
;
579 * Returns the child tree item of the specified item at the given sub-path.
580 * The project element labels may have a count suffix in the format ' [n]'.
583 * a given workbench bot
585 * the parent tree item
587 * the desired child element sub-path (without suffix)
588 * @return the a {@link SWTBotTreeItem} with the specified name
590 public static SWTBotTreeItem
getTraceProjectItem(SWTBot bot
, final SWTBotTreeItem parentItem
, final String
... path
) {
591 SWTBotTreeItem item
= parentItem
;
592 for (String name
: path
) {
593 item
= getTraceProjectItem(bot
, item
, name
);
599 * Returns the child tree item of the specified item with the given name.
600 * The project element label may have a count suffix in the format ' [n]'.
603 * a given workbench bot
605 * the parent tree item
607 * the desired child element name (without suffix)
608 * @return the a {@link SWTBotTreeItem} with the specified name
610 public static SWTBotTreeItem
getTraceProjectItem(SWTBot bot
, final SWTBotTreeItem parentItem
, final String name
) {
611 ProjectElementHasChild condition
= new ProjectElementHasChild(parentItem
, name
);
612 bot
.waitUntil(condition
);
613 return condition
.getItem();
617 * Select the traces folder
620 * a given workbench bot
622 * the name of the project (it needs to exist or else it would
624 * @return a {@link SWTBotTreeItem} of the "Traces" folder
626 public static SWTBotTreeItem
selectTracesFolder(SWTWorkbenchBot bot
, String projectName
) {
627 SWTBotTreeItem projectTreeItem
= selectProject(bot
, projectName
);
628 projectTreeItem
.select();
629 SWTBotTreeItem tracesFolderItem
= getTraceProjectItem(bot
, projectTreeItem
, TmfTracesFolder
.TRACES_FOLDER_NAME
);
630 tracesFolderItem
.select();
631 return tracesFolderItem
;
635 * Clear the traces folder
638 * a given workbench bot
640 * the name of the project (needs to exist)
642 public static void clearTracesFolder(SWTWorkbenchBot bot
, String projectName
) {
643 IProject project
= ResourcesPlugin
.getWorkspace().getRoot().getProject(projectName
);
644 TmfProjectElement tmfProject
= TmfProjectRegistry
.getProject(project
, false);
645 TmfTraceFolder tracesFolder
= tmfProject
.getTracesFolder();
646 if (tracesFolder
== null) {
650 for (TmfTraceElement traceElement
: tracesFolder
.getTraces()) {
651 traceElement
.delete(null);
654 final IFolder resource
= tracesFolder
.getResource();
655 resource
.accept(new IResourceVisitor() {
657 public boolean visit(IResource visitedResource
) throws CoreException
{
658 if (visitedResource
!= resource
) {
659 visitedResource
.delete(true, null);
663 }, IResource
.DEPTH_ONE
, 0);
664 } catch (CoreException e
) {
665 fail(e
.getMessage());
668 bot
.waitUntil(new DefaultCondition() {
669 private int fTraceNb
= 0;
672 public boolean test() throws Exception
{
673 List
<TmfTraceElement
> traces
= tracesFolder
.getTraces();
674 fTraceNb
= traces
.size();
675 return fTraceNb
== 0;
679 public String
getFailureMessage() {
680 return "Traces Folder not empty (" + fTraceNb
+ ")";
686 * Clear the trace folder (using the UI)
689 * a given workbench bot
691 * the name of the project (needs to exist)
693 public static void clearTracesFolderUI(SWTWorkbenchBot bot
, String projectName
) {
694 SWTBotTreeItem tracesFolder
= selectTracesFolder(bot
, projectName
);
695 tracesFolder
.contextMenu().menu("Clear").click();
696 String CONFIRM_CLEAR_DIALOG_TITLE
= "Confirm Clear";
697 bot
.waitUntil(Conditions
.shellIsActive(CONFIRM_CLEAR_DIALOG_TITLE
));
699 SWTBotShell shell
= bot
.shell(CONFIRM_CLEAR_DIALOG_TITLE
);
700 shell
.bot().button("Yes").click();
701 bot
.waitUntil(Conditions
.shellCloses(shell
));
702 bot
.waitWhile(ConditionHelpers
.treeItemHasChildren(tracesFolder
));
706 * Clear the experiment folder
709 * a given workbench bot
711 * the name of the project (needs to exist)
713 public static void clearExperimentFolder(SWTWorkbenchBot bot
, String projectName
) {
714 IProject project
= ResourcesPlugin
.getWorkspace().getRoot().getProject(projectName
);
715 TmfProjectElement tmfProject
= TmfProjectRegistry
.getProject(project
, false);
716 TmfExperimentFolder expFolder
= tmfProject
.getExperimentsFolder();
717 if (expFolder
== null) {
720 expFolder
.getExperiments().forEach(experiment
-> {
721 IResource resource
= experiment
.getResource();
723 // Close the experiment if open
724 experiment
.closeEditors();
726 IPath path
= resource
.getLocation();
728 // Delete supplementary files
729 experiment
.deleteSupplementaryFolder();
731 // Finally, delete the experiment
732 resource
.delete(true, null);
733 } catch (CoreException e
) {
734 fail(e
.getMessage());
738 bot
.waitUntil(new DefaultCondition() {
739 private int fExperimentNb
= 0;
742 public boolean test() throws Exception
{
743 List
<TmfExperimentElement
> experiments
= expFolder
.getExperiments();
744 fExperimentNb
= experiments
.size();
745 return fExperimentNb
== 0;
749 public String
getFailureMessage() {
750 return "Experiment Folder not empty (" + fExperimentNb
+ ")";
756 * Select the project in Project Explorer
759 * a given workbench bot
761 * the name of the project (it needs to exist or else it would
763 * @return a {@link SWTBotTreeItem} of the project
765 public static SWTBotTreeItem
selectProject(SWTWorkbenchBot bot
, String projectName
) {
766 SWTBotView projectExplorerBot
= bot
.viewByTitle("Project Explorer");
767 projectExplorerBot
.show();
768 // FIXME: Bug 496519. Sometimes, the tree becomes disabled for a certain
769 // amount of time. This can happen during a long running operation
770 // (BusyIndicator.showWhile) which brings up the modal dialog "operation
771 // in progress" and this disables all shells
772 projectExplorerBot
.bot().waitUntil(Conditions
.widgetIsEnabled(projectExplorerBot
.bot().tree()));
773 SWTBotTreeItem treeItem
= projectExplorerBot
.bot().tree().getTreeItem(projectName
);
784 public static void openView(final String id
) {
789 * Open a view by id and secondary id
796 public static void openView(final String id
, final @Nullable String secondaryId
) {
797 final PartInitException res
[] = new PartInitException
[1];
798 UIThreadRunnable
.syncExec(new VoidResult() {
802 if (secondaryId
== null) {
803 PlatformUI
.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(id
);
805 PlatformUI
.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(id
, secondaryId
, IWorkbenchPage
.VIEW_ACTIVATE
);
807 } catch (PartInitException e
) {
812 if (res
[0] != null) {
813 fail(res
[0].getMessage());
815 WaitUtils
.waitForJobs();
822 * the {@link SWTBotTable} table
824 public static void maximizeTable(SWTBotTable tableBot
) {
825 final AtomicBoolean controlResized
= new AtomicBoolean();
826 UIThreadRunnable
.syncExec(new VoidResult() {
829 tableBot
.widget
.addControlListener(new ControlAdapter() {
831 public void controlResized(ControlEvent e
) {
832 tableBot
.widget
.removeControlListener(this);
833 controlResized
.set(true);
839 tableBot
.pressShortcut(KeyStroke
.getInstance(IKeyLookup
.CTRL_NAME
+ "+"), KeyStroke
.getInstance("M"));
840 } catch (ParseException e
) {
843 new SWTBot().waitUntil(new DefaultCondition() {
845 public boolean test() throws Exception
{
846 return controlResized
.get();
850 public String
getFailureMessage() {
851 return "Control was not resized";
857 * Get the bounds of a widget in display coordinates
861 * @return the widget bounds, in display coordinates
863 public static Rectangle
getBoundsToDisplay(AbstractSWTBot
<?
> bot
) {
864 if (bot
.widget
instanceof Control
) {
865 final Control control
= checkNotNull((Control
) bot
.widget
);
866 return UIThreadRunnable
.syncExec(new Result
<Rectangle
>() {
868 public Rectangle
run() {
869 Point location
= control
.toDisplay(0, 0);
870 Point size
= control
.getSize();
871 return new Rectangle(location
.x
, location
.y
, size
.x
, size
.y
);
875 throw new IllegalArgumentException(bot
+" is not a Control widget");
879 * Get the bounds of a cell (SWT.Rectangle) for the specified row and column
885 * the row of the table to look up
887 * the column of the table to look up
888 * @return the bounds in display relative coordinates
890 public static Rectangle
getCellBounds(final Table table
, final int row
, final int col
) {
891 return UIThreadRunnable
.syncExec(new Result
<Rectangle
>() {
893 public Rectangle
run() {
894 TableItem item
= table
.getItem(row
);
895 Rectangle bounds
= item
.getBounds(col
);
896 Point p
= table
.toDisplay(bounds
.x
, bounds
.y
);
897 Rectangle rect
= new Rectangle(p
.x
, p
.y
, bounds
.width
, bounds
.height
);
904 * Get the tree item from a tree at the specified location
909 * the tree to find the tree item in
911 * the path to the tree item, in the form of node names (from
913 * @return the tree item
915 public static SWTBotTreeItem
getTreeItem(SWTBot bot
, SWTBotTree tree
, String
... nodeNames
) {
916 if (nodeNames
.length
== 0) {
920 bot
.waitUntil(ConditionHelpers
.IsTreeNodeAvailable(nodeNames
[0], tree
));
921 SWTBotTreeItem currentNode
= tree
.getTreeItem(nodeNames
[0]);
922 return getTreeItem(bot
, currentNode
, Arrays
.copyOfRange(nodeNames
, 1, nodeNames
.length
));
926 * Get the tree item from a parent tree item at the specified location
931 * the treeItem to find the tree item under
933 * the path to the tree item, in the form of node names (from
935 * @return the tree item
937 public static SWTBotTreeItem
getTreeItem(SWTBot bot
, SWTBotTreeItem treeItem
, String
... nodeNames
) {
938 if (nodeNames
.length
== 0) {
942 SWTBotTreeItem currentNode
= treeItem
;
943 for (int i
= 0; i
< nodeNames
.length
; i
++) {
944 bot
.waitUntil(ConditionHelpers
.treeItemHasChildren(treeItem
));
945 currentNode
.expand();
947 String nodeName
= nodeNames
[i
];
949 bot
.waitUntil(ConditionHelpers
.IsTreeChildNodeAvailable(nodeName
, currentNode
));
950 } catch (TimeoutException e
) {
951 // FIXME: Sometimes in a JFace TreeViewer, it expands to
952 // nothing. Need to find out why.
953 currentNode
.collapse();
954 currentNode
.expand();
955 bot
.waitUntil(ConditionHelpers
.IsTreeChildNodeAvailable(nodeName
, currentNode
));
958 SWTBotTreeItem newNode
= currentNode
.getNode(nodeName
);
959 currentNode
= newNode
;
966 * Press the shortcut specified by the given keys. The method returns when
967 * the key events have been received by the focus control.
974 public static void pressShortcut(Keyboard keyboard
, KeyStroke
... keys
) {
975 Control focusControl
= UIThreadRunnable
.syncExec(new Result
<Control
>() {
977 public Control
run() {
978 return Display
.getCurrent().getFocusControl();
981 pressShortcut(focusControl
, () -> keyboard
.pressShortcut(keys
), keys
);
985 * Press the shortcut specified by the given keys. The method returns when
986 * the key events have been received by the given control.
993 public static void pressShortcut(AbstractSWTBotControl
<?
> bot
, KeyStroke
... keys
) {
994 pressShortcut(bot
.widget
, () -> bot
.pressShortcut(keys
), keys
);
997 private static void pressShortcut(Control control
, Runnable pressShortcut
, KeyStroke
... keys
) {
998 AtomicInteger keysPressed
= new AtomicInteger();
999 AtomicInteger keysReleased
= new AtomicInteger();
1000 KeyListener keyListener
= new KeyListener() {
1002 public void keyPressed(KeyEvent e
) {
1003 keysPressed
.incrementAndGet();
1006 public void keyReleased(KeyEvent e
) {
1007 keysReleased
.incrementAndGet();
1010 UIThreadRunnable
.syncExec(() -> control
.addKeyListener(keyListener
));
1011 pressShortcut
.run();
1012 new SWTBot().waitUntil(new DefaultCondition() {
1014 public boolean test() throws Exception
{
1015 return keysPressed
.get() > 0 && keysPressed
.get() == keysReleased
.get();
1018 public String
getFailureMessage() {
1019 return "key press " + Arrays
.toString(keys
) + " not detected";
1022 UIThreadRunnable
.syncExec(() -> control
.removeKeyListener(keyListener
));
1026 * Press the keyboard shortcut that goes to the top of a tree widget. The
1027 * key combination can differ on different platforms.
1030 * the keyboard to use
1032 public static void pressShortcutGoToTreeTop(Keyboard keyboard
) {
1033 if (SWTUtils
.isMac()) {
1034 pressShortcut(keyboard
, Keystrokes
.ALT
, Keystrokes
.UP
);
1036 pressShortcut(keyboard
, Keystrokes
.HOME
);
1041 * Get the active events editor. Note that this will wait until such editor
1044 * @param workbenchBot
1045 * a given workbench bot
1046 * @return the active events editor
1048 public static SWTBotEditor
activeEventsEditor(final SWTWorkbenchBot workbenchBot
) {
1049 ConditionHelpers
.ActiveEventsEditor condition
= new ConditionHelpers
.ActiveEventsEditor(workbenchBot
, null);
1050 workbenchBot
.waitUntil(condition
);
1051 return condition
.getActiveEditor();
1055 * Get the active events editor. Note that this will wait until such editor
1058 * @param workbenchBot
1059 * a given workbench bot
1060 * @param editorTitle
1061 * the desired editor title. If null, any active events editor
1062 * will be considered valid.
1063 * @return the active events editor
1065 public static SWTBotEditor
activeEventsEditor(final SWTWorkbenchBot workbenchBot
, String editorTitle
) {
1066 ConditionHelpers
.ActiveEventsEditor condition
= new ConditionHelpers
.ActiveEventsEditor(workbenchBot
, editorTitle
);
1067 workbenchBot
.waitUntil(condition
);
1068 return condition
.getActiveEditor();
1072 * Open the preferences dialog and return the corresponding shell. See also
1073 * {@link #pressOKishButtonInPreferences(SWTBot)} to close the dialog.
1076 * a given workbench bot
1077 * @return the preferences shell
1079 public static SWTBotShell
openPreferences(SWTBot bot
) {
1080 if (SWTUtils
.isMac()) {
1081 // On Mac, the Preferences menu item is under the application name.
1082 // For some reason, we can't access the application menu anymore so
1083 // we use the keyboard shortcut.
1085 bot
.activeShell().pressShortcut(KeyStroke
.getInstance(IKeyLookup
.COMMAND_NAME
+ "+"), KeyStroke
.getInstance(","));
1086 } catch (ParseException e
) {
1090 bot
.menu(WINDOW_MENU
).menu(PREFERENCES_MENU_ITEM
).click();
1093 bot
.waitUntil(Conditions
.shellIsActive(PREFERENCES_MENU_ITEM
));
1094 return bot
.activeShell();
1098 * Click the OK or "Apply and Close" button the preferences dialog. The
1099 * button label changed from OK to "Apply and Close" in Eclipse version
1100 * 4.7-I20170329-2000.
1103 * a given workbench bot
1105 public static void pressOKishButtonInPreferences(SWTBot bot
) {
1107 String okIshLabel
= "Apply and Close";
1108 // We do it this more manual way in order to not have to timout and
1109 // wait 30 secs when the button is not there
1110 bot
.waitUntil(Conditions
.waitForWidget(withMnemonic(okIshLabel
)), 100);
1111 bot
.button(okIshLabel
).click();
1112 } catch (TimeoutException e
) {
1113 // Doesn't exist pre-4.7-I20170329-2000, try old "OK" button
1114 bot
.button("OK").click();
1119 * Maximize a view by reference. Calling this a second time will "un-maximize" a view.
1121 * TODO: if this is useful, maybe uplift to SWTViewBot
1124 * the view reference
1126 public static void maximize(@NonNull IViewPart view
) {
1127 assertNotNull(view
);
1128 IWorkbenchPartSite site
= view
.getSite();
1129 assertNotNull(site
);
1130 // The annotation is to make the compiler not complain.
1132 Object handlerServiceObject
= site
.getService(IHandlerService
.class);
1133 assertTrue(handlerServiceObject
instanceof IHandlerService
);
1134 IHandlerService handlerService
= (IHandlerService
) handlerServiceObject
;
1136 handlerService
.executeCommand(IWorkbenchCommandConstants
.WINDOW_MAXIMIZE_ACTIVE_VIEW_OR_EDITOR
, null);
1137 } catch (ExecutionException
| NotDefinedException
| NotEnabledException
| NotHandledException e
) {
1138 fail(e
.getMessage());
1143 * Get the number of checked items of a tree
1147 * @return The number of checked items
1149 public static int getTreeCheckedItemCount(SWTBotTree tree
) {
1150 return UIThreadRunnable
.syncExec(new IntResult() {
1153 public Integer
run() {
1155 for (TreeItem item
: tree
.widget
.getItems()) {
1156 checked
+= getChecked(item
);
1161 private int getChecked(TreeItem item
) {
1163 if (item
.getChecked()) {
1166 for (TreeItem child
: item
.getItems()) {
1167 total
+= getChecked(child
);
1175 * Filter the specified list of items in a time graph view.
1179 * @param filterItems
1180 * the list of filter dialog item tree paths
1181 * @param checkSubTree
1182 * true if the filter items sub-trees should be checked, or false
1183 * to only check the filter items
1185 public static void applyTimeGraphFilter(SWTBotView viewBot
, List
<String
[]> filterItems
, boolean checkSubTree
) {
1186 final String FILTER_ACTION
= "Show View Filters";
1187 final String FILTER_DIALOG_TITLE
= "Filter";
1188 final String UNCHECK_ALL
= "Uncheck all";
1189 final String CHECK_SUBTREE
= "Check subtree";
1190 final String OK_BUTTON
= "OK";
1192 SWTBotToolbarButton filterButton
= viewBot
.toolbarButton(FILTER_ACTION
);
1193 filterButton
.click();
1194 SWTBotShell shell
= viewBot
.bot().shell(FILTER_DIALOG_TITLE
).activate();
1196 SWTBot bot
= shell
.bot();
1197 SWTBotTree treeBot
= bot
.tree();
1198 bot
.button(UNCHECK_ALL
).click();
1200 for (String
[] filterItem
: filterItems
) {
1201 SWTBotTreeItem item
= SWTBotUtils
.getTreeItem(bot
, treeBot
, filterItem
);
1204 bot
.button(CHECK_SUBTREE
).click();
1210 bot
.button(OK_BUTTON
).click();