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