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