tmf: Add command to manually refresh traces
[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 2.0
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 || cs.getFileName() == 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 final ArrayList<IFile> files = new ArrayList<>();
1029 ResourcesPlugin.getWorkspace().getRoot().accept(new IResourceVisitor() {
1030 @Override
1031 public boolean visit(IResource resource) throws CoreException {
1032 if (resource instanceof IFile && resource.getFullPath().toString().endsWith(trimmedPath)) {
1033 files.add((IFile) resource);
1034 }
1035 return true;
1036 }
1037 });
1038 IFile file = null;
1039 if (files.size() > 1) {
1040 ListDialog dialog = new ListDialog(getTable().getShell());
1041 dialog.setContentProvider(ArrayContentProvider.getInstance());
1042 dialog.setLabelProvider(new LabelProvider() {
1043 @Override
1044 public String getText(Object element) {
1045 return ((IFile) element).getFullPath().toString();
1046 }
1047 });
1048 dialog.setInput(files);
1049 dialog.setTitle(Messages.TmfEventsTable_OpenSourceCodeSelectFileDialogTitle);
1050 dialog.setMessage(Messages.TmfEventsTable_OpenSourceCodeSelectFileDialogTitle + '\n' + cs.toString());
1051 dialog.open();
1052 Object[] result = dialog.getResult();
1053 if (result != null && result.length > 0) {
1054 file = (IFile) result[0];
1055 }
1056 } else if (files.size() == 1) {
1057 file = files.get(0);
1058 }
1059 if (file != null) {
1060 marker = file.createMarker(IMarker.MARKER);
1061 marker.setAttribute(IMarker.LINE_NUMBER, Long.valueOf(cs.getLineNumber()).intValue());
1062 IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), marker);
1063 marker.delete();
1064 } else if (files.size() == 0) {
1065 displayException(new FileNotFoundException('\'' + cs.toString() + '\'' + '\n' + Messages.TmfEventsTable_OpenSourceCodeNotFound));
1066 }
1067 } catch (CoreException e) {
1068 displayException(e);
1069 }
1070 }
1071 }
1072 };
1073
1074 final IAction openModelAction = new Action(Messages.TmfEventsTable_OpenModelActionText) {
1075 @Override
1076 public void run() {
1077
1078 final TableItem items[] = fTable.getSelection();
1079 if (items.length != 1) {
1080 return;
1081 }
1082 final TableItem item = items[0];
1083
1084 final Object eventData = item.getData();
1085 if (eventData instanceof ITmfModelLookup) {
1086 String modelURI = ((ITmfModelLookup) eventData).getModelUri();
1087
1088 if (modelURI != null) {
1089 IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
1090
1091 IFile file = null;
1092 final URI uri = URI.createURI(modelURI);
1093 if (uri.isPlatformResource()) {
1094 IPath path = new Path(uri.toPlatformString(true));
1095 file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
1096 } else if (uri.isFile() && !uri.isRelative()) {
1097 file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(
1098 new Path(uri.toFileString()));
1099 }
1100
1101 if (file != null) {
1102 try {
1103 /*
1104 * create a temporary validation marker on the
1105 * model file, remove it afterwards thus,
1106 * navigation works with all model editors
1107 * supporting the navigation to a marker
1108 */
1109 IMarker marker = file.createMarker(EValidator.MARKER);
1110 marker.setAttribute(EValidator.URI_ATTRIBUTE, modelURI);
1111 marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO);
1112
1113 IDE.openEditor(activePage, marker, OpenStrategy.activateOnOpen());
1114 marker.delete();
1115 } catch (CoreException e) {
1116 displayException(e);
1117 }
1118 } else {
1119 displayException(new FileNotFoundException('\'' + modelURI + '\'' + '\n' + Messages.TmfEventsTable_OpenModelUnsupportedURI));
1120 }
1121 }
1122 }
1123 }
1124 };
1125
1126 final IAction exportToTextAction = new Action(Messages.TmfEventsTable_Export_to_text) {
1127 @Override
1128 public void run() {
1129 IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
1130 Object handlerServiceObject = activePage.getActiveEditor().getSite().getService(IHandlerService.class);
1131 IHandlerService handlerService = (IHandlerService) handlerServiceObject;
1132 Object cmdServiceObject = activePage.getActiveEditor().getSite().getService(ICommandService.class);
1133 ICommandService cmdService = (ICommandService) cmdServiceObject;
1134 try {
1135 HashMap<String, Object> parameters = new HashMap<>();
1136 Command command = cmdService.getCommand(ExportToTextCommandHandler.COMMAND_ID);
1137 ParameterizedCommand cmd = ParameterizedCommand.generateCommand(command, parameters);
1138
1139 IEvaluationContext context = handlerService.getCurrentState();
1140 List<TmfEventTableColumn> exportColumns = new ArrayList<>();
1141 for (int i : fTable.getColumnOrder()) {
1142 TableColumn column = fTable.getColumns()[i];
1143 // Omit the margin column and hidden columns
1144 if (i >= EVENT_COLUMNS_START_INDEX && (column.getResizable() || column.getWidth() > 0)) {
1145 exportColumns.add(fColumns.get(i));
1146 }
1147 }
1148 context.addVariable(ExportToTextCommandHandler.TMF_EVENT_TABLE_COLUMNS_ID, exportColumns);
1149
1150 handlerService.executeCommandInContext(cmd, null, context);
1151 } catch (ExecutionException | NotDefinedException | NotEnabledException | NotHandledException e) {
1152 displayException(e);
1153 }
1154 }
1155 };
1156
1157 final IAction showSearchBarAction = new Action(Messages.TmfEventsTable_ShowSearchBarActionText) {
1158 @Override
1159 public void run() {
1160 fHeaderState = HeaderState.SEARCH;
1161 fTable.refresh();
1162 fTable.redraw();
1163 }
1164 };
1165
1166 final IAction showFilterBarAction = new Action(Messages.TmfEventsTable_ShowFilterBarActionText) {
1167 @Override
1168 public void run() {
1169 fHeaderState = HeaderState.FILTER;
1170 fTable.refresh();
1171 fTable.redraw();
1172 }
1173 };
1174
1175 final IAction clearFiltersAction = new Action(Messages.TmfEventsTable_ClearFiltersActionText) {
1176 @Override
1177 public void run() {
1178 clearFilters();
1179 }
1180 };
1181
1182 final IAction collapseAction = new Action(Messages.TmfEventsTable_CollapseFilterMenuName) {
1183 @Override
1184 public void run() {
1185 applyFilter(new TmfCollapseFilter());
1186 }
1187 };
1188
1189 class ToggleBookmarkAction extends Action {
1190 Long fRank;
1191
1192 public ToggleBookmarkAction(final String text, final Long rank) {
1193 super(text);
1194 fRank = rank;
1195 }
1196
1197 @Override
1198 public void run() {
1199 toggleBookmark(fRank);
1200 }
1201 }
1202
1203 fHeaderPopupMenuManager = new MenuManager();
1204 fHeaderPopupMenuManager.setRemoveAllWhenShown(true);
1205 fHeaderPopupMenuManager.addMenuListener(new IMenuListener() {
1206 @Override
1207 public void menuAboutToShow(IMenuManager manager) {
1208 for (int index : fTable.getColumnOrder()) {
1209 if (fTable.getColumns()[index].getData(Key.WIDTH) != null) {
1210 fHeaderPopupMenuManager.add(createHeaderAction(fTable.getColumns()[index]));
1211 }
1212 }
1213 fHeaderPopupMenuManager.add(new Separator());
1214 fHeaderPopupMenuManager.add(createResetHeaderAction());
1215 }
1216 });
1217
1218 fTablePopupMenuManager = new MenuManager();
1219 fTablePopupMenuManager.setRemoveAllWhenShown(true);
1220 fTablePopupMenuManager.addMenuListener(new IMenuListener() {
1221 @Override
1222 public void menuAboutToShow(final IMenuManager manager) {
1223 if (fTable.getSelectionIndices().length == 1 && fTable.getSelectionIndices()[0] == 0) {
1224 // Right-click on header row
1225 if (fHeaderState == HeaderState.FILTER) {
1226 fTablePopupMenuManager.add(showSearchBarAction);
1227 } else {
1228 fTablePopupMenuManager.add(showFilterBarAction);
1229 }
1230 return;
1231 }
1232 final Point point = fTable.toControl(fLastMenuCursorLocation);
1233 final TableItem item = fTable.getSelection().length > 0 ? fTable.getSelection()[0] : null;
1234 if (item != null) {
1235 final Rectangle imageBounds = item.getImageBounds(0);
1236 imageBounds.width = BOOKMARK_IMAGE.getBounds().width;
1237 if (point.x <= (imageBounds.x + imageBounds.width)) {
1238 // Right-click on left margin
1239 final Long rank = (Long) item.getData(Key.RANK);
1240 if ((rank != null) && (fBookmarksFile != null)) {
1241 if (fBookmarksMap.containsKey(rank)) {
1242 fTablePopupMenuManager.add(new ToggleBookmarkAction(
1243 Messages.TmfEventsTable_RemoveBookmarkActionText, rank));
1244 } else {
1245 fTablePopupMenuManager.add(new ToggleBookmarkAction(
1246 Messages.TmfEventsTable_AddBookmarkActionText, rank));
1247 }
1248 }
1249 return;
1250 }
1251 }
1252
1253 // Right-click on table
1254 if (fSelectedRank != -1 && fSelectedBeginRank != -1) {
1255 fTablePopupMenuManager.add(copyAction);
1256 fTablePopupMenuManager.add(new Separator());
1257 }
1258 if (fTable.isVisible() && fRawViewer.isVisible()) {
1259 fTablePopupMenuManager.add(hideTableAction);
1260 fTablePopupMenuManager.add(hideRawAction);
1261 } else if (!fTable.isVisible()) {
1262 fTablePopupMenuManager.add(showTableAction);
1263 } else if (!fRawViewer.isVisible()) {
1264 fTablePopupMenuManager.add(showRawAction);
1265 }
1266 fTablePopupMenuManager.add(exportToTextAction);
1267 fTablePopupMenuManager.add(new Separator());
1268
1269 if (item != null) {
1270 final Object data = item.getData();
1271 Separator separator = null;
1272 if (data instanceof ITmfSourceLookup) {
1273 ITmfSourceLookup event = (ITmfSourceLookup) data;
1274 if (event.getCallsite() != null) {
1275 fTablePopupMenuManager.add(openCallsiteAction);
1276 separator = new Separator();
1277 }
1278 }
1279
1280 if (data instanceof ITmfModelLookup) {
1281 ITmfModelLookup event = (ITmfModelLookup) data;
1282 if (event.getModelUri() != null) {
1283 fTablePopupMenuManager.add(openModelAction);
1284 separator = new Separator();
1285 }
1286
1287 if (separator != null) {
1288 fTablePopupMenuManager.add(separator);
1289 }
1290 }
1291 }
1292
1293 /*
1294 * Only show collapse filter if at least one trace can be
1295 * collapsed.
1296 */
1297 boolean isCollapsible = false;
1298 if (fTrace != null) {
1299 for (ITmfTrace trace : TmfTraceManager.getTraceSet(fTrace)) {
1300 Class<? extends ITmfEvent> eventClass = trace.getEventType();
1301 isCollapsible = ITmfCollapsibleEvent.class.isAssignableFrom(eventClass);
1302 if (isCollapsible) {
1303 break;
1304 }
1305 }
1306 }
1307
1308 if (isCollapsible && !(fTable.getData(Key.FILTER_OBJ) instanceof TmfCollapseFilter)) {
1309 fTablePopupMenuManager.add(collapseAction);
1310 fTablePopupMenuManager.add(new Separator());
1311 }
1312
1313 fTablePopupMenuManager.add(clearFiltersAction);
1314 final ITmfFilterTreeNode[] savedFilters = FilterManager.getSavedFilters();
1315 if (savedFilters.length > 0) {
1316 final MenuManager subMenu = new MenuManager(Messages.TmfEventsTable_ApplyPresetFilterMenuName);
1317 for (final ITmfFilterTreeNode node : savedFilters) {
1318 if (node instanceof TmfFilterNode) {
1319 final TmfFilterNode filter = (TmfFilterNode) node;
1320 subMenu.add(new Action(filter.getFilterName()) {
1321 @Override
1322 public void run() {
1323 applyFilter(filter);
1324 }
1325 });
1326 }
1327 }
1328 fTablePopupMenuManager.add(subMenu);
1329 }
1330 appendToTablePopupMenu(fTablePopupMenuManager, item);
1331 }
1332 });
1333
1334 fRawViewerPopupMenuManager = new MenuManager();
1335 fRawViewerPopupMenuManager.setRemoveAllWhenShown(true);
1336 fRawViewerPopupMenuManager.addMenuListener(new IMenuListener() {
1337 @Override
1338 public void menuAboutToShow(final IMenuManager manager) {
1339 if (fTable.isVisible() && fRawViewer.isVisible()) {
1340 fRawViewerPopupMenuManager.add(hideTableAction);
1341 fRawViewerPopupMenuManager.add(hideRawAction);
1342 } else if (!fTable.isVisible()) {
1343 fRawViewerPopupMenuManager.add(showTableAction);
1344 } else if (!fRawViewer.isVisible()) {
1345 fRawViewerPopupMenuManager.add(showRawAction);
1346 }
1347 appendToRawPopupMenu(fRawViewerPopupMenuManager);
1348 }
1349 });
1350
1351 fHeaderMenu = fHeaderPopupMenuManager.createContextMenu(fTable);
1352
1353 fTablePopup = fTablePopupMenuManager.createContextMenu(fTable);
1354 fTable.setMenu(fTablePopup);
1355
1356 fRawTablePopup = fRawViewerPopupMenuManager.createContextMenu(fRawViewer);
1357 fRawViewer.setMenu(fRawTablePopup);
1358 }
1359
1360 /**
1361 * Append an item to the event table's pop-up menu.
1362 *
1363 * @param tablePopupMenu
1364 * The menu manager
1365 * @param selectedItem
1366 * The item to append
1367 */
1368 protected void appendToTablePopupMenu(final MenuManager tablePopupMenu, final TableItem selectedItem) {
1369 // override to append more actions
1370 }
1371
1372 /**
1373 * Append an item to the raw viewer's pop-up menu.
1374 *
1375 * @param rawViewerPopupMenu
1376 * The menu manager
1377 */
1378 protected void appendToRawPopupMenu(final MenuManager rawViewerPopupMenu) {
1379 // override to append more actions
1380 }
1381
1382 @Override
1383 public void dispose() {
1384 stopSearchThread();
1385 stopFilterThread();
1386 PlatformUI.getWorkbench().getThemeManager().removePropertyChangeListener(this);
1387 ColorSettingsManager.removeColorSettingsListener(this);
1388 fComposite.dispose();
1389 if ((fTrace != null) && fDisposeOnClose) {
1390 fTrace.dispose();
1391 }
1392 fResourceManager.dispose();
1393 fRawViewer.dispose();
1394 if (fRawViewerPopupMenuManager != null) {
1395 fRawViewerPopupMenuManager.dispose();
1396 }
1397 if (fHeaderPopupMenuManager != null) {
1398 fHeaderPopupMenuManager.dispose();
1399 }
1400 if (fTablePopupMenuManager != null) {
1401 fTablePopupMenuManager.dispose();
1402 }
1403
1404 super.dispose();
1405 }
1406
1407 /**
1408 * Assign a layout data object to this view.
1409 *
1410 * @param layoutData
1411 * The layout data to assign
1412 */
1413 public void setLayoutData(final Object layoutData) {
1414 fComposite.setLayoutData(layoutData);
1415 }
1416
1417 /**
1418 * Get the virtual table contained in this event table.
1419 *
1420 * @return The TMF virtual table
1421 */
1422 public TmfVirtualTable getTable() {
1423 return fTable;
1424 }
1425
1426 /**
1427 * @param columnData
1428 * columnData
1429 * @deprecated The column headers are now set at the constructor, this
1430 * shouldn't be called anymore.
1431 */
1432 @Deprecated
1433 protected void setColumnHeaders(final org.eclipse.tracecompass.tmf.ui.widgets.virtualtable.ColumnData[] columnData) {
1434 /* No-op */
1435 }
1436
1437 /**
1438 * Set a table item's data.
1439 *
1440 * @param item
1441 * The item to set
1442 * @param event
1443 * Which trace event to link with this entry
1444 * @param rank
1445 * Which rank this event has in the trace/experiment
1446 */
1447 protected void setItemData(final TableItem item, final ITmfEvent event, final long rank) {
1448 String[] itemStrings = getItemStrings(fColumns, event);
1449
1450 // Get the actual ITmfEvent from the CachedEvent
1451 ITmfEvent tmfEvent = event;
1452 if (event instanceof CachedEvent) {
1453 tmfEvent = ((CachedEvent) event).event;
1454 }
1455 item.setText(itemStrings);
1456 item.setData(tmfEvent);
1457 item.setData(Key.TIMESTAMP, new TmfTimestamp(tmfEvent.getTimestamp()));
1458 item.setData(Key.RANK, rank);
1459
1460 final Collection<Long> markerIds = fBookmarksMap.get(rank);
1461 if (!markerIds.isEmpty()) {
1462 Joiner joiner = Joiner.on("\n -").skipNulls(); //$NON-NLS-1$
1463 List<Object> parts = new ArrayList<>();
1464 if (markerIds.size() > 1) {
1465 parts.add(Messages.TmfEventsTable_MultipleBookmarksToolTip);
1466 }
1467 try {
1468 for (long markerId : markerIds) {
1469 final IMarker marker = fBookmarksFile.findMarker(markerId);
1470 parts.add(marker.getAttribute(IMarker.MESSAGE));
1471 }
1472 } catch (CoreException e) {
1473 displayException(e);
1474 }
1475 item.setData(Key.BOOKMARK, joiner.join(parts));
1476 } else {
1477 item.setData(Key.BOOKMARK, null);
1478 }
1479
1480 boolean searchMatch = false;
1481 boolean searchNoMatch = false;
1482 final ITmfFilter searchFilter = (ITmfFilter) fTable.getData(Key.SEARCH_OBJ);
1483 if (searchFilter != null) {
1484 if (searchFilter.matches(tmfEvent)) {
1485 searchMatch = true;
1486 } else {
1487 searchNoMatch = true;
1488 }
1489 }
1490
1491 final ColorSetting colorSetting = ColorSettingsManager.getColorSetting(tmfEvent);
1492 if (searchNoMatch) {
1493 item.setForeground(colorSetting.getDimmedForegroundColor());
1494 item.setBackground(colorSetting.getDimmedBackgroundColor());
1495 } else {
1496 item.setForeground(colorSetting.getForegroundColor());
1497 item.setBackground(colorSetting.getBackgroundColor());
1498 }
1499 item.setFont(fFont);
1500
1501 if (searchMatch) {
1502 if (!markerIds.isEmpty()) {
1503 item.setImage(SEARCH_MATCH_BOOKMARK_IMAGE);
1504 } else {
1505 item.setImage(SEARCH_MATCH_IMAGE);
1506 }
1507 } else if (!markerIds.isEmpty()) {
1508 item.setImage(BOOKMARK_IMAGE);
1509 } else {
1510 item.setImage((Image) null);
1511 }
1512
1513 List<StyleRange> styleRanges = new ArrayList<>();
1514 for (int index = 0; index < fTable.getColumns().length; index++) {
1515 TableColumn column = fTable.getColumns()[index];
1516 String regex = null;
1517 if (fHeaderState == HeaderState.FILTER) {
1518 regex = (String) column.getData(Key.FILTER_TXT);
1519 } else if (searchMatch) {
1520 regex = (String) column.getData(Key.SEARCH_TXT);
1521 }
1522 if (regex != null) {
1523 String text = item.getText(index);
1524 try {
1525 Pattern pattern = Pattern.compile(regex);
1526 Matcher matcher = pattern.matcher(text);
1527 while (matcher.find()) {
1528 int start = matcher.start();
1529 int length = matcher.end() - start;
1530 Color foreground = colorSetting.getForegroundColor();
1531 Color background = fHighlightColor;
1532 StyleRange styleRange = new StyleRange(start, length, foreground, background);
1533 styleRange.data = index;
1534 styleRanges.add(styleRange);
1535 }
1536 } catch (PatternSyntaxException e) {
1537 /* ignored */
1538 }
1539 }
1540 }
1541 if (styleRanges.isEmpty()) {
1542 item.setData(Key.STYLE_RANGES, null);
1543 } else {
1544 item.setData(Key.STYLE_RANGES, styleRanges);
1545 }
1546 item.getParent().redraw();
1547
1548 if ((itemStrings[MARGIN_COLUMN_INDEX] != null) && !itemStrings[MARGIN_COLUMN_INDEX].isEmpty()) {
1549 packMarginColumn();
1550 }
1551 }
1552
1553 /**
1554 * Set the item data of the header row.
1555 *
1556 * @param item
1557 * The item to use as table header
1558 */
1559 protected void setHeaderRowItemData(final TableItem item) {
1560 String txtKey = null;
1561 if (fHeaderState == HeaderState.SEARCH) {
1562 item.setImage(SEARCH_IMAGE);
1563 txtKey = Key.SEARCH_TXT;
1564 } else if (fHeaderState == HeaderState.FILTER) {
1565 item.setImage(FILTER_IMAGE);
1566 txtKey = Key.FILTER_TXT;
1567 }
1568 item.setForeground(fGrayColor);
1569 // Ignore collapse and image column
1570 for (int i = EVENT_COLUMNS_START_INDEX; i < fTable.getColumns().length; i++) {
1571 final TableColumn column = fTable.getColumns()[i];
1572 final String filter = (String) column.getData(txtKey);
1573 if (filter == null) {
1574 if (fHeaderState == HeaderState.SEARCH) {
1575 item.setText(i, SEARCH_HINT);
1576 } else if (fHeaderState == HeaderState.FILTER) {
1577 item.setText(i, FILTER_HINT);
1578 }
1579 item.setForeground(i, fGrayColor);
1580 item.setFont(i, fFont);
1581 } else {
1582 item.setText(i, filter);
1583 item.setForeground(i, fGreenColor);
1584 item.setFont(i, fBoldFont);
1585 }
1586 }
1587 }
1588
1589 /**
1590 * Set the item data of the "filter status" row.
1591 *
1592 * @param item
1593 * The item to use as filter status row
1594 */
1595 protected void setFilterStatusRowItemData(final TableItem item) {
1596 for (int i = 0; i < fTable.getColumns().length; i++) {
1597 if (i == MARGIN_COLUMN_INDEX) {
1598 if ((fTrace == null) || (fFilterCheckCount == fTrace.getNbEvents())) {
1599 item.setImage(FILTER_IMAGE);
1600 } else {
1601 item.setImage(STOP_IMAGE);
1602 }
1603 }
1604
1605 if (i == FILTER_SUMMARY_INDEX) {
1606 item.setText(FILTER_SUMMARY_INDEX, fFilterMatchCount + "/" + fFilterCheckCount); //$NON-NLS-1$
1607 } else {
1608 item.setText(i, EMPTY_STRING);
1609 }
1610 }
1611 item.setData(null);
1612 item.setData(Key.TIMESTAMP, null);
1613 item.setData(Key.RANK, null);
1614 item.setData(Key.STYLE_RANGES, null);
1615 item.setForeground(null);
1616 item.setBackground(null);
1617 item.setFont(fFont);
1618 }
1619
1620 /**
1621 * Create an editor for the header.
1622 */
1623 private void createHeaderEditor() {
1624 final TableEditor tableEditor = fTable.createTableEditor();
1625 tableEditor.horizontalAlignment = SWT.LEFT;
1626 tableEditor.verticalAlignment = SWT.CENTER;
1627 tableEditor.grabHorizontal = true;
1628 tableEditor.minimumWidth = 50;
1629
1630 // Handle the header row selection
1631 fTable.addMouseListener(new MouseAdapter() {
1632 int columnIndex;
1633 TableColumn column;
1634 TableItem item;
1635
1636 @Override
1637 public void mouseDown(final MouseEvent event) {
1638 if (event.button != 1) {
1639 return;
1640 }
1641 // Identify the selected row
1642 final Point point = new Point(event.x, event.y);
1643 item = fTable.getItem(point);
1644
1645 // Header row selected
1646 if ((item != null) && (fTable.indexOf(item) == 0)) {
1647
1648 // Margin column selected
1649 if (item.getBounds(0).contains(point)) {
1650 if (fHeaderState == HeaderState.SEARCH) {
1651 fHeaderState = HeaderState.FILTER;
1652 } else if (fHeaderState == HeaderState.FILTER) {
1653 fHeaderState = HeaderState.SEARCH;
1654 }
1655 fTable.setSelection(0);
1656 fTable.refresh();
1657 fTable.redraw();
1658 return;
1659 }
1660
1661 // Identify the selected column
1662 columnIndex = -1;
1663 for (int i = 0; i < fTable.getColumns().length; i++) {
1664 final Rectangle rect = item.getBounds(i);
1665 if (rect.contains(point)) {
1666 columnIndex = i;
1667 break;
1668 }
1669 }
1670
1671 if (columnIndex == -1) {
1672 return;
1673 }
1674
1675 column = fTable.getColumns()[columnIndex];
1676
1677 String txtKey = null;
1678 if (fHeaderState == HeaderState.SEARCH) {
1679 txtKey = Key.SEARCH_TXT;
1680 } else if (fHeaderState == HeaderState.FILTER) {
1681 txtKey = Key.FILTER_TXT;
1682 }
1683
1684 /*
1685 * The control that will be the editor must be a child of
1686 * the Table
1687 */
1688 final Text newEditor = (Text) fTable.createTableEditorControl(Text.class);
1689 final String headerString = (String) column.getData(txtKey);
1690 if (headerString != null) {
1691 newEditor.setText(headerString);
1692 }
1693 newEditor.addFocusListener(new FocusAdapter() {
1694 @Override
1695 public void focusLost(final FocusEvent e) {
1696 final boolean changed = updateHeader(newEditor.getText());
1697 if (changed) {
1698 applyHeader();
1699 }
1700 }
1701 });
1702 newEditor.addKeyListener(new KeyAdapter() {
1703 @Override
1704 public void keyPressed(final KeyEvent e) {
1705 if (e.character == SWT.CR) {
1706 updateHeader(newEditor.getText());
1707 applyHeader();
1708
1709 /*
1710 * Set focus on the table so that the next
1711 * carriage return goes to the next result
1712 */
1713 TmfEventsTable.this.getTable().setFocus();
1714 } else if (e.character == SWT.ESC) {
1715 tableEditor.getEditor().dispose();
1716 }
1717 }
1718 });
1719 newEditor.selectAll();
1720 newEditor.setFocus();
1721 tableEditor.setEditor(newEditor, item, columnIndex);
1722 }
1723 }
1724
1725 /*
1726 * returns true is value was changed
1727 */
1728 private boolean updateHeader(final String regex) {
1729 String objKey = null;
1730 String txtKey = null;
1731 if (fHeaderState == HeaderState.SEARCH) {
1732 objKey = Key.SEARCH_OBJ;
1733 txtKey = Key.SEARCH_TXT;
1734 } else if (fHeaderState == HeaderState.FILTER) {
1735 objKey = Key.FILTER_OBJ;
1736 txtKey = Key.FILTER_TXT;
1737 }
1738 if (regex.length() > 0) {
1739 try {
1740 Pattern.compile(regex);
1741 if (regex.equals(column.getData(txtKey))) {
1742 tableEditor.getEditor().dispose();
1743 return false;
1744 }
1745 final TmfFilterMatchesNode filter = new TmfFilterMatchesNode(null);
1746 ITmfEventAspect aspect = (ITmfEventAspect) column.getData(Key.ASPECT);
1747 filter.setEventAspect(aspect);
1748 filter.setRegex(regex);
1749 column.setData(objKey, filter);
1750 column.setData(txtKey, regex);
1751 } catch (final PatternSyntaxException ex) {
1752 tableEditor.getEditor().dispose();
1753 MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
1754 ex.getDescription(), ex.getMessage());
1755 return false;
1756 }
1757 } else {
1758 if (column.getData(txtKey) == null) {
1759 tableEditor.getEditor().dispose();
1760 return false;
1761 }
1762 column.setData(objKey, null);
1763 column.setData(txtKey, null);
1764 }
1765 return true;
1766 }
1767
1768 private void applyHeader() {
1769 if (fHeaderState == HeaderState.SEARCH) {
1770 stopSearchThread();
1771 final TmfFilterAndNode filter = new TmfFilterAndNode(null);
1772 for (final TableColumn col : fTable.getColumns()) {
1773 final Object filterObj = col.getData(Key.SEARCH_OBJ);
1774 if (filterObj instanceof ITmfFilterTreeNode) {
1775 filter.addChild((ITmfFilterTreeNode) filterObj);
1776 }
1777 }
1778 if (filter.getChildrenCount() > 0) {
1779 fTable.setData(Key.SEARCH_OBJ, filter);
1780 fTable.refresh();
1781 searchNext();
1782 fireSearchApplied(filter);
1783 } else {
1784 fTable.setData(Key.SEARCH_OBJ, null);
1785 fTable.refresh();
1786 fireSearchApplied(null);
1787 }
1788 } else if (fHeaderState == HeaderState.FILTER) {
1789 final TmfFilterAndNode filter = new TmfFilterAndNode(null);
1790 for (final TableColumn col : fTable.getColumns()) {
1791 final Object filterObj = col.getData(Key.FILTER_OBJ);
1792 if (filterObj instanceof ITmfFilterTreeNode) {
1793 filter.addChild((ITmfFilterTreeNode) filterObj);
1794 }
1795 }
1796 if (filter.getChildrenCount() > 0) {
1797 applyFilter(filter);
1798 } else {
1799 clearFilters();
1800 }
1801 }
1802
1803 tableEditor.getEditor().dispose();
1804 }
1805 });
1806
1807 fTable.addKeyListener(new KeyAdapter() {
1808 @Override
1809 public void keyPressed(final KeyEvent e) {
1810 e.doit = false;
1811 if (e.character == SWT.ESC) {
1812 stopFilterThread();
1813 stopSearchThread();
1814 fTable.refresh();
1815 } else if (e.character == SWT.DEL) {
1816 if (fHeaderState == HeaderState.SEARCH) {
1817 stopSearchThread();
1818 for (final TableColumn column : fTable.getColumns()) {
1819 column.setData(Key.SEARCH_OBJ, null);
1820 column.setData(Key.SEARCH_TXT, null);
1821 }
1822 fTable.setData(Key.SEARCH_OBJ, null);
1823 fTable.refresh();
1824 fireSearchApplied(null);
1825 } else if (fHeaderState == HeaderState.FILTER) {
1826 clearFilters();
1827 }
1828 } else if (e.character == SWT.CR) {
1829 if ((e.stateMask & SWT.SHIFT) == 0) {
1830 searchNext();
1831 } else {
1832 searchPrevious();
1833 }
1834 }
1835 }
1836 });
1837 }
1838
1839 /**
1840 * Send an event indicating a filter has been applied.
1841 *
1842 * @param filter
1843 * The filter that was just applied
1844 */
1845 protected void fireFilterApplied(final ITmfFilter filter) {
1846 broadcast(new TmfEventFilterAppliedSignal(this, fTrace, filter));
1847 }
1848
1849 /**
1850 * Send an event indicating that a search has been applied.
1851 *
1852 * @param filter
1853 * The search filter that was just applied
1854 */
1855 protected void fireSearchApplied(final ITmfFilter filter) {
1856 broadcast(new TmfEventSearchAppliedSignal(this, fTrace, filter));
1857 }
1858
1859 /**
1860 * Start the filtering thread.
1861 */
1862 protected void startFilterThread() {
1863 synchronized (fFilterSyncObj) {
1864 final ITmfFilterTreeNode filter = (ITmfFilterTreeNode) fTable.getData(Key.FILTER_OBJ);
1865 if (fFilterThread == null || fFilterThread.filter != filter) {
1866 if (fFilterThread != null) {
1867 fFilterThread.cancel();
1868 fFilterThreadResume = false;
1869 }
1870 fFilterThread = new FilterThread(filter);
1871 fFilterThread.start();
1872 } else {
1873 fFilterThreadResume = true;
1874 }
1875 }
1876 }
1877
1878 /**
1879 * Stop the filtering thread.
1880 */
1881 protected void stopFilterThread() {
1882 synchronized (fFilterSyncObj) {
1883 if (fFilterThread != null) {
1884 fFilterThread.cancel();
1885 fFilterThread = null;
1886 fFilterThreadResume = false;
1887 }
1888 }
1889 }
1890
1891 /**
1892 * Apply a filter.
1893 *
1894 * @param filter
1895 * The filter to apply
1896 */
1897 protected void applyFilter(ITmfFilter filter) {
1898 stopFilterThread();
1899 stopSearchThread();
1900 fFilterMatchCount = 0;
1901 fFilterCheckCount = 0;
1902 fCache.applyFilter(filter);
1903 fTable.clearAll();
1904 fTable.setData(Key.FILTER_OBJ, filter);
1905 /* +1 for header row, +2 for top and bottom filter status rows */
1906 fTable.setItemCount(3);
1907 startFilterThread();
1908 fireFilterApplied(filter);
1909 }
1910
1911 /**
1912 * Clear all currently active filters.
1913 */
1914 protected void clearFilters() {
1915 if (fTable.getData(Key.FILTER_OBJ) == null) {
1916 return;
1917 }
1918 stopFilterThread();
1919 stopSearchThread();
1920 fCache.clearFilter();
1921 fTable.clearAll();
1922 for (final TableColumn column : fTable.getColumns()) {
1923 column.setData(Key.FILTER_OBJ, null);
1924 column.setData(Key.FILTER_TXT, null);
1925 }
1926 fTable.setData(Key.FILTER_OBJ, null);
1927 if (fTrace != null) {
1928 /* +1 for header row */
1929 fTable.setItemCount((int) fTrace.getNbEvents() + 1);
1930 } else {
1931 /* +1 for header row */
1932 fTable.setItemCount(1);
1933 }
1934 fFilterMatchCount = 0;
1935 fFilterCheckCount = 0;
1936 if (fSelectedRank >= 0) {
1937 /* +1 for header row */
1938 fTable.setSelection((int) fSelectedRank + 1);
1939 } else {
1940 fTable.setSelection(0);
1941 }
1942 fireFilterApplied(null);
1943 updateStatusLine(null);
1944
1945 // Set original width
1946 fTable.getColumns()[MARGIN_COLUMN_INDEX].setWidth(0);
1947 packMarginColumn();
1948 }
1949
1950 /**
1951 * Wrapper Thread object for the filtering thread.
1952 */
1953 protected class FilterThread extends Thread {
1954 private final ITmfFilterTreeNode filter;
1955 private TmfEventRequest request;
1956 private boolean refreshBusy = false;
1957 private boolean refreshPending = false;
1958 private final Object syncObj = new Object();
1959
1960 /**
1961 * Constructor.
1962 *
1963 * @param filter
1964 * The filter this thread will be processing
1965 */
1966 public FilterThread(final ITmfFilterTreeNode filter) {
1967 super("Filter Thread"); //$NON-NLS-1$
1968 this.filter = filter;
1969 }
1970
1971 @Override
1972 public void run() {
1973 if (fTrace == null) {
1974 return;
1975 }
1976 final int nbRequested = (int) (fTrace.getNbEvents() - fFilterCheckCount);
1977 if (nbRequested <= 0) {
1978 return;
1979 }
1980 request = new TmfEventRequest(ITmfEvent.class, TmfTimeRange.ETERNITY,
1981 (int) fFilterCheckCount, nbRequested, ExecutionType.BACKGROUND) {
1982 @Override
1983 public void handleData(final ITmfEvent event) {
1984 super.handleData(event);
1985 if (request.isCancelled()) {
1986 return;
1987 }
1988 boolean refresh = false;
1989 if (filter.matches(event)) {
1990 final long rank = fFilterCheckCount;
1991 final int index = (int) fFilterMatchCount;
1992 fFilterMatchCount++;
1993 fCache.storeEvent(event, rank, index);
1994 refresh = true;
1995 } else {
1996 if (filter instanceof TmfCollapseFilter) {
1997 fCache.updateCollapsedEvent((int) fFilterMatchCount - 1);
1998 }
1999 }
2000
2001 if (refresh || (fFilterCheckCount % 100) == 0) {
2002 refreshTable();
2003 }
2004 fFilterCheckCount++;
2005 }
2006 };
2007 ((ITmfEventProvider) fTrace).sendRequest(request);
2008 try {
2009 request.waitForCompletion();
2010 } catch (final InterruptedException e) {
2011 }
2012 refreshTable();
2013 synchronized (fFilterSyncObj) {
2014 fFilterThread = null;
2015 if (fFilterThreadResume) {
2016 fFilterThreadResume = false;
2017 fFilterThread = new FilterThread(filter);
2018 fFilterThread.start();
2019 }
2020 }
2021 }
2022
2023 /**
2024 * Refresh the filter.
2025 */
2026 public void refreshTable() {
2027 synchronized (syncObj) {
2028 if (refreshBusy) {
2029 refreshPending = true;
2030 return;
2031 }
2032 refreshBusy = true;
2033 }
2034 Display.getDefault().asyncExec(new Runnable() {
2035 @Override
2036 public void run() {
2037 if (request.isCancelled()) {
2038 return;
2039 }
2040 if (fTable.isDisposed()) {
2041 return;
2042 }
2043 /*
2044 * +1 for header row, +2 for top and bottom filter status
2045 * rows
2046 */
2047 fTable.setItemCount((int) fFilterMatchCount + 3);
2048 fTable.refresh();
2049 synchronized (syncObj) {
2050 refreshBusy = false;
2051 if (refreshPending) {
2052 refreshPending = false;
2053 refreshTable();
2054 }
2055 }
2056 }
2057 });
2058 }
2059
2060 /**
2061 * Cancel this filtering thread.
2062 */
2063 public void cancel() {
2064 if (request != null) {
2065 request.cancel();
2066 }
2067 }
2068 }
2069
2070 /**
2071 * Go to the next item of a search.
2072 */
2073 protected void searchNext() {
2074 synchronized (fSearchSyncObj) {
2075 if (fSearchThread != null) {
2076 return;
2077 }
2078 final ITmfFilterTreeNode searchFilter = (ITmfFilterTreeNode) fTable.getData(Key.SEARCH_OBJ);
2079 if (searchFilter == null) {
2080 return;
2081 }
2082 final int selectionIndex = fTable.getSelectionIndex();
2083 int startIndex;
2084 if (selectionIndex > 0) {
2085 /* -1 for header row, +1 for next event */
2086 startIndex = selectionIndex;
2087 } else {
2088 /*
2089 * header row is selected, start at top event
2090 */
2091 /* -1 for header row */
2092 startIndex = Math.max(0, fTable.getTopIndex() - 1);
2093 }
2094 final ITmfFilterTreeNode eventFilter = (ITmfFilterTreeNode) fTable.getData(Key.FILTER_OBJ);
2095 if (eventFilter != null) {
2096 // -1 for top filter status row
2097 startIndex = Math.max(0, startIndex - 1);
2098 }
2099 fSearchThread = new SearchThread(searchFilter, eventFilter, startIndex, fSelectedRank, Direction.FORWARD);
2100 fSearchThread.schedule();
2101 }
2102 }
2103
2104 /**
2105 * Go to the previous item of a search.
2106 */
2107 protected void searchPrevious() {
2108 synchronized (fSearchSyncObj) {
2109 if (fSearchThread != null) {
2110 return;
2111 }
2112 final ITmfFilterTreeNode searchFilter = (ITmfFilterTreeNode) fTable.getData(Key.SEARCH_OBJ);
2113 if (searchFilter == null) {
2114 return;
2115 }
2116 final int selectionIndex = fTable.getSelectionIndex();
2117 int startIndex;
2118 if (selectionIndex > 0) {
2119 /* -1 for header row, -1 for previous event */
2120 startIndex = selectionIndex - 2;
2121 } else {
2122 /*
2123 * Header row is selected, start at precedent of top event
2124 */
2125 /* -1 for header row, -1 for previous event */
2126 startIndex = fTable.getTopIndex() - 2;
2127 }
2128 final ITmfFilterTreeNode eventFilter = (ITmfFilterTreeNode) fTable.getData(Key.FILTER_OBJ);
2129 if (eventFilter != null) {
2130 /* -1 for top filter status row */
2131 startIndex = startIndex - 1;
2132 }
2133 fSearchThread = new SearchThread(searchFilter, eventFilter, startIndex, fSelectedRank, Direction.BACKWARD);
2134 fSearchThread.schedule();
2135 }
2136 }
2137
2138 /**
2139 * Stop the search thread.
2140 */
2141 protected void stopSearchThread() {
2142 fPendingGotoRank = -1;
2143 synchronized (fSearchSyncObj) {
2144 if (fSearchThread != null) {
2145 fSearchThread.cancel();
2146 fSearchThread = null;
2147 }
2148 }
2149 }
2150
2151 /**
2152 * Wrapper for the search thread.
2153 */
2154 protected class SearchThread extends Job {
2155
2156 private ITmfFilterTreeNode searchFilter;
2157 private ITmfFilterTreeNode eventFilter;
2158 private int startIndex;
2159 private int direction;
2160 private long rank;
2161 private long foundRank = -1;
2162 private TmfEventRequest request;
2163 private ITmfTimestamp foundTimestamp = null;
2164
2165 /**
2166 * Constructor.
2167 *
2168 * @param searchFilter
2169 * The search filter
2170 * @param eventFilter
2171 * The event filter
2172 * @param startIndex
2173 * The index at which we should start searching
2174 * @param currentRank
2175 * The current rank
2176 * @param direction
2177 * In which direction should we search, forward or backwards
2178 */
2179 public SearchThread(final ITmfFilterTreeNode searchFilter,
2180 final ITmfFilterTreeNode eventFilter, final int startIndex,
2181 final long currentRank, final int direction) {
2182 super(Messages.TmfEventsTable_SearchingJobName);
2183 this.searchFilter = searchFilter;
2184 this.eventFilter = eventFilter;
2185 this.startIndex = startIndex;
2186 this.rank = currentRank;
2187 this.direction = direction;
2188 }
2189
2190 @Override
2191 protected IStatus run(final IProgressMonitor monitor) {
2192 final ITmfTrace trace = fTrace;
2193 if (trace == null) {
2194 return Status.OK_STATUS;
2195 }
2196 final Display display = Display.getDefault();
2197 if (startIndex < 0) {
2198 rank = (int) trace.getNbEvents() - 1;
2199 /*
2200 * -1 for header row, -3 for header and top and bottom filter
2201 * status rows
2202 */
2203 } else if (startIndex >= (fTable.getItemCount() - (eventFilter == null ? 1 : 3))) {
2204 rank = 0;
2205 } else {
2206 int idx = startIndex;
2207 while (foundRank == -1) {
2208 final CachedEvent event = fCache.peekEvent(idx);
2209 if (event == null) {
2210 break;
2211 }
2212 rank = event.rank;
2213 if (searchFilter.matches(event.event) && ((eventFilter == null) || eventFilter.matches(event.event))) {
2214 foundRank = event.rank;
2215 foundTimestamp = event.event.getTimestamp();
2216 break;
2217 }
2218 if (direction == Direction.FORWARD) {
2219 idx++;
2220 } else {
2221 idx--;
2222 }
2223 }
2224 if (foundRank == -1) {
2225 if (direction == Direction.FORWARD) {
2226 rank++;
2227 if (rank > (trace.getNbEvents() - 1)) {
2228 rank = 0;
2229 }
2230 } else {
2231 rank--;
2232 if (rank < 0) {
2233 rank = (int) trace.getNbEvents() - 1;
2234 }
2235 }
2236 }
2237 }
2238 final int startRank = (int) rank;
2239 boolean wrapped = false;
2240 while (!monitor.isCanceled() && (foundRank == -1)) {
2241 int nbRequested = (direction == Direction.FORWARD ? Integer.MAX_VALUE : Math.min((int) rank + 1, trace.getCacheSize()));
2242 if (direction == Direction.BACKWARD) {
2243 rank = Math.max(0, rank - trace.getCacheSize() + 1);
2244 }
2245 request = new TmfEventRequest(ITmfEvent.class, TmfTimeRange.ETERNITY,
2246 (int) rank, nbRequested, ExecutionType.BACKGROUND) {
2247 long currentRank = rank;
2248
2249 @Override
2250 public void handleData(final ITmfEvent event) {
2251 super.handleData(event);
2252 if (searchFilter.matches(event) && ((eventFilter == null) || eventFilter.matches(event))) {
2253 foundRank = currentRank;
2254 foundTimestamp = event.getTimestamp();
2255 if (direction == Direction.FORWARD) {
2256 done();
2257 return;
2258 }
2259 }
2260 currentRank++;
2261 }
2262 };
2263 ((ITmfEventProvider) trace).sendRequest(request);
2264 try {
2265 request.waitForCompletion();
2266 if (request.isCancelled()) {
2267 return Status.OK_STATUS;
2268 }
2269 } catch (final InterruptedException e) {
2270 synchronized (fSearchSyncObj) {
2271 fSearchThread = null;
2272 }
2273 return Status.OK_STATUS;
2274 }
2275 if (foundRank == -1) {
2276 if (direction == Direction.FORWARD) {
2277 if (rank == 0) {
2278 synchronized (fSearchSyncObj) {
2279 fSearchThread = null;
2280 }
2281 return Status.OK_STATUS;
2282 }
2283 nbRequested = (int) rank;
2284 rank = 0;
2285 wrapped = true;
2286 } else {
2287 rank--;
2288 if (rank < 0) {
2289 rank = (int) trace.getNbEvents() - 1;
2290 wrapped = true;
2291 }
2292 if ((rank <= startRank) && wrapped) {
2293 synchronized (fSearchSyncObj) {
2294 fSearchThread = null;
2295 }
2296 return Status.OK_STATUS;
2297 }
2298 }
2299 }
2300 }
2301 int index = (int) foundRank;
2302 if (eventFilter != null) {
2303 index = fCache.getFilteredEventIndex(foundRank);
2304 }
2305 /* +1 for header row, +1 for top filter status row */
2306 final int selection = index + 1 + (eventFilter != null ? +1 : 0);
2307
2308 display.asyncExec(new Runnable() {
2309 @Override
2310 public void run() {
2311 if (monitor.isCanceled()) {
2312 return;
2313 }
2314 if (fTable.isDisposed()) {
2315 return;
2316 }
2317 fTable.setSelection(selection);
2318 fSelectedRank = foundRank;
2319 fSelectedBeginRank = fSelectedRank;
2320 fRawViewer.selectAndReveal(fSelectedRank);
2321 if (foundTimestamp != null) {
2322 broadcast(new TmfSelectionRangeUpdatedSignal(TmfEventsTable.this, foundTimestamp));
2323 }
2324 fireSelectionChanged(new SelectionChangedEvent(TmfEventsTable.this, getSelection()));
2325 synchronized (fSearchSyncObj) {
2326 fSearchThread = null;
2327 }
2328 updateStatusLine(null);
2329 }
2330 });
2331 return Status.OK_STATUS;
2332 }
2333
2334 @Override
2335 protected void canceling() {
2336 request.cancel();
2337 synchronized (fSearchSyncObj) {
2338 fSearchThread = null;
2339 }
2340 }
2341 }
2342
2343 /**
2344 * Create the resources.
2345 */
2346 private void createResources() {
2347 fGrayColor = fResourceManager.createColor(ColorUtil.blend(fTable.getBackground().getRGB(), fTable.getForeground().getRGB()));
2348 fGreenColor = PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_DARK_GREEN);
2349 }
2350
2351 /**
2352 * Initialize the fonts.
2353 */
2354 private void initializeFonts() {
2355 FontRegistry fontRegistry = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getFontRegistry();
2356 fFont = fontRegistry.get(FONT_DEFINITION_ID);
2357 fBoldFont = fontRegistry.getBold(FONT_DEFINITION_ID);
2358 fTable.setFont(fFont);
2359 /* Column header font cannot be set. See Bug 63038 */
2360 }
2361
2362 /**
2363 * Initialize the colors.
2364 */
2365 private void initializeColors() {
2366 ColorRegistry colorRegistry = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getColorRegistry();
2367 fHighlightColor = colorRegistry.get(HIGHLIGHT_COLOR_DEFINITION_ID);
2368 }
2369
2370 /**
2371 * @since 1.0
2372 */
2373 @Override
2374 public void propertyChange(PropertyChangeEvent event) {
2375 if ((IThemeManager.CHANGE_CURRENT_THEME.equals(event.getProperty())) ||
2376 (FONT_DEFINITION_ID.equals(event.getProperty()))) {
2377 initializeFonts();
2378 fTable.refresh();
2379 }
2380 if ((IThemeManager.CHANGE_CURRENT_THEME.equals(event.getProperty())) ||
2381 (HIGHLIGHT_COLOR_DEFINITION_ID.equals(event.getProperty()))) {
2382 initializeColors();
2383 fTable.refresh();
2384 }
2385 }
2386
2387 /**
2388 * Pack the columns.
2389 */
2390 protected void packColumns() {
2391 if (fPackDone) {
2392 return;
2393 }
2394 fTable.setRedraw(false);
2395 try {
2396 TableColumn tableColumns[] = fTable.getColumns();
2397 for (int i = 0; i < tableColumns.length; i++) {
2398 final TableColumn column = tableColumns[i];
2399 packSingleColumn(i, column);
2400 }
2401
2402 } finally {
2403 // Make sure that redraw is always enabled.
2404 fTable.setRedraw(true);
2405 }
2406 fPackDone = true;
2407 }
2408
2409 private void packMarginColumn() {
2410 TableColumn[] columns = fTable.getColumns();
2411 if (columns.length > 0) {
2412 packSingleColumn(0, columns[0]);
2413 }
2414 }
2415
2416 private void packSingleColumn(int i, final TableColumn column) {
2417 final int headerWidth = column.getWidth();
2418 column.pack();
2419 /*
2420 * Workaround for Linux which doesn't consider the image width of
2421 * search/filter row in TableColumn.pack() after having executed
2422 * TableItem.setImage(null) for other rows than search/filter row.
2423 */
2424 boolean isCollapseFilter = fTable.getData(Key.FILTER_OBJ) instanceof TmfCollapseFilter;
2425 if (IS_LINUX && (i == 0) && isCollapseFilter) {
2426 column.setWidth(column.getWidth() + SEARCH_IMAGE.getBounds().width);
2427 }
2428
2429 if (column.getWidth() < headerWidth) {
2430 column.setWidth(headerWidth);
2431 }
2432 }
2433
2434 /**
2435 * Get the array of item strings (e.g., what to display in each cell of the
2436 * table row) corresponding to the columns and trace event passed in
2437 * parameter. The order of the Strings in the returned array will correspond
2438 * to the iteration order of 'columns'.
2439 *
2440 * <p>
2441 * To ensure consistent results, make sure only call this within a scope
2442 * synchronized on 'columns'! If the order of 'columns' changes right after
2443 * this method is called, the returned value won't be ordered correctly
2444 * anymore.
2445 */
2446 private static String[] getItemStrings(List<TmfEventTableColumn> columns, ITmfEvent event) {
2447 if (event == null) {
2448 return EMPTY_STRING_ARRAY;
2449 }
2450 synchronized (columns) {
2451 List<String> itemStrings = new ArrayList<>(columns.size());
2452 for (TmfEventTableColumn column : columns) {
2453 ITmfEvent passedEvent = event;
2454 if (!(column instanceof TmfMarginColumn) && (event instanceof CachedEvent)) {
2455 /*
2456 * Make sure that the event object from the trace is passed
2457 * to all columns but the TmfMarginColumn
2458 */
2459 passedEvent = ((CachedEvent) event).event;
2460 }
2461 if (passedEvent == null) {
2462 itemStrings.add(EMPTY_STRING);
2463 } else {
2464 itemStrings.add(column.getItemString(passedEvent));
2465 }
2466
2467 }
2468 return itemStrings.toArray(new String[0]);
2469 }
2470 }
2471
2472 /**
2473 * Get the contents of the row in the events table corresponding to an
2474 * event. The order of the elements corresponds to the current order of the
2475 * columns.
2476 *
2477 * @param event
2478 * The event printed in this row
2479 * @return The event row entries
2480 */
2481 public String[] getItemStrings(ITmfEvent event) {
2482 List<TmfEventTableColumn> columns = new ArrayList<>();
2483 for (int i : fTable.getColumnOrder()) {
2484 columns.add(fColumns.get(i));
2485 }
2486 return getItemStrings(columns, event);
2487 }
2488
2489 /**
2490 * Returns an array of zero-relative integers that map the creation order of
2491 * the receiver's columns to the order in which they are currently being
2492 * displayed.
2493 * <p>
2494 * Specifically, the indices of the returned array represent the current
2495 * visual order of the columns, and the contents of the array represent the
2496 * creation order of the columns.
2497 *
2498 * @return the current visual order of the receiver's columns
2499 * @since 1.0
2500 */
2501 public int[] getColumnOrder() {
2502 return fColumnOrder;
2503 }
2504
2505 /**
2506 * Sets the order that the columns in the receiver should be displayed in to
2507 * the given argument which is described in terms of the zero-relative
2508 * ordering of when the columns were added.
2509 * <p>
2510 * Specifically, the contents of the array represent the original position
2511 * of each column at the time its creation.
2512 *
2513 * @param order
2514 * the new order to display the columns
2515 * @since 1.0
2516 */
2517 public void setColumnOrder(int[] order) {
2518 if (order == null || order.length != fTable.getColumns().length) {
2519 return;
2520 }
2521 fTable.setColumnOrder(order);
2522 fColumnOrder = fTable.getColumnOrder();
2523 }
2524
2525 /**
2526 * Notify this table that is got the UI focus.
2527 */
2528 public void setFocus() {
2529 fTable.setFocus();
2530 }
2531
2532 /**
2533 * Registers context menus with a site for extension. This method can be
2534 * called for part sites so that context menu contributions can be added.
2535 *
2536 * @param site
2537 * the site that the context menus will be registered for
2538 *
2539 * @since 2.0
2540 */
2541 public void registerContextMenus(IWorkbenchPartSite site) {
2542 if (site instanceof IEditorSite) {
2543 IEditorSite editorSite = (IEditorSite) site;
2544 // Don't use the editor input when adding contributions, otherwise
2545 // we get too many unwanted things.
2546 editorSite.registerContextMenu(fTablePopupMenuManager, this, false);
2547 }
2548 }
2549
2550 /**
2551 * Assign a new trace to this event table.
2552 *
2553 * @param trace
2554 * The trace to assign to this event table
2555 * @param disposeOnClose
2556 * true if the trace should be disposed when the table is
2557 * disposed
2558 */
2559 public void setTrace(final ITmfTrace trace, final boolean disposeOnClose) {
2560 if ((fTrace != null) && fDisposeOnClose) {
2561 fTrace.dispose();
2562 }
2563 fTrace = trace;
2564 fPackDone = false;
2565 fDisposeOnClose = disposeOnClose;
2566
2567 // Perform the updates on the UI thread
2568 PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
2569 @Override
2570 public void run() {
2571 fSelectedRank = -1;
2572 fSelectedBeginRank = -1;
2573 fTable.removeAll();
2574 fCache.setTrace(trace); // Clear the cache
2575 if (trace != null) {
2576 if (!fTable.isDisposed()) {
2577 if (fTable.getData(Key.FILTER_OBJ) == null) {
2578 // +1 for header row
2579 fTable.setItemCount((int) trace.getNbEvents() + 1);
2580 } else {
2581 stopFilterThread();
2582 fFilterMatchCount = 0;
2583 fFilterCheckCount = 0;
2584 /*
2585 * +1 for header row, +2 for top and bottom filter
2586 * status rows
2587 */
2588 fTable.setItemCount(3);
2589 startFilterThread();
2590 }
2591 }
2592 }
2593 fRawViewer.setTrace(trace);
2594 }
2595 });
2596 }
2597
2598 /**
2599 * Assign the status line manager
2600 *
2601 * @param statusLineManager
2602 * The status line manager, or null to disable status line
2603 * messages
2604 */
2605 public void setStatusLineManager(IStatusLineManager statusLineManager) {
2606 if (fStatusLineManager != null && statusLineManager == null) {
2607 fStatusLineManager.setMessage(EMPTY_STRING);
2608 }
2609 fStatusLineManager = statusLineManager;
2610 }
2611
2612 private void updateStatusLine(ITmfTimestamp delta) {
2613 if (fStatusLineManager != null) {
2614 if (delta != null) {
2615 fStatusLineManager.setMessage("\u0394: " + delta); //$NON-NLS-1$
2616 } else {
2617 fStatusLineManager.setMessage(null);
2618 }
2619 }
2620 }
2621
2622 // ------------------------------------------------------------------------
2623 // Event cache
2624 // ------------------------------------------------------------------------
2625
2626 /**
2627 * Notify that the event cache has been updated
2628 *
2629 * @param completed
2630 * Also notify if the populating of the cache is complete, or
2631 * not.
2632 */
2633 public void cacheUpdated(final boolean completed) {
2634 synchronized (fCacheUpdateSyncObj) {
2635 if (fCacheUpdateBusy) {
2636 fCacheUpdatePending = true;
2637 fCacheUpdateCompleted = completed;
2638 return;
2639 }
2640 fCacheUpdateBusy = true;
2641 }
2642 // Event cache is now updated. Perform update on the UI thread
2643 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
2644 @Override
2645 public void run() {
2646 if (!fTable.isDisposed()) {
2647 fTable.refresh();
2648 packColumns();
2649 }
2650 if (completed) {
2651 populateCompleted();
2652 }
2653 synchronized (fCacheUpdateSyncObj) {
2654 fCacheUpdateBusy = false;
2655 if (fCacheUpdatePending) {
2656 fCacheUpdatePending = false;
2657 cacheUpdated(fCacheUpdateCompleted);
2658 }
2659 }
2660 }
2661 });
2662 }
2663
2664 /**
2665 * Callback for when populating the table is complete.
2666 */
2667 protected void populateCompleted() {
2668 // Nothing by default;
2669 }
2670
2671 // ------------------------------------------------------------------------
2672 // ISelectionProvider
2673 // ------------------------------------------------------------------------
2674
2675 @Override
2676 public void addSelectionChangedListener(ISelectionChangedListener listener) {
2677 selectionChangedListeners.add(listener);
2678 }
2679
2680 @Override
2681 public ISelection getSelection() {
2682 if (fTable == null || fTable.isDisposed()) {
2683 return StructuredSelection.EMPTY;
2684 }
2685 List<Object> list = new ArrayList<>(fTable.getSelection().length);
2686 for (TableItem item : fTable.getSelection()) {
2687 if (item.getData() != null) {
2688 list.add(item.getData());
2689 }
2690 }
2691 return new StructuredSelection(list);
2692 }
2693
2694 @Override
2695 public void removeSelectionChangedListener(ISelectionChangedListener listener) {
2696 selectionChangedListeners.remove(listener);
2697 }
2698
2699 @Override
2700 public void setSelection(ISelection selection) {
2701 // not implemented
2702 }
2703
2704 /**
2705 * Notifies any selection changed listeners that the viewer's selection has
2706 * changed. Only listeners registered at the time this method is called are
2707 * notified.
2708 *
2709 * @param event
2710 * a selection changed event
2711 *
2712 * @see ISelectionChangedListener#selectionChanged
2713 */
2714 protected void fireSelectionChanged(final SelectionChangedEvent event) {
2715 Object[] listeners = selectionChangedListeners.getListeners();
2716 for (int i = 0; i < listeners.length; ++i) {
2717 final ISelectionChangedListener l = (ISelectionChangedListener) listeners[i];
2718 SafeRunnable.run(new SafeRunnable() {
2719 @Override
2720 public void run() {
2721 l.selectionChanged(event);
2722 }
2723 });
2724 }
2725 }
2726
2727 // ------------------------------------------------------------------------
2728 // Bookmark handling
2729 // ------------------------------------------------------------------------
2730
2731 /**
2732 * Add a bookmark to this event table.
2733 *
2734 * @param bookmarksFile
2735 * The file to use for the bookmarks
2736 */
2737 public void addBookmark(final IFile bookmarksFile) {
2738 fBookmarksFile = bookmarksFile;
2739 final TableItem[] selection = fTable.getSelection();
2740 if (selection.length > 0) {
2741 final TableItem tableItem = selection[0];
2742 if (tableItem.getData(Key.RANK) != null) {
2743 final StringBuffer defaultMessage = new StringBuffer();
2744 for (int i = 0; i < fTable.getColumns().length; i++) {
2745 if (i > 0) {
2746 defaultMessage.append(", "); //$NON-NLS-1$
2747 }
2748 defaultMessage.append(tableItem.getText(i));
2749 }
2750 final InputDialog dialog = new MultiLineInputDialog(
2751 PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
2752 Messages.TmfEventsTable_AddBookmarkDialogTitle,
2753 Messages.TmfEventsTable_AddBookmarkDialogMessage,
2754 defaultMessage.toString());
2755 if (dialog.open() == Window.OK) {
2756 final String message = dialog.getValue();
2757 try {
2758 final IMarker bookmark = bookmarksFile.createMarker(IMarker.BOOKMARK);
2759 if (bookmark.exists()) {
2760 bookmark.setAttribute(IMarker.MESSAGE, message.toString());
2761 final Long rank = (Long) tableItem.getData(Key.RANK);
2762 final int location = rank.intValue();
2763 bookmark.setAttribute(IMarker.LOCATION, Integer.valueOf(location));
2764 fBookmarksMap.put(rank, bookmark.getId());
2765 fTable.refresh();
2766 }
2767 } catch (final CoreException e) {
2768 displayException(e);
2769 }
2770 }
2771 }
2772 }
2773
2774 }
2775
2776 /**
2777 * Remove a bookmark from this event table.
2778 *
2779 * @param bookmark
2780 * The bookmark to remove
2781 */
2782 public void removeBookmark(final IMarker bookmark) {
2783 for (final Entry<Long, Long> entry : fBookmarksMap.entries()) {
2784 if (entry.getValue().equals(bookmark.getId())) {
2785 fBookmarksMap.remove(entry.getKey(), entry.getValue());
2786 fTable.refresh();
2787 return;
2788 }
2789 }
2790 }
2791
2792 private void toggleBookmark(final Long rank) {
2793 if (fBookmarksFile == null) {
2794 return;
2795 }
2796 if (fBookmarksMap.containsKey(rank)) {
2797 final Collection<Long> markerIds = fBookmarksMap.removeAll(rank);
2798 fTable.refresh();
2799 try {
2800 for (long markerId : markerIds) {
2801 final IMarker bookmark = fBookmarksFile.findMarker(markerId);
2802 if (bookmark != null) {
2803 bookmark.delete();
2804 }
2805 }
2806 } catch (final CoreException e) {
2807 displayException(e);
2808 }
2809 } else {
2810 addBookmark(fBookmarksFile);
2811 }
2812 }
2813
2814 /**
2815 * Refresh the bookmarks assigned to this trace, from the contents of a
2816 * bookmark file.
2817 *
2818 * @param bookmarksFile
2819 * The bookmark file to use
2820 */
2821 public void refreshBookmarks(final IFile bookmarksFile) {
2822 fBookmarksFile = bookmarksFile;
2823 if (bookmarksFile == null) {
2824 fBookmarksMap.clear();
2825 fTable.refresh();
2826 return;
2827 }
2828 try {
2829 fBookmarksMap.clear();
2830 for (final IMarker bookmark : bookmarksFile.findMarkers(IMarker.BOOKMARK, false, IResource.DEPTH_ZERO)) {
2831 final int location = bookmark.getAttribute(IMarker.LOCATION, -1);
2832 if (location != -1) {
2833 final long rank = location;
2834 fBookmarksMap.put(rank, bookmark.getId());
2835 }
2836 }
2837 fTable.refresh();
2838 } catch (final CoreException e) {
2839 displayException(e);
2840 }
2841 }
2842
2843 @Override
2844 public void gotoMarker(final IMarker marker) {
2845 final int rank = marker.getAttribute(IMarker.LOCATION, -1);
2846 if (rank != -1) {
2847 int index = rank;
2848 if (fTable.getData(Key.FILTER_OBJ) != null) {
2849 // +1 for top filter status row
2850 index = fCache.getFilteredEventIndex(rank) + 1;
2851 } else if (rank >= fTable.getItemCount()) {
2852 fPendingGotoRank = rank;
2853 }
2854 fSelectedRank = rank;
2855 fSelectedBeginRank = fSelectedRank;
2856 fTable.setSelection(index + 1); // +1 for header row
2857 updateStatusLine(null);
2858 }
2859 }
2860
2861 // ------------------------------------------------------------------------
2862 // Listeners
2863 // ------------------------------------------------------------------------
2864
2865 @Override
2866 public void colorSettingsChanged(final ColorSetting[] colorSettings) {
2867 fTable.refresh();
2868 }
2869
2870 // ------------------------------------------------------------------------
2871 // Signal handlers
2872 // ------------------------------------------------------------------------
2873
2874 /**
2875 * Handler for the trace updated signal
2876 *
2877 * @param signal
2878 * The incoming signal
2879 */
2880 @TmfSignalHandler
2881 public void traceUpdated(final TmfTraceUpdatedSignal signal) {
2882 if ((signal.getTrace() != fTrace) || fTable.isDisposed()) {
2883 return;
2884 }
2885 // Perform the refresh on the UI thread
2886 Display.getDefault().asyncExec(new Runnable() {
2887 @Override
2888 public void run() {
2889 if (!fTable.isDisposed() && (fTrace != null)) {
2890 if (fTable.getData(Key.FILTER_OBJ) == null) {
2891 /* +1 for header row */
2892 fTable.setItemCount((int) fTrace.getNbEvents() + 1);
2893 /* +1 for header row */
2894 if ((fPendingGotoRank != -1) && ((fPendingGotoRank + 1) < fTable.getItemCount())) {
2895 /* +1 for header row */
2896 fTable.setSelection((int) fPendingGotoRank + 1);
2897 fPendingGotoRank = -1;
2898 updateStatusLine(null);
2899 }
2900 } else {
2901 startFilterThread();
2902 }
2903 }
2904 if (!fRawViewer.isDisposed() && (fTrace != null)) {
2905 fRawViewer.refreshEventCount();
2906 }
2907 }
2908 });
2909 }
2910
2911 /**
2912 * Handler for the selection range signal.
2913 *
2914 * @param signal
2915 * The incoming signal
2916 * @since 1.0
2917 */
2918 @TmfSignalHandler
2919 public void selectionRangeUpdated(final TmfSelectionRangeUpdatedSignal signal) {
2920 if ((signal.getSource() != this) && (fTrace != null) && (!fTable.isDisposed())) {
2921
2922 /*
2923 * Create a request for one event that will be queued after other
2924 * ongoing requests. When this request is completed do the work to
2925 * select the actual event with the timestamp specified in the
2926 * signal. This procedure prevents the method fTrace.getRank() from
2927 * interfering and delaying ongoing requests.
2928 */
2929 final TmfEventRequest subRequest = new TmfEventRequest(ITmfEvent.class,
2930 TmfTimeRange.ETERNITY, 0, 1, ExecutionType.FOREGROUND) {
2931
2932 TmfTimestamp ts = new TmfTimestamp(signal.getBeginTime());
2933
2934 @Override
2935 public void handleData(final ITmfEvent event) {
2936 super.handleData(event);
2937 }
2938
2939 @Override
2940 public void handleSuccess() {
2941 super.handleSuccess();
2942 if (fTrace == null) {
2943 return;
2944 }
2945
2946 /*
2947 * Verify if the event is within the trace range and adjust
2948 * if necessary
2949 */
2950 ITmfTimestamp timestamp = ts;
2951 if (timestamp.compareTo(fTrace.getStartTime()) == -1) {
2952 timestamp = fTrace.getStartTime();
2953 }
2954 if (timestamp.compareTo(fTrace.getEndTime()) == 1) {
2955 timestamp = fTrace.getEndTime();
2956 }
2957
2958 // Get the rank of the selected event in the table
2959 final ITmfContext context = fTrace.seekEvent(timestamp);
2960 final long rank = context.getRank();
2961 context.dispose();
2962
2963 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
2964 @Override
2965 public void run() {
2966 // Return if table is disposed
2967 if (fTable.isDisposed()) {
2968 return;
2969 }
2970
2971 fSelectedRank = rank;
2972 fSelectedBeginRank = fSelectedRank;
2973 int index = (int) rank;
2974 if (fTable.getData(Key.FILTER_OBJ) != null) {
2975 /* +1 for top filter status row */
2976 index = fCache.getFilteredEventIndex(rank) + 1;
2977 }
2978 /* +1 for header row */
2979 fTable.setSelection(index + 1);
2980 fRawViewer.selectAndReveal(rank);
2981 updateStatusLine(null);
2982 }
2983 });
2984 }
2985 };
2986
2987 ((ITmfEventProvider) fTrace).sendRequest(subRequest);
2988 }
2989 }
2990
2991 // ------------------------------------------------------------------------
2992 // Error handling
2993 // ------------------------------------------------------------------------
2994
2995 /**
2996 * Display an exception in a message box
2997 *
2998 * @param e
2999 * the exception
3000 */
3001 private static void displayException(final Exception e) {
3002 final MessageBox mb = new MessageBox(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
3003 mb.setText(e.getClass().getSimpleName());
3004 mb.setMessage(e.getMessage());
3005 mb.open();
3006 }
3007
3008 /**
3009 * Refresh the table
3010 */
3011 public void refresh() {
3012 fCache.clear();
3013 fTable.refresh();
3014 fTable.redraw();
3015 }
3016
3017 /**
3018 * Margin column for images and special text (e.g. collapse count)
3019 */
3020 private static final class TmfMarginColumn extends TmfEventTableColumn {
3021
3022 private static final @NonNull ITmfEventAspect MARGIN_ASPECT = new ITmfEventAspect() {
3023
3024 @Override
3025 public String getName() {
3026 return EMPTY_STRING;
3027 }
3028
3029 @Override
3030 public String resolve(ITmfEvent event) {
3031 if (!(event instanceof CachedEvent) || ((CachedEvent) event).repeatCount == 0) {
3032 return EMPTY_STRING;
3033 }
3034 return "+" + ((CachedEvent) event).repeatCount; //$NON-NLS-1$
3035 }
3036
3037 @Override
3038 public String getHelpText() {
3039 return EMPTY_STRING;
3040 }
3041 };
3042
3043 /**
3044 * Constructor
3045 */
3046 public TmfMarginColumn() {
3047 super(MARGIN_ASPECT);
3048 }
3049 }
3050
3051 }
This page took 0.103477 seconds and 5 git commands to generate.