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