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