tmf: Add a more reliable way to get the active editor with SWTBot
[deliverable/tracecompass.git] / tmf / org.eclipse.tracecompass.tmf.ui.swtbot.tests / shared / org / eclipse / tracecompass / tmf / ui / swtbot / tests / shared / SWTBotUtils.java
1 /*******************************************************************************
2 * Copyright (c) 2014, 2015 Ericsson
3 *
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 *
9 * Contributors:
10 * Matthew Khouzam - Initial API and implementation
11 *******************************************************************************/
12
13 package org.eclipse.tracecompass.tmf.ui.swtbot.tests.shared;
14
15 import static org.junit.Assert.assertNotNull;
16 import static org.junit.Assert.assertTrue;
17 import static org.junit.Assert.fail;
18
19 import java.util.List;
20
21 import org.eclipse.core.resources.IProject;
22 import org.eclipse.core.resources.IResource;
23 import org.eclipse.core.resources.ResourcesPlugin;
24 import org.eclipse.core.runtime.CoreException;
25 import org.eclipse.core.runtime.IPath;
26 import org.eclipse.core.runtime.NullProgressMonitor;
27 import org.eclipse.core.runtime.jobs.Job;
28 import org.eclipse.jface.bindings.keys.IKeyLookup;
29 import org.eclipse.jface.bindings.keys.KeyStroke;
30 import org.eclipse.jface.bindings.keys.ParseException;
31 import org.eclipse.swt.graphics.Point;
32 import org.eclipse.swt.graphics.Rectangle;
33 import org.eclipse.swt.widgets.Display;
34 import org.eclipse.swt.widgets.Table;
35 import org.eclipse.swt.widgets.TableItem;
36 import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
37 import org.eclipse.swtbot.eclipse.finder.matchers.WidgetMatcherFactory;
38 import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor;
39 import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView;
40 import org.eclipse.swtbot.swt.finder.SWTBot;
41 import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable;
42 import org.eclipse.swtbot.swt.finder.results.Result;
43 import org.eclipse.swtbot.swt.finder.results.VoidResult;
44 import org.eclipse.swtbot.swt.finder.waits.Conditions;
45 import org.eclipse.swtbot.swt.finder.waits.DefaultCondition;
46 import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton;
47 import org.eclipse.swtbot.swt.finder.widgets.SWTBotCheckBox;
48 import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu;
49 import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
50 import org.eclipse.swtbot.swt.finder.widgets.SWTBotTable;
51 import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
52 import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
53 import org.eclipse.tracecompass.tmf.ui.editors.TmfEventsEditor;
54 import org.eclipse.tracecompass.tmf.ui.project.model.TmfOpenTraceHelper;
55 import org.eclipse.tracecompass.tmf.ui.project.model.TmfProjectRegistry;
56 import org.eclipse.tracecompass.tmf.ui.project.model.TmfTraceFolder;
57 import org.eclipse.tracecompass.tmf.ui.project.model.TmfTracesFolder;
58 import org.eclipse.tracecompass.tmf.ui.swtbot.tests.shared.ConditionHelpers.ProjectElementHasChild;
59 import org.eclipse.tracecompass.tmf.ui.views.TracingPerspectiveFactory;
60 import org.eclipse.ui.IEditorPart;
61 import org.eclipse.ui.IEditorReference;
62 import org.eclipse.ui.IPageLayout;
63 import org.eclipse.ui.PartInitException;
64 import org.eclipse.ui.PlatformUI;
65 import org.eclipse.ui.WorkbenchException;
66 import org.hamcrest.Matcher;
67
68 /**
69 * SWTBot Helper functions
70 *
71 * @author Matthew Khouzam
72 */
73 public final class SWTBotUtils {
74
75 private SWTBotUtils() {
76 }
77
78 private static final String TRACING_PERSPECTIVE_ID = TracingPerspectiveFactory.ID;
79
80 /**
81 * Waits for all Eclipse jobs to finish
82 */
83 public static void waitForJobs() {
84 while (!Job.getJobManager().isIdle()) {
85 delay(100);
86 }
87 }
88
89 /**
90 * Sleeps current thread for a given time.
91 *
92 * @param waitTimeMillis
93 * time in milliseconds to wait
94 */
95 public static void delay(final long waitTimeMillis) {
96 try {
97 Thread.sleep(waitTimeMillis);
98 } catch (final InterruptedException e) {
99 // Ignored
100 }
101 }
102
103 /**
104 * Create a tracing project
105 *
106 * @param projectName
107 * the name of the tracing project
108 */
109 public static void createProject(final String projectName) {
110 /*
111 * Make a new test
112 */
113 UIThreadRunnable.syncExec(new VoidResult() {
114 @Override
115 public void run() {
116 IProject project = TmfProjectRegistry.createProject(projectName, null, new NullProgressMonitor());
117 assertNotNull(project);
118 }
119 });
120
121 SWTBotUtils.waitForJobs();
122 }
123
124 /**
125 * Deletes a project
126 *
127 * @param projectName
128 * the name of the tracing project
129 * @param deleteResources
130 * whether or not to deleted resources under the project
131 * @param bot
132 * the workbench bot
133 */
134 public static void deleteProject(final String projectName, boolean deleteResources, SWTWorkbenchBot bot) {
135 // Wait for any analysis to complete because it might create
136 // supplementary files
137 SWTBotUtils.waitForJobs();
138 try {
139 ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).refreshLocal(IResource.DEPTH_INFINITE, null);
140 } catch (CoreException e) {
141 }
142
143 SWTBotUtils.waitForJobs();
144
145 final SWTBotView projectViewBot = bot.viewById(IPageLayout.ID_PROJECT_EXPLORER);
146 projectViewBot.setFocus();
147
148 SWTBotTree treeBot = projectViewBot.bot().tree();
149 SWTBotTreeItem treeItem = treeBot.getTreeItem(projectName);
150 SWTBotMenu contextMenu = treeItem.contextMenu("Delete");
151 contextMenu.click();
152
153 if (deleteResources) {
154 bot.shell("Delete Resources").setFocus();
155 final SWTBotCheckBox checkBox = bot.checkBox();
156 bot.waitUntil(Conditions.widgetIsEnabled(checkBox));
157 checkBox.click();
158 }
159
160 final SWTBotButton okButton = bot.button("OK");
161 bot.waitUntil(Conditions.widgetIsEnabled(okButton));
162 okButton.click();
163
164 SWTBotUtils.waitForJobs();
165 }
166
167 /**
168 * Deletes a project and its resources
169 *
170 * @param projectName
171 * the name of the tracing project
172 * @param bot
173 * the workbench bot
174 */
175 public static void deleteProject(String projectName, SWTWorkbenchBot bot) {
176 deleteProject(projectName, true, bot);
177 }
178
179 /**
180 * Focus on the main window
181 *
182 * @param shellBots
183 * swtbotshells for all the shells
184 */
185 public static void focusMainWindow(SWTBotShell[] shellBots) {
186 for (SWTBotShell shellBot : shellBots) {
187 if (shellBot.getText().toLowerCase().contains("eclipse")) {
188 shellBot.activate();
189 }
190 }
191 }
192
193 /**
194 * Close a view with a title
195 *
196 * @param title
197 * the title, like "welcome"
198 * @param bot
199 * the workbench bot
200 */
201 public static void closeView(String title, SWTWorkbenchBot bot) {
202 final List<SWTBotView> openViews = bot.views();
203 for (SWTBotView view : openViews) {
204 if (view.getTitle().equalsIgnoreCase(title)) {
205 view.close();
206 bot.waitUntil(ConditionHelpers.ViewIsClosed(view));
207 }
208 }
209 }
210
211 /**
212 * Close a view with an id
213 *
214 * @param viewId
215 * the view id, like "org.eclipse.linuxtools.tmf.ui.views.histogram"
216 * @param bot
217 * the workbench bot
218 */
219 public static void closeViewById(String viewId, SWTWorkbenchBot bot) {
220 final SWTBotView view = bot.viewById(viewId);
221 view.close();
222 bot.waitUntil(ConditionHelpers.ViewIsClosed(view));
223 }
224
225 /**
226 * Switch to the tracing perspective
227 */
228 public static void switchToTracingPerspective() {
229 switchToPerspective(TRACING_PERSPECTIVE_ID);
230 }
231
232 /**
233 * Switch to a given perspective
234 *
235 * @param id
236 * the perspective id (like
237 * "org.eclipse.linuxtools.tmf.ui.perspective"
238 */
239 public static void switchToPerspective(final String id) {
240 UIThreadRunnable.syncExec(new VoidResult() {
241 @Override
242 public void run() {
243 try {
244 PlatformUI.getWorkbench().showPerspective(id, PlatformUI.getWorkbench().getActiveWorkbenchWindow());
245 } catch (WorkbenchException e) {
246 fail(e.getMessage());
247 }
248 }
249 });
250 }
251
252 /**
253 * If the test is running in the UI thread then fail
254 */
255 public static void failIfUIThread() {
256 if (Display.getCurrent() != null && Display.getCurrent().getThread() == Thread.currentThread()) {
257 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"
258 + " that useUIThread is set to false in the pom.xml");
259 }
260
261 }
262
263 /**
264 * Open a trace, this does not perform any validation though
265 *
266 * @param projectName
267 * The project name
268 * @param tracePath
269 * the path of the trace file (absolute or relative)
270 * @param traceType
271 * the trace type id (eg: org.eclipse.linuxtools.btf.trace)
272 */
273 public static void openTrace(final String projectName, final String tracePath, final String traceType) {
274 openTrace(projectName, tracePath, traceType, true);
275 }
276
277 /**
278 * Open a trace, this does not perform any validation though
279 *
280 * @param projectName
281 * The project name
282 * @param tracePath
283 * the path of the trace file (absolute or relative)
284 * @param traceType
285 * the trace type id (eg: org.eclipse.linuxtools.btf.trace)
286 * @param delay
287 * delay and wait for jobs
288 */
289 public static void openTrace(final String projectName, final String tracePath, final String traceType, boolean delay) {
290 final Exception exception[] = new Exception[1];
291 exception[0] = null;
292 UIThreadRunnable.syncExec(new VoidResult() {
293 @Override
294 public void run() {
295 try {
296 IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
297 TmfTraceFolder destinationFolder = TmfProjectRegistry.getProject(project, true).getTracesFolder();
298 TmfOpenTraceHelper.openTraceFromPath(destinationFolder, tracePath, PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), traceType);
299 } catch (CoreException e) {
300 exception[0] = e;
301 }
302 }
303 });
304 if (exception[0] != null) {
305 fail(exception[0].getMessage());
306 }
307
308 if (delay) {
309 delay(1000);
310 waitForJobs();
311 }
312 }
313
314 /**
315 * Finds an editor and sets focus to the editor
316 *
317 * @param bot
318 * the workbench bot
319 * @param editorName
320 * the editor name
321 * @return the corresponding SWTBotEditor
322 */
323 public static SWTBotEditor activateEditor(SWTWorkbenchBot bot, String editorName) {
324 Matcher<IEditorReference> matcher = WidgetMatcherFactory.withPartName(editorName);
325 final SWTBotEditor editorBot = bot.editor(matcher);
326 IEditorPart iep = editorBot.getReference().getEditor(true);
327 final TmfEventsEditor tmfEd = (TmfEventsEditor) iep;
328 editorBot.show();
329 UIThreadRunnable.syncExec(new VoidResult() {
330 @Override
331 public void run() {
332 tmfEd.setFocus();
333 }
334 });
335
336 SWTBotUtils.waitForJobs();
337 SWTBotUtils.delay(1000);
338 assertNotNull(tmfEd);
339 return editorBot;
340 }
341
342 /**
343 * Opens a trace in an editor and get the TmfEventsEditor
344 *
345 * @param bot
346 * the workbench bot
347 * @param projectName
348 * the name of the project that contains the trace
349 * @param elementPath
350 * the trace element path (relative to Traces folder)
351 * @return TmfEventsEditor the opened editor
352 */
353 public static TmfEventsEditor openEditor(SWTWorkbenchBot bot, String projectName, IPath elementPath) {
354 final SWTBotView projectExplorerView = bot.viewById(IPageLayout.ID_PROJECT_EXPLORER);
355 projectExplorerView.setFocus();
356 SWTBot projectExplorerBot = projectExplorerView.bot();
357
358 final SWTBotTree tree = projectExplorerBot.tree();
359 projectExplorerBot.waitUntil(ConditionHelpers.IsTreeNodeAvailable(projectName, tree));
360 final SWTBotTreeItem treeItem = tree.getTreeItem(projectName);
361 treeItem.expand();
362
363 SWTBotTreeItem tracesNode = getTraceProjectItem(projectExplorerBot, treeItem, TmfTracesFolder.TRACES_FOLDER_NAME);
364 tracesNode.expand();
365
366 SWTBotTreeItem currentItem = tracesNode;
367 for (String segment : elementPath.segments()) {
368 currentItem = getTraceProjectItem(projectExplorerBot, currentItem, segment);
369 currentItem.select();
370 currentItem.doubleClick();
371 }
372
373 SWTBotEditor editor = bot.editorByTitle(elementPath.toString());
374 IEditorPart editorPart = editor.getReference().getEditor(false);
375 assertTrue(editorPart instanceof TmfEventsEditor);
376 return (TmfEventsEditor) editorPart;
377 }
378
379 /**
380 * Returns the child tree item of the specified item with the given name.
381 * The project element label may have a count suffix in the format ' [n]'.
382 *
383 * @param bot
384 * a given workbench bot
385 * @param parentItem
386 * the parent tree item
387 * @param name
388 * the desired child element name (without suffix)
389 * @return the a {@link SWTBotTreeItem} with the specified name
390 */
391 public static SWTBotTreeItem getTraceProjectItem(SWTBot bot, final SWTBotTreeItem parentItem, final String name) {
392 ProjectElementHasChild condition = new ProjectElementHasChild(parentItem, name);
393 bot.waitUntil(condition);
394 return condition.getItem();
395 }
396
397 /**
398 * Select the traces folder
399 *
400 * @param bot
401 * a given workbench bot
402 * @param projectName
403 * the name of the project (it needs to exist or else it would
404 * time out)
405 * @return a {@link SWTBotTreeItem} of the "Traces" folder
406 */
407 public static SWTBotTreeItem selectTracesFolder(SWTWorkbenchBot bot, String projectName) {
408 SWTBotTreeItem projectTreeItem = selectProject(bot, projectName);
409 projectTreeItem.select();
410 SWTBotTreeItem tracesFolderItem = getTraceProjectItem(bot, projectTreeItem, TmfTracesFolder.TRACES_FOLDER_NAME);
411 tracesFolderItem.select();
412 return tracesFolderItem;
413 }
414
415 /**
416 * Select the project in Project Explorer
417 *
418 * @param bot
419 * a given workbench bot
420 * @param projectName
421 * the name of the project (it needs to exist or else it would time out)
422 * @return a {@link SWTBotTreeItem} of the project
423 */
424 public static SWTBotTreeItem selectProject(SWTWorkbenchBot bot, String projectName) {
425 SWTBotView projectExplorerBot = bot.viewByTitle("Project Explorer");
426 projectExplorerBot.show();
427 SWTBotTreeItem treeItem = projectExplorerBot.bot().tree().getTreeItem(projectName);
428 treeItem.select();
429 return treeItem;
430 }
431
432 /**
433 * Open a view by id.
434 *
435 * @param id
436 * view id.
437 */
438 public static void openView(final String id) {
439 final PartInitException res[] = new PartInitException[1];
440 UIThreadRunnable.syncExec(new VoidResult() {
441 @Override
442 public void run() {
443 try {
444 PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(id);
445 } catch (PartInitException e) {
446 res[0] = e;
447 }
448 }
449 });
450 if (res[0] != null) {
451 fail(res[0].getMessage());
452 }
453 waitForJobs();
454 }
455
456 /**
457 * Maximize a table
458 *
459 * @param tableBot
460 * the {@link SWTBotTable} table
461 */
462 public static void maximizeTable(SWTBotTable tableBot) {
463 try {
464 tableBot.pressShortcut(KeyStroke.getInstance(IKeyLookup.CTRL_NAME + "+"), KeyStroke.getInstance("M"));
465 } catch (ParseException e) {
466 fail();
467 }
468 }
469
470 /**
471 * Get the bounds of a cell (SWT.Rectangle) for the specified row and column
472 * index in a table
473 *
474 * @param table
475 * the table
476 * @param row
477 * the row of the table to look up
478 * @param col
479 * the column of the table to look up
480 * @return the bounds in display relative coordinates
481 */
482 public static Rectangle getCellBounds(final Table table, final int row, final int col) {
483 return UIThreadRunnable.syncExec(new Result<Rectangle>() {
484 @Override
485 public Rectangle run() {
486 TableItem item = table.getItem(row);
487 Rectangle bounds = item.getBounds(col);
488 Point p = table.toDisplay(bounds.x, bounds.y);
489 Rectangle rect = new Rectangle(p.x, p.y, bounds.width, bounds.height);
490 return rect;
491 }
492 });
493 }
494
495 /**
496 * Get the tree item from a tree at the specified location
497 *
498 * @param bot
499 * the SWTBot
500 * @param tree
501 * the tree to find the tree item in
502 * @param nodeNames
503 * the path to the tree item, in the form of node names (from
504 * parent to child).
505 * @return the tree item
506 */
507 public static SWTBotTreeItem getTreeItem(SWTBot bot, SWTBotTree tree, String... nodeNames) {
508 if (nodeNames.length == 0) {
509 return null;
510 }
511
512 bot.waitUntil(ConditionHelpers.IsTreeNodeAvailable(nodeNames[0], tree));
513 SWTBotTreeItem currentNode = tree.getTreeItem(nodeNames[0]);
514 for (int i = 1; i < nodeNames.length; i++) {
515 currentNode.expand();
516
517 String nodeName = nodeNames[i];
518 bot.waitUntil(ConditionHelpers.IsTreeChildNodeAvailable(nodeName, currentNode));
519 SWTBotTreeItem newNode = currentNode.getNode(nodeName);
520 currentNode = newNode;
521 }
522
523 return currentNode;
524 }
525
526 /**
527 * Get the active events editor. Note that this will wait until such editor
528 * is available.
529 *
530 * @param workbenchBot
531 * a given workbench bot
532 * @return the active events editor
533 */
534 public static SWTBotEditor activeEventsEditor(final SWTWorkbenchBot workbenchBot) {
535 final SWTBotEditor editor[] = new SWTBotEditor[1];
536 workbenchBot.waitUntil(new DefaultCondition() {
537 @Override
538 public boolean test() throws Exception {
539 List<SWTBotEditor> editors = workbenchBot.editors(WidgetMatcherFactory.withPartId(TmfEventsEditor.ID));
540 for (SWTBotEditor e : editors) {
541 if (e.isActive() && !e.getWidget().isDisposed()) {
542 editor[0] = e;
543 return true;
544 }
545 }
546 return false;
547 }
548
549 @Override
550 public String getFailureMessage() {
551 return "Active events editor not found";
552 }
553 });
554 return editor[0];
555 }
556 }
This page took 0.04475 seconds and 6 git commands to generate.