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