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