os.linux: Remove latency table view and use the one from timing
[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.Arrays;
20 import java.util.List;
21 import java.util.TimeZone;
22 import java.util.concurrent.atomic.AtomicBoolean;
23
24 import org.apache.log4j.Logger;
25 import org.eclipse.core.resources.IFolder;
26 import org.eclipse.core.resources.IProject;
27 import org.eclipse.core.resources.IResource;
28 import org.eclipse.core.resources.IResourceVisitor;
29 import org.eclipse.core.resources.ResourcesPlugin;
30 import org.eclipse.core.runtime.CoreException;
31 import org.eclipse.core.runtime.IPath;
32 import org.eclipse.core.runtime.NullProgressMonitor;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.eclipse.jface.bindings.keys.IKeyLookup;
36 import org.eclipse.jface.bindings.keys.KeyStroke;
37 import org.eclipse.jface.bindings.keys.ParseException;
38 import org.eclipse.swt.events.ControlAdapter;
39 import org.eclipse.swt.events.ControlEvent;
40 import org.eclipse.swt.graphics.Point;
41 import org.eclipse.swt.graphics.Rectangle;
42 import org.eclipse.swt.widgets.Display;
43 import org.eclipse.swt.widgets.Shell;
44 import org.eclipse.swt.widgets.Table;
45 import org.eclipse.swt.widgets.TableItem;
46 import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
47 import org.eclipse.swtbot.eclipse.finder.matchers.WidgetMatcherFactory;
48 import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor;
49 import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView;
50 import org.eclipse.swtbot.swt.finder.SWTBot;
51 import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable;
52 import org.eclipse.swtbot.swt.finder.keyboard.Keyboard;
53 import org.eclipse.swtbot.swt.finder.keyboard.Keystrokes;
54 import org.eclipse.swtbot.swt.finder.results.Result;
55 import org.eclipse.swtbot.swt.finder.results.VoidResult;
56 import org.eclipse.swtbot.swt.finder.utils.MessageFormat;
57 import org.eclipse.swtbot.swt.finder.utils.SWTUtils;
58 import org.eclipse.swtbot.swt.finder.waits.Conditions;
59 import org.eclipse.swtbot.swt.finder.waits.DefaultCondition;
60 import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton;
61 import org.eclipse.swtbot.swt.finder.widgets.SWTBotCheckBox;
62 import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu;
63 import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
64 import org.eclipse.swtbot.swt.finder.widgets.SWTBotTable;
65 import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
66 import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
67 import org.eclipse.swtbot.swt.finder.widgets.TimeoutException;
68 import org.eclipse.tracecompass.internal.tmf.ui.project.operations.NewExperimentOperation;
69 import org.eclipse.tracecompass.tmf.ui.editors.TmfEventsEditor;
70 import org.eclipse.tracecompass.tmf.ui.project.model.TmfExperimentElement;
71 import org.eclipse.tracecompass.tmf.ui.project.model.TmfExperimentFolder;
72 import org.eclipse.tracecompass.tmf.ui.project.model.TmfOpenTraceHelper;
73 import org.eclipse.tracecompass.tmf.ui.project.model.TmfProjectElement;
74 import org.eclipse.tracecompass.tmf.ui.project.model.TmfProjectRegistry;
75 import org.eclipse.tracecompass.tmf.ui.project.model.TmfTraceElement;
76 import org.eclipse.tracecompass.tmf.ui.project.model.TmfTraceFolder;
77 import org.eclipse.tracecompass.tmf.ui.project.model.TmfTracesFolder;
78 import org.eclipse.tracecompass.tmf.ui.swtbot.tests.shared.ConditionHelpers.ProjectElementHasChild;
79 import org.eclipse.tracecompass.tmf.ui.tests.shared.WaitUtils;
80 import org.eclipse.tracecompass.tmf.ui.views.TracingPerspectiveFactory;
81 import org.eclipse.ui.IEditorPart;
82 import org.eclipse.ui.IEditorReference;
83 import org.eclipse.ui.IPageLayout;
84 import org.eclipse.ui.IWorkbenchPage;
85 import org.eclipse.ui.PartInitException;
86 import org.eclipse.ui.PlatformUI;
87 import org.eclipse.ui.WorkbenchException;
88 import org.hamcrest.Matcher;
89
90 /**
91 * SWTBot Helper functions
92 *
93 * @author Matthew Khouzam
94 */
95 @SuppressWarnings("restriction")
96 public final class SWTBotUtils {
97
98 private static final String WINDOW_MENU = "Window";
99 private static final String PREFERENCES_MENU_ITEM = "Preferences";
100 private static boolean fPrintedEnvironment = false;
101 private static Logger log = Logger.getLogger(SWTBotUtils.class);
102
103 private SWTBotUtils() {
104
105 }
106
107 private static final String TRACING_PERSPECTIVE_ID = TracingPerspectiveFactory.ID;
108
109 /**
110 * Waits for all Eclipse jobs to finish. Times out after
111 * WaitUtils#MAX_JOBS_WAIT_TIME by default.
112 *
113 * @throws RuntimeException
114 * once the waiting time passes the default maximum value
115 *
116 * @deprecated Use {@link WaitUtils#waitForJobs()} instead
117 */
118 @Deprecated
119 public static void waitForJobs() {
120 WaitUtils.waitForJobs();
121 }
122
123 /**
124 * Sleeps current thread for a given time.
125 *
126 * @param waitTimeMillis
127 * time in milliseconds to wait
128 */
129 public static void delay(final long waitTimeMillis) {
130 try {
131 Thread.sleep(waitTimeMillis);
132 } catch (final InterruptedException e) {
133 // Ignored
134 }
135 }
136
137 /**
138 * Create a tracing project
139 *
140 * @param projectName
141 * the name of the tracing project
142 */
143 public static void createProject(final String projectName) {
144 /*
145 * Make a new test
146 */
147 UIThreadRunnable.syncExec(new VoidResult() {
148 @Override
149 public void run() {
150 IProject project = TmfProjectRegistry.createProject(projectName, null, new NullProgressMonitor());
151 assertNotNull(project);
152 }
153 });
154
155 WaitUtils.waitForJobs();
156 }
157
158 /**
159 * Deletes a project
160 *
161 * @param projectName
162 * the name of the tracing project
163 * @param deleteResources
164 * whether or not to deleted resources under the project
165 * @param bot
166 * the workbench bot
167 */
168 public static void deleteProject(final String projectName, boolean deleteResources, SWTWorkbenchBot bot) {
169 // Wait for any analysis to complete because it might create
170 // supplementary files
171 WaitUtils.waitForJobs();
172 try {
173 ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).refreshLocal(IResource.DEPTH_INFINITE, null);
174 } catch (CoreException e) {
175 }
176
177 WaitUtils.waitForJobs();
178
179 closeSecondaryShells(bot);
180 WaitUtils.waitForJobs();
181
182 if (!ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).exists()) {
183 return;
184 }
185
186 final SWTBotView projectViewBot = bot.viewById(IPageLayout.ID_PROJECT_EXPLORER);
187 projectViewBot.setFocus();
188
189 SWTBotTree treeBot = projectViewBot.bot().tree();
190 SWTBotTreeItem treeItem = treeBot.getTreeItem(projectName);
191 SWTBotMenu contextMenu = treeItem.contextMenu("Delete");
192 contextMenu.click();
193
194 if (deleteResources) {
195 bot.shell("Delete Resources").setFocus();
196 final SWTBotCheckBox checkBox = bot.checkBox();
197 bot.waitUntil(Conditions.widgetIsEnabled(checkBox));
198 checkBox.click();
199 }
200
201 final SWTBotButton okButton = bot.button("OK");
202 bot.waitUntil(Conditions.widgetIsEnabled(okButton));
203 okButton.click();
204
205 WaitUtils.waitForJobs();
206 }
207
208 /**
209 * Deletes a project and its resources
210 *
211 * @param projectName
212 * the name of the tracing project
213 * @param bot
214 * the workbench bot
215 */
216 public static void deleteProject(String projectName, SWTWorkbenchBot bot) {
217 deleteProject(projectName, true, bot);
218 }
219
220 /**
221 * Creates an experiment
222 *
223 * @param bot
224 * a given workbench bot
225 * @param projectName
226 * the name of the project, creates the project if needed
227 * @param expName
228 * the experiment name
229 */
230 public static void createExperiment(SWTWorkbenchBot bot, String projectName, final @NonNull String expName) {
231 IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
232 TmfProjectElement tmfProject = TmfProjectRegistry.getProject(project, true);
233 TmfExperimentFolder expFolder = tmfProject.getExperimentsFolder();
234 assertNotNull(expFolder);
235 NewExperimentOperation operation = new NewExperimentOperation(expFolder, expName);
236 operation.run(new NullProgressMonitor());
237
238 bot.waitUntil(new DefaultCondition() {
239 @Override
240 public boolean test() throws Exception {
241 TmfExperimentElement experiment = expFolder.getExperiment(expName);
242 return experiment != null;
243 }
244
245 @Override
246 public String getFailureMessage() {
247 return "Experiment (" + expName + ") couldn't be created";
248 }
249 });
250 }
251
252 /**
253 * Focus on the main window
254 *
255 * @param shellBots
256 * swtbotshells for all the shells
257 */
258 public static void focusMainWindow(SWTBotShell[] shellBots) {
259 SWTBotShell mainShell = getMainShell(shellBots);
260 if (mainShell != null) {
261 mainShell.activate();
262 }
263 }
264
265 private static SWTBotShell getMainShell(SWTBotShell[] shellBots) {
266 SWTBotShell mainShell = null;
267 for (SWTBotShell shellBot : shellBots) {
268 if (shellBot.getText().toLowerCase().contains("eclipse")) {
269 mainShell = shellBot;
270 }
271 }
272 return mainShell;
273 }
274
275 /**
276 * Close all non-main shells that are visible.
277 *
278 * @param bot
279 * the workbench bot
280 */
281 public static void closeSecondaryShells(SWTWorkbenchBot bot) {
282 SWTBotShell[] shells = bot.shells();
283 SWTBotShell mainShell = getMainShell(shells);
284 if (mainShell == null) {
285 return;
286 }
287
288 // Close all non-main shell but make sure we don't close an invisible
289 // shell such the special "limbo shell" that Eclipse needs to work
290 Arrays.stream(shells)
291 .filter(shell -> shell != mainShell)
292 .filter(s -> !s.widget.isDisposed())
293 .filter(SWTBotShell::isVisible)
294 .peek(shell -> log.debug(MessageFormat.format("Closing lingering shell with title {0}", shell.getText())))
295 .forEach(SWTBotShell::close);
296 }
297
298 /**
299 * Close a view with a title
300 *
301 * @param title
302 * the title, like "welcome"
303 * @param bot
304 * the workbench bot
305 */
306 public static void closeView(String title, SWTWorkbenchBot bot) {
307 final List<SWTBotView> openViews = bot.views();
308 for (SWTBotView view : openViews) {
309 if (view.getTitle().equalsIgnoreCase(title)) {
310 view.close();
311 bot.waitUntil(ConditionHelpers.ViewIsClosed(view));
312 }
313 }
314 }
315
316 /**
317 * Close a view with an id
318 *
319 * @param viewId
320 * the view id, like
321 * "org.eclipse.linuxtools.tmf.ui.views.histogram"
322 * @param bot
323 * the workbench bot
324 */
325 public static void closeViewById(String viewId, SWTWorkbenchBot bot) {
326 final SWTBotView view = bot.viewById(viewId);
327 view.close();
328 bot.waitUntil(ConditionHelpers.ViewIsClosed(view));
329 }
330
331 /**
332 * Switch to the tracing perspective
333 */
334 public static void switchToTracingPerspective() {
335 switchToPerspective(TRACING_PERSPECTIVE_ID);
336 }
337
338 /**
339 * Switch to a given perspective
340 *
341 * @param id
342 * the perspective id (like
343 * "org.eclipse.linuxtools.tmf.ui.perspective"
344 */
345 public static void switchToPerspective(final String id) {
346 UIThreadRunnable.syncExec(new VoidResult() {
347 @Override
348 public void run() {
349 try {
350 PlatformUI.getWorkbench().showPerspective(id, PlatformUI.getWorkbench().getActiveWorkbenchWindow());
351 } catch (WorkbenchException e) {
352 fail(e.getMessage());
353 }
354 }
355 });
356 }
357
358 /**
359 * Initialize the environment for SWTBot
360 */
361 public static void initialize() {
362 failIfUIThread();
363
364 SWTWorkbenchBot bot = new SWTWorkbenchBot();
365 UIThreadRunnable.syncExec(() -> {
366 printEnvironment();
367
368 // There seems to be problems on some system where the main shell is
369 // not in focus initially. This was seen using Xvfb and Xephyr on
370 // some occasions.
371 focusMainWindow(bot.shells());
372
373 Shell shell = bot.activeShell().widget;
374
375 // Only adjust shell if it appears to be the top-most
376 if (shell.getParent() == null) {
377 makeShellFullyVisible(shell);
378 }
379 });
380 }
381
382 private static void printEnvironment() {
383 if (fPrintedEnvironment) {
384 return;
385 }
386
387 // Print some information about the environment that could affect test
388 // outcome
389 Rectangle bounds = Display.getDefault().getBounds();
390 System.out.println("Display size: " + bounds.width + "x" + bounds.height);
391
392 String osVersion = System.getProperty("os.version");
393 if (osVersion != null) {
394 System.out.println("OS version=" + osVersion);
395 }
396 String gtkVersion = System.getProperty("org.eclipse.swt.internal.gtk.version");
397 if (gtkVersion != null) {
398 System.out.println("GTK version=" + gtkVersion);
399 // Try to print the GTK theme information as behavior can change
400 // depending on the theme
401 String gtkTheme = System.getProperty("org.eclipse.swt.internal.gtk.theme");
402 System.out.println("GTK theme=" + (gtkTheme == null ? "unknown" : gtkTheme));
403
404 String overlayScrollbar = System.getenv("LIBOVERLAY_SCROLLBAR");
405 if (overlayScrollbar != null) {
406 System.out.println("LIBOVERLAY_SCROLLBAR=" + overlayScrollbar);
407 }
408 String ubuntuMenuProxy = System.getenv("UBUNTU_MENUPROXY");
409 if (ubuntuMenuProxy != null) {
410 System.out.println("UBUNTU_MENUPROXY=" + ubuntuMenuProxy);
411 }
412 }
413
414 System.out.println("Time zone: " + TimeZone.getDefault().getDisplayName());
415
416 fPrintedEnvironment = true;
417 }
418
419 /**
420 * If the test is running in the UI thread then fail
421 */
422 private static void failIfUIThread() {
423 if (Display.getCurrent() != null && Display.getCurrent().getThread() == Thread.currentThread()) {
424 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"
425 + " that useUIThread is set to false in the pom.xml");
426 }
427 }
428
429 /**
430 * Try to make the shell fully visible in the display. If the shell cannot
431 * fit the display, it will be positioned so that top-left corner is at
432 * <code>(0, 0)</code> in display-relative coordinates.
433 *
434 * @param shell
435 * the shell to make fully visible
436 */
437 private static void makeShellFullyVisible(Shell shell) {
438 Rectangle displayBounds = shell.getDisplay().getBounds();
439 Point absCoord = shell.toDisplay(0, 0);
440 Point shellSize = shell.getSize();
441
442 Point newLocation = new Point(absCoord.x, absCoord.y);
443 newLocation.x = Math.max(0, Math.min(absCoord.x, displayBounds.width - shellSize.x));
444 newLocation.y = Math.max(0, Math.min(absCoord.y, displayBounds.height - shellSize.y));
445 if (!newLocation.equals(absCoord)) {
446 shell.setLocation(newLocation);
447 }
448 }
449
450 /**
451 * Open a trace, this does not perform any validation though
452 *
453 * @param projectName
454 * The project name
455 * @param tracePath
456 * the path of the trace file (absolute or relative)
457 * @param traceType
458 * the trace type id (eg: org.eclipse.linuxtools.btf.trace)
459 */
460 public static void openTrace(final String projectName, final String tracePath, final String traceType) {
461 openTrace(projectName, tracePath, traceType, true);
462 }
463
464 /**
465 * Open a trace, this does not perform any validation though
466 *
467 * @param projectName
468 * The project name
469 * @param tracePath
470 * the path of the trace file (absolute or relative)
471 * @param traceType
472 * the trace type id (eg: org.eclipse.linuxtools.btf.trace)
473 * @param delay
474 * delay and wait for jobs
475 */
476 public static void openTrace(final String projectName, final String tracePath, final String traceType, boolean delay) {
477 final Exception exception[] = new Exception[1];
478 exception[0] = null;
479 UIThreadRunnable.syncExec(new VoidResult() {
480 @Override
481 public void run() {
482 try {
483 IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
484 TmfTraceFolder destinationFolder = TmfProjectRegistry.getProject(project, true).getTracesFolder();
485 TmfOpenTraceHelper.openTraceFromPath(destinationFolder, tracePath, PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), traceType);
486 } catch (CoreException e) {
487 exception[0] = e;
488 }
489 }
490 });
491 if (exception[0] != null) {
492 fail(exception[0].getMessage());
493 }
494
495 if (delay) {
496 delay(1000);
497 WaitUtils.waitForJobs();
498 }
499 }
500
501 /**
502 * Finds an editor and sets focus to the editor
503 *
504 * @param bot
505 * the workbench bot
506 * @param editorName
507 * the editor name
508 * @return the corresponding SWTBotEditor
509 */
510 public static SWTBotEditor activateEditor(SWTWorkbenchBot bot, String editorName) {
511 Matcher<IEditorReference> matcher = WidgetMatcherFactory.withPartName(editorName);
512 final SWTBotEditor editorBot = bot.editor(matcher);
513 IEditorPart iep = editorBot.getReference().getEditor(true);
514 final TmfEventsEditor tmfEd = (TmfEventsEditor) iep;
515 editorBot.show();
516 UIThreadRunnable.syncExec(new VoidResult() {
517 @Override
518 public void run() {
519 tmfEd.setFocus();
520 }
521 });
522
523 WaitUtils.waitForJobs();
524 SWTBotUtils.delay(1000);
525 assertNotNull(tmfEd);
526 return editorBot;
527 }
528
529 /**
530 * Opens a trace in an editor and get the TmfEventsEditor
531 *
532 * @param bot
533 * the workbench bot
534 * @param projectName
535 * the name of the project that contains the trace
536 * @param elementPath
537 * the trace element path (relative to Traces folder)
538 * @return TmfEventsEditor the opened editor
539 */
540 public static TmfEventsEditor openEditor(SWTWorkbenchBot bot, String projectName, IPath elementPath) {
541 final SWTBotView projectExplorerView = bot.viewById(IPageLayout.ID_PROJECT_EXPLORER);
542 projectExplorerView.setFocus();
543 SWTBot projectExplorerBot = projectExplorerView.bot();
544
545 final SWTBotTree tree = projectExplorerBot.tree();
546 projectExplorerBot.waitUntil(ConditionHelpers.IsTreeNodeAvailable(projectName, tree));
547 final SWTBotTreeItem treeItem = tree.getTreeItem(projectName);
548 treeItem.expand();
549
550 SWTBotTreeItem tracesNode = getTraceProjectItem(projectExplorerBot, treeItem, TmfTracesFolder.TRACES_FOLDER_NAME);
551 tracesNode.expand();
552
553 SWTBotTreeItem currentItem = tracesNode;
554 for (String segment : elementPath.segments()) {
555 currentItem = getTraceProjectItem(projectExplorerBot, currentItem, segment);
556 currentItem.doubleClick();
557 }
558
559 SWTBotEditor editor = bot.editorByTitle(elementPath.toString());
560 IEditorPart editorPart = editor.getReference().getEditor(false);
561 assertTrue(editorPart instanceof TmfEventsEditor);
562 return (TmfEventsEditor) editorPart;
563 }
564
565 /**
566 * Returns the child tree item of the specified item at the given sub-path.
567 * The project element labels may have a count suffix in the format ' [n]'.
568 *
569 * @param bot
570 * a given workbench bot
571 * @param parentItem
572 * the parent tree item
573 * @param path
574 * the desired child element sub-path (without suffix)
575 * @return the a {@link SWTBotTreeItem} with the specified name
576 */
577 public static SWTBotTreeItem getTraceProjectItem(SWTBot bot, final SWTBotTreeItem parentItem, final String... path) {
578 SWTBotTreeItem item = parentItem;
579 for (String name : path) {
580 item = getTraceProjectItem(bot, item, name);
581 }
582 return item;
583 }
584
585 /**
586 * Returns the child tree item of the specified item with the given name.
587 * The project element label may have a count suffix in the format ' [n]'.
588 *
589 * @param bot
590 * a given workbench bot
591 * @param parentItem
592 * the parent tree item
593 * @param name
594 * the desired child element name (without suffix)
595 * @return the a {@link SWTBotTreeItem} with the specified name
596 */
597 public static SWTBotTreeItem getTraceProjectItem(SWTBot bot, final SWTBotTreeItem parentItem, final String name) {
598 ProjectElementHasChild condition = new ProjectElementHasChild(parentItem, name);
599 bot.waitUntil(condition);
600 return condition.getItem();
601 }
602
603 /**
604 * Select the traces folder
605 *
606 * @param bot
607 * a given workbench bot
608 * @param projectName
609 * the name of the project (it needs to exist or else it would
610 * time out)
611 * @return a {@link SWTBotTreeItem} of the "Traces" folder
612 */
613 public static SWTBotTreeItem selectTracesFolder(SWTWorkbenchBot bot, String projectName) {
614 SWTBotTreeItem projectTreeItem = selectProject(bot, projectName);
615 projectTreeItem.select();
616 SWTBotTreeItem tracesFolderItem = getTraceProjectItem(bot, projectTreeItem, TmfTracesFolder.TRACES_FOLDER_NAME);
617 tracesFolderItem.select();
618 return tracesFolderItem;
619 }
620
621 /**
622 * Clear the traces folder
623 *
624 * @param bot
625 * a given workbench bot
626 * @param projectName
627 * the name of the project (needs to exist)
628 */
629 public static void clearTracesFolder(SWTWorkbenchBot bot, String projectName) {
630 IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
631 TmfProjectElement tmfProject = TmfProjectRegistry.getProject(project, false);
632 TmfTraceFolder tracesFolder = tmfProject.getTracesFolder();
633 try {
634 for (TmfTraceElement traceElement : tracesFolder.getTraces()) {
635 traceElement.delete(null);
636 }
637
638 final IFolder resource = tracesFolder.getResource();
639 resource.accept(new IResourceVisitor() {
640 @Override
641 public boolean visit(IResource visitedResource) throws CoreException {
642 if (visitedResource != resource) {
643 visitedResource.delete(true, null);
644 }
645 return true;
646 }
647 }, IResource.DEPTH_ONE, 0);
648 } catch (CoreException e) {
649 fail(e.getMessage());
650 }
651
652 bot.waitUntil(new DefaultCondition() {
653 private int fTraceNb = 0;
654
655 @Override
656 public boolean test() throws Exception {
657 List<TmfTraceElement> traces = tracesFolder.getTraces();
658 fTraceNb = traces.size();
659 return fTraceNb == 0;
660 }
661
662 @Override
663 public String getFailureMessage() {
664 return "Traces Folder not empty (" + fTraceNb + ")";
665 }
666 });
667 }
668
669 /**
670 * Clear the trace folder (using the UI)
671 *
672 * @param bot
673 * a given workbench bot
674 * @param projectName
675 * the name of the project (needs to exist)
676 */
677 public static void clearTracesFolderUI(SWTWorkbenchBot bot, String projectName) {
678 SWTBotTreeItem tracesFolder = selectTracesFolder(bot, projectName);
679 tracesFolder.contextMenu().menu("Clear").click();
680 String CONFIRM_CLEAR_DIALOG_TITLE = "Confirm Clear";
681 bot.waitUntil(Conditions.shellIsActive(CONFIRM_CLEAR_DIALOG_TITLE));
682
683 SWTBotShell shell = bot.shell(CONFIRM_CLEAR_DIALOG_TITLE);
684 shell.bot().button("Yes").click();
685 bot.waitUntil(Conditions.shellCloses(shell));
686 bot.waitWhile(ConditionHelpers.treeItemHasChildren(tracesFolder));
687 }
688
689 /**
690 * Clear the experiment folder
691 *
692 * @param bot
693 * a given workbench bot
694 * @param projectName
695 * the name of the project (needs to exist)
696 */
697 public static void clearExperimentFolder(SWTWorkbenchBot bot, String projectName) {
698 IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
699 TmfProjectElement tmfProject = TmfProjectRegistry.getProject(project, false);
700 TmfExperimentFolder expFolder = tmfProject.getExperimentsFolder();
701 expFolder.getExperiments().forEach(experiment -> {
702 IResource resource = experiment.getResource();
703 try {
704 // Close the experiment if open
705 experiment.closeEditors();
706
707 IPath path = resource.getLocation();
708 if (path != null) {
709 // Delete supplementary files
710 experiment.deleteSupplementaryFolder();
711 }
712 // Finally, delete the experiment
713 resource.delete(true, null);
714 } catch (CoreException e) {
715 fail(e.getMessage());
716 }
717 });
718
719 bot.waitUntil(new DefaultCondition() {
720 private int fExperimentNb = 0;
721
722 @Override
723 public boolean test() throws Exception {
724 List<TmfExperimentElement> experiments = expFolder.getExperiments();
725 fExperimentNb = experiments.size();
726 return fExperimentNb == 0;
727 }
728
729 @Override
730 public String getFailureMessage() {
731 return "Experiment Folder not empty (" + fExperimentNb + ")";
732 }
733 });
734 }
735
736 /**
737 * Select the project in Project Explorer
738 *
739 * @param bot
740 * a given workbench bot
741 * @param projectName
742 * the name of the project (it needs to exist or else it would
743 * time out)
744 * @return a {@link SWTBotTreeItem} of the project
745 */
746 public static SWTBotTreeItem selectProject(SWTWorkbenchBot bot, String projectName) {
747 SWTBotView projectExplorerBot = bot.viewByTitle("Project Explorer");
748 projectExplorerBot.show();
749 // FIXME: Bug 496519. Sometimes, the tree becomes disabled for a certain
750 // amount of time. This can happen during a long running operation
751 // (BusyIndicator.showWhile) which brings up the modal dialog "operation
752 // in progress" and this disables all shells
753 projectExplorerBot.bot().waitUntil(Conditions.widgetIsEnabled(projectExplorerBot.bot().tree()));
754 SWTBotTreeItem treeItem = projectExplorerBot.bot().tree().getTreeItem(projectName);
755 treeItem.select();
756 return treeItem;
757 }
758
759 /**
760 * Open a view by id.
761 *
762 * @param id
763 * view id.
764 */
765 public static void openView(final String id) {
766 openView(id, null);
767 }
768
769 /**
770 * Open a view by id and secondary id
771 *
772 * @param id
773 * view id.
774 * @param secondaryId
775 * The secondary ID
776 */
777 public static void openView(final String id, final @Nullable String secondaryId) {
778 final PartInitException res[] = new PartInitException[1];
779 UIThreadRunnable.syncExec(new VoidResult() {
780 @Override
781 public void run() {
782 try {
783 if (secondaryId == null) {
784 PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(id);
785 } else {
786 PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(id, secondaryId, IWorkbenchPage.VIEW_ACTIVATE);
787 }
788 } catch (PartInitException e) {
789 res[0] = e;
790 }
791 }
792 });
793 if (res[0] != null) {
794 fail(res[0].getMessage());
795 }
796 WaitUtils.waitForJobs();
797 }
798
799 /**
800 * Maximize a table
801 *
802 * @param tableBot
803 * the {@link SWTBotTable} table
804 */
805 public static void maximizeTable(SWTBotTable tableBot) {
806 final AtomicBoolean controlResized = new AtomicBoolean();
807 UIThreadRunnable.syncExec(new VoidResult() {
808 @Override
809 public void run() {
810 tableBot.widget.addControlListener(new ControlAdapter() {
811 @Override
812 public void controlResized(ControlEvent e) {
813 tableBot.widget.removeControlListener(this);
814 controlResized.set(true);
815 }
816 });
817 }
818 });
819 try {
820 tableBot.pressShortcut(KeyStroke.getInstance(IKeyLookup.CTRL_NAME + "+"), KeyStroke.getInstance("M"));
821 } catch (ParseException e) {
822 fail();
823 }
824 new SWTBot().waitUntil(new DefaultCondition() {
825 @Override
826 public boolean test() throws Exception {
827 return controlResized.get();
828 }
829
830 @Override
831 public String getFailureMessage() {
832 return "Control was not resized";
833 }
834 });
835 }
836
837 /**
838 * Get the bounds of a cell (SWT.Rectangle) for the specified row and column
839 * index in a table
840 *
841 * @param table
842 * the table
843 * @param row
844 * the row of the table to look up
845 * @param col
846 * the column of the table to look up
847 * @return the bounds in display relative coordinates
848 */
849 public static Rectangle getCellBounds(final Table table, final int row, final int col) {
850 return UIThreadRunnable.syncExec(new Result<Rectangle>() {
851 @Override
852 public Rectangle run() {
853 TableItem item = table.getItem(row);
854 Rectangle bounds = item.getBounds(col);
855 Point p = table.toDisplay(bounds.x, bounds.y);
856 Rectangle rect = new Rectangle(p.x, p.y, bounds.width, bounds.height);
857 return rect;
858 }
859 });
860 }
861
862 /**
863 * Get the tree item from a tree at the specified location
864 *
865 * @param bot
866 * the SWTBot
867 * @param tree
868 * the tree to find the tree item in
869 * @param nodeNames
870 * the path to the tree item, in the form of node names (from
871 * parent to child).
872 * @return the tree item
873 */
874 public static SWTBotTreeItem getTreeItem(SWTBot bot, SWTBotTree tree, String... nodeNames) {
875 if (nodeNames.length == 0) {
876 return null;
877 }
878
879 bot.waitUntil(ConditionHelpers.IsTreeNodeAvailable(nodeNames[0], tree));
880 SWTBotTreeItem currentNode = tree.getTreeItem(nodeNames[0]);
881 return getTreeItem(bot, currentNode, Arrays.copyOfRange(nodeNames, 1, nodeNames.length));
882 }
883
884 /**
885 * Get the tree item from a parent tree item at the specified location
886 *
887 * @param bot
888 * the SWTBot
889 * @param treeItem
890 * the treeItem to find the tree item under
891 * @param nodeNames
892 * the path to the tree item, in the form of node names (from
893 * parent to child).
894 * @return the tree item
895 */
896 public static SWTBotTreeItem getTreeItem(SWTBot bot, SWTBotTreeItem treeItem, String... nodeNames) {
897 if (nodeNames.length == 0) {
898 return treeItem;
899 }
900
901 SWTBotTreeItem currentNode = treeItem;
902 for (int i = 0; i < nodeNames.length; i++) {
903 bot.waitUntil(ConditionHelpers.treeItemHasChildren(treeItem));
904 currentNode.expand();
905
906 String nodeName = nodeNames[i];
907 try {
908 bot.waitUntil(ConditionHelpers.IsTreeChildNodeAvailable(nodeName, currentNode));
909 } catch (TimeoutException e) {
910 // FIXME: Sometimes in a JFace TreeViewer, it expands to
911 // nothing. Need to find out why.
912 currentNode.collapse();
913 currentNode.expand();
914 bot.waitUntil(ConditionHelpers.IsTreeChildNodeAvailable(nodeName, currentNode));
915 }
916
917 SWTBotTreeItem newNode = currentNode.getNode(nodeName);
918 currentNode = newNode;
919 }
920
921 return currentNode;
922 }
923
924 /**
925 * Press the keyboard shortcut that goes to the top of a tree widget. The
926 * key combination can differ on different platforms.
927 *
928 * @param keyboard
929 * the keyboard to use
930 */
931 public static void pressShortcutGoToTreeTop(Keyboard keyboard) {
932 if (SWTUtils.isMac()) {
933 keyboard.pressShortcut(Keystrokes.ALT, Keystrokes.UP);
934 } else {
935 keyboard.pressShortcut(Keystrokes.HOME);
936 }
937 }
938
939 /**
940 * Get the active events editor. Note that this will wait until such editor
941 * is available.
942 *
943 * @param workbenchBot
944 * a given workbench bot
945 * @return the active events editor
946 */
947 public static SWTBotEditor activeEventsEditor(final SWTWorkbenchBot workbenchBot) {
948 ConditionHelpers.ActiveEventsEditor condition = new ConditionHelpers.ActiveEventsEditor(workbenchBot, null);
949 workbenchBot.waitUntil(condition);
950 return condition.getActiveEditor();
951 }
952
953 /**
954 * Get the active events editor. Note that this will wait until such editor
955 * is available.
956 *
957 * @param workbenchBot
958 * a given workbench bot
959 * @param editorTitle
960 * the desired editor title. If null, any active events editor
961 * will be considered valid.
962 * @return the active events editor
963 */
964 public static SWTBotEditor activeEventsEditor(final SWTWorkbenchBot workbenchBot, String editorTitle) {
965 ConditionHelpers.ActiveEventsEditor condition = new ConditionHelpers.ActiveEventsEditor(workbenchBot, editorTitle);
966 workbenchBot.waitUntil(condition);
967 return condition.getActiveEditor();
968 }
969
970 /**
971 * Open the preferences dialog and return the corresponding shell.
972 *
973 * @param bot
974 * a given workbench bot
975 * @return the preferences shell
976 */
977 public static SWTBotShell openPreferences(SWTBot bot) {
978 if (SWTUtils.isMac()) {
979 // On Mac, the Preferences menu item is under the application name.
980 // For some reason, we can't access the application menu anymore so
981 // we use the keyboard shortcut.
982 try {
983 bot.activeShell().pressShortcut(KeyStroke.getInstance(IKeyLookup.COMMAND_NAME + "+"), KeyStroke.getInstance(","));
984 } catch (ParseException e) {
985 fail();
986 }
987 } else {
988 bot.menu(WINDOW_MENU).menu(PREFERENCES_MENU_ITEM).click();
989 }
990
991 bot.waitUntil(Conditions.shellIsActive(PREFERENCES_MENU_ITEM));
992 return bot.activeShell();
993 }
994 }
This page took 0.052881 seconds and 5 git commands to generate.