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