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