releng: Transition to jdt.annotation 2.0
[deliverable/tracecompass.git] / tmf / org.eclipse.tracecompass.tmf.ui / src / org / eclipse / tracecompass / tmf / ui / viewers / events / TmfEventsTable.java
1 /*******************************************************************************
2 * Copyright (c) 2010, 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 * Francois Chouinard - Initial API and implementation, replaced Table by TmfVirtualTable
11 * Patrick Tasse - Factored out from events view,
12 * Filter implementation (inspired by www.eclipse.org/mat)
13 * Ansgar Radermacher - Support navigation to model URIs (Bug 396956)
14 * Bernd Hufmann - Updated call site and model URI implementation
15 * Alexandre Montplaisir - Update to new column API
16 * Matthew Khouzam - Add hide columns
17 *******************************************************************************/
18
19 package org.eclipse.tracecompass.tmf.ui.viewers.events;
20
21 import static org.eclipse.tracecompass.common.core.NonNullUtils.checkNotNull;
22
23 import java.io.File;
24 import java.io.FileNotFoundException;
25 import java.lang.reflect.InvocationTargetException;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.LinkedList;
30 import java.util.List;
31 import java.util.Map.Entry;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34 import java.util.regex.PatternSyntaxException;
35
36 import org.eclipse.core.commands.Command;
37 import org.eclipse.core.commands.ExecutionException;
38 import org.eclipse.core.commands.NotEnabledException;
39 import org.eclipse.core.commands.NotHandledException;
40 import org.eclipse.core.commands.ParameterizedCommand;
41 import org.eclipse.core.commands.common.NotDefinedException;
42 import org.eclipse.core.expressions.IEvaluationContext;
43 import org.eclipse.core.filesystem.EFS;
44 import org.eclipse.core.filesystem.IFileStore;
45 import org.eclipse.core.resources.IFile;
46 import org.eclipse.core.resources.IMarker;
47 import org.eclipse.core.resources.IResource;
48 import org.eclipse.core.resources.IResourceVisitor;
49 import org.eclipse.core.resources.IWorkspaceRunnable;
50 import org.eclipse.core.resources.ResourcesPlugin;
51 import org.eclipse.core.runtime.CoreException;
52 import org.eclipse.core.runtime.IPath;
53 import org.eclipse.core.runtime.IProgressMonitor;
54 import org.eclipse.core.runtime.IStatus;
55 import org.eclipse.core.runtime.ListenerList;
56 import org.eclipse.core.runtime.Path;
57 import org.eclipse.core.runtime.Status;
58 import org.eclipse.core.runtime.jobs.Job;
59 import org.eclipse.emf.common.util.URI;
60 import org.eclipse.emf.ecore.EValidator;
61 import org.eclipse.jdt.annotation.NonNull;
62 import org.eclipse.jface.action.Action;
63 import org.eclipse.jface.action.IAction;
64 import org.eclipse.jface.action.IMenuListener;
65 import org.eclipse.jface.action.IMenuManager;
66 import org.eclipse.jface.action.IStatusLineManager;
67 import org.eclipse.jface.action.MenuManager;
68 import org.eclipse.jface.action.Separator;
69 import org.eclipse.jface.dialogs.MessageDialog;
70 import org.eclipse.jface.operation.IRunnableWithProgress;
71 import org.eclipse.jface.resource.ColorRegistry;
72 import org.eclipse.jface.resource.FontRegistry;
73 import org.eclipse.jface.resource.JFaceResources;
74 import org.eclipse.jface.resource.LocalResourceManager;
75 import org.eclipse.jface.text.BadLocationException;
76 import org.eclipse.jface.text.IDocument;
77 import org.eclipse.jface.text.IRegion;
78 import org.eclipse.jface.util.IPropertyChangeListener;
79 import org.eclipse.jface.util.OpenStrategy;
80 import org.eclipse.jface.util.PropertyChangeEvent;
81 import org.eclipse.jface.util.SafeRunnable;
82 import org.eclipse.jface.viewers.ArrayContentProvider;
83 import org.eclipse.jface.viewers.ISelection;
84 import org.eclipse.jface.viewers.ISelectionChangedListener;
85 import org.eclipse.jface.viewers.ISelectionProvider;
86 import org.eclipse.jface.viewers.LabelProvider;
87 import org.eclipse.jface.viewers.SelectionChangedEvent;
88 import org.eclipse.jface.viewers.StructuredSelection;
89 import org.eclipse.jface.window.Window;
90 import org.eclipse.osgi.util.NLS;
91 import org.eclipse.swt.SWT;
92 import org.eclipse.swt.custom.SashForm;
93 import org.eclipse.swt.custom.StyleRange;
94 import org.eclipse.swt.custom.TableEditor;
95 import org.eclipse.swt.events.ControlAdapter;
96 import org.eclipse.swt.events.ControlEvent;
97 import org.eclipse.swt.events.FocusAdapter;
98 import org.eclipse.swt.events.FocusEvent;
99 import org.eclipse.swt.events.KeyAdapter;
100 import org.eclipse.swt.events.KeyEvent;
101 import org.eclipse.swt.events.MouseAdapter;
102 import org.eclipse.swt.events.MouseEvent;
103 import org.eclipse.swt.events.SelectionAdapter;
104 import org.eclipse.swt.events.SelectionEvent;
105 import org.eclipse.swt.graphics.Color;
106 import org.eclipse.swt.graphics.Font;
107 import org.eclipse.swt.graphics.GC;
108 import org.eclipse.swt.graphics.Image;
109 import org.eclipse.swt.graphics.Point;
110 import org.eclipse.swt.graphics.Rectangle;
111 import org.eclipse.swt.layout.FillLayout;
112 import org.eclipse.swt.layout.GridData;
113 import org.eclipse.swt.layout.GridLayout;
114 import org.eclipse.swt.widgets.Composite;
115 import org.eclipse.swt.widgets.Display;
116 import org.eclipse.swt.widgets.Event;
117 import org.eclipse.swt.widgets.Label;
118 import org.eclipse.swt.widgets.Listener;
119 import org.eclipse.swt.widgets.Menu;
120 import org.eclipse.swt.widgets.MessageBox;
121 import org.eclipse.swt.widgets.Shell;
122 import org.eclipse.swt.widgets.TableColumn;
123 import org.eclipse.swt.widgets.TableItem;
124 import org.eclipse.swt.widgets.Text;
125 import org.eclipse.tracecompass.common.core.NonNullUtils;
126 import org.eclipse.tracecompass.internal.tmf.core.filter.TmfCollapseFilter;
127 import org.eclipse.tracecompass.internal.tmf.ui.Activator;
128 import org.eclipse.tracecompass.internal.tmf.ui.Messages;
129 import org.eclipse.tracecompass.internal.tmf.ui.commands.CopyToClipboardOperation;
130 import org.eclipse.tracecompass.internal.tmf.ui.commands.ExportToTextCommandHandler;
131 import org.eclipse.tracecompass.internal.tmf.ui.dialogs.AddBookmarkDialog;
132 import org.eclipse.tracecompass.tmf.core.component.ITmfEventProvider;
133 import org.eclipse.tracecompass.tmf.core.component.TmfComponent;
134 import org.eclipse.tracecompass.tmf.core.event.ITmfEvent;
135 import org.eclipse.tracecompass.tmf.core.event.aspect.ITmfEventAspect;
136 import org.eclipse.tracecompass.tmf.core.event.aspect.TmfContentFieldAspect;
137 import org.eclipse.tracecompass.tmf.core.event.collapse.ITmfCollapsibleEvent;
138 import org.eclipse.tracecompass.tmf.core.event.lookup.ITmfCallsite;
139 import org.eclipse.tracecompass.tmf.core.event.lookup.ITmfModelLookup;
140 import org.eclipse.tracecompass.tmf.core.event.lookup.ITmfSourceLookup;
141 import org.eclipse.tracecompass.tmf.core.filter.ITmfFilter;
142 import org.eclipse.tracecompass.tmf.core.filter.model.ITmfFilterTreeNode;
143 import org.eclipse.tracecompass.tmf.core.filter.model.TmfFilterAndNode;
144 import org.eclipse.tracecompass.tmf.core.filter.model.TmfFilterMatchesNode;
145 import org.eclipse.tracecompass.tmf.core.filter.model.TmfFilterNode;
146 import org.eclipse.tracecompass.tmf.core.request.ITmfEventRequest.ExecutionType;
147 import org.eclipse.tracecompass.tmf.core.request.TmfEventRequest;
148 import org.eclipse.tracecompass.tmf.core.resources.ITmfMarker;
149 import org.eclipse.tracecompass.tmf.core.signal.TmfEventFilterAppliedSignal;
150 import org.eclipse.tracecompass.tmf.core.signal.TmfEventSearchAppliedSignal;
151 import org.eclipse.tracecompass.tmf.core.signal.TmfEventSelectedSignal;
152 import org.eclipse.tracecompass.tmf.core.signal.TmfSelectionRangeUpdatedSignal;
153 import org.eclipse.tracecompass.tmf.core.signal.TmfSignalHandler;
154 import org.eclipse.tracecompass.tmf.core.signal.TmfTraceUpdatedSignal;
155 import org.eclipse.tracecompass.tmf.core.timestamp.ITmfTimestamp;
156 import org.eclipse.tracecompass.tmf.core.timestamp.TmfNanoTimestamp;
157 import org.eclipse.tracecompass.tmf.core.timestamp.TmfTimeRange;
158 import org.eclipse.tracecompass.tmf.core.timestamp.TmfTimestamp;
159 import org.eclipse.tracecompass.tmf.core.trace.ITmfContext;
160 import org.eclipse.tracecompass.tmf.core.trace.ITmfTrace;
161 import org.eclipse.tracecompass.tmf.core.trace.TmfTrace;
162 import org.eclipse.tracecompass.tmf.core.trace.TmfTraceManager;
163 import org.eclipse.tracecompass.tmf.core.trace.location.ITmfLocation;
164 import org.eclipse.tracecompass.tmf.ui.viewers.events.TmfEventsCache.CachedEvent;
165 import org.eclipse.tracecompass.tmf.ui.viewers.events.columns.TmfEventTableColumn;
166 import org.eclipse.tracecompass.tmf.ui.views.colors.ColorSetting;
167 import org.eclipse.tracecompass.tmf.ui.views.colors.ColorSettingsManager;
168 import org.eclipse.tracecompass.tmf.ui.views.colors.IColorSettingsListener;
169 import org.eclipse.tracecompass.tmf.ui.views.filter.FilterManager;
170 import org.eclipse.tracecompass.tmf.ui.widgets.rawviewer.TmfRawEventViewer;
171 import org.eclipse.tracecompass.tmf.ui.widgets.virtualtable.TmfVirtualTable;
172 import org.eclipse.ui.IEditorSite;
173 import org.eclipse.ui.IEditorPart;
174 import org.eclipse.ui.IWorkbenchPage;
175 import org.eclipse.ui.IWorkbenchPartSite;
176 import org.eclipse.ui.PlatformUI;
177 import org.eclipse.ui.commands.ICommandService;
178 import org.eclipse.ui.dialogs.ListDialog;
179 import org.eclipse.ui.handlers.IHandlerService;
180 import org.eclipse.ui.ide.IDE;
181 import org.eclipse.ui.ide.IGotoMarker;
182 import org.eclipse.ui.texteditor.ITextEditor;
183 import org.eclipse.ui.themes.ColorUtil;
184 import org.eclipse.ui.themes.IThemeManager;
185
186 import com.google.common.base.Joiner;
187 import com.google.common.collect.HashMultimap;
188 import com.google.common.collect.ImmutableList;
189 import com.google.common.collect.Multimap;
190
191 /**
192 * The generic TMF Events table
193 *
194 * This is a view that will list events that are read from a trace.
195 *
196 * @author Francois Chouinard
197 * @author Patrick Tasse
198 */
199 public class TmfEventsTable extends TmfComponent implements IGotoMarker, IColorSettingsListener, ISelectionProvider, IPropertyChangeListener {
200
201 /**
202 * Empty string array, used by {@link #getItemStrings}.
203 */
204 protected static final String @NonNull [] EMPTY_STRING_ARRAY = new String[0];
205
206 /**
207 * Empty string
208 */
209 protected static final @NonNull String EMPTY_STRING = ""; //$NON-NLS-1$
210
211 private static final boolean IS_LINUX = System.getProperty("os.name").contains("Linux") ? true : false; //$NON-NLS-1$ //$NON-NLS-2$
212
213 private static final String FONT_DEFINITION_ID = "org.eclipse.tracecompass.tmf.ui.font.eventtable"; //$NON-NLS-1$
214 private static final String HIGHLIGHT_COLOR_DEFINITION_ID = "org.eclipse.tracecompass.tmf.ui.color.eventtable.highlight"; //$NON-NLS-1$
215
216 private static final Image BOOKMARK_IMAGE = Activator.getDefault().getImageFromPath(
217 "icons/elcl16/bookmark_obj.gif"); //$NON-NLS-1$
218 private static final Image SEARCH_IMAGE = Activator.getDefault().getImageFromPath("icons/elcl16/search.gif"); //$NON-NLS-1$
219 private static final Image SEARCH_MATCH_IMAGE = Activator.getDefault().getImageFromPath(
220 "icons/elcl16/search_match.gif"); //$NON-NLS-1$
221 private static final Image SEARCH_MATCH_BOOKMARK_IMAGE = Activator.getDefault().getImageFromPath(
222 "icons/elcl16/search_match_bookmark.gif"); //$NON-NLS-1$
223 private static final Image FILTER_IMAGE = Activator.getDefault().getImageFromPath("icons/elcl16/filter_items.gif"); //$NON-NLS-1$
224 private static final Image STOP_IMAGE = Activator.getDefault().getImageFromPath("icons/elcl16/stop.gif"); //$NON-NLS-1$
225 private static final String SEARCH_HINT = Messages.TmfEventsTable_SearchHint;
226 private static final String FILTER_HINT = Messages.TmfEventsTable_FilterHint;
227 private static final int MAX_CACHE_SIZE = 1000;
228
229 private static final int MARGIN_COLUMN_INDEX = 0;
230 private static final int FILTER_SUMMARY_INDEX = 1;
231 private static final int EVENT_COLUMNS_START_INDEX = MARGIN_COLUMN_INDEX + 1;
232
233 private final class ColumnMovedListener extends ControlAdapter {
234 /*
235 * Make sure that the margin column is always first and keep the
236 * column order variable up to date.
237 */
238 @Override
239 public void controlMoved(ControlEvent e) {
240 int[] order = fTable.getColumnOrder();
241 if (order[0] == MARGIN_COLUMN_INDEX) {
242 fColumnOrder = order;
243 return;
244 }
245 for (int i = order.length - 1; i > 0; i--) {
246 if (order[i] == MARGIN_COLUMN_INDEX) {
247 order[i] = order[i - 1];
248 order[i - 1] = MARGIN_COLUMN_INDEX;
249 }
250 }
251 fTable.setColumnOrder(order);
252 fColumnOrder = fTable.getColumnOrder();
253 }
254 }
255
256 private final class TableSelectionListener extends SelectionAdapter {
257 @Override
258 public void widgetSelected(final SelectionEvent e) {
259 if (e.item == null) {
260 return;
261 }
262 updateStatusLine(null);
263 if (fTable.getSelectionIndices().length > 0) {
264 if (e.item.getData(Key.RANK) instanceof Long) {
265 fSelectedRank = (Long) e.item.getData(Key.RANK);
266 fRawViewer.selectAndReveal((Long) e.item.getData(Key.RANK));
267 } else {
268 fSelectedRank = -1;
269 }
270 if (fTable.getSelectionIndices().length == 1) {
271 fSelectedBeginRank = fSelectedRank;
272 }
273 if (e.item.getData(Key.TIMESTAMP) instanceof ITmfTimestamp) {
274 final ITmfTimestamp ts = NonNullUtils.checkNotNull((ITmfTimestamp) e.item.getData(Key.TIMESTAMP));
275 if (fTable.getSelectionIndices().length == 1) {
276 fSelectedBeginTimestamp = ts;
277 }
278 ITmfTimestamp selectedBeginTimestamp = fSelectedBeginTimestamp;
279 if (selectedBeginTimestamp != null) {
280 broadcast(new TmfSelectionRangeUpdatedSignal(TmfEventsTable.this, selectedBeginTimestamp, ts));
281 if (fTable.getSelectionIndices().length == 2) {
282 updateStatusLine(ts.getDelta(selectedBeginTimestamp));
283 }
284 }
285 } else {
286 if (fTable.getSelectionIndices().length == 1) {
287 fSelectedBeginTimestamp = null;
288 }
289 }
290 }
291 if (e.item.getData() instanceof ITmfEvent) {
292 broadcast(new TmfEventSelectedSignal(TmfEventsTable.this, (ITmfEvent) e.item.getData()));
293 fireSelectionChanged(new SelectionChangedEvent(TmfEventsTable.this, new StructuredSelection(e.item.getData())));
294 } else {
295 fireSelectionChanged(new SelectionChangedEvent(TmfEventsTable.this, StructuredSelection.EMPTY));
296 }
297 }
298 }
299
300 private final class MouseDoubleClickListener extends MouseAdapter {
301 @Override
302 public void mouseDoubleClick(final MouseEvent event) {
303 if (event.button != 1) {
304 return;
305 }
306 // Identify the selected row
307 final Point point = new Point(event.x, event.y);
308 final TableItem item = fTable.getItem(point);
309 if (item != null) {
310 final Rectangle imageBounds = item.getImageBounds(0);
311 imageBounds.width = BOOKMARK_IMAGE.getBounds().width;
312 if (imageBounds.contains(point)) {
313 final Long rank = (Long) item.getData(Key.RANK);
314 if (rank != null) {
315 toggleBookmark(rank);
316 }
317 }
318 }
319 }
320 }
321
322 private final class RawSelectionListener implements Listener {
323 @Override
324 public void handleEvent(final Event e) {
325 if (fTrace == null) {
326 return;
327 }
328 long rank;
329 if (e.data instanceof Long) {
330 rank = (Long) e.data;
331 } else if (e.data instanceof ITmfLocation) {
332 rank = findRank((ITmfLocation) e.data);
333 } else {
334 return;
335 }
336 int index = (int) rank;
337 if (fTable.getData(Key.FILTER_OBJ) != null) {
338 // +1 for top filter status row
339 index = fCache.getFilteredEventIndex(rank) + 1;
340 }
341 // +1 for header row
342 fTable.setSelection(index + 1);
343 fSelectedRank = rank;
344 fSelectedBeginRank = fSelectedRank;
345 updateStatusLine(null);
346 final TableItem[] selection = fTable.getSelection();
347 if ((selection != null) && (selection.length > 0)) {
348 TableItem item = fTable.getSelection()[0];
349 final TmfTimestamp ts = (TmfTimestamp) item.getData(Key.TIMESTAMP);
350 if (ts != null) {
351 broadcast(new TmfSelectionRangeUpdatedSignal(TmfEventsTable.this, ts));
352 }
353 if (item.getData() instanceof ITmfEvent) {
354 broadcast(new TmfEventSelectedSignal(TmfEventsTable.this, (ITmfEvent) item.getData()));
355 fireSelectionChanged(new SelectionChangedEvent(TmfEventsTable.this, new StructuredSelection(item.getData())));
356 } else {
357 fireSelectionChanged(new SelectionChangedEvent(TmfEventsTable.this, StructuredSelection.EMPTY));
358 }
359 }
360 }
361
362 private long findRank(final ITmfLocation selectedLocation) {
363 final double selectedRatio = fTrace.getLocationRatio(selectedLocation);
364 long low = 0;
365 long high = fTrace.getNbEvents();
366 long rank = high / 2;
367 double ratio = -1;
368 while (ratio != selectedRatio) {
369 ITmfContext context = fTrace.seekEvent(rank);
370 ratio = fTrace.getLocationRatio(context.getLocation());
371 context.dispose();
372 if (ratio < selectedRatio) {
373 low = rank;
374 rank = (rank + high) / 2;
375 } else if (ratio > selectedRatio) {
376 high = rank;
377 rank = (rank + low) / 2;
378 }
379 if ((high - low) < 2) {
380 break;
381 }
382 }
383 return rank;
384 }
385 }
386
387 private final class SetDataListener implements Listener {
388 @Override
389 public void handleEvent(final Event event) {
390
391 final TableItem item = (TableItem) event.item;
392 int index = event.index - 1; // -1 for the header row
393
394 if (event.index == 0) {
395 setHeaderRowItemData(item);
396 return;
397 }
398
399 if (fTable.getData(Key.FILTER_OBJ) != null) {
400 if ((event.index == 1) || (event.index == (fTable.getItemCount() - 1))) {
401 setFilterStatusRowItemData(item);
402 return;
403 }
404 /* -1 for top filter status row */
405 index = index - 1;
406 }
407
408 final CachedEvent cachedEvent = fCache.getEvent(index);
409 if (cachedEvent != null) {
410 setItemData(item, cachedEvent, cachedEvent.rank);
411 return;
412 }
413
414 // Else, fill the cache asynchronously (and off the UI thread)
415 event.doit = false;
416 }
417 }
418
419 private final class PainItemListener implements Listener {
420 @Override
421 public void handleEvent(Event event) {
422 TableItem item = (TableItem) event.item;
423
424 // we promised to paint the table item's foreground
425 GC gc = event.gc;
426 Image image = item.getImage(event.index);
427 if (image != null) {
428 Rectangle imageBounds = item.getImageBounds(event.index);
429 /*
430 * The image bounds don't match the default image position.
431 */
432 if (IS_LINUX) {
433 gc.drawImage(image, imageBounds.x + 1, imageBounds.y + 3);
434 } else {
435 gc.drawImage(image, imageBounds.x, imageBounds.y + 1);
436 }
437 }
438 gc.setForeground(item.getForeground(event.index));
439 gc.setFont(item.getFont(event.index));
440 String text = item.getText(event.index);
441 Rectangle textBounds = item.getTextBounds(event.index);
442 /*
443 * The text bounds don't match the default text position.
444 */
445 if (IS_LINUX) {
446 gc.drawText(text, textBounds.x + 1, textBounds.y + 3, true);
447 } else {
448 gc.drawText(text, textBounds.x - 1, textBounds.y + 2, true);
449 }
450 }
451 }
452
453 private final class EraseItemListener implements Listener {
454 @Override
455 public void handleEvent(Event event) {
456 TableItem item = (TableItem) event.item;
457 List<?> styleRanges = (List<?>) item.getData(Key.STYLE_RANGES);
458
459 GC gc = event.gc;
460 Color background = item.getBackground(event.index);
461 /*
462 * Paint the background if it is not the default system color.
463 * In Windows, if you let the widget draw the background, it
464 * will not show the item's background color if the item is
465 * selected or hot. If there are no style ranges and the item
466 * background is the default system color, we do not want to
467 * paint it or otherwise we would override the platform theme
468 * (e.g. alternating colors).
469 */
470 if (styleRanges != null || !background.equals(item.getParent().getBackground())) {
471 // we will paint the table item's background
472 event.detail &= ~SWT.BACKGROUND;
473
474 // paint the item's default background
475 gc.setBackground(background);
476 gc.fillRectangle(event.x, event.y, event.width, event.height);
477 }
478
479 /*
480 * We will paint the table item's foreground. In Windows, if you
481 * paint the background but let the widget draw the foreground,
482 * it will override your background, unless the item is selected
483 * or hot.
484 */
485 event.detail &= ~SWT.FOREGROUND;
486
487 // paint the highlighted background for all style ranges
488 if (styleRanges != null) {
489 Rectangle textBounds = item.getTextBounds(event.index);
490 String text = item.getText(event.index);
491 for (Object o : styleRanges) {
492 if (o instanceof StyleRange) {
493 StyleRange styleRange = (StyleRange) o;
494 if (styleRange.data.equals(event.index)) {
495 int startIndex = styleRange.start;
496 int endIndex = startIndex + styleRange.length;
497 int startX = gc.textExtent(text.substring(0, startIndex)).x;
498 int endX = gc.textExtent(text.substring(0, endIndex)).x;
499 gc.setBackground(styleRange.background);
500 gc.fillRectangle(textBounds.x + startX, textBounds.y, (endX - startX), textBounds.height);
501 }
502 }
503 }
504 }
505 }
506 }
507
508 private final class TooltipListener implements Listener {
509 Shell tooltipShell = null;
510
511 @Override
512 public void handleEvent(final Event event) {
513 switch (event.type) {
514 case SWT.MouseHover:
515 final TableItem item = fTable.getItem(new Point(event.x, event.y));
516 if (item == null) {
517 return;
518 }
519 final Long rank = (Long) item.getData(Key.RANK);
520 if (rank == null) {
521 return;
522 }
523 final String tooltipText = (String) item.getData(Key.BOOKMARK);
524 final Rectangle bounds = item.getImageBounds(0);
525 bounds.width = BOOKMARK_IMAGE.getBounds().width;
526 if (!bounds.contains(event.x, event.y)) {
527 return;
528 }
529 if ((tooltipShell != null) && !tooltipShell.isDisposed()) {
530 tooltipShell.dispose();
531 }
532 tooltipShell = new Shell(fTable.getShell(), SWT.ON_TOP | SWT.NO_FOCUS | SWT.TOOL);
533 tooltipShell.setBackground(PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND));
534 final FillLayout layout = new FillLayout();
535 layout.marginWidth = 2;
536 tooltipShell.setLayout(layout);
537 final Label label = new Label(tooltipShell, SWT.WRAP);
538 String text = rank.toString() + (tooltipText != null ? ": " + tooltipText : EMPTY_STRING); //$NON-NLS-1$
539 label.setForeground(PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND));
540 label.setBackground(PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND));
541 label.setText(text);
542 label.addListener(SWT.MouseExit, this);
543 label.addListener(SWT.MouseDown, this);
544 label.addListener(SWT.MouseWheel, this);
545 final Point size = tooltipShell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
546 /*
547 * Bug in Linux. The coordinates of the event have an origin
548 * that excludes the table header but the method toDisplay()
549 * expects coordinates relative to an origin that includes
550 * the table header.
551 */
552 int y = event.y;
553 if (IS_LINUX) {
554 y += fTable.getHeaderHeight();
555 }
556 Point pt = fTable.toDisplay(event.x, y);
557 pt.x += BOOKMARK_IMAGE.getBounds().width;
558 pt.y += item.getBounds().height;
559 tooltipShell.setBounds(pt.x, pt.y, size.x, size.y);
560 tooltipShell.setVisible(true);
561 break;
562 case SWT.Dispose:
563 case SWT.KeyDown:
564 case SWT.MouseMove:
565 case SWT.MouseExit:
566 case SWT.MouseDown:
567 case SWT.MouseWheel:
568 if (tooltipShell != null) {
569 tooltipShell.dispose();
570 tooltipShell = null;
571 }
572 break;
573 default:
574 break;
575 }
576 }
577 }
578
579 /**
580 * The events table search/filter/data keys
581 *
582 * @author Patrick Tasse
583 * @noimplement This interface only contains Event Table specific
584 * static definitions.
585 */
586 public interface Key {
587
588 /** Search text */
589 String SEARCH_TXT = "$srch_txt"; //$NON-NLS-1$
590
591 /** Search object */
592 String SEARCH_OBJ = "$srch_obj"; //$NON-NLS-1$
593
594 /** Filter text */
595 String FILTER_TXT = "$fltr_txt"; //$NON-NLS-1$
596
597 /** Filter object */
598 String FILTER_OBJ = "$fltr_obj"; //$NON-NLS-1$
599
600 /** Timestamp */
601 String TIMESTAMP = "$time"; //$NON-NLS-1$
602
603 /** Rank */
604 String RANK = "$rank"; //$NON-NLS-1$
605
606 /** Bookmark indicator */
607 String BOOKMARK = "$bookmark"; //$NON-NLS-1$
608
609 /** Event aspect represented by this column */
610 String ASPECT = "$aspect"; //$NON-NLS-1$
611
612 /**
613 * Table item list of style ranges
614 *
615 * @since 1.0
616 */
617 String STYLE_RANGES = "$style_ranges"; //$NON-NLS-1$
618
619 /**
620 * The width of a table item
621 *
622 * @since 1.1
623 */
624 String WIDTH = "$width"; //$NON-NLS-1$
625 }
626
627 /**
628 * The events table search/filter state
629 *
630 * @version 1.0
631 * @author Patrick Tasse
632 */
633 public static enum HeaderState {
634 /** A search is being run */
635 SEARCH,
636
637 /** A filter is applied */
638 FILTER
639 }
640
641 interface Direction {
642 int FORWARD = +1;
643 int BACKWARD = -1;
644 }
645
646 // ------------------------------------------------------------------------
647 // Table data
648 // ------------------------------------------------------------------------
649
650 /** The virtual event table */
651 protected TmfVirtualTable fTable;
652
653 private Composite fComposite;
654 private SashForm fSashForm;
655 private TmfRawEventViewer fRawViewer;
656 private ITmfTrace fTrace;
657 private volatile boolean fPackDone = false;
658 private HeaderState fHeaderState = HeaderState.SEARCH;
659 private long fSelectedRank = -1;
660 private long fSelectedBeginRank = -1;
661 private ITmfTimestamp fSelectedBeginTimestamp = null;
662 private IStatusLineManager fStatusLineManager = null;
663
664 // Filter data
665 private long fFilterMatchCount;
666 private long fFilterCheckCount;
667 private FilterThread fFilterThread;
668 private boolean fFilterThreadResume = false;
669 private final Object fFilterSyncObj = new Object();
670 private SearchThread fSearchThread;
671 private final Object fSearchSyncObj = new Object();
672
673 /**
674 * List of selection change listeners (element type:
675 * <code>ISelectionChangedListener</code>).
676 *
677 * @see #fireSelectionChanged
678 */
679 private ListenerList selectionChangedListeners = new ListenerList();
680
681 // Bookmark map <Rank, MarkerId>
682 private Multimap<Long, Long> fBookmarksMap = HashMultimap.create();
683 private IFile fBookmarksFile;
684 private long fPendingGotoRank = -1;
685
686 // SWT resources
687 private LocalResourceManager fResourceManager = new LocalResourceManager(JFaceResources.getResources());
688 private Color fGrayColor;
689 private Color fGreenColor;
690 private Color fHighlightColor;
691 private Font fFont;
692 private Font fBoldFont;
693
694 private final List<TmfEventTableColumn> fColumns = new LinkedList<>();
695
696 // Event cache
697 private final TmfEventsCache fCache;
698 private boolean fCacheUpdateBusy = false;
699 private boolean fCacheUpdatePending = false;
700 private boolean fCacheUpdateCompleted = false;
701 private final Object fCacheUpdateSyncObj = new Object();
702
703 // Keep track of column order, it is needed after table is disposed
704 private int[] fColumnOrder;
705
706 private boolean fDisposeOnClose;
707
708 private Menu fHeaderMenu;
709
710 private Menu fTablePopup;
711
712 private Menu fRawTablePopup;
713
714 private Point fLastMenuCursorLocation;
715 private MenuManager fRawViewerPopupMenuManager;
716 private MenuManager fTablePopupMenuManager;
717 private MenuManager fHeaderPopupMenuManager;
718
719 // ------------------------------------------------------------------------
720 // Constructors
721 // ------------------------------------------------------------------------
722
723 /**
724 * Basic constructor, using the default set of columns
725 *
726 * @param parent
727 * The parent composite UI object
728 * @param cacheSize
729 * The size of the event table cache
730 */
731 public TmfEventsTable(final Composite parent, final int cacheSize) {
732 this(parent, cacheSize, TmfTrace.BASE_ASPECTS);
733 }
734
735 /**
736 * Legacy constructor, using ColumnData to define columns
737 *
738 * @param parent
739 * The parent composite UI object
740 * @param cacheSize
741 * The size of the event table cache
742 * @param columnData
743 * The column data array
744 * @deprecated Deprecated constructor, use
745 * {@link #TmfEventsTable(Composite, int, Collection)}
746 */
747 @Deprecated
748 public TmfEventsTable(final Composite parent, int cacheSize,
749 final org.eclipse.tracecompass.tmf.ui.widgets.virtualtable.ColumnData[] columnData) {
750 /*
751 * We'll do a "best-effort" to keep trace types still using this API to
752 * keep working, by defining a TmfEventTableColumn for each ColumnData
753 * they passed.
754 */
755 this(parent, cacheSize, convertFromColumnData(columnData));
756 }
757
758 @Deprecated
759 private static @NonNull Iterable<ITmfEventAspect> convertFromColumnData(
760 org.eclipse.tracecompass.tmf.ui.widgets.virtualtable.ColumnData[] columnData) {
761
762 ImmutableList.Builder<ITmfEventAspect> builder = new ImmutableList.Builder<>();
763 for (org.eclipse.tracecompass.tmf.ui.widgets.virtualtable.ColumnData col : columnData) {
764 String fieldName = col.header;
765 if (fieldName != null) {
766 builder.add(new TmfContentFieldAspect(fieldName, fieldName));
767 }
768 }
769 return checkNotNull(builder.build());
770 }
771
772 /**
773 * Standard constructor, where we define which columns to use.
774 *
775 * @param parent
776 * The parent composite UI object
777 * @param cacheSize
778 * The size of the event table cache
779 * @param aspects
780 * The event aspects to display in this table. One column per
781 * aspect will be created.
782 * <p>
783 * The iteration order of this collection will correspond to the
784 * initial ordering of the columns in the table.
785 * </p>
786 */
787 public TmfEventsTable(final Composite parent, int cacheSize,
788 @NonNull Iterable<ITmfEventAspect> aspects) {
789 super("TmfEventsTable"); //$NON-NLS-1$
790
791 fComposite = new Composite(parent, SWT.NONE);
792 final GridLayout gl = new GridLayout(1, false);
793 gl.marginHeight = 0;
794 gl.marginWidth = 0;
795 gl.verticalSpacing = 0;
796 fComposite.setLayout(gl);
797
798 fSashForm = new SashForm(fComposite, SWT.HORIZONTAL);
799 fSashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
800
801 // Create a virtual table
802 final int style = SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION;
803 fTable = new TmfVirtualTable(fSashForm, style);
804
805 // Set the table layout
806 final GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
807 fTable.setLayoutData(layoutData);
808
809 // Some cosmetic enhancements
810 fTable.setHeaderVisible(true);
811 fTable.setLinesVisible(true);
812
813 // Setup the columns
814 for (ITmfEventAspect aspect : aspects) {
815 if (aspect != null) {
816 fColumns.add(new TmfEventTableColumn(aspect));
817 }
818 }
819
820 TmfMarginColumn collapseCol = new TmfMarginColumn();
821 fColumns.add(MARGIN_COLUMN_INDEX, collapseCol);
822
823 fHeaderMenu = new Menu(fTable);
824 // Create the UI columns in the table
825 for (TmfEventTableColumn col : fColumns) {
826 TableColumn column = fTable.newTableColumn(SWT.LEFT);
827 column.setText(col.getHeaderName());
828 column.setToolTipText(col.getHeaderTooltip());
829 column.setData(Key.ASPECT, col.getEventAspect());
830 column.pack();
831 if (col instanceof TmfMarginColumn) {
832 column.setResizable(false);
833 } else {
834 column.setMoveable(true);
835 column.setData(Key.WIDTH, -1);
836 }
837 column.addControlListener(new ColumnMovedListener());
838 }
839 fColumnOrder = fTable.getColumnOrder();
840
841 // Set the frozen row for header row
842 fTable.setFrozenRowCount(1);
843
844 // Create the header row cell editor
845 createHeaderEditor();
846
847 // Handle the table item selection
848 fTable.addSelectionListener(new TableSelectionListener());
849
850 int realCacheSize = Math.max(cacheSize, Display.getDefault().getBounds().height / fTable.getItemHeight());
851 realCacheSize = Math.min(realCacheSize, MAX_CACHE_SIZE);
852 fCache = new TmfEventsCache(realCacheSize, this);
853
854 // Handle the table item requests
855 fTable.addListener(SWT.SetData, new SetDataListener());
856
857 fTable.addListener(SWT.MenuDetect, new Listener() {
858 @Override
859 public void handleEvent(Event event) {
860 fLastMenuCursorLocation = new Point(event.x, event.y);
861 Point pt = fTable.getDisplay().map(null, fTable, fLastMenuCursorLocation);
862 Rectangle clientArea = fTable.getClientArea();
863 boolean header = clientArea.y <= pt.y && pt.y < (clientArea.y + fTable.getHeaderHeight());
864 fTable.setMenu(header ? fHeaderMenu : fTablePopup);
865 }
866 });
867
868 fTable.addMouseListener(new MouseDoubleClickListener());
869
870 final Listener tooltipListener = new TooltipListener();
871
872 fTable.addListener(SWT.MouseHover, tooltipListener);
873 fTable.addListener(SWT.Dispose, tooltipListener);
874 fTable.addListener(SWT.KeyDown, tooltipListener);
875 fTable.addListener(SWT.MouseMove, tooltipListener);
876 fTable.addListener(SWT.MouseExit, tooltipListener);
877 fTable.addListener(SWT.MouseDown, tooltipListener);
878 fTable.addListener(SWT.MouseWheel, tooltipListener);
879
880 fTable.addListener(SWT.EraseItem, new EraseItemListener());
881
882 fTable.addListener(SWT.PaintItem, new PainItemListener());
883
884 // Create resources
885 createResources();
886
887 initializeFonts();
888 initializeColors();
889 PlatformUI.getWorkbench().getThemeManager().addPropertyChangeListener(this);
890
891 ColorSettingsManager.addColorSettingsListener(this);
892
893 fTable.setItemCount(1); // +1 for header row
894
895 fRawViewer = new TmfRawEventViewer(fSashForm, SWT.H_SCROLL | SWT.V_SCROLL);
896
897 fRawViewer.addSelectionListener(new RawSelectionListener());
898
899 fSashForm.setWeights(new int[] { 1, 1 });
900 fRawViewer.setVisible(false);
901
902 createPopupMenu();
903 }
904
905 /**
906 * Checked menu creator to make columns visible or not.
907 *
908 * @param parent
909 * the parent menu
910 * @param column
911 * the column
912 */
913 private static IAction createHeaderAction(final TableColumn column) {
914 final IAction columnMenuAction = new Action(column.getText(), IAction.AS_CHECK_BOX) {
915 @Override
916 public void run() {
917 if (isChecked()) {
918 column.setWidth((int) column.getData(Key.WIDTH));
919 column.setResizable(true);
920 } else {
921 column.setData(Key.WIDTH, column.getWidth());
922 column.setWidth(0);
923 column.setResizable(false);
924 }
925 }
926 };
927 columnMenuAction.setChecked(column.getResizable());
928 return columnMenuAction;
929 }
930
931 private IAction createResetHeaderAction() {
932 return new Action(Messages.TmfEventsTable_ShowAll) {
933 @Override
934 public void run() {
935 for (TableColumn column : fTable.getColumns()) {
936 final Object widthVal = column.getData(Key.WIDTH);
937 if (widthVal instanceof Integer) {
938 Integer width = (Integer) widthVal;
939 if (!column.getResizable()) {
940 column.setWidth(width);
941 column.setResizable(true);
942 /*
943 * This is because Linux always resizes the last
944 * column to fill in the void, this means that
945 * hiding a column resizes others and we can have 10
946 * columns that are 1000 pixels wide by hiding the
947 * last one progressively.
948 */
949 if (IS_LINUX) {
950 column.pack();
951 }
952 }
953 }
954 }
955 }
956 };
957 }
958
959 // ------------------------------------------------------------------------
960 // Operations
961 // ------------------------------------------------------------------------
962
963 /**
964 * Create a pop-up menu.
965 */
966 private void createPopupMenu() {
967 final IAction copyAction = new Action(Messages.TmfEventsTable_CopyToClipboardActionText) {
968 @Override
969 public void run() {
970 ITmfTrace trace = fTrace;
971 if (trace == null || (fSelectedRank == -1 && fSelectedBeginRank == -1)) {
972 return;
973 }
974
975 List<TmfEventTableColumn> columns = new ArrayList<>();
976 for (int i : fTable.getColumnOrder()) {
977 TableColumn column = fTable.getColumns()[i];
978 // Omit the margin column and hidden columns
979 if (isVisibleEventColumn(column)) {
980 columns.add(fColumns.get(i));
981 }
982 }
983
984 long start = Math.min(fSelectedBeginRank, fSelectedRank);
985 long end = Math.max(fSelectedBeginRank, fSelectedRank);
986 final ITmfFilter filter = (ITmfFilter) fTable.getData(Key.FILTER_OBJ);
987 IRunnableWithProgress operation = new CopyToClipboardOperation(trace, filter, columns, start, end);
988 try {
989 PlatformUI.getWorkbench().getProgressService().busyCursorWhile(operation);
990 } catch (InvocationTargetException e) {
991 Activator.getDefault().logError("Invocation target exception copying to clipboard ", e); //$NON-NLS-1$
992 } catch (InterruptedException e) {
993 /* ignored */
994 }
995 }
996 };
997
998 final IAction showTableAction = new Action(Messages.TmfEventsTable_ShowTableActionText) {
999 @Override
1000 public void run() {
1001 fTable.setVisible(true);
1002 fSashForm.layout();
1003 }
1004 };
1005
1006 final IAction hideTableAction = new Action(Messages.TmfEventsTable_HideTableActionText) {
1007 @Override
1008 public void run() {
1009 fTable.setVisible(false);
1010 fSashForm.layout();
1011 }
1012 };
1013
1014 final IAction showRawAction = new Action(Messages.TmfEventsTable_ShowRawActionText) {
1015 @Override
1016 public void run() {
1017 fRawViewer.setVisible(true);
1018 fSashForm.layout();
1019 final int index = fTable.getSelectionIndex();
1020 if (index >= 1) {
1021 fRawViewer.selectAndReveal(index - 1);
1022 }
1023 }
1024 };
1025
1026 final IAction hideRawAction = new Action(Messages.TmfEventsTable_HideRawActionText) {
1027 @Override
1028 public void run() {
1029 fRawViewer.setVisible(false);
1030 fSashForm.layout();
1031 }
1032 };
1033
1034 final IAction openCallsiteAction = new Action(Messages.TmfEventsTable_OpenSourceCodeActionText) {
1035 @Override
1036 public void run() {
1037 final TableItem items[] = fTable.getSelection();
1038 if (items.length != 1) {
1039 return;
1040 }
1041 final TableItem item = items[0];
1042
1043 final Object data = item.getData();
1044 if (!(data instanceof ITmfSourceLookup)) {
1045 return;
1046 }
1047 ITmfSourceLookup event = (ITmfSourceLookup) data;
1048 ITmfCallsite cs = event.getCallsite();
1049 if (cs == null) {
1050 return;
1051 }
1052
1053 String fileName = cs.getFileName();
1054 final String trimmedPath = fileName.replaceAll("\\.\\./", EMPTY_STRING); //$NON-NLS-1$
1055 File fileToOpen = new File(trimmedPath);
1056
1057 try {
1058 if (fileToOpen.exists() && fileToOpen.isFile()) {
1059 /*
1060 * The path points to a "real" file, attempt to open
1061 * that
1062 */
1063 IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI());
1064 IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
1065
1066 IEditorPart editor = IDE.openEditorOnFileStore(page, fileStore);
1067 if (editor instanceof ITextEditor) {
1068 /*
1069 * Calculate the "document offset" corresponding to
1070 * the line number, then seek there.
1071 */
1072 ITextEditor textEditor = (ITextEditor) editor;
1073 int lineNumber = Long.valueOf(cs.getLineNumber()).intValue();
1074 IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
1075
1076 IRegion region = document.getLineInformation(lineNumber - 1);
1077 if (region != null) {
1078 textEditor.selectAndReveal(region.getOffset(), region.getLength());
1079 }
1080 }
1081
1082 } else {
1083 /*
1084 * The file was not found on disk, attempt to find it in
1085 * the workspace instead.
1086 */
1087 IMarker marker = null;
1088 final ArrayList<IFile> files = new ArrayList<>();
1089 ResourcesPlugin.getWorkspace().getRoot().accept(new IResourceVisitor() {
1090 @Override
1091 public boolean visit(IResource resource) throws CoreException {
1092 if (resource instanceof IFile && resource.getFullPath().toString().endsWith(trimmedPath)) {
1093 files.add((IFile) resource);
1094 }
1095 return true;
1096 }
1097 });
1098 IFile file = null;
1099 if (files.size() > 1) {
1100 ListDialog dialog = new ListDialog(getTable().getShell());
1101 dialog.setContentProvider(ArrayContentProvider.getInstance());
1102 dialog.setLabelProvider(new LabelProvider() {
1103 @Override
1104 public String getText(Object element) {
1105 return ((IFile) element).getFullPath().toString();
1106 }
1107 });
1108 dialog.setInput(files);
1109 dialog.setTitle(Messages.TmfEventsTable_OpenSourceCodeSelectFileDialogTitle);
1110 dialog.setMessage(Messages.TmfEventsTable_OpenSourceCodeSelectFileDialogTitle + '\n' + cs.toString());
1111 dialog.open();
1112 Object[] result = dialog.getResult();
1113 if (result != null && result.length > 0) {
1114 file = (IFile) result[0];
1115 }
1116 } else if (files.size() == 1) {
1117 file = files.get(0);
1118 }
1119 if (file != null) {
1120 marker = file.createMarker(IMarker.MARKER);
1121 marker.setAttribute(IMarker.LINE_NUMBER, Long.valueOf(cs.getLineNumber()).intValue());
1122 IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), marker);
1123 marker.delete();
1124 } else if (files.isEmpty()) {
1125 displayException(new FileNotFoundException('\'' + cs.toString() + '\'' + '\n' + Messages.TmfEventsTable_OpenSourceCodeNotFound));
1126 }
1127 }
1128 } catch (BadLocationException | CoreException e) {
1129 displayException(e);
1130 }
1131 }
1132 };
1133
1134 final IAction openModelAction = new Action(Messages.TmfEventsTable_OpenModelActionText) {
1135 @Override
1136 public void run() {
1137
1138 final TableItem items[] = fTable.getSelection();
1139 if (items.length != 1) {
1140 return;
1141 }
1142 final TableItem item = items[0];
1143
1144 final Object eventData = item.getData();
1145 if (eventData instanceof ITmfModelLookup) {
1146 String modelURI = ((ITmfModelLookup) eventData).getModelUri();
1147
1148 if (modelURI != null) {
1149 IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
1150
1151 IFile file = null;
1152 final URI uri = URI.createURI(modelURI);
1153 if (uri.isPlatformResource()) {
1154 IPath path = new Path(uri.toPlatformString(true));
1155 file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
1156 } else if (uri.isFile() && !uri.isRelative()) {
1157 file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(
1158 new Path(uri.toFileString()));
1159 }
1160
1161 if (file != null) {
1162 try {
1163 /*
1164 * create a temporary validation marker on the
1165 * model file, remove it afterwards thus,
1166 * navigation works with all model editors
1167 * supporting the navigation to a marker
1168 */
1169 IMarker marker = file.createMarker(EValidator.MARKER);
1170 marker.setAttribute(EValidator.URI_ATTRIBUTE, modelURI);
1171 marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO);
1172
1173 IDE.openEditor(activePage, marker, OpenStrategy.activateOnOpen());
1174 marker.delete();
1175 } catch (CoreException e) {
1176 displayException(e);
1177 }
1178 } else {
1179 displayException(new FileNotFoundException('\'' + modelURI + '\'' + '\n' + Messages.TmfEventsTable_OpenModelUnsupportedURI));
1180 }
1181 }
1182 }
1183 }
1184 };
1185
1186 final IAction exportToTextAction = new Action(Messages.TmfEventsTable_Export_to_text) {
1187 @Override
1188 public void run() {
1189 IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
1190 Object handlerServiceObject = activePage.getActiveEditor().getSite().getService(IHandlerService.class);
1191 IHandlerService handlerService = (IHandlerService) handlerServiceObject;
1192 Object cmdServiceObject = activePage.getActiveEditor().getSite().getService(ICommandService.class);
1193 ICommandService cmdService = (ICommandService) cmdServiceObject;
1194 try {
1195 HashMap<String, Object> parameters = new HashMap<>();
1196 Command command = cmdService.getCommand(ExportToTextCommandHandler.COMMAND_ID);
1197 ParameterizedCommand cmd = ParameterizedCommand.generateCommand(command, parameters);
1198
1199 IEvaluationContext context = handlerService.getCurrentState();
1200 List<TmfEventTableColumn> exportColumns = new ArrayList<>();
1201 for (int i : fTable.getColumnOrder()) {
1202 TableColumn column = fTable.getColumns()[i];
1203 // Omit the margin column and hidden columns
1204 if (isVisibleEventColumn(column)) {
1205 exportColumns.add(fColumns.get(i));
1206 }
1207 }
1208 context.addVariable(ExportToTextCommandHandler.TMF_EVENT_TABLE_COLUMNS_ID, exportColumns);
1209
1210 handlerService.executeCommandInContext(cmd, null, context);
1211 } catch (ExecutionException | NotDefinedException | NotEnabledException | NotHandledException e) {
1212 displayException(e);
1213 }
1214 }
1215 };
1216
1217 final IAction showSearchBarAction = new Action(Messages.TmfEventsTable_ShowSearchBarActionText) {
1218 @Override
1219 public void run() {
1220 fHeaderState = HeaderState.SEARCH;
1221 fTable.refresh();
1222 fTable.redraw();
1223 }
1224 };
1225
1226 final IAction showFilterBarAction = new Action(Messages.TmfEventsTable_ShowFilterBarActionText) {
1227 @Override
1228 public void run() {
1229 fHeaderState = HeaderState.FILTER;
1230 fTable.refresh();
1231 fTable.redraw();
1232 }
1233 };
1234
1235 final IAction clearFiltersAction = new Action(Messages.TmfEventsTable_ClearFiltersActionText) {
1236 @Override
1237 public void run() {
1238 clearFilters();
1239 }
1240 };
1241
1242 final IAction collapseAction = new Action(Messages.TmfEventsTable_CollapseFilterMenuName) {
1243 @Override
1244 public void run() {
1245 applyFilter(new TmfCollapseFilter());
1246 }
1247 };
1248
1249 class ToggleBookmarkAction extends Action {
1250 Long fRank;
1251
1252 public ToggleBookmarkAction(final String text, final Long rank) {
1253 super(text);
1254 fRank = rank;
1255 }
1256
1257 @Override
1258 public void run() {
1259 toggleBookmark(fRank);
1260 }
1261 }
1262
1263 fHeaderPopupMenuManager = new MenuManager();
1264 fHeaderPopupMenuManager.setRemoveAllWhenShown(true);
1265 fHeaderPopupMenuManager.addMenuListener(new IMenuListener() {
1266 @Override
1267 public void menuAboutToShow(IMenuManager manager) {
1268 for (int index : fTable.getColumnOrder()) {
1269 if (fTable.getColumns()[index].getData(Key.WIDTH) != null) {
1270 fHeaderPopupMenuManager.add(createHeaderAction(fTable.getColumns()[index]));
1271 }
1272 }
1273 fHeaderPopupMenuManager.add(new Separator());
1274 fHeaderPopupMenuManager.add(createResetHeaderAction());
1275 }
1276 });
1277
1278 fTablePopupMenuManager = new MenuManager();
1279 fTablePopupMenuManager.setRemoveAllWhenShown(true);
1280 fTablePopupMenuManager.addMenuListener(new IMenuListener() {
1281 @Override
1282 public void menuAboutToShow(final IMenuManager manager) {
1283 if (fTable.getSelectionIndices().length == 1 && fTable.getSelectionIndices()[0] == 0) {
1284 // Right-click on header row
1285 if (fHeaderState == HeaderState.FILTER) {
1286 fTablePopupMenuManager.add(showSearchBarAction);
1287 } else {
1288 fTablePopupMenuManager.add(showFilterBarAction);
1289 }
1290 return;
1291 }
1292 final Point point = fTable.toControl(fLastMenuCursorLocation);
1293 final TableItem item = fTable.getSelection().length > 0 ? fTable.getSelection()[0] : null;
1294 if (item != null) {
1295 final Rectangle imageBounds = item.getImageBounds(0);
1296 imageBounds.width = BOOKMARK_IMAGE.getBounds().width;
1297 if (point.x <= (imageBounds.x + imageBounds.width)) {
1298 // Right-click on left margin
1299 final Long rank = (Long) item.getData(Key.RANK);
1300 if ((rank != null) && (fBookmarksFile != null)) {
1301 if (fBookmarksMap.containsKey(rank)) {
1302 fTablePopupMenuManager.add(new ToggleBookmarkAction(
1303 Messages.TmfEventsTable_RemoveBookmarkActionText, rank));
1304 } else {
1305 fTablePopupMenuManager.add(new ToggleBookmarkAction(
1306 Messages.TmfEventsTable_AddBookmarkActionText, rank));
1307 }
1308 }
1309 return;
1310 }
1311 }
1312
1313 // Right-click on table
1314 if (fSelectedRank != -1 && fSelectedBeginRank != -1) {
1315 fTablePopupMenuManager.add(copyAction);
1316 fTablePopupMenuManager.add(new Separator());
1317 }
1318 if (fTable.isVisible() && fRawViewer.isVisible()) {
1319 fTablePopupMenuManager.add(hideTableAction);
1320 fTablePopupMenuManager.add(hideRawAction);
1321 } else if (!fTable.isVisible()) {
1322 fTablePopupMenuManager.add(showTableAction);
1323 } else if (!fRawViewer.isVisible()) {
1324 fTablePopupMenuManager.add(showRawAction);
1325 }
1326 fTablePopupMenuManager.add(exportToTextAction);
1327 fTablePopupMenuManager.add(new Separator());
1328
1329 if (item != null) {
1330 final Object data = item.getData();
1331 Separator separator = null;
1332 if (data instanceof ITmfSourceLookup) {
1333 ITmfSourceLookup event = (ITmfSourceLookup) data;
1334 if (event.getCallsite() != null) {
1335 fTablePopupMenuManager.add(openCallsiteAction);
1336 separator = new Separator();
1337 }
1338 }
1339
1340 if (data instanceof ITmfModelLookup) {
1341 ITmfModelLookup event = (ITmfModelLookup) data;
1342 if (event.getModelUri() != null) {
1343 fTablePopupMenuManager.add(openModelAction);
1344 separator = new Separator();
1345 }
1346
1347 if (separator != null) {
1348 fTablePopupMenuManager.add(separator);
1349 }
1350 }
1351 }
1352
1353 /*
1354 * Only show collapse filter if at least one trace can be
1355 * collapsed.
1356 */
1357 boolean isCollapsible = false;
1358 if (fTrace != null) {
1359 for (ITmfTrace trace : TmfTraceManager.getTraceSet(fTrace)) {
1360 Class<? extends ITmfEvent> eventClass = trace.getEventType();
1361 isCollapsible = ITmfCollapsibleEvent.class.isAssignableFrom(eventClass);
1362 if (isCollapsible) {
1363 break;
1364 }
1365 }
1366 }
1367
1368 if (isCollapsible && !(fTable.getData(Key.FILTER_OBJ) instanceof TmfCollapseFilter)) {
1369 fTablePopupMenuManager.add(collapseAction);
1370 fTablePopupMenuManager.add(new Separator());
1371 }
1372
1373 fTablePopupMenuManager.add(clearFiltersAction);
1374 final ITmfFilterTreeNode[] savedFilters = FilterManager.getSavedFilters();
1375 if (savedFilters.length > 0) {
1376 final MenuManager subMenu = new MenuManager(Messages.TmfEventsTable_ApplyPresetFilterMenuName);
1377 for (final ITmfFilterTreeNode node : savedFilters) {
1378 if (node instanceof TmfFilterNode) {
1379 final TmfFilterNode filter = (TmfFilterNode) node;
1380 subMenu.add(new Action(filter.getFilterName()) {
1381 @Override
1382 public void run() {
1383 applyFilter(filter);
1384 }
1385 });
1386 }
1387 }
1388 fTablePopupMenuManager.add(subMenu);
1389 }
1390 appendToTablePopupMenu(fTablePopupMenuManager, item);
1391 }
1392 });
1393
1394 fRawViewerPopupMenuManager = new MenuManager();
1395 fRawViewerPopupMenuManager.setRemoveAllWhenShown(true);
1396 fRawViewerPopupMenuManager.addMenuListener(new IMenuListener() {
1397 @Override
1398 public void menuAboutToShow(final IMenuManager manager) {
1399 if (fTable.isVisible() && fRawViewer.isVisible()) {
1400 fRawViewerPopupMenuManager.add(hideTableAction);
1401 fRawViewerPopupMenuManager.add(hideRawAction);
1402 } else if (!fTable.isVisible()) {
1403 fRawViewerPopupMenuManager.add(showTableAction);
1404 } else if (!fRawViewer.isVisible()) {
1405 fRawViewerPopupMenuManager.add(showRawAction);
1406 }
1407 appendToRawPopupMenu(fRawViewerPopupMenuManager);
1408 }
1409 });
1410
1411 fHeaderMenu = fHeaderPopupMenuManager.createContextMenu(fTable);
1412
1413 fTablePopup = fTablePopupMenuManager.createContextMenu(fTable);
1414 fTable.setMenu(fTablePopup);
1415
1416 fRawTablePopup = fRawViewerPopupMenuManager.createContextMenu(fRawViewer);
1417 fRawViewer.setMenu(fRawTablePopup);
1418 }
1419
1420 /**
1421 * Append an item to the event table's pop-up menu.
1422 *
1423 * @param tablePopupMenu
1424 * The menu manager
1425 * @param selectedItem
1426 * The item to append
1427 */
1428 protected void appendToTablePopupMenu(final MenuManager tablePopupMenu, final TableItem selectedItem) {
1429 // override to append more actions
1430 }
1431
1432 /**
1433 * Append an item to the raw viewer's pop-up menu.
1434 *
1435 * @param rawViewerPopupMenu
1436 * The menu manager
1437 */
1438 protected void appendToRawPopupMenu(final MenuManager rawViewerPopupMenu) {
1439 // override to append more actions
1440 }
1441
1442 @Override
1443 public void dispose() {
1444 stopSearchThread();
1445 stopFilterThread();
1446 PlatformUI.getWorkbench().getThemeManager().removePropertyChangeListener(this);
1447 ColorSettingsManager.removeColorSettingsListener(this);
1448 fComposite.dispose();
1449 if ((fTrace != null) && fDisposeOnClose) {
1450 fTrace.dispose();
1451 }
1452 fResourceManager.dispose();
1453 fRawViewer.dispose();
1454 if (fRawViewerPopupMenuManager != null) {
1455 fRawViewerPopupMenuManager.dispose();
1456 }
1457 if (fHeaderPopupMenuManager != null) {
1458 fHeaderPopupMenuManager.dispose();
1459 }
1460 if (fTablePopupMenuManager != null) {
1461 fTablePopupMenuManager.dispose();
1462 }
1463
1464 super.dispose();
1465 }
1466
1467 /**
1468 * Assign a layout data object to this view.
1469 *
1470 * @param layoutData
1471 * The layout data to assign
1472 */
1473 public void setLayoutData(final Object layoutData) {
1474 fComposite.setLayoutData(layoutData);
1475 }
1476
1477 /**
1478 * Get the virtual table contained in this event table.
1479 *
1480 * @return The TMF virtual table
1481 */
1482 public TmfVirtualTable getTable() {
1483 return fTable;
1484 }
1485
1486 /**
1487 * @param columnData
1488 * columnData
1489 * @deprecated The column headers are now set at the constructor, this
1490 * shouldn't be called anymore.
1491 */
1492 @Deprecated
1493 protected void setColumnHeaders(final org.eclipse.tracecompass.tmf.ui.widgets.virtualtable.ColumnData[] columnData) {
1494 /* No-op */
1495 }
1496
1497 /**
1498 * Set a table item's data.
1499 *
1500 * @param item
1501 * The item to set
1502 * @param event
1503 * Which trace event to link with this entry
1504 * @param rank
1505 * Which rank this event has in the trace/experiment
1506 */
1507 protected void setItemData(final TableItem item, final ITmfEvent event, final long rank) {
1508 String[] itemStrings = getItemStrings(fColumns, event);
1509
1510 // Get the actual ITmfEvent from the CachedEvent
1511 ITmfEvent tmfEvent = event;
1512 if (event instanceof CachedEvent) {
1513 tmfEvent = ((CachedEvent) event).event;
1514 }
1515 item.setText(itemStrings);
1516 item.setData(tmfEvent);
1517 item.setData(Key.TIMESTAMP, new TmfTimestamp(tmfEvent.getTimestamp()));
1518 item.setData(Key.RANK, rank);
1519
1520 final Collection<Long> markerIds = fBookmarksMap.get(rank);
1521 if (!markerIds.isEmpty()) {
1522 Joiner joiner = Joiner.on("\n -").skipNulls(); //$NON-NLS-1$
1523 List<Object> parts = new ArrayList<>();
1524 if (markerIds.size() > 1) {
1525 parts.add(Messages.TmfEventsTable_MultipleBookmarksToolTip);
1526 }
1527 try {
1528 for (long markerId : markerIds) {
1529 final IMarker marker = fBookmarksFile.findMarker(markerId);
1530 if (marker != null) {
1531 parts.add(marker.getAttribute(IMarker.MESSAGE));
1532 }
1533 }
1534 } catch (CoreException e) {
1535 displayException(e);
1536 }
1537 item.setData(Key.BOOKMARK, joiner.join(parts));
1538 } else {
1539 item.setData(Key.BOOKMARK, null);
1540 }
1541
1542 boolean searchMatch = false;
1543 boolean searchNoMatch = false;
1544 final ITmfFilter searchFilter = (ITmfFilter) fTable.getData(Key.SEARCH_OBJ);
1545 if (searchFilter != null) {
1546 if (searchFilter.matches(tmfEvent)) {
1547 searchMatch = true;
1548 } else {
1549 searchNoMatch = true;
1550 }
1551 }
1552
1553 final ColorSetting colorSetting = ColorSettingsManager.getColorSetting(tmfEvent);
1554 if (searchNoMatch) {
1555 item.setForeground(colorSetting.getDimmedForegroundColor());
1556 item.setBackground(colorSetting.getDimmedBackgroundColor());
1557 } else {
1558 item.setForeground(colorSetting.getForegroundColor());
1559 item.setBackground(colorSetting.getBackgroundColor());
1560 }
1561 item.setFont(fFont);
1562
1563 if (searchMatch) {
1564 if (!markerIds.isEmpty()) {
1565 item.setImage(SEARCH_MATCH_BOOKMARK_IMAGE);
1566 } else {
1567 item.setImage(SEARCH_MATCH_IMAGE);
1568 }
1569 } else if (!markerIds.isEmpty()) {
1570 item.setImage(BOOKMARK_IMAGE);
1571 } else {
1572 item.setImage((Image) null);
1573 }
1574
1575 List<StyleRange> styleRanges = new ArrayList<>();
1576 for (int index = 0; index < fTable.getColumns().length; index++) {
1577 TableColumn column = fTable.getColumns()[index];
1578 String regex = null;
1579 if (fHeaderState == HeaderState.FILTER) {
1580 regex = (String) column.getData(Key.FILTER_TXT);
1581 } else if (searchMatch) {
1582 regex = (String) column.getData(Key.SEARCH_TXT);
1583 }
1584 if (regex != null) {
1585 String text = item.getText(index);
1586 try {
1587 Pattern pattern = Pattern.compile(regex);
1588 Matcher matcher = pattern.matcher(text);
1589 while (matcher.find()) {
1590 int start = matcher.start();
1591 int length = matcher.end() - start;
1592 Color foreground = colorSetting.getForegroundColor();
1593 Color background = fHighlightColor;
1594 StyleRange styleRange = new StyleRange(start, length, foreground, background);
1595 styleRange.data = index;
1596 styleRanges.add(styleRange);
1597 }
1598 } catch (PatternSyntaxException e) {
1599 /* ignored */
1600 }
1601 }
1602 }
1603 if (styleRanges.isEmpty()) {
1604 item.setData(Key.STYLE_RANGES, null);
1605 } else {
1606 item.setData(Key.STYLE_RANGES, styleRanges);
1607 }
1608 item.getParent().redraw();
1609
1610 if ((itemStrings[MARGIN_COLUMN_INDEX] != null) && !itemStrings[MARGIN_COLUMN_INDEX].isEmpty()) {
1611 packMarginColumn();
1612 }
1613 }
1614
1615 /**
1616 * Set the item data of the header row.
1617 *
1618 * @param item
1619 * The item to use as table header
1620 */
1621 protected void setHeaderRowItemData(final TableItem item) {
1622 String txtKey = null;
1623 if (fHeaderState == HeaderState.SEARCH) {
1624 item.setImage(SEARCH_IMAGE);
1625 txtKey = Key.SEARCH_TXT;
1626 } else if (fHeaderState == HeaderState.FILTER) {
1627 item.setImage(FILTER_IMAGE);
1628 txtKey = Key.FILTER_TXT;
1629 }
1630 item.setForeground(fGrayColor);
1631 // Ignore collapse and image column
1632 for (int i = EVENT_COLUMNS_START_INDEX; i < fTable.getColumns().length; i++) {
1633 final TableColumn column = fTable.getColumns()[i];
1634 final String filter = (String) column.getData(txtKey);
1635 if (filter == null) {
1636 if (fHeaderState == HeaderState.SEARCH) {
1637 item.setText(i, SEARCH_HINT);
1638 } else if (fHeaderState == HeaderState.FILTER) {
1639 item.setText(i, FILTER_HINT);
1640 }
1641 item.setForeground(i, fGrayColor);
1642 item.setFont(i, fFont);
1643 } else {
1644 item.setText(i, filter);
1645 item.setForeground(i, fGreenColor);
1646 item.setFont(i, fBoldFont);
1647 }
1648 }
1649 }
1650
1651 /**
1652 * Set the item data of the "filter status" row.
1653 *
1654 * @param item
1655 * The item to use as filter status row
1656 */
1657 protected void setFilterStatusRowItemData(final TableItem item) {
1658 for (int i = 0; i < fTable.getColumns().length; i++) {
1659 if (i == MARGIN_COLUMN_INDEX) {
1660 if ((fTrace == null) || (fFilterCheckCount == fTrace.getNbEvents())) {
1661 item.setImage(FILTER_IMAGE);
1662 } else {
1663 item.setImage(STOP_IMAGE);
1664 }
1665 }
1666
1667 if (i == FILTER_SUMMARY_INDEX) {
1668 item.setText(FILTER_SUMMARY_INDEX, fFilterMatchCount + "/" + fFilterCheckCount); //$NON-NLS-1$
1669 } else {
1670 item.setText(i, EMPTY_STRING);
1671 }
1672 }
1673 item.setData(null);
1674 item.setData(Key.TIMESTAMP, null);
1675 item.setData(Key.RANK, null);
1676 item.setData(Key.STYLE_RANGES, null);
1677 item.setForeground(null);
1678 item.setBackground(null);
1679 item.setFont(fFont);
1680 }
1681
1682 /**
1683 * Create an editor for the header.
1684 */
1685 private void createHeaderEditor() {
1686 final TableEditor tableEditor = fTable.createTableEditor();
1687 tableEditor.horizontalAlignment = SWT.LEFT;
1688 tableEditor.verticalAlignment = SWT.CENTER;
1689 tableEditor.grabHorizontal = true;
1690 tableEditor.minimumWidth = 50;
1691
1692 // Handle the header row selection
1693 fTable.addMouseListener(new MouseAdapter() {
1694 int columnIndex;
1695 TableColumn column;
1696 TableItem item;
1697
1698 @Override
1699 public void mouseDown(final MouseEvent event) {
1700 if (event.button != 1) {
1701 return;
1702 }
1703 // Identify the selected row
1704 final Point point = new Point(event.x, event.y);
1705 item = fTable.getItem(point);
1706
1707 // Header row selected
1708 if ((item != null) && (fTable.indexOf(item) == 0)) {
1709
1710 // Margin column selected
1711 if (item.getBounds(0).contains(point)) {
1712 if (fHeaderState == HeaderState.SEARCH) {
1713 fHeaderState = HeaderState.FILTER;
1714 } else if (fHeaderState == HeaderState.FILTER) {
1715 fHeaderState = HeaderState.SEARCH;
1716 }
1717 fTable.setSelection(0);
1718 fTable.refresh();
1719 fTable.redraw();
1720 return;
1721 }
1722
1723 // Identify the selected column
1724 columnIndex = -1;
1725 for (int i = 0; i < fTable.getColumns().length; i++) {
1726 final Rectangle rect = item.getBounds(i);
1727 if (rect.contains(point)) {
1728 columnIndex = i;
1729 break;
1730 }
1731 }
1732
1733 if (columnIndex == -1) {
1734 return;
1735 }
1736
1737 column = fTable.getColumns()[columnIndex];
1738
1739 String txtKey = null;
1740 if (fHeaderState == HeaderState.SEARCH) {
1741 txtKey = Key.SEARCH_TXT;
1742 } else if (fHeaderState == HeaderState.FILTER) {
1743 txtKey = Key.FILTER_TXT;
1744 }
1745
1746 /*
1747 * The control that will be the editor must be a child of
1748 * the Table
1749 */
1750 final Text newEditor = (Text) fTable.createTableEditorControl(Text.class);
1751 final String headerString = (String) column.getData(txtKey);
1752 if (headerString != null) {
1753 newEditor.setText(headerString);
1754 }
1755 newEditor.addFocusListener(new FocusAdapter() {
1756 @Override
1757 public void focusLost(final FocusEvent e) {
1758 final boolean changed = updateHeader(newEditor.getText());
1759 if (changed) {
1760 applyHeader();
1761 }
1762 }
1763 });
1764 newEditor.addKeyListener(new KeyAdapter() {
1765 @Override
1766 public void keyPressed(final KeyEvent e) {
1767 if (e.character == SWT.CR) {
1768 updateHeader(newEditor.getText());
1769 applyHeader();
1770
1771 /*
1772 * Set focus on the table so that the next
1773 * carriage return goes to the next result
1774 */
1775 TmfEventsTable.this.getTable().setFocus();
1776 } else if (e.character == SWT.ESC) {
1777 tableEditor.getEditor().dispose();
1778 }
1779 }
1780 });
1781 newEditor.selectAll();
1782 newEditor.setFocus();
1783 tableEditor.setEditor(newEditor, item, columnIndex);
1784 }
1785 }
1786
1787 /*
1788 * returns true is value was changed
1789 */
1790 private boolean updateHeader(final String regex) {
1791 String objKey = null;
1792 String txtKey = null;
1793 if (fHeaderState == HeaderState.SEARCH) {
1794 objKey = Key.SEARCH_OBJ;
1795 txtKey = Key.SEARCH_TXT;
1796 } else if (fHeaderState == HeaderState.FILTER) {
1797 objKey = Key.FILTER_OBJ;
1798 txtKey = Key.FILTER_TXT;
1799 }
1800 if (regex.length() > 0) {
1801 try {
1802 Pattern.compile(regex);
1803 if (regex.equals(column.getData(txtKey))) {
1804 tableEditor.getEditor().dispose();
1805 return false;
1806 }
1807 final TmfFilterMatchesNode filter = new TmfFilterMatchesNode(null);
1808 ITmfEventAspect aspect = (ITmfEventAspect) column.getData(Key.ASPECT);
1809 filter.setEventAspect(aspect);
1810 filter.setRegex(regex);
1811 column.setData(objKey, filter);
1812 column.setData(txtKey, regex);
1813 } catch (final PatternSyntaxException ex) {
1814 tableEditor.getEditor().dispose();
1815 MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
1816 ex.getDescription(), ex.getMessage());
1817 return false;
1818 }
1819 } else {
1820 if (column.getData(txtKey) == null) {
1821 tableEditor.getEditor().dispose();
1822 return false;
1823 }
1824 column.setData(objKey, null);
1825 column.setData(txtKey, null);
1826 }
1827 return true;
1828 }
1829
1830 private void applyHeader() {
1831 if (fHeaderState == HeaderState.SEARCH) {
1832 stopSearchThread();
1833 final TmfFilterAndNode filter = new TmfFilterAndNode(null);
1834 for (final TableColumn col : fTable.getColumns()) {
1835 final Object filterObj = col.getData(Key.SEARCH_OBJ);
1836 if (filterObj instanceof ITmfFilterTreeNode) {
1837 filter.addChild((ITmfFilterTreeNode) filterObj);
1838 }
1839 }
1840 if (filter.getChildrenCount() > 0) {
1841 fTable.setData(Key.SEARCH_OBJ, filter);
1842 fTable.refresh();
1843 searchNext();
1844 fireSearchApplied(filter);
1845 } else {
1846 fTable.setData(Key.SEARCH_OBJ, null);
1847 fTable.refresh();
1848 fireSearchApplied(null);
1849 }
1850 } else if (fHeaderState == HeaderState.FILTER) {
1851 final TmfFilterAndNode filter = new TmfFilterAndNode(null);
1852 for (final TableColumn col : fTable.getColumns()) {
1853 final Object filterObj = col.getData(Key.FILTER_OBJ);
1854 if (filterObj instanceof ITmfFilterTreeNode) {
1855 filter.addChild((ITmfFilterTreeNode) filterObj);
1856 }
1857 }
1858 if (filter.getChildrenCount() > 0) {
1859 applyFilter(filter);
1860 } else {
1861 clearFilters();
1862 }
1863 }
1864
1865 tableEditor.getEditor().dispose();
1866 }
1867 });
1868
1869 fTable.addKeyListener(new KeyAdapter() {
1870 @Override
1871 public void keyPressed(final KeyEvent e) {
1872 e.doit = false;
1873 if (e.character == SWT.ESC) {
1874 stopFilterThread();
1875 stopSearchThread();
1876 fTable.refresh();
1877 } else if (e.character == SWT.DEL) {
1878 if (fHeaderState == HeaderState.SEARCH) {
1879 stopSearchThread();
1880 for (final TableColumn column : fTable.getColumns()) {
1881 column.setData(Key.SEARCH_OBJ, null);
1882 column.setData(Key.SEARCH_TXT, null);
1883 }
1884 fTable.setData(Key.SEARCH_OBJ, null);
1885 fTable.refresh();
1886 fireSearchApplied(null);
1887 } else if (fHeaderState == HeaderState.FILTER) {
1888 clearFilters();
1889 }
1890 } else if (e.character == SWT.CR) {
1891 if ((e.stateMask & SWT.SHIFT) == 0) {
1892 searchNext();
1893 } else {
1894 searchPrevious();
1895 }
1896 }
1897 }
1898 });
1899 }
1900
1901 /**
1902 * Send an event indicating a filter has been applied.
1903 *
1904 * @param filter
1905 * The filter that was just applied
1906 */
1907 protected void fireFilterApplied(final ITmfFilter filter) {
1908 broadcast(new TmfEventFilterAppliedSignal(this, fTrace, filter));
1909 }
1910
1911 /**
1912 * Send an event indicating that a search has been applied.
1913 *
1914 * @param filter
1915 * The search filter that was just applied
1916 */
1917 protected void fireSearchApplied(final ITmfFilter filter) {
1918 broadcast(new TmfEventSearchAppliedSignal(this, fTrace, filter));
1919 }
1920
1921 /**
1922 * Start the filtering thread.
1923 */
1924 protected void startFilterThread() {
1925 synchronized (fFilterSyncObj) {
1926 final ITmfFilterTreeNode filter = (ITmfFilterTreeNode) fTable.getData(Key.FILTER_OBJ);
1927 if (fFilterThread == null || fFilterThread.filter != filter) {
1928 if (fFilterThread != null) {
1929 fFilterThread.cancel();
1930 fFilterThreadResume = false;
1931 }
1932 fFilterThread = new FilterThread(filter);
1933 fFilterThread.start();
1934 } else {
1935 fFilterThreadResume = true;
1936 }
1937 }
1938 }
1939
1940 /**
1941 * Stop the filtering thread.
1942 */
1943 protected void stopFilterThread() {
1944 synchronized (fFilterSyncObj) {
1945 if (fFilterThread != null) {
1946 fFilterThread.cancel();
1947 fFilterThread = null;
1948 fFilterThreadResume = false;
1949 }
1950 }
1951 }
1952
1953 /**
1954 * Apply a filter.
1955 *
1956 * @param filter
1957 * The filter to apply
1958 */
1959 protected void applyFilter(ITmfFilter filter) {
1960 stopFilterThread();
1961 stopSearchThread();
1962 fFilterMatchCount = 0;
1963 fFilterCheckCount = 0;
1964 fCache.applyFilter(filter);
1965 fTable.clearAll();
1966 fTable.setData(Key.FILTER_OBJ, filter);
1967 /* +1 for header row, +2 for top and bottom filter status rows */
1968 fTable.setItemCount(3);
1969 startFilterThread();
1970 fireFilterApplied(filter);
1971 }
1972
1973 /**
1974 * Clear all currently active filters.
1975 */
1976 protected void clearFilters() {
1977 if (fTable.getData(Key.FILTER_OBJ) == null) {
1978 return;
1979 }
1980 stopFilterThread();
1981 stopSearchThread();
1982 fCache.clearFilter();
1983 fTable.clearAll();
1984 for (final TableColumn column : fTable.getColumns()) {
1985 column.setData(Key.FILTER_OBJ, null);
1986 column.setData(Key.FILTER_TXT, null);
1987 }
1988 fTable.setData(Key.FILTER_OBJ, null);
1989 if (fTrace != null) {
1990 /* +1 for header row */
1991 fTable.setItemCount((int) fTrace.getNbEvents() + 1);
1992 } else {
1993 /* +1 for header row */
1994 fTable.setItemCount(1);
1995 }
1996 fFilterMatchCount = 0;
1997 fFilterCheckCount = 0;
1998 if (fSelectedRank >= 0) {
1999 /* +1 for header row */
2000 fTable.setSelection((int) fSelectedRank + 1);
2001 } else {
2002 fTable.setSelection(0);
2003 }
2004 fireFilterApplied(null);
2005 updateStatusLine(null);
2006
2007 // Set original width
2008 fTable.getColumns()[MARGIN_COLUMN_INDEX].setWidth(0);
2009 packMarginColumn();
2010 }
2011
2012 /**
2013 * Wrapper Thread object for the filtering thread.
2014 */
2015 protected class FilterThread extends Thread {
2016 private final ITmfFilterTreeNode filter;
2017 private TmfEventRequest request;
2018 private boolean refreshBusy = false;
2019 private boolean refreshPending = false;
2020 private final Object syncObj = new Object();
2021
2022 /**
2023 * Constructor.
2024 *
2025 * @param filter
2026 * The filter this thread will be processing
2027 */
2028 public FilterThread(final ITmfFilterTreeNode filter) {
2029 super("Filter Thread"); //$NON-NLS-1$
2030 this.filter = filter;
2031 }
2032
2033 @Override
2034 public void run() {
2035 if (fTrace == null) {
2036 return;
2037 }
2038 final int nbRequested = (int) (fTrace.getNbEvents() - fFilterCheckCount);
2039 if (nbRequested <= 0) {
2040 return;
2041 }
2042 request = new TmfEventRequest(ITmfEvent.class, TmfTimeRange.ETERNITY,
2043 (int) fFilterCheckCount, nbRequested, ExecutionType.BACKGROUND) {
2044 @Override
2045 public void handleData(final ITmfEvent event) {
2046 super.handleData(event);
2047 if (request.isCancelled()) {
2048 return;
2049 }
2050 boolean refresh = false;
2051 if (filter.matches(event)) {
2052 final long rank = fFilterCheckCount;
2053 final int index = (int) fFilterMatchCount;
2054 fFilterMatchCount++;
2055 fCache.storeEvent(event, rank, index);
2056 refresh = true;
2057 } else {
2058 if (filter instanceof TmfCollapseFilter) {
2059 fCache.updateCollapsedEvent((int) fFilterMatchCount - 1);
2060 }
2061 }
2062
2063 if (refresh || (fFilterCheckCount % 100) == 0) {
2064 refreshTable();
2065 }
2066 fFilterCheckCount++;
2067 }
2068 };
2069 ((ITmfEventProvider) fTrace).sendRequest(request);
2070 try {
2071 request.waitForCompletion();
2072 } catch (final InterruptedException e) {
2073 }
2074 refreshTable();
2075 synchronized (fFilterSyncObj) {
2076 fFilterThread = null;
2077 if (fFilterThreadResume) {
2078 fFilterThreadResume = false;
2079 fFilterThread = new FilterThread(filter);
2080 fFilterThread.start();
2081 }
2082 }
2083 }
2084
2085 /**
2086 * Refresh the filter.
2087 */
2088 public void refreshTable() {
2089 synchronized (syncObj) {
2090 if (refreshBusy) {
2091 refreshPending = true;
2092 return;
2093 }
2094 refreshBusy = true;
2095 }
2096 Display.getDefault().asyncExec(new Runnable() {
2097 @Override
2098 public void run() {
2099 if (request.isCancelled()) {
2100 return;
2101 }
2102 if (fTable.isDisposed()) {
2103 return;
2104 }
2105 /*
2106 * +1 for header row, +2 for top and bottom filter status
2107 * rows
2108 */
2109 fTable.setItemCount((int) fFilterMatchCount + 3);
2110 fTable.refresh();
2111 synchronized (syncObj) {
2112 refreshBusy = false;
2113 if (refreshPending) {
2114 refreshPending = false;
2115 refreshTable();
2116 }
2117 }
2118 }
2119 });
2120 }
2121
2122 /**
2123 * Cancel this filtering thread.
2124 */
2125 public void cancel() {
2126 if (request != null) {
2127 request.cancel();
2128 }
2129 }
2130 }
2131
2132 /**
2133 * Go to the next item of a search.
2134 */
2135 protected void searchNext() {
2136 synchronized (fSearchSyncObj) {
2137 if (fSearchThread != null) {
2138 return;
2139 }
2140 final ITmfFilterTreeNode searchFilter = (ITmfFilterTreeNode) fTable.getData(Key.SEARCH_OBJ);
2141 if (searchFilter == null) {
2142 return;
2143 }
2144 final int selectionIndex = fTable.getSelectionIndex();
2145 int startIndex;
2146 if (selectionIndex > 0) {
2147 /* -1 for header row, +1 for next event */
2148 startIndex = selectionIndex;
2149 } else {
2150 /*
2151 * header row is selected, start at top event
2152 */
2153 /* -1 for header row */
2154 startIndex = Math.max(0, fTable.getTopIndex() - 1);
2155 }
2156 final ITmfFilterTreeNode eventFilter = (ITmfFilterTreeNode) fTable.getData(Key.FILTER_OBJ);
2157 if (eventFilter != null) {
2158 // -1 for top filter status row
2159 startIndex = Math.max(0, startIndex - 1);
2160 }
2161 fSearchThread = new SearchThread(searchFilter, eventFilter, startIndex, fSelectedRank, Direction.FORWARD);
2162 fSearchThread.schedule();
2163 }
2164 }
2165
2166 /**
2167 * Go to the previous item of a search.
2168 */
2169 protected void searchPrevious() {
2170 synchronized (fSearchSyncObj) {
2171 if (fSearchThread != null) {
2172 return;
2173 }
2174 final ITmfFilterTreeNode searchFilter = (ITmfFilterTreeNode) fTable.getData(Key.SEARCH_OBJ);
2175 if (searchFilter == null) {
2176 return;
2177 }
2178 final int selectionIndex = fTable.getSelectionIndex();
2179 int startIndex;
2180 if (selectionIndex > 0) {
2181 /* -1 for header row, -1 for previous event */
2182 startIndex = selectionIndex - 2;
2183 } else {
2184 /*
2185 * Header row is selected, start at precedent of top event
2186 */
2187 /* -1 for header row, -1 for previous event */
2188 startIndex = fTable.getTopIndex() - 2;
2189 }
2190 final ITmfFilterTreeNode eventFilter = (ITmfFilterTreeNode) fTable.getData(Key.FILTER_OBJ);
2191 if (eventFilter != null) {
2192 /* -1 for top filter status row */
2193 startIndex = startIndex - 1;
2194 }
2195 fSearchThread = new SearchThread(searchFilter, eventFilter, startIndex, fSelectedRank, Direction.BACKWARD);
2196 fSearchThread.schedule();
2197 }
2198 }
2199
2200 /**
2201 * Stop the search thread.
2202 */
2203 protected void stopSearchThread() {
2204 fPendingGotoRank = -1;
2205 synchronized (fSearchSyncObj) {
2206 if (fSearchThread != null) {
2207 fSearchThread.cancel();
2208 fSearchThread = null;
2209 }
2210 }
2211 }
2212
2213 /**
2214 * Wrapper for the search thread.
2215 */
2216 protected class SearchThread extends Job {
2217
2218 private ITmfFilterTreeNode searchFilter;
2219 private ITmfFilterTreeNode eventFilter;
2220 private int startIndex;
2221 private int direction;
2222 private long rank;
2223 private long foundRank = -1;
2224 private TmfEventRequest request;
2225 private ITmfTimestamp foundTimestamp = null;
2226
2227 /**
2228 * Constructor.
2229 *
2230 * @param searchFilter
2231 * The search filter
2232 * @param eventFilter
2233 * The event filter
2234 * @param startIndex
2235 * The index at which we should start searching
2236 * @param currentRank
2237 * The current rank
2238 * @param direction
2239 * In which direction should we search, forward or backwards
2240 */
2241 public SearchThread(final ITmfFilterTreeNode searchFilter,
2242 final ITmfFilterTreeNode eventFilter, final int startIndex,
2243 final long currentRank, final int direction) {
2244 super(Messages.TmfEventsTable_SearchingJobName);
2245 this.searchFilter = searchFilter;
2246 this.eventFilter = eventFilter;
2247 this.startIndex = startIndex;
2248 this.rank = currentRank;
2249 this.direction = direction;
2250 }
2251
2252 @Override
2253 protected IStatus run(final IProgressMonitor monitor) {
2254 final ITmfTrace trace = fTrace;
2255 if (trace == null) {
2256 return Status.OK_STATUS;
2257 }
2258 final Display display = Display.getDefault();
2259 if (startIndex < 0) {
2260 rank = (int) trace.getNbEvents() - 1;
2261 /*
2262 * -1 for header row, -3 for header and top and bottom filter
2263 * status rows
2264 */
2265 } else if (startIndex >= (fTable.getItemCount() - (eventFilter == null ? 1 : 3))) {
2266 rank = 0;
2267 } else {
2268 int idx = startIndex;
2269 while (foundRank == -1) {
2270 final CachedEvent event = fCache.peekEvent(idx);
2271 if (event == null) {
2272 break;
2273 }
2274 rank = event.rank;
2275 if (searchFilter.matches(event.event) && ((eventFilter == null) || eventFilter.matches(event.event))) {
2276 foundRank = event.rank;
2277 foundTimestamp = event.event.getTimestamp();
2278 break;
2279 }
2280 if (direction == Direction.FORWARD) {
2281 idx++;
2282 } else {
2283 idx--;
2284 }
2285 }
2286 if (foundRank == -1) {
2287 if (direction == Direction.FORWARD) {
2288 rank++;
2289 if (rank > (trace.getNbEvents() - 1)) {
2290 rank = 0;
2291 }
2292 } else {
2293 rank--;
2294 if (rank < 0) {
2295 rank = (int) trace.getNbEvents() - 1;
2296 }
2297 }
2298 }
2299 }
2300 final int startRank = (int) rank;
2301 boolean wrapped = false;
2302 while (!monitor.isCanceled() && (foundRank == -1)) {
2303 int nbRequested = (direction == Direction.FORWARD ? Integer.MAX_VALUE : Math.min((int) rank + 1, trace.getCacheSize()));
2304 if (direction == Direction.BACKWARD) {
2305 rank = Math.max(0, rank - trace.getCacheSize() + 1);
2306 }
2307 request = new TmfEventRequest(ITmfEvent.class, TmfTimeRange.ETERNITY,
2308 (int) rank, nbRequested, ExecutionType.BACKGROUND) {
2309 long currentRank = rank;
2310
2311 @Override
2312 public void handleData(final ITmfEvent event) {
2313 super.handleData(event);
2314 if (searchFilter.matches(event) && ((eventFilter == null) || eventFilter.matches(event))) {
2315 foundRank = currentRank;
2316 foundTimestamp = event.getTimestamp();
2317 if (direction == Direction.FORWARD) {
2318 done();
2319 return;
2320 }
2321 }
2322 currentRank++;
2323 }
2324 };
2325 ((ITmfEventProvider) trace).sendRequest(request);
2326 try {
2327 request.waitForCompletion();
2328 if (request.isCancelled()) {
2329 return Status.OK_STATUS;
2330 }
2331 } catch (final InterruptedException e) {
2332 synchronized (fSearchSyncObj) {
2333 fSearchThread = null;
2334 }
2335 return Status.OK_STATUS;
2336 }
2337 if (foundRank == -1) {
2338 if (direction == Direction.FORWARD) {
2339 if (rank == 0) {
2340 synchronized (fSearchSyncObj) {
2341 fSearchThread = null;
2342 }
2343 return Status.OK_STATUS;
2344 }
2345 nbRequested = (int) rank;
2346 rank = 0;
2347 wrapped = true;
2348 } else {
2349 rank--;
2350 if (rank < 0) {
2351 rank = (int) trace.getNbEvents() - 1;
2352 wrapped = true;
2353 }
2354 if ((rank <= startRank) && wrapped) {
2355 synchronized (fSearchSyncObj) {
2356 fSearchThread = null;
2357 }
2358 return Status.OK_STATUS;
2359 }
2360 }
2361 }
2362 }
2363 int index = (int) foundRank;
2364 if (eventFilter != null) {
2365 index = fCache.getFilteredEventIndex(foundRank);
2366 }
2367 /* +1 for header row, +1 for top filter status row */
2368 final int selection = index + 1 + (eventFilter != null ? +1 : 0);
2369
2370 display.asyncExec(new Runnable() {
2371 @Override
2372 public void run() {
2373 if (monitor.isCanceled()) {
2374 return;
2375 }
2376 if (fTable.isDisposed()) {
2377 return;
2378 }
2379 fTable.setSelection(selection);
2380 fSelectedRank = foundRank;
2381 fSelectedBeginRank = fSelectedRank;
2382 fRawViewer.selectAndReveal(fSelectedRank);
2383 if (foundTimestamp != null) {
2384 broadcast(new TmfSelectionRangeUpdatedSignal(TmfEventsTable.this, foundTimestamp));
2385 }
2386 fireSelectionChanged(new SelectionChangedEvent(TmfEventsTable.this, getSelection()));
2387 synchronized (fSearchSyncObj) {
2388 fSearchThread = null;
2389 }
2390 updateStatusLine(null);
2391 }
2392 });
2393 return Status.OK_STATUS;
2394 }
2395
2396 @Override
2397 protected void canceling() {
2398 request.cancel();
2399 synchronized (fSearchSyncObj) {
2400 fSearchThread = null;
2401 }
2402 }
2403 }
2404
2405 /**
2406 * Create the resources.
2407 */
2408 private void createResources() {
2409 fGrayColor = fResourceManager.createColor(ColorUtil.blend(fTable.getBackground().getRGB(), fTable.getForeground().getRGB()));
2410 fGreenColor = PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_DARK_GREEN);
2411 }
2412
2413 /**
2414 * Initialize the fonts.
2415 */
2416 private void initializeFonts() {
2417 FontRegistry fontRegistry = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getFontRegistry();
2418 fFont = fontRegistry.get(FONT_DEFINITION_ID);
2419 fBoldFont = fontRegistry.getBold(FONT_DEFINITION_ID);
2420 fTable.setFont(fFont);
2421 /* Column header font cannot be set. See Bug 63038 */
2422 }
2423
2424 /**
2425 * Initialize the colors.
2426 */
2427 private void initializeColors() {
2428 ColorRegistry colorRegistry = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getColorRegistry();
2429 fHighlightColor = colorRegistry.get(HIGHLIGHT_COLOR_DEFINITION_ID);
2430 }
2431
2432 /**
2433 * @since 1.0
2434 */
2435 @Override
2436 public void propertyChange(PropertyChangeEvent event) {
2437 if ((IThemeManager.CHANGE_CURRENT_THEME.equals(event.getProperty())) ||
2438 (FONT_DEFINITION_ID.equals(event.getProperty()))) {
2439 initializeFonts();
2440 fTable.refresh();
2441 }
2442 if ((IThemeManager.CHANGE_CURRENT_THEME.equals(event.getProperty())) ||
2443 (HIGHLIGHT_COLOR_DEFINITION_ID.equals(event.getProperty()))) {
2444 initializeColors();
2445 fTable.refresh();
2446 }
2447 }
2448
2449 /**
2450 * Pack the columns.
2451 */
2452 protected void packColumns() {
2453 if (fPackDone) {
2454 return;
2455 }
2456 fTable.setRedraw(false);
2457 try {
2458 TableColumn tableColumns[] = fTable.getColumns();
2459 for (int i = 0; i < tableColumns.length; i++) {
2460 final TableColumn column = tableColumns[i];
2461 packSingleColumn(i, column);
2462 }
2463
2464 } finally {
2465 // Make sure that redraw is always enabled.
2466 fTable.setRedraw(true);
2467 }
2468 fPackDone = true;
2469 }
2470
2471 private void packMarginColumn() {
2472 TableColumn[] columns = fTable.getColumns();
2473 if (columns.length > 0) {
2474 packSingleColumn(0, columns[0]);
2475 }
2476 }
2477
2478 private void packSingleColumn(int i, final TableColumn column) {
2479 final int headerWidth = column.getWidth();
2480 column.pack();
2481 /*
2482 * Workaround for Linux which doesn't consider the image width of
2483 * search/filter row in TableColumn.pack() after having executed
2484 * TableItem.setImage(null) for other rows than search/filter row.
2485 */
2486 boolean isCollapseFilter = fTable.getData(Key.FILTER_OBJ) instanceof TmfCollapseFilter;
2487 if (IS_LINUX && (i == 0) && isCollapseFilter) {
2488 column.setWidth(column.getWidth() + SEARCH_IMAGE.getBounds().width);
2489 }
2490
2491 if (column.getWidth() < headerWidth) {
2492 column.setWidth(headerWidth);
2493 }
2494 }
2495
2496 /**
2497 * Returns true if the column is a visible event column.
2498 *
2499 * @param column the column
2500 * @return false if the column is the margin column or hidden, true otherwise
2501 */
2502 private static boolean isVisibleEventColumn(TableColumn column) {
2503 if (column.getData(Key.ASPECT) == TmfMarginColumn.MARGIN_ASPECT) {
2504 return false;
2505 }
2506 if (!column.getResizable() && column.getWidth() == 0) {
2507 return false;
2508 }
2509 return true;
2510 }
2511
2512 /**
2513 * Get the array of item strings (e.g., what to display in each cell of the
2514 * table row) corresponding to the columns and trace event passed in
2515 * parameter. The order of the Strings in the returned array will correspond
2516 * to the iteration order of 'columns'.
2517 *
2518 * <p>
2519 * To ensure consistent results, make sure only call this within a scope
2520 * synchronized on 'columns'! If the order of 'columns' changes right after
2521 * this method is called, the returned value won't be ordered correctly
2522 * anymore.
2523 */
2524 private static String[] getItemStrings(List<TmfEventTableColumn> columns, ITmfEvent event) {
2525 if (event == null) {
2526 return EMPTY_STRING_ARRAY;
2527 }
2528 synchronized (columns) {
2529 List<String> itemStrings = new ArrayList<>(columns.size());
2530 for (TmfEventTableColumn column : columns) {
2531 ITmfEvent passedEvent = event;
2532 if (!(column instanceof TmfMarginColumn) && (event instanceof CachedEvent)) {
2533 /*
2534 * Make sure that the event object from the trace is passed
2535 * to all columns but the TmfMarginColumn
2536 */
2537 passedEvent = ((CachedEvent) event).event;
2538 }
2539 if (passedEvent == null) {
2540 itemStrings.add(EMPTY_STRING);
2541 } else {
2542 itemStrings.add(column.getItemString(passedEvent));
2543 }
2544
2545 }
2546 return itemStrings.toArray(new String[0]);
2547 }
2548 }
2549
2550 /**
2551 * Get the contents of the row in the events table corresponding to an
2552 * event. The order of the elements corresponds to the current order of the
2553 * columns.
2554 *
2555 * @param event
2556 * The event printed in this row
2557 * @return The event row entries
2558 */
2559 public String[] getItemStrings(ITmfEvent event) {
2560 List<TmfEventTableColumn> columns = new ArrayList<>();
2561 for (int i : fTable.getColumnOrder()) {
2562 columns.add(fColumns.get(i));
2563 }
2564 return getItemStrings(columns, event);
2565 }
2566
2567 /**
2568 * Returns an array of zero-relative integers that map the creation order of
2569 * the receiver's columns to the order in which they are currently being
2570 * displayed.
2571 * <p>
2572 * Specifically, the indices of the returned array represent the current
2573 * visual order of the columns, and the contents of the array represent the
2574 * creation order of the columns.
2575 *
2576 * @return the current visual order of the receiver's columns
2577 * @since 1.0
2578 */
2579 public int[] getColumnOrder() {
2580 return fColumnOrder;
2581 }
2582
2583 /**
2584 * Sets the order that the columns in the receiver should be displayed in to
2585 * the given argument which is described in terms of the zero-relative
2586 * ordering of when the columns were added.
2587 * <p>
2588 * Specifically, the contents of the array represent the original position
2589 * of each column at the time its creation.
2590 *
2591 * @param order
2592 * the new order to display the columns
2593 * @since 1.0
2594 */
2595 public void setColumnOrder(int[] order) {
2596 if (order == null || order.length != fTable.getColumns().length) {
2597 return;
2598 }
2599 fTable.setColumnOrder(order);
2600 fColumnOrder = fTable.getColumnOrder();
2601 }
2602
2603 /**
2604 * Notify this table that is got the UI focus.
2605 */
2606 public void setFocus() {
2607 fTable.setFocus();
2608 }
2609
2610 /**
2611 * Registers context menus with a site for extension. This method can be
2612 * called for part sites so that context menu contributions can be added.
2613 *
2614 * @param site
2615 * the site that the context menus will be registered for
2616 *
2617 * @since 2.0
2618 */
2619 public void registerContextMenus(IWorkbenchPartSite site) {
2620 if (site instanceof IEditorSite) {
2621 IEditorSite editorSite = (IEditorSite) site;
2622 // Don't use the editor input when adding contributions, otherwise
2623 // we get too many unwanted things.
2624 editorSite.registerContextMenu(fTablePopupMenuManager, this, false);
2625 }
2626 }
2627
2628 /**
2629 * Assign a new trace to this event table.
2630 *
2631 * @param trace
2632 * The trace to assign to this event table
2633 * @param disposeOnClose
2634 * true if the trace should be disposed when the table is
2635 * disposed
2636 */
2637 public void setTrace(final ITmfTrace trace, final boolean disposeOnClose) {
2638 if ((fTrace != null) && fDisposeOnClose) {
2639 fTrace.dispose();
2640 }
2641 fTrace = trace;
2642 fPackDone = false;
2643 fDisposeOnClose = disposeOnClose;
2644
2645 // Perform the updates on the UI thread
2646 PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
2647 @Override
2648 public void run() {
2649 fSelectedRank = -1;
2650 fSelectedBeginRank = -1;
2651 fTable.removeAll();
2652 fCache.setTrace(trace); // Clear the cache
2653 if (trace != null) {
2654 if (!fTable.isDisposed()) {
2655 if (fTable.getData(Key.FILTER_OBJ) == null) {
2656 // +1 for header row
2657 fTable.setItemCount((int) trace.getNbEvents() + 1);
2658 } else {
2659 stopFilterThread();
2660 fFilterMatchCount = 0;
2661 fFilterCheckCount = 0;
2662 /*
2663 * +1 for header row, +2 for top and bottom filter
2664 * status rows
2665 */
2666 fTable.setItemCount(3);
2667 startFilterThread();
2668 }
2669 }
2670 }
2671 fRawViewer.setTrace(trace);
2672 }
2673 });
2674 }
2675
2676 /**
2677 * Assign the status line manager
2678 *
2679 * @param statusLineManager
2680 * The status line manager, or null to disable status line
2681 * messages
2682 */
2683 public void setStatusLineManager(IStatusLineManager statusLineManager) {
2684 if (fStatusLineManager != null && statusLineManager == null) {
2685 fStatusLineManager.setMessage(EMPTY_STRING);
2686 }
2687 fStatusLineManager = statusLineManager;
2688 }
2689
2690 private void updateStatusLine(ITmfTimestamp delta) {
2691 if (fStatusLineManager != null) {
2692 if (delta != null) {
2693 fStatusLineManager.setMessage("\u0394: " + delta); //$NON-NLS-1$
2694 } else {
2695 fStatusLineManager.setMessage(null);
2696 }
2697 }
2698 }
2699
2700 // ------------------------------------------------------------------------
2701 // Event cache
2702 // ------------------------------------------------------------------------
2703
2704 /**
2705 * Notify that the event cache has been updated
2706 *
2707 * @param completed
2708 * Also notify if the populating of the cache is complete, or
2709 * not.
2710 */
2711 public void cacheUpdated(final boolean completed) {
2712 synchronized (fCacheUpdateSyncObj) {
2713 if (fCacheUpdateBusy) {
2714 fCacheUpdatePending = true;
2715 fCacheUpdateCompleted = completed;
2716 return;
2717 }
2718 fCacheUpdateBusy = true;
2719 }
2720 // Event cache is now updated. Perform update on the UI thread
2721 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
2722 @Override
2723 public void run() {
2724 if (!fTable.isDisposed()) {
2725 fTable.refresh();
2726 packColumns();
2727 }
2728 if (completed) {
2729 populateCompleted();
2730 }
2731 synchronized (fCacheUpdateSyncObj) {
2732 fCacheUpdateBusy = false;
2733 if (fCacheUpdatePending) {
2734 fCacheUpdatePending = false;
2735 cacheUpdated(fCacheUpdateCompleted);
2736 }
2737 }
2738 }
2739 });
2740 }
2741
2742 /**
2743 * Callback for when populating the table is complete.
2744 */
2745 protected void populateCompleted() {
2746 // Nothing by default;
2747 }
2748
2749 // ------------------------------------------------------------------------
2750 // ISelectionProvider
2751 // ------------------------------------------------------------------------
2752
2753 @Override
2754 public void addSelectionChangedListener(ISelectionChangedListener listener) {
2755 selectionChangedListeners.add(listener);
2756 }
2757
2758 @Override
2759 public ISelection getSelection() {
2760 if (fTable == null || fTable.isDisposed()) {
2761 return StructuredSelection.EMPTY;
2762 }
2763 List<Object> list = new ArrayList<>(fTable.getSelection().length);
2764 for (TableItem item : fTable.getSelection()) {
2765 if (item.getData() != null) {
2766 list.add(item.getData());
2767 }
2768 }
2769 return new StructuredSelection(list);
2770 }
2771
2772 @Override
2773 public void removeSelectionChangedListener(ISelectionChangedListener listener) {
2774 selectionChangedListeners.remove(listener);
2775 }
2776
2777 @Override
2778 public void setSelection(ISelection selection) {
2779 // not implemented
2780 }
2781
2782 /**
2783 * Notifies any selection changed listeners that the viewer's selection has
2784 * changed. Only listeners registered at the time this method is called are
2785 * notified.
2786 *
2787 * @param event
2788 * a selection changed event
2789 *
2790 * @see ISelectionChangedListener#selectionChanged
2791 */
2792 protected void fireSelectionChanged(final SelectionChangedEvent event) {
2793 Object[] listeners = selectionChangedListeners.getListeners();
2794 for (int i = 0; i < listeners.length; ++i) {
2795 final ISelectionChangedListener l = (ISelectionChangedListener) listeners[i];
2796 SafeRunnable.run(new SafeRunnable() {
2797 @Override
2798 public void run() {
2799 l.selectionChanged(event);
2800 }
2801 });
2802 }
2803 }
2804
2805 // ------------------------------------------------------------------------
2806 // Bookmark handling
2807 // ------------------------------------------------------------------------
2808
2809 /**
2810 * Add a bookmark to this event table.
2811 *
2812 * @param bookmarksFile
2813 * The file to use for the bookmarks
2814 */
2815 public void addBookmark(final IFile bookmarksFile) {
2816 fBookmarksFile = bookmarksFile;
2817 final TableItem[] selection = fTable.getSelection();
2818 if (selection.length > 0) {
2819 final TableItem tableItem = selection[0];
2820 if (tableItem.getData(Key.RANK) != null) {
2821 final StringBuffer defaultMessage = new StringBuffer();
2822 for (int i : fTable.getColumnOrder()) {
2823 TableColumn column = fTable.getColumns()[i];
2824 // Omit the margin column and hidden columns
2825 if (isVisibleEventColumn(column)) {
2826 if (defaultMessage.length() > 0) {
2827 defaultMessage.append(", "); //$NON-NLS-1$
2828 }
2829 defaultMessage.append(tableItem.getText(i));
2830 }
2831 }
2832 final AddBookmarkDialog dialog = new AddBookmarkDialog(
2833 PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), defaultMessage.toString());
2834 if (dialog.open() == Window.OK) {
2835 final String message = dialog.getValue();
2836 try {
2837 final Long rank = (Long) tableItem.getData(Key.RANK);
2838 final String location = NLS.bind(Messages.TmfMarker_LocationRank, rank.toString());
2839 final ITmfTimestamp timestamp = (ITmfTimestamp) tableItem.getData(Key.TIMESTAMP);
2840 final long[] id = new long[1];
2841 ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
2842 @Override
2843 public void run(IProgressMonitor monitor) throws CoreException {
2844 final IMarker bookmark = bookmarksFile.createMarker(IMarker.BOOKMARK);
2845 bookmark.setAttribute(IMarker.MESSAGE, message.toString());
2846 bookmark.setAttribute(IMarker.LOCATION, location);
2847 bookmark.setAttribute(ITmfMarker.MARKER_RANK, rank.toString());
2848 bookmark.setAttribute(ITmfMarker.MARKER_TIME, Long.toString(new TmfNanoTimestamp(timestamp).getValue()));
2849 bookmark.setAttribute(ITmfMarker.MARKER_COLOR, dialog.getColorValue().toString());
2850 id[0] = bookmark.getId();
2851 }
2852 }, null);
2853 fBookmarksMap.put(rank, id[0]);
2854 fTable.refresh();
2855 } catch (final CoreException e) {
2856 displayException(e);
2857 }
2858 }
2859 }
2860 }
2861
2862 }
2863
2864 /**
2865 * Add one or more bookmarks to this event table.
2866 *
2867 * @param bookmarks
2868 * The bookmarks to add
2869 * @since 2.0
2870 */
2871 public void addBookmark(final IMarker... bookmarks) {
2872 for (IMarker bookmark : bookmarks) {
2873 /* try location as an integer for backward compatibility */
2874 long rank = bookmark.getAttribute(IMarker.LOCATION, -1);
2875 if (rank == -1) {
2876 String rankString = bookmark.getAttribute(ITmfMarker.MARKER_RANK, (String) null);
2877 if (rankString != null) {
2878 try {
2879 rank = Long.parseLong(rankString);
2880 } catch (NumberFormatException e) {
2881 Activator.getDefault().logError("Invalid marker rank", e); //$NON-NLS-1$
2882 }
2883 }
2884 }
2885 if (rank != -1) {
2886 fBookmarksMap.put(rank, bookmark.getId());
2887 }
2888 }
2889 fTable.refresh();
2890 }
2891
2892 /**
2893 * Remove one or more bookmarks from this event table.
2894 *
2895 * @param bookmarks
2896 * The bookmarks to remove
2897 * @since 2.0
2898 */
2899 public void removeBookmark(final IMarker... bookmarks) {
2900 for (IMarker bookmark : bookmarks) {
2901 for (final Entry<Long, Long> entry : fBookmarksMap.entries()) {
2902 if (entry.getValue().equals(bookmark.getId())) {
2903 fBookmarksMap.remove(entry.getKey(), entry.getValue());
2904 break;
2905 }
2906 }
2907 }
2908 fTable.refresh();
2909 }
2910
2911 private void toggleBookmark(final Long rank) {
2912 if (fBookmarksFile == null) {
2913 return;
2914 }
2915 if (fBookmarksMap.containsKey(rank)) {
2916 final Collection<Long> markerIds = fBookmarksMap.removeAll(rank);
2917 fTable.refresh();
2918 try {
2919 for (long markerId : markerIds) {
2920 final IMarker bookmark = fBookmarksFile.findMarker(markerId);
2921 if (bookmark != null) {
2922 bookmark.delete();
2923 }
2924 }
2925 } catch (final CoreException e) {
2926 displayException(e);
2927 }
2928 } else {
2929 addBookmark(fBookmarksFile);
2930 }
2931 }
2932
2933 /**
2934 * Refresh the bookmarks assigned to this trace, from the contents of a
2935 * bookmark file.
2936 *
2937 * @param bookmarksFile
2938 * The bookmark file to use
2939 */
2940 public void refreshBookmarks(final IFile bookmarksFile) {
2941 fBookmarksFile = bookmarksFile;
2942 if (bookmarksFile == null) {
2943 fBookmarksMap.clear();
2944 fTable.refresh();
2945 return;
2946 }
2947 try {
2948 fBookmarksMap.clear();
2949 IMarker[] bookmarks = bookmarksFile.findMarkers(IMarker.BOOKMARK, false, IResource.DEPTH_ZERO);
2950 addBookmark(bookmarks);
2951 } catch (final CoreException e) {
2952 displayException(e);
2953 }
2954 }
2955
2956 @Override
2957 public void gotoMarker(final IMarker marker) {
2958 ITmfTimestamp tsBegin = null;
2959 ITmfTimestamp tsEnd = null;
2960 /* try location as an integer for backward compatibility */
2961 long rank = marker.getAttribute(IMarker.LOCATION, -1);
2962 if (rank == -1) {
2963 String rankString = marker.getAttribute(ITmfMarker.MARKER_RANK, (String) null);
2964 try {
2965 rank = Long.parseLong(rankString);
2966 } catch (NumberFormatException e) {
2967 /* ignored */
2968 }
2969 }
2970 try {
2971 String timeString = marker.getAttribute(ITmfMarker.MARKER_TIME, (String) null);
2972 long time = Long.parseLong(timeString);
2973 tsBegin = new TmfNanoTimestamp(time);
2974 String durationString = marker.getAttribute(ITmfMarker.MARKER_DURATION, (String) null);
2975 long duration = Long.parseLong(durationString);
2976 tsEnd = new TmfNanoTimestamp(time + duration);
2977 } catch (NumberFormatException e) {
2978 /* ignored */
2979 }
2980 if (rank == -1 && tsBegin != null) {
2981 final ITmfContext context = fTrace.seekEvent(tsBegin);
2982 rank = context.getRank();
2983 context.dispose();
2984 }
2985 if (rank != -1) {
2986 int index = (int) rank;
2987 if (fTable.getData(Key.FILTER_OBJ) != null) {
2988 // +1 for top filter status row
2989 index = fCache.getFilteredEventIndex(rank) + 1;
2990 } else if (rank >= fTable.getItemCount()) {
2991 fPendingGotoRank = rank;
2992 }
2993 fSelectedRank = rank;
2994 fSelectedBeginRank = fSelectedRank;
2995 fTable.setSelection(index + 1); // +1 for header row
2996 updateStatusLine(null);
2997 if (tsBegin != null) {
2998 if (tsEnd != null) {
2999 broadcast(new TmfSelectionRangeUpdatedSignal(TmfEventsTable.this, tsBegin, tsEnd));
3000 } else {
3001 broadcast(new TmfSelectionRangeUpdatedSignal(TmfEventsTable.this, tsBegin));
3002 }
3003 }
3004 }
3005 }
3006
3007 // ------------------------------------------------------------------------
3008 // Listeners
3009 // ------------------------------------------------------------------------
3010
3011 @Override
3012 public void colorSettingsChanged(final ColorSetting[] colorSettings) {
3013 fTable.refresh();
3014 }
3015
3016 // ------------------------------------------------------------------------
3017 // Signal handlers
3018 // ------------------------------------------------------------------------
3019
3020 /**
3021 * Handler for the trace updated signal
3022 *
3023 * @param signal
3024 * The incoming signal
3025 */
3026 @TmfSignalHandler
3027 public void traceUpdated(final TmfTraceUpdatedSignal signal) {
3028 if ((signal.getTrace() != fTrace) || fTable.isDisposed()) {
3029 return;
3030 }
3031 // Perform the refresh on the UI thread
3032 Display.getDefault().asyncExec(new Runnable() {
3033 @Override
3034 public void run() {
3035 if (!fTable.isDisposed() && (fTrace != null)) {
3036 if (fTable.getData(Key.FILTER_OBJ) == null) {
3037 /* +1 for header row */
3038 fTable.setItemCount((int) fTrace.getNbEvents() + 1);
3039 /* +1 for header row */
3040 if ((fPendingGotoRank != -1) && ((fPendingGotoRank + 1) < fTable.getItemCount())) {
3041 /* +1 for header row */
3042 fTable.setSelection((int) fPendingGotoRank + 1);
3043 fPendingGotoRank = -1;
3044 updateStatusLine(null);
3045 }
3046 } else {
3047 startFilterThread();
3048 }
3049 }
3050 if (!fRawViewer.isDisposed() && (fTrace != null)) {
3051 fRawViewer.refreshEventCount();
3052 }
3053 }
3054 });
3055 }
3056
3057 /**
3058 * Handler for the selection range signal.
3059 *
3060 * @param signal
3061 * The incoming signal
3062 * @since 1.0
3063 */
3064 @TmfSignalHandler
3065 public void selectionRangeUpdated(final TmfSelectionRangeUpdatedSignal signal) {
3066 if ((signal.getSource() != this) && (fTrace != null) && (!fTable.isDisposed())) {
3067
3068 /*
3069 * Create a request for one event that will be queued after other
3070 * ongoing requests. When this request is completed do the work to
3071 * select the actual event with the timestamp specified in the
3072 * signal. This procedure prevents the method fTrace.getRank() from
3073 * interfering and delaying ongoing requests.
3074 */
3075 final TmfEventRequest subRequest = new TmfEventRequest(ITmfEvent.class,
3076 TmfTimeRange.ETERNITY, 0, 1, ExecutionType.FOREGROUND) {
3077
3078 TmfTimestamp ts = new TmfTimestamp(signal.getBeginTime());
3079
3080 @Override
3081 public void handleData(final ITmfEvent event) {
3082 super.handleData(event);
3083 }
3084
3085 @Override
3086 public void handleSuccess() {
3087 super.handleSuccess();
3088 if (fTrace == null) {
3089 return;
3090 }
3091
3092 /*
3093 * Verify if the event is within the trace range and adjust
3094 * if necessary
3095 */
3096 ITmfTimestamp timestamp = ts;
3097 if (timestamp.compareTo(fTrace.getStartTime()) == -1) {
3098 timestamp = fTrace.getStartTime();
3099 }
3100 if (timestamp.compareTo(fTrace.getEndTime()) == 1) {
3101 timestamp = fTrace.getEndTime();
3102 }
3103
3104 // Get the rank of the selected event in the table
3105 final ITmfContext context = fTrace.seekEvent(timestamp);
3106 final long rank = context.getRank();
3107 context.dispose();
3108
3109 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
3110 @Override
3111 public void run() {
3112 // Return if table is disposed
3113 if (fTable.isDisposed()) {
3114 return;
3115 }
3116
3117 fSelectedRank = rank;
3118 fSelectedBeginRank = fSelectedRank;
3119 int index = (int) rank;
3120 if (fTable.getData(Key.FILTER_OBJ) != null) {
3121 /* +1 for top filter status row */
3122 index = fCache.getFilteredEventIndex(rank) + 1;
3123 }
3124 /* +1 for header row */
3125 fTable.setSelection(index + 1);
3126 fRawViewer.selectAndReveal(rank);
3127 updateStatusLine(null);
3128 }
3129 });
3130 }
3131 };
3132
3133 ((ITmfEventProvider) fTrace).sendRequest(subRequest);
3134 }
3135 }
3136
3137 // ------------------------------------------------------------------------
3138 // Error handling
3139 // ------------------------------------------------------------------------
3140
3141 /**
3142 * Display an exception in a message box
3143 *
3144 * @param e
3145 * the exception
3146 */
3147 private static void displayException(final Exception e) {
3148 final MessageBox mb = new MessageBox(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
3149 mb.setText(e.getClass().getSimpleName());
3150 mb.setMessage(e.getMessage());
3151 mb.open();
3152 }
3153
3154 /**
3155 * Refresh the table
3156 */
3157 public void refresh() {
3158 fCache.clear();
3159 fTable.refresh();
3160 fTable.redraw();
3161 }
3162
3163 /**
3164 * Margin column for images and special text (e.g. collapse count)
3165 */
3166 private static final class TmfMarginColumn extends TmfEventTableColumn {
3167
3168 private static final @NonNull ITmfEventAspect MARGIN_ASPECT = new ITmfEventAspect() {
3169
3170 @Override
3171 public String getName() {
3172 return EMPTY_STRING;
3173 }
3174
3175 @Override
3176 public String resolve(ITmfEvent event) {
3177 if (!(event instanceof CachedEvent) || ((CachedEvent) event).repeatCount == 0) {
3178 return EMPTY_STRING;
3179 }
3180 return "+" + ((CachedEvent) event).repeatCount; //$NON-NLS-1$
3181 }
3182
3183 @Override
3184 public String getHelpText() {
3185 return EMPTY_STRING;
3186 }
3187 };
3188
3189 /**
3190 * Constructor
3191 */
3192 public TmfMarginColumn() {
3193 super(MARGIN_ASPECT);
3194 }
3195 }
3196
3197 }
This page took 0.115473 seconds and 6 git commands to generate.