tmf: Support right mouse button selection of time graph entries
[deliverable/tracecompass.git] / tmf / org.eclipse.tracecompass.tmf.ui / src / org / eclipse / tracecompass / tmf / ui / widgets / timegraph / widgets / TimeGraphControl.java
1 /*****************************************************************************
2 * Copyright (c) 2007, 2016 Intel Corporation and others
3 *
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 *
9 * Contributors:
10 * Intel Corporation - Initial API and implementation
11 * Ruslan A. Scherbakov, Intel - Initial API and implementation
12 * Alvaro Sanchez-Leon, Ericsson - Updated for TMF
13 * Patrick Tasse, Ericsson - Refactoring
14 * Geneviève Bastien, École Polytechnique de Montréal - Move code to
15 * provide base classes for time graph view
16 * Add display of links between items
17 * Xavier Raynaud, Kalray - Code optimization
18 * Generoso Pagano, Inria - Support for drag selection listeners
19 *****************************************************************************/
20
21 package org.eclipse.tracecompass.tmf.ui.widgets.timegraph.widgets;
22
23 import java.util.AbstractMap.SimpleEntry;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.LinkedHashMap;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Map.Entry;
33
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.eclipse.jface.action.IStatusLineManager;
36 import org.eclipse.jface.resource.JFaceResources;
37 import org.eclipse.jface.resource.LocalResourceManager;
38 import org.eclipse.jface.viewers.AbstractTreeViewer;
39 import org.eclipse.jface.viewers.ISelection;
40 import org.eclipse.jface.viewers.ISelectionChangedListener;
41 import org.eclipse.jface.viewers.ISelectionProvider;
42 import org.eclipse.jface.viewers.ViewerFilter;
43 import org.eclipse.osgi.util.NLS;
44 import org.eclipse.swt.SWT;
45 import org.eclipse.swt.events.FocusEvent;
46 import org.eclipse.swt.events.FocusListener;
47 import org.eclipse.swt.events.KeyEvent;
48 import org.eclipse.swt.events.KeyListener;
49 import org.eclipse.swt.events.MenuDetectEvent;
50 import org.eclipse.swt.events.MenuDetectListener;
51 import org.eclipse.swt.events.MouseEvent;
52 import org.eclipse.swt.events.MouseListener;
53 import org.eclipse.swt.events.MouseMoveListener;
54 import org.eclipse.swt.events.MouseTrackListener;
55 import org.eclipse.swt.events.MouseWheelListener;
56 import org.eclipse.swt.events.PaintEvent;
57 import org.eclipse.swt.events.SelectionListener;
58 import org.eclipse.swt.events.TraverseEvent;
59 import org.eclipse.swt.events.TraverseListener;
60 import org.eclipse.swt.events.TypedEvent;
61 import org.eclipse.swt.graphics.Color;
62 import org.eclipse.swt.graphics.Cursor;
63 import org.eclipse.swt.graphics.Font;
64 import org.eclipse.swt.graphics.FontData;
65 import org.eclipse.swt.graphics.GC;
66 import org.eclipse.swt.graphics.Image;
67 import org.eclipse.swt.graphics.Point;
68 import org.eclipse.swt.graphics.Rectangle;
69 import org.eclipse.swt.widgets.Composite;
70 import org.eclipse.swt.widgets.Display;
71 import org.eclipse.swt.widgets.Event;
72 import org.eclipse.swt.widgets.Listener;
73 import org.eclipse.tracecompass.tmf.core.signal.TmfSignalManager;
74 import org.eclipse.tracecompass.tmf.ui.signal.TmfTimeViewAlignmentInfo;
75 import org.eclipse.tracecompass.tmf.ui.signal.TmfTimeViewAlignmentSignal;
76 import org.eclipse.tracecompass.tmf.ui.views.ITmfTimeAligned;
77 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.ITimeGraphColorListener;
78 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider;
79 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider2;
80 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.ITimeGraphTimeListener;
81 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.ITimeGraphTreeListener;
82 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.StateItem;
83 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.TimeGraphTimeEvent;
84 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.TimeGraphTreeExpansionEvent;
85 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.ILinkEvent;
86 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.IMarkerEvent;
87 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.ITimeEvent;
88 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.ITimeGraphEntry;
89 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.widgets.Utils.Resolution;
90 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.widgets.Utils.TimeFormat;
91
92 import com.google.common.collect.Iterables;
93
94 /**
95 * Time graph control implementation
96 *
97 * @author Alvaro Sanchez-Leon
98 * @author Patrick Tasse
99 */
100 public class TimeGraphControl extends TimeGraphBaseControl
101 implements FocusListener, KeyListener, MouseMoveListener, MouseListener,
102 MouseWheelListener, MouseTrackListener, TraverseListener, ISelectionProvider,
103 MenuDetectListener, ITmfTimeGraphDrawingHelper, ITimeGraphColorListener, Listener {
104
105 /** Constant indicating that all levels of the time graph should be expanded */
106 public static final int ALL_LEVELS = AbstractTreeViewer.ALL_LEVELS;
107
108 private static final int DRAG_NONE = 0;
109 private static final int DRAG_TRACE_ITEM = 1;
110 private static final int DRAG_SPLIT_LINE = 2;
111 private static final int DRAG_ZOOM = 3;
112 private static final int DRAG_SELECTION = 4;
113
114 private static final int CUSTOM_ITEM_HEIGHT = -1; // get item height from provider
115
116 private static final double ZOOM_FACTOR = 1.5;
117 private static final double ZOOM_IN_FACTOR = 0.8;
118 private static final double ZOOM_OUT_FACTOR = 1.25;
119
120 private static final int SNAP_WIDTH = 2;
121 private static final int ARROW_HOVER_MAX_DIST = 5;
122
123 private static final int NO_STATUS = -1;
124 private static final int STATUS_WITHOUT_CURSOR_TIME = -2;
125
126 private static final int MAX_LABEL_LENGTH = 256;
127
128 private static final int PPI = 72; // points per inch
129 private static final int DPI = Display.getDefault().getDPI().y;
130
131 private static final int VERTICAL_ZOOM_DELAY = 400;
132
133 /** Resource manager */
134 private LocalResourceManager fResourceManager = new LocalResourceManager(JFaceResources.getResources());
135
136 /** Color map for event types */
137 private Color[] fEventColorMap = null;
138
139 private ITimeDataProvider fTimeProvider;
140 private IStatusLineManager fStatusLineManager = null;
141 private TimeGraphScale fTimeGraphScale = null;
142
143 private boolean fIsInFocus = false;
144 private boolean fMouseOverSplitLine = false;
145 private int fGlobalItemHeight = CUSTOM_ITEM_HEIGHT;
146 private int fHeightAdjustment = 0;
147 private Map<Integer, Font> fFonts = new HashMap<>();
148 private boolean fBlendSubPixelEvents = false;
149 private int fMinimumItemWidth = 0;
150 private int fTopIndex = 0;
151 private int fDragState = DRAG_NONE;
152 private boolean fDragBeginMarker = false;
153 private int fDragButton;
154 private int fDragX0 = 0;
155 private int fDragX = 0;
156 private long fDragTime0 = 0; // used to preserve accuracy of modified selection
157 private int fIdealNameSpace = 0;
158 private long fTime0bak;
159 private long fTime1bak;
160 private ITimeGraphPresentationProvider fTimeGraphProvider = null;
161 private ItemData fItemData = null;
162 private List<IMarkerEvent> fMarkers = null;
163 private boolean fMarkersVisible = true;
164 private List<SelectionListener> fSelectionListeners;
165 private List<ITimeGraphTimeListener> fDragSelectionListeners;
166 private final List<ISelectionChangedListener> fSelectionChangedListeners = new ArrayList<>();
167 private final List<ITimeGraphTreeListener> fTreeListeners = new ArrayList<>();
168 private final List<MenuDetectListener> fTimeGraphEntryMenuListeners = new ArrayList<>();
169 private final List<MenuDetectListener> fTimeEventMenuListeners = new ArrayList<>();
170 private final Cursor fDragCursor = Display.getDefault().getSystemCursor(SWT.CURSOR_HAND);
171 private final Cursor fResizeCursor = Display.getDefault().getSystemCursor(SWT.CURSOR_IBEAM);
172 private final Cursor fWaitCursor = Display.getDefault().getSystemCursor(SWT.CURSOR_WAIT);
173 private final Cursor fZoomCursor = Display.getDefault().getSystemCursor(SWT.CURSOR_SIZEWE);
174 private final List<@NonNull ViewerFilter> fFilters = new ArrayList<>();
175 private MenuDetectEvent fPendingMenuDetectEvent = null;
176 private boolean fGridLinesVisible = true;
177 private Color fGridLineColor = Display.getDefault().getSystemColor(SWT.COLOR_GRAY);
178 private boolean fHideArrows = false;
179 private int fAutoExpandLevel = ALL_LEVELS;
180 private Entry<ITimeGraphEntry, Integer> fVerticalZoomAlignEntry = null;
181 private long fVerticalZoomAlignTime = 0;
182 private int fBorderWidth = 0;
183 private int fHeaderHeight = 0;
184
185 /**
186 * Standard constructor
187 *
188 * @param parent
189 * The parent composite object
190 * @param colors
191 * The color scheme to use
192 */
193 public TimeGraphControl(Composite parent, TimeGraphColorScheme colors) {
194
195 super(parent, colors, SWT.NO_BACKGROUND | SWT.DOUBLE_BUFFERED);
196
197 fItemData = new ItemData();
198
199 addFocusListener(this);
200 addMouseListener(this);
201 addMouseMoveListener(this);
202 addMouseTrackListener(this);
203 addMouseWheelListener(this);
204 addTraverseListener(this);
205 addKeyListener(this);
206 addMenuDetectListener(this);
207 addListener(SWT.MouseWheel, this);
208 addDisposeListener((e) -> {
209 fResourceManager.dispose();
210 for (Font font : fFonts.values()) {
211 font.dispose();
212 }
213 });
214 }
215
216 /**
217 * Sets the timegraph provider used by this timegraph viewer.
218 *
219 * @param timeGraphProvider the timegraph provider
220 */
221 public void setTimeGraphProvider(ITimeGraphPresentationProvider timeGraphProvider) {
222 fTimeGraphProvider = timeGraphProvider;
223
224 if (timeGraphProvider instanceof ITimeGraphPresentationProvider2) {
225 ((ITimeGraphPresentationProvider2) timeGraphProvider).setDrawingHelper(this);
226 ((ITimeGraphPresentationProvider2) timeGraphProvider).addColorListener(this);
227 }
228
229 StateItem[] stateItems = fTimeGraphProvider.getStateTable();
230 colorSettingsChanged(stateItems);
231 }
232
233 /**
234 * Gets the timegraph provider used by this timegraph viewer.
235 *
236 * @return the timegraph provider, or <code>null</code> if not set.
237 */
238 public ITimeGraphPresentationProvider getTimeGraphProvider() {
239 return fTimeGraphProvider;
240 }
241
242 /**
243 * Gets the color map used by this timegraph viewer.
244 *
245 * @return a color map, or <code>null</code> if not set.
246 */
247 public Color[] getEventColorMap() {
248 return fEventColorMap;
249 }
250
251 /**
252 * Assign the given time provider
253 *
254 * @param timeProvider
255 * The time provider
256 */
257 public void setTimeProvider(ITimeDataProvider timeProvider) {
258 fTimeProvider = timeProvider;
259 redraw();
260 }
261
262 /**
263 * Assign the status line manager
264 *
265 * @param statusLineManager
266 * The status line manager, or null to disable status line messages
267 */
268 public void setStatusLineManager(IStatusLineManager statusLineManager) {
269 if (fStatusLineManager != null && statusLineManager == null) {
270 fStatusLineManager.setMessage(""); //$NON-NLS-1$
271 }
272 fStatusLineManager = statusLineManager;
273 }
274
275 /**
276 * Assign the time graph scale
277 *
278 * @param timeGraphScale
279 * The time graph scale
280 */
281 public void setTimeGraphScale(TimeGraphScale timeGraphScale) {
282 fTimeGraphScale = timeGraphScale;
283 }
284
285 /**
286 * Add a selection listener
287 *
288 * @param listener
289 * The listener to add
290 */
291 public void addSelectionListener(SelectionListener listener) {
292 if (listener == null) {
293 SWT.error(SWT.ERROR_NULL_ARGUMENT);
294 }
295 if (null == fSelectionListeners) {
296 fSelectionListeners = new ArrayList<>();
297 }
298 fSelectionListeners.add(listener);
299 }
300
301 /**
302 * Remove a selection listener
303 *
304 * @param listener
305 * The listener to remove
306 */
307 public void removeSelectionListener(SelectionListener listener) {
308 if (null != fSelectionListeners) {
309 fSelectionListeners.remove(listener);
310 }
311 }
312
313 /**
314 * Selection changed callback
315 */
316 public void fireSelectionChanged() {
317 if (null != fSelectionListeners) {
318 Iterator<SelectionListener> it = fSelectionListeners.iterator();
319 while (it.hasNext()) {
320 SelectionListener listener = it.next();
321 listener.widgetSelected(null);
322 }
323 }
324 }
325
326 /**
327 * Default selection callback
328 */
329 public void fireDefaultSelection() {
330 if (null != fSelectionListeners) {
331 Iterator<SelectionListener> it = fSelectionListeners.iterator();
332 while (it.hasNext()) {
333 SelectionListener listener = it.next();
334 listener.widgetDefaultSelected(null);
335 }
336 }
337 }
338
339 /**
340 * Add a drag selection listener
341 *
342 * @param listener
343 * The listener to add
344 */
345 public void addDragSelectionListener(ITimeGraphTimeListener listener) {
346 if (listener == null) {
347 SWT.error(SWT.ERROR_NULL_ARGUMENT);
348 }
349 if (null == fDragSelectionListeners) {
350 fDragSelectionListeners = new ArrayList<>();
351 }
352 fDragSelectionListeners.add(listener);
353 }
354
355 /**
356 * Remove a drag selection listener
357 *
358 * @param listener
359 * The listener to remove
360 */
361 public void removeDragSelectionListener(ITimeGraphTimeListener listener) {
362 if (null != fDragSelectionListeners) {
363 fDragSelectionListeners.remove(listener);
364 }
365 }
366
367 /**
368 * Drag Selection changed callback
369 *
370 * @param start
371 * Time interval start
372 * @param end
373 * Time interval end
374 */
375 public void fireDragSelectionChanged(long start, long end) {
376 // check for backward intervals
377 long beginTime, endTime;
378 if (start > end) {
379 beginTime = end;
380 endTime = start;
381 } else {
382 beginTime = start;
383 endTime = end;
384 }
385 // call the listeners
386 if (null != fDragSelectionListeners) {
387 Iterator<ITimeGraphTimeListener> it = fDragSelectionListeners.iterator();
388 while (it.hasNext()) {
389 ITimeGraphTimeListener listener = it.next();
390 listener.timeSelected(new TimeGraphTimeEvent(this, beginTime, endTime));
391 }
392 }
393 }
394
395 /**
396 * Get the traces in the model
397 *
398 * @return The array of traces
399 */
400 public ITimeGraphEntry[] getTraces() {
401 return fItemData.getEntries();
402 }
403
404 /**
405 * Refresh the data for the thing
406 */
407 public void refreshData() {
408 fItemData.refreshData();
409 redraw();
410 }
411
412 /**
413 * Refresh data for the given traces
414 *
415 * @param traces
416 * The traces to refresh
417 */
418 public void refreshData(ITimeGraphEntry[] traces) {
419 fItemData.refreshData(traces);
420 redraw();
421 }
422
423 /**
424 * Refresh the links (arrows) of this widget
425 *
426 * @param events The link event list
427 */
428 public void refreshArrows(List<ILinkEvent> events) {
429 fItemData.refreshArrows(events);
430 }
431
432 /**
433 * Get the links (arrows) of this widget
434 *
435 * @return The unmodifiable link event list
436 *
437 * @since 1.1
438 */
439 public List<ILinkEvent> getArrows() {
440 return Collections.unmodifiableList(fItemData.fLinks);
441 }
442
443 boolean ensureVisibleItem(int idx, boolean redraw) {
444 boolean changed = false;
445 int index = idx;
446 if (index < 0) {
447 for (index = 0; index < fItemData.fExpandedItems.length; index++) {
448 if (fItemData.fExpandedItems[index].fSelected) {
449 break;
450 }
451 }
452 }
453 if (index >= fItemData.fExpandedItems.length) {
454 return changed;
455 }
456 if (index < fTopIndex) {
457 setTopIndex(index);
458 if (redraw) {
459 redraw();
460 }
461 changed = true;
462 } else {
463 int page = countPerPage();
464 if (index >= fTopIndex + page) {
465 setTopIndex(index - page + 1);
466 if (redraw) {
467 redraw();
468 }
469 changed = true;
470 }
471 }
472 return changed;
473 }
474
475 /**
476 * Assign the given index as the top one
477 *
478 * @param idx
479 * The index
480 */
481 public void setTopIndex(int idx) {
482 int index = Math.min(idx, fItemData.fExpandedItems.length - countPerPage());
483 index = Math.max(0, index);
484 fTopIndex = index;
485 redraw();
486 }
487
488 /**
489 * Set the top index so that the requested element is at the specified
490 * position.
491 *
492 * @param entry
493 * the time graph entry to be positioned
494 * @param y
495 * the requested y-coordinate
496 * @since 2.0
497 */
498 public void setElementPosition(ITimeGraphEntry entry, int y) {
499 Item item = fItemData.fItemMap.get(entry);
500 if (item == null || item.fExpandedIndex == -1) {
501 return;
502 }
503 int index = item.fExpandedIndex;
504 Rectangle itemRect = getItemRect(getClientArea(), index);
505 int delta = itemRect.y + itemRect.height - y;
506 int topIndex = getItemIndexAtY(delta);
507 if (topIndex != -1) {
508 setTopIndex(topIndex);
509 } else {
510 if (delta < 0) {
511 setTopIndex(0);
512 } else {
513 setTopIndex(getExpandedElementCount());
514 }
515 }
516 }
517
518 /**
519 * Sets the auto-expand level to be used for new entries discovered when
520 * calling {@link #refreshData()} or {@link #refreshData(ITimeGraphEntry[])}
521 * . The value 0 means that there is no auto-expand; 1 means that top-level
522 * entries are expanded, but not their children; 2 means that top-level
523 * entries are expanded, and their children, but not grand-children; and so
524 * on.
525 * <p>
526 * The value {@link #ALL_LEVELS} means that all subtrees should be expanded.
527 * </p>
528 *
529 * @param level
530 * non-negative level, or <code>ALL_LEVELS</code> to expand all
531 * levels of the tree
532 */
533 public void setAutoExpandLevel(int level) {
534 fAutoExpandLevel = level;
535 }
536
537 /**
538 * Returns the auto-expand level.
539 *
540 * @return non-negative level, or <code>ALL_LEVELS</code> if all levels of
541 * the tree are expanded automatically
542 * @see #setAutoExpandLevel
543 */
544 public int getAutoExpandLevel() {
545 return fAutoExpandLevel;
546 }
547
548 /**
549 * Get the expanded state of a given entry.
550 *
551 * @param entry
552 * The entry
553 * @return true if the entry is expanded, false if collapsed
554 * @since 1.1
555 */
556 public boolean getExpandedState(ITimeGraphEntry entry) {
557 Item item = fItemData.fItemMap.get(entry);
558 return (item != null ? item.fExpanded : false);
559 }
560
561 /**
562 * Set the expanded state of a given entry
563 *
564 * @param entry
565 * The entry
566 * @param expanded
567 * True if expanded, false if collapsed
568 */
569 public void setExpandedState(ITimeGraphEntry entry, boolean expanded) {
570 Item item = fItemData.findItem(entry);
571 if (item != null && item.fExpanded != expanded) {
572 item.fExpanded = expanded;
573 fItemData.updateExpandedItems();
574 redraw();
575 }
576 }
577
578 /**
579 * Collapses all nodes of the viewer's tree, starting with the root.
580 */
581 public void collapseAll() {
582 for (Item item : fItemData.fItems) {
583 item.fExpanded = false;
584 }
585 fItemData.updateExpandedItems();
586 redraw();
587 }
588
589 /**
590 * Expands all nodes of the viewer's tree, starting with the root.
591 */
592 public void expandAll() {
593 for (Item item : fItemData.fItems) {
594 item.fExpanded = true;
595 }
596 fItemData.updateExpandedItems();
597 redraw();
598 }
599
600 /**
601 * Add a tree listener
602 *
603 * @param listener
604 * The listener to add
605 */
606 public void addTreeListener(ITimeGraphTreeListener listener) {
607 if (!fTreeListeners.contains(listener)) {
608 fTreeListeners.add(listener);
609 }
610 }
611
612 /**
613 * Remove a tree listener
614 *
615 * @param listener
616 * The listener to remove
617 */
618 public void removeTreeListener(ITimeGraphTreeListener listener) {
619 if (fTreeListeners.contains(listener)) {
620 fTreeListeners.remove(listener);
621 }
622 }
623
624 /**
625 * Tree event callback
626 *
627 * @param entry
628 * The affected entry
629 * @param expanded
630 * The expanded state (true for expanded, false for collapsed)
631 */
632 public void fireTreeEvent(ITimeGraphEntry entry, boolean expanded) {
633 TimeGraphTreeExpansionEvent event = new TimeGraphTreeExpansionEvent(this, entry);
634 for (ITimeGraphTreeListener listener : fTreeListeners) {
635 if (expanded) {
636 listener.treeExpanded(event);
637 } else {
638 listener.treeCollapsed(event);
639 }
640 }
641 }
642
643 /**
644 * Add a menu listener on {@link ITimeGraphEntry}s
645 *
646 * @param listener
647 * The listener to add
648 */
649 public void addTimeGraphEntryMenuListener(MenuDetectListener listener) {
650 if (!fTimeGraphEntryMenuListeners.contains(listener)) {
651 fTimeGraphEntryMenuListeners.add(listener);
652 }
653 }
654
655 /**
656 * Remove a menu listener on {@link ITimeGraphEntry}s
657 *
658 * @param listener
659 * The listener to remove
660 */
661 public void removeTimeGraphEntryMenuListener(MenuDetectListener listener) {
662 if (fTimeGraphEntryMenuListeners.contains(listener)) {
663 fTimeGraphEntryMenuListeners.remove(listener);
664 }
665 }
666
667 /**
668 * Menu event callback on {@link ITimeGraphEntry}s
669 *
670 * @param event
671 * The MenuDetectEvent, with field {@link TypedEvent#data} set to the selected {@link ITimeGraphEntry}
672 */
673 private void fireMenuEventOnTimeGraphEntry(MenuDetectEvent event) {
674 for (MenuDetectListener listener : fTimeGraphEntryMenuListeners) {
675 listener.menuDetected(event);
676 }
677 }
678
679 /**
680 * Add a menu listener on {@link ITimeEvent}s
681 *
682 * @param listener
683 * The listener to add
684 */
685 public void addTimeEventMenuListener(MenuDetectListener listener) {
686 if (!fTimeEventMenuListeners.contains(listener)) {
687 fTimeEventMenuListeners.add(listener);
688 }
689 }
690
691 /**
692 * Remove a menu listener on {@link ITimeEvent}s
693 *
694 * @param listener
695 * The listener to remove
696 */
697 public void removeTimeEventMenuListener(MenuDetectListener listener) {
698 if (fTimeEventMenuListeners.contains(listener)) {
699 fTimeEventMenuListeners.remove(listener);
700 }
701 }
702
703 /**
704 * Menu event callback on {@link ITimeEvent}s
705 *
706 * @param event
707 * The MenuDetectEvent, with field {@link TypedEvent#data} set to the selected {@link ITimeEvent}
708 */
709 private void fireMenuEventOnTimeEvent(MenuDetectEvent event) {
710 for (MenuDetectListener listener : fTimeEventMenuListeners) {
711 listener.menuDetected(event);
712 }
713 }
714
715 @Override
716 public ISelection getSelection() {
717 TimeGraphSelection sel = new TimeGraphSelection();
718 ITimeGraphEntry trace = getSelectedTrace();
719 if (null != trace && null != fTimeProvider) {
720 long selectedTime = fTimeProvider.getSelectionBegin();
721 ITimeEvent event = Utils.findEvent(trace, selectedTime, 0);
722 if (event != null) {
723 sel.add(event);
724 } else {
725 sel.add(trace);
726 }
727 }
728 return sel;
729 }
730
731 /**
732 * Get the selection object
733 *
734 * @return The selection
735 */
736 public ISelection getSelectionTrace() {
737 TimeGraphSelection sel = new TimeGraphSelection();
738 ITimeGraphEntry trace = getSelectedTrace();
739 if (null != trace) {
740 sel.add(trace);
741 }
742 return sel;
743 }
744
745 /**
746 * Enable/disable one of the traces in the model
747 *
748 * @param n
749 * 1 to enable it, -1 to disable. The method returns immediately
750 * if another value is used.
751 */
752 public void selectTrace(int n) {
753 if ((n != 1) && (n != -1)) {
754 return;
755 }
756
757 boolean changed = false;
758 int lastSelection = -1;
759 for (int i = 0; i < fItemData.fExpandedItems.length; i++) {
760 Item item = fItemData.fExpandedItems[i];
761 if (item.fSelected) {
762 lastSelection = i;
763 if ((1 == n) && (i < fItemData.fExpandedItems.length - 1)) {
764 item.fSelected = false;
765 item = fItemData.fExpandedItems[i + 1];
766 item.fSelected = true;
767 changed = true;
768 } else if ((-1 == n) && (i > 0)) {
769 item.fSelected = false;
770 item = fItemData.fExpandedItems[i - 1];
771 item.fSelected = true;
772 changed = true;
773 }
774 break;
775 }
776 }
777
778 if (lastSelection < 0 && fItemData.fExpandedItems.length > 0) {
779 Item item = fItemData.fExpandedItems[0];
780 item.fSelected = true;
781 changed = true;
782 }
783
784 if (changed) {
785 ensureVisibleItem(-1, false);
786 redraw();
787 fireSelectionChanged();
788 }
789 }
790
791 /**
792 * Select an event
793 *
794 * @param n
795 * 1 for next event, -1 for previous event
796 * @param extend
797 * true to extend selection range, false for single selection
798 * @since 1.0
799 */
800 public void selectEvent(int n, boolean extend) {
801 if (null == fTimeProvider) {
802 return;
803 }
804 ITimeGraphEntry trace = getSelectedTrace();
805 if (trace == null) {
806 return;
807 }
808 long selectedTime = fTimeProvider.getSelectionEnd();
809 long endTime = fTimeProvider.getMaxTime();
810 ITimeEvent nextEvent;
811 if (n == -1 && selectedTime > endTime) {
812 nextEvent = Utils.findEvent(trace, selectedTime, 0);
813 } else {
814 nextEvent = Utils.findEvent(trace, selectedTime, n);
815 }
816 if (null == nextEvent && n == -1) {
817 nextEvent = Utils.getFirstEvent(trace);
818 }
819 if (null != nextEvent) {
820 long nextTime = nextEvent.getTime();
821 // If last event detected e.g. going back or not moving to a next
822 // event
823 if (nextTime <= selectedTime && n == 1) {
824 // Select to the end of this last event
825 nextTime = nextEvent.getTime() + nextEvent.getDuration();
826 // but not beyond the end of the trace
827 if (nextTime > endTime) {
828 nextTime = endTime;
829 }
830 } else if (n == -1 && nextEvent.getTime() + nextEvent.getDuration() < selectedTime) {
831 // for previous event go to its end time unless we were already there
832 nextTime = nextEvent.getTime() + nextEvent.getDuration();
833 }
834 if (extend) {
835 fTimeProvider.setSelectionRangeNotify(fTimeProvider.getSelectionBegin(), nextTime, true);
836 } else {
837 fTimeProvider.setSelectedTimeNotify(nextTime, true);
838 }
839 fireSelectionChanged();
840 } else if (n == 1) {
841 if (extend) {
842 fTimeProvider.setSelectionRangeNotify(fTimeProvider.getSelectionBegin(), endTime, true);
843 } else {
844 fTimeProvider.setSelectedTimeNotify(endTime, true);
845 }
846 fireSelectionChanged();
847 }
848 updateStatusLine(STATUS_WITHOUT_CURSOR_TIME);
849 }
850
851 /**
852 * Select the next event
853 *
854 * @param extend
855 * true to extend selection range, false for single selection
856 * @since 1.0
857 */
858 public void selectNextEvent(boolean extend) {
859 selectEvent(1, extend);
860 // Notify if visible time window has been adjusted
861 fTimeProvider.setStartFinishTimeNotify(fTimeProvider.getTime0(), fTimeProvider.getTime1());
862 }
863
864 /**
865 * Select the previous event
866 *
867 * @param extend
868 * true to extend selection range, false for single selection
869 * @since 1.0
870 */
871 public void selectPrevEvent(boolean extend) {
872 selectEvent(-1, extend);
873 // Notify if visible time window has been adjusted
874 fTimeProvider.setStartFinishTimeNotify(fTimeProvider.getTime0(), fTimeProvider.getTime1());
875 }
876
877 /**
878 * Select the next trace
879 */
880 public void selectNextTrace() {
881 selectTrace(1);
882 }
883
884 /**
885 * Select the previous trace
886 */
887 public void selectPrevTrace() {
888 selectTrace(-1);
889 }
890
891 /**
892 * Scroll left or right by one half window size
893 *
894 * @param left
895 * true to scroll left, false to scroll right
896 */
897 public void horizontalScroll(boolean left) {
898 long time0 = fTimeProvider.getTime0();
899 long time1 = fTimeProvider.getTime1();
900 long timeMin = fTimeProvider.getMinTime();
901 long timeMax = fTimeProvider.getMaxTime();
902 long range = time1 - time0;
903 if (range <= 0) {
904 return;
905 }
906 long increment = Math.max(1, range / 2);
907 if (left) {
908 time0 = Math.max(time0 - increment, timeMin);
909 time1 = time0 + range;
910 } else {
911 time1 = Math.min(time1 + increment, timeMax);
912 time0 = time1 - range;
913 }
914 fTimeProvider.setStartFinishTimeNotify(time0, time1);
915 }
916
917 /**
918 * Zoom based on mouse cursor location with mouse scrolling
919 *
920 * @param zoomIn true to zoom in, false to zoom out
921 */
922 public void zoom(boolean zoomIn) {
923 int globalX = getDisplay().getCursorLocation().x;
924 Point p = toControl(globalX, 0);
925 int nameSpace = fTimeProvider.getNameSpace();
926 int timeSpace = fTimeProvider.getTimeSpace();
927 int xPos = Math.max(nameSpace, Math.min(nameSpace + timeSpace, p.x));
928 long time0 = fTimeProvider.getTime0();
929 long time1 = fTimeProvider.getTime1();
930 long interval = time1 - time0;
931 if (interval == 0) {
932 interval = 1;
933 } // to allow getting out of single point interval
934 long newInterval;
935 if (zoomIn) {
936 newInterval = Math.max(Math.round(interval * ZOOM_IN_FACTOR), fTimeProvider.getMinTimeInterval());
937 } else {
938 newInterval = (long) Math.ceil(interval * ZOOM_OUT_FACTOR);
939 }
940 long center = time0 + Math.round(((double) (xPos - nameSpace) / timeSpace * interval));
941 long newTime0 = center - Math.round((double) newInterval * (center - time0) / interval);
942 long newTime1 = newTime0 + newInterval;
943 fTimeProvider.setStartFinishTimeNotify(newTime0, newTime1);
944 }
945
946 /**
947 * zoom in using single click
948 */
949 public void zoomIn() {
950 long prevTime0 = fTimeProvider.getTime0();
951 long prevTime1 = fTimeProvider.getTime1();
952 long prevRange = prevTime1 - prevTime0;
953 if (prevRange == 0) {
954 return;
955 }
956 ITimeDataProvider provider = fTimeProvider;
957 long selTime = (provider.getSelectionEnd() + provider.getSelectionBegin()) / 2;
958 if (selTime <= prevTime0 || selTime >= prevTime1) {
959 selTime = (prevTime0 + prevTime1) / 2;
960 }
961 long time0 = selTime - (long) ((selTime - prevTime0) / ZOOM_FACTOR);
962 long time1 = selTime + (long) ((prevTime1 - selTime) / ZOOM_FACTOR);
963
964 long inaccuracy = (fTimeProvider.getMaxTime() - fTimeProvider.getMinTime()) - (time1 - time0);
965
966 if (inaccuracy > 0 && inaccuracy < 100) {
967 fTimeProvider.setStartFinishTimeNotify(fTimeProvider.getMinTime(), fTimeProvider.getMaxTime());
968 return;
969 }
970
971 long min = fTimeProvider.getMinTimeInterval();
972 if ((time1 - time0) < min) {
973 time0 = selTime - (selTime - prevTime0) * min / prevRange;
974 time1 = time0 + min;
975 }
976
977 fTimeProvider.setStartFinishTimeNotify(time0, time1);
978 }
979
980 /**
981 * zoom out using single click
982 */
983 public void zoomOut() {
984 long prevTime0 = fTimeProvider.getTime0();
985 long prevTime1 = fTimeProvider.getTime1();
986 ITimeDataProvider provider = fTimeProvider;
987 long selTime = (provider.getSelectionEnd() + provider.getSelectionBegin()) / 2;
988 if (selTime <= prevTime0 || selTime >= prevTime1) {
989 selTime = (prevTime0 + prevTime1) / 2;
990 }
991 long time0 = (long) (selTime - (selTime - prevTime0) * ZOOM_FACTOR);
992 long time1 = (long) (selTime + (prevTime1 - selTime) * ZOOM_FACTOR);
993
994 long inaccuracy = (fTimeProvider.getMaxTime() - fTimeProvider.getMinTime()) - (time1 - time0);
995 if (inaccuracy > 0 && inaccuracy < 100) {
996 fTimeProvider.setStartFinishTimeNotify(fTimeProvider.getMinTime(), fTimeProvider.getMaxTime());
997 return;
998 }
999
1000 fTimeProvider.setStartFinishTimeNotify(time0, time1);
1001 }
1002
1003 /**
1004 * Zoom vertically.
1005 *
1006 * @param zoomIn
1007 * true to zoom in, false to zoom out
1008 * @since 2.0
1009 */
1010 public void verticalZoom(boolean zoomIn) {
1011 if (zoomIn) {
1012 fHeightAdjustment++;
1013 } else {
1014 fHeightAdjustment--;
1015 }
1016 fItemData.refreshData();
1017 redraw();
1018 }
1019
1020 /**
1021 * Reset the vertical zoom to default.
1022 *
1023 * @since 2.0
1024 */
1025 public void resetVerticalZoom() {
1026 fHeightAdjustment = 0;
1027 fItemData.refreshData();
1028 redraw();
1029 }
1030
1031 /**
1032 * Set the grid lines visibility. The default is true.
1033 *
1034 * @param visible
1035 * true to show the grid lines, false otherwise
1036 * @since 2.0
1037 */
1038 public void setGridLinesVisible(boolean visible) {
1039 fGridLinesVisible = visible;
1040 }
1041
1042 /**
1043 * Get the grid lines visibility.
1044 *
1045 * @return true if the grid lines are visible, false otherwise
1046 * @since 2.0
1047 */
1048 public boolean getGridLinesVisible() {
1049 return fGridLinesVisible;
1050 }
1051
1052 /**
1053 * Set the grid line color. The default is SWT.COLOR_GRAY.
1054 *
1055 * @param color
1056 * the grid line color
1057 * @since 2.0
1058 */
1059 public void setGridLineColor(Color color) {
1060 fGridLineColor = color;
1061 }
1062
1063 /**
1064 * Get the grid line color.
1065 *
1066 * @return the grid line color
1067 * @since 2.0
1068 */
1069 public Color getGridLineColor() {
1070 return fGridLineColor;
1071 }
1072
1073 /**
1074 * Set the markers list.
1075 *
1076 * @param markers
1077 * The markers list, or null
1078 * @since 2.0
1079 */
1080 public void setMarkers(List<IMarkerEvent> markers) {
1081 fMarkers = markers;
1082 }
1083
1084 /**
1085 * Get the markers list.
1086 *
1087 * @return The markers list, or null
1088 * @since 2.0
1089 */
1090 public List<IMarkerEvent> getMarkers() {
1091 return fMarkers;
1092 }
1093
1094 /**
1095 * Set the markers visibility. The default is true.
1096 *
1097 * @param visible
1098 * true to show the markers, false otherwise
1099 * @since 2.0
1100 */
1101 public void setMarkersVisible(boolean visible) {
1102 fMarkersVisible = visible;
1103 }
1104
1105 /**
1106 * Get the markers visibility.
1107 *
1108 * @return true if the markers are visible, false otherwise
1109 * @since 2.0
1110 */
1111 public boolean getMarkersVisible() {
1112 return fMarkersVisible;
1113 }
1114
1115 /**
1116 * Hide arrows
1117 *
1118 * @param hideArrows true to hide arrows
1119 */
1120 public void hideArrows(boolean hideArrows) {
1121 fHideArrows = hideArrows;
1122 }
1123
1124 /**
1125 * Follow the arrow forward
1126 *
1127 * @param extend
1128 * true to extend selection range, false for single selection
1129 * @since 1.0
1130 */
1131 public void followArrowFwd(boolean extend) {
1132 ITimeGraphEntry trace = getSelectedTrace();
1133 if (trace == null) {
1134 return;
1135 }
1136 long selectedTime = fTimeProvider.getSelectionEnd();
1137 for (ILinkEvent link : fItemData.fLinks) {
1138 if (link.getEntry() == trace && link.getTime() == selectedTime) {
1139 selectItem(link.getDestinationEntry(), false);
1140 if (link.getDuration() != 0) {
1141 if (extend) {
1142 fTimeProvider.setSelectionRangeNotify(fTimeProvider.getSelectionBegin(), link.getTime() + link.getDuration(), true);
1143 } else {
1144 fTimeProvider.setSelectedTimeNotify(link.getTime() + link.getDuration(), true);
1145 }
1146 // Notify if visible time window has been adjusted
1147 fTimeProvider.setStartFinishTimeNotify(fTimeProvider.getTime0(), fTimeProvider.getTime1());
1148 }
1149 fireSelectionChanged();
1150 updateStatusLine(STATUS_WITHOUT_CURSOR_TIME);
1151 return;
1152 }
1153 }
1154 selectNextEvent(extend);
1155 }
1156
1157 /**
1158 * Follow the arrow backward
1159 *
1160 * @param extend
1161 * true to extend selection range, false for single selection
1162 * @since 1.0
1163 */
1164 public void followArrowBwd(boolean extend) {
1165 ITimeGraphEntry trace = getSelectedTrace();
1166 if (trace == null) {
1167 return;
1168 }
1169 long selectedTime = fTimeProvider.getSelectionEnd();
1170 for (ILinkEvent link : fItemData.fLinks) {
1171 if (link.getDestinationEntry() == trace && link.getTime() + link.getDuration() == selectedTime) {
1172 selectItem(link.getEntry(), false);
1173 if (link.getDuration() != 0) {
1174 if (extend) {
1175 fTimeProvider.setSelectionRangeNotify(fTimeProvider.getSelectionBegin(), link.getTime(), true);
1176 } else {
1177 fTimeProvider.setSelectedTimeNotify(link.getTime(), true);
1178 }
1179 // Notify if visible time window has been adjusted
1180 fTimeProvider.setStartFinishTimeNotify(fTimeProvider.getTime0(), fTimeProvider.getTime1());
1181 }
1182 fireSelectionChanged();
1183 updateStatusLine(STATUS_WITHOUT_CURSOR_TIME);
1184 return;
1185 }
1186 }
1187 selectPrevEvent(extend);
1188 }
1189
1190 /**
1191 * Return the currently selected trace
1192 *
1193 * @return The entry matching the trace
1194 */
1195 public ITimeGraphEntry getSelectedTrace() {
1196 ITimeGraphEntry trace = null;
1197 int idx = getSelectedIndex();
1198 if (idx >= 0) {
1199 trace = fItemData.fExpandedItems[idx].fEntry;
1200 }
1201 return trace;
1202 }
1203
1204 /**
1205 * Retrieve the index of the currently selected item
1206 *
1207 * @return The index
1208 */
1209 public int getSelectedIndex() {
1210 int idx = -1;
1211 for (int i = 0; i < fItemData.fExpandedItems.length; i++) {
1212 Item item = fItemData.fExpandedItems[i];
1213 if (item.fSelected) {
1214 idx = i;
1215 break;
1216 }
1217 }
1218 return idx;
1219 }
1220
1221 boolean toggle(int idx) {
1222 boolean toggled = false;
1223 if (idx >= 0 && idx < fItemData.fExpandedItems.length) {
1224 Item item = fItemData.fExpandedItems[idx];
1225 if (item.fHasChildren) {
1226 item.fExpanded = !item.fExpanded;
1227 fItemData.updateExpandedItems();
1228 redraw();
1229 toggled = true;
1230 fireTreeEvent(item.fEntry, item.fExpanded);
1231 }
1232 }
1233 return toggled;
1234 }
1235
1236 /**
1237 * Gets the index of the item at the given location.
1238 *
1239 * @param y
1240 * the y coordinate
1241 * @return the index of the item at the given location, of -1 if none.
1242 */
1243 protected int getItemIndexAtY(int y) {
1244 int ySum = 0;
1245 if (y < 0) {
1246 for (int idx = fTopIndex - 1; idx >= 0; idx--) {
1247 ySum -= fItemData.fExpandedItems[idx].fItemHeight;
1248 if (y >= ySum) {
1249 return idx;
1250 }
1251 }
1252 } else {
1253 for (int idx = fTopIndex; idx < fItemData.fExpandedItems.length; idx++) {
1254 ySum += fItemData.fExpandedItems[idx].fItemHeight;
1255 if (y < ySum) {
1256 return idx;
1257 }
1258 }
1259 }
1260 return -1;
1261 }
1262
1263 boolean isOverSplitLine(int x) {
1264 if (x < 0 || null == fTimeProvider) {
1265 return false;
1266 }
1267 int nameWidth = fTimeProvider.getNameSpace();
1268 return Math.abs(x - nameWidth) < SNAP_WIDTH;
1269 }
1270
1271 /**
1272 * Gets the {@link ITimeGraphEntry} at the given location.
1273 *
1274 * @param pt
1275 * a point in the widget
1276 * @return the {@link ITimeGraphEntry} at this point, or <code>null</code>
1277 * if none.
1278 * @since 2.0
1279 */
1280 public ITimeGraphEntry getEntry(Point pt) {
1281 int idx = getItemIndexAtY(pt.y);
1282 return idx >= 0 ? fItemData.fExpandedItems[idx].fEntry : null;
1283 }
1284
1285 /**
1286 * Return the arrow event closest to the given point that is no further than
1287 * a maximum distance.
1288 *
1289 * @param pt
1290 * a point in the widget
1291 * @return The closest arrow event, or null if there is none close enough.
1292 */
1293 protected ILinkEvent getArrow(Point pt) {
1294 if (fHideArrows) {
1295 return null;
1296 }
1297 ILinkEvent linkEvent = null;
1298 double minDistance = Double.MAX_VALUE;
1299 for (ILinkEvent event : fItemData.fLinks) {
1300 Rectangle rect = getArrowRectangle(new Rectangle(0, 0, 0, 0), event);
1301 if (rect != null) {
1302 int x1 = rect.x;
1303 int y1 = rect.y;
1304 int x2 = x1 + rect.width;
1305 int y2 = y1 + rect.height;
1306 double d = Utils.distance(pt.x, pt.y, x1, y1, x2, y2);
1307 if (minDistance > d) {
1308 minDistance = d;
1309 linkEvent = event;
1310 }
1311 }
1312 }
1313 if (minDistance <= ARROW_HOVER_MAX_DIST) {
1314 return linkEvent;
1315 }
1316 return null;
1317 }
1318
1319 @Override
1320 public int getXForTime(long time) {
1321 if (null == fTimeProvider) {
1322 return -1;
1323 }
1324 long time0 = fTimeProvider.getTime0();
1325 long time1 = fTimeProvider.getTime1();
1326 int width = getSize().x;
1327 int nameSpace = fTimeProvider.getNameSpace();
1328 double pixelsPerNanoSec = (width - nameSpace <= RIGHT_MARGIN) ? 0 : (double) (width - nameSpace - RIGHT_MARGIN) / (time1 - time0);
1329 int x = getBounds().x + nameSpace + (int) ((time - time0) * pixelsPerNanoSec);
1330 return x;
1331 }
1332
1333 @Override
1334 public long getTimeAtX(int coord) {
1335 if (null == fTimeProvider) {
1336 return -1;
1337 }
1338 long hitTime = -1;
1339 Point size = getSize();
1340 long time0 = fTimeProvider.getTime0();
1341 long time1 = fTimeProvider.getTime1();
1342 int nameWidth = fTimeProvider.getNameSpace();
1343 final int x = coord - nameWidth;
1344 int timeWidth = size.x - nameWidth - RIGHT_MARGIN;
1345 if (x >= 0 && size.x >= nameWidth) {
1346 if (time1 - time0 > timeWidth) {
1347 // nanosecond smaller than one pixel: use the first integer nanosecond of this pixel's time range
1348 hitTime = time0 + (long) Math.ceil((time1 - time0) * ((double) x / timeWidth));
1349 } else {
1350 // nanosecond greater than one pixel: use the nanosecond that covers this pixel start position
1351 hitTime = time0 + (long) Math.floor((time1 - time0) * ((double) x / timeWidth));
1352 }
1353 }
1354 return hitTime;
1355 }
1356
1357 void selectItem(int idx, boolean addSelection) {
1358 boolean changed = false;
1359 if (addSelection) {
1360 if (idx >= 0 && idx < fItemData.fExpandedItems.length) {
1361 Item item = fItemData.fExpandedItems[idx];
1362 changed = !item.fSelected;
1363 item.fSelected = true;
1364 }
1365 } else {
1366 for (int i = 0; i < fItemData.fExpandedItems.length; i++) {
1367 Item item = fItemData.fExpandedItems[i];
1368 if ((i == idx && !item.fSelected) || (idx == -1 && item.fSelected)) {
1369 changed = true;
1370 }
1371 item.fSelected = i == idx;
1372 }
1373 }
1374 changed |= ensureVisibleItem(idx, true);
1375 if (changed) {
1376 redraw();
1377 }
1378 }
1379
1380 /**
1381 * Callback for item selection
1382 *
1383 * @param trace
1384 * The entry matching the trace
1385 * @param addSelection
1386 * If the selection is added or removed
1387 */
1388 public void selectItem(ITimeGraphEntry trace, boolean addSelection) {
1389 int idx = fItemData.findItemIndex(trace);
1390 selectItem(idx, addSelection);
1391 }
1392
1393 /**
1394 * Retrieve the number of entries shown per page.
1395 *
1396 * @return The count
1397 */
1398 public int countPerPage() {
1399 int height = getSize().y;
1400 int count = 0;
1401 int ySum = 0;
1402 for (int idx = fTopIndex; idx < fItemData.fExpandedItems.length; idx++) {
1403 ySum += fItemData.fExpandedItems[idx].fItemHeight;
1404 if (ySum >= height) {
1405 return count;
1406 }
1407 count++;
1408 }
1409 for (int idx = fTopIndex - 1; idx >= 0; idx--) {
1410 ySum += fItemData.fExpandedItems[idx].fItemHeight;
1411 if (ySum >= height) {
1412 return count;
1413 }
1414 count++;
1415 }
1416 return count;
1417 }
1418
1419 /**
1420 * Get the index of the top element
1421 *
1422 * @return The index
1423 */
1424 public int getTopIndex() {
1425 return fTopIndex;
1426 }
1427
1428 /**
1429 * Get the number of expanded (visible) items
1430 *
1431 * @return The count of expanded (visible) items
1432 */
1433 public int getExpandedElementCount() {
1434 return fItemData.fExpandedItems.length;
1435 }
1436
1437 /**
1438 * Get an array of all expanded (visible) elements
1439 *
1440 * @return The expanded (visible) elements
1441 */
1442 public ITimeGraphEntry[] getExpandedElements() {
1443 ArrayList<ITimeGraphEntry> elements = new ArrayList<>();
1444 for (Item item : fItemData.fExpandedItems) {
1445 elements.add(item.fEntry);
1446 }
1447 return elements.toArray(new ITimeGraphEntry[0]);
1448 }
1449
1450 /**
1451 * Get the expanded (visible) element at the specified index.
1452 *
1453 * @param index
1454 * the element index
1455 * @return The expanded (visible) element or null if out of range
1456 * @since 2.0
1457 */
1458 public ITimeGraphEntry getExpandedElement(int index) {
1459 if (index < 0 || index >= fItemData.fExpandedItems.length) {
1460 return null;
1461 }
1462 return fItemData.fExpandedItems[index].fEntry;
1463 }
1464
1465 Rectangle getNameRect(Rectangle bounds, int idx, int nameWidth) {
1466 Rectangle rect = getItemRect(bounds, idx);
1467 rect.width = nameWidth;
1468 return rect;
1469 }
1470
1471 Rectangle getStatesRect(Rectangle bounds, int idx, int nameWidth) {
1472 Rectangle rect = getItemRect(bounds, idx);
1473 rect.x += nameWidth;
1474 rect.width -= nameWidth;
1475 return rect;
1476 }
1477
1478 Rectangle getItemRect(Rectangle bounds, int idx) {
1479 int ySum = 0;
1480 if (idx >= fTopIndex) {
1481 for (int i = fTopIndex; i < idx; i++) {
1482 ySum += fItemData.fExpandedItems[i].fItemHeight;
1483 }
1484 } else {
1485 for (int i = fTopIndex - 1; i >= idx; i--) {
1486 ySum -= fItemData.fExpandedItems[i].fItemHeight;
1487 }
1488 }
1489 int y = bounds.y + ySum;
1490 int height = fItemData.fExpandedItems[idx].fItemHeight;
1491 return new Rectangle(bounds.x, y, bounds.width, height);
1492 }
1493
1494 @Override
1495 void paint(Rectangle bounds, PaintEvent e) {
1496 GC gc = e.gc;
1497
1498 if (bounds.width < 2 || bounds.height < 2 || null == fTimeProvider) {
1499 return;
1500 }
1501
1502 fIdealNameSpace = 0;
1503 int nameSpace = fTimeProvider.getNameSpace();
1504
1505 // draw the background layer
1506 drawBackground(bounds, nameSpace, gc);
1507
1508 // draw the grid lines
1509 drawGridLines(bounds, gc);
1510
1511 // draw the background markers
1512 drawMarkers(bounds, fTimeProvider, fMarkers, false, nameSpace, gc);
1513
1514 // draw the items
1515 drawItems(bounds, fTimeProvider, fItemData.fExpandedItems, fTopIndex, nameSpace, gc);
1516
1517 // draw the foreground markers
1518 drawMarkers(bounds, fTimeProvider, fMarkers, true, nameSpace, gc);
1519
1520 // draw the links (arrows)
1521 drawLinks(bounds, fTimeProvider, fItemData.fLinks, nameSpace, gc);
1522
1523 fTimeGraphProvider.postDrawControl(bounds, gc);
1524
1525 int alpha = gc.getAlpha();
1526 gc.setAlpha(100);
1527
1528 long time0 = fTimeProvider.getTime0();
1529 long time1 = fTimeProvider.getTime1();
1530 long selectionBegin = fTimeProvider.getSelectionBegin();
1531 long selectionEnd = fTimeProvider.getSelectionEnd();
1532 double pixelsPerNanoSec = (bounds.width - nameSpace <= RIGHT_MARGIN) ? 0 : (double) (bounds.width - nameSpace - RIGHT_MARGIN) / (time1 - time0);
1533 int x0 = bounds.x + nameSpace + (int) ((selectionBegin - time0) * pixelsPerNanoSec);
1534 int x1 = bounds.x + nameSpace + (int) ((selectionEnd - time0) * pixelsPerNanoSec);
1535
1536 // draw selection lines
1537 if (fDragState != DRAG_SELECTION) {
1538 gc.setForeground(getColorScheme().getColor(TimeGraphColorScheme.SELECTED_TIME));
1539 if (x0 >= nameSpace && x0 < bounds.x + bounds.width) {
1540 gc.drawLine(x0, bounds.y, x0, bounds.y + bounds.height);
1541 }
1542 if (x1 != x0) {
1543 if (x1 >= nameSpace && x1 < bounds.x + bounds.width) {
1544 gc.drawLine(x1, bounds.y, x1, bounds.y + bounds.height);
1545 }
1546 }
1547 }
1548
1549 // draw selection background
1550 if (selectionBegin != 0 && selectionEnd != 0 && fDragState != DRAG_SELECTION) {
1551 x0 = Math.max(nameSpace, Math.min(bounds.x + bounds.width, x0));
1552 x1 = Math.max(nameSpace, Math.min(bounds.x + bounds.width, x1));
1553 gc.setBackground(getColorScheme().getBkColor(false, false, true));
1554 if (x1 - x0 > 1) {
1555 gc.fillRectangle(new Rectangle(x0 + 1, bounds.y, x1 - x0 - 1, bounds.height));
1556 } else if (x0 - x1 > 1) {
1557 gc.fillRectangle(new Rectangle(x1 + 1, bounds.y, x0 - x1 - 1, bounds.height));
1558 }
1559 }
1560
1561 // draw drag selection background
1562 if (fDragState == DRAG_ZOOM || fDragState == DRAG_SELECTION) {
1563 gc.setBackground(getColorScheme().getBkColor(false, false, true));
1564 if (fDragX0 < fDragX) {
1565 gc.fillRectangle(new Rectangle(fDragX0, bounds.y, fDragX - fDragX0, bounds.height));
1566 } else if (fDragX0 > fDragX) {
1567 gc.fillRectangle(new Rectangle(fDragX, bounds.y, fDragX0 - fDragX, bounds.height));
1568 }
1569 }
1570
1571 // draw drag line
1572 if (DRAG_SPLIT_LINE == fDragState) {
1573 gc.setForeground(getColorScheme().getColor(TimeGraphColorScheme.BLACK));
1574 gc.drawLine(bounds.x + nameSpace, bounds.y, bounds.x + nameSpace, bounds.y + bounds.height - 1);
1575 } else if (DRAG_ZOOM == fDragState && Math.max(fDragX, fDragX0) > nameSpace) {
1576 gc.setForeground(getColorScheme().getColor(TimeGraphColorScheme.TOOL_FOREGROUND));
1577 gc.drawLine(fDragX0, bounds.y, fDragX0, bounds.y + bounds.height - 1);
1578 if (fDragX != fDragX0) {
1579 gc.drawLine(fDragX, bounds.y, fDragX, bounds.y + bounds.height - 1);
1580 }
1581 } else if (DRAG_SELECTION == fDragState && Math.max(fDragX, fDragX0) > nameSpace) {
1582 gc.setForeground(getColorScheme().getColor(TimeGraphColorScheme.SELECTED_TIME));
1583 gc.drawLine(fDragX0, bounds.y, fDragX0, bounds.y + bounds.height - 1);
1584 if (fDragX != fDragX0) {
1585 gc.drawLine(fDragX, bounds.y, fDragX, bounds.y + bounds.height - 1);
1586 }
1587 } else if (DRAG_NONE == fDragState && fMouseOverSplitLine && fTimeProvider.getNameSpace() > 0) {
1588 gc.setForeground(getColorScheme().getColor(TimeGraphColorScheme.RED));
1589 gc.drawLine(bounds.x + nameSpace, bounds.y, bounds.x + nameSpace, bounds.y + bounds.height - 1);
1590 }
1591
1592 gc.setAlpha(alpha);
1593 }
1594
1595 /**
1596 * Draw the background layer. Fills the background of the control's name
1597 * space and states space, updates the background of items if necessary,
1598 * and draws the item's name text and middle line.
1599 *
1600 * @param bounds
1601 * The bounds of the control
1602 * @param nameSpace
1603 * The name space width
1604 * @param gc
1605 * Graphics context
1606 * @since 2.0
1607 */
1608 protected void drawBackground(Rectangle bounds, int nameSpace, GC gc) {
1609 // draw empty name space background
1610 gc.setBackground(getColorScheme().getBkColor(false, false, true));
1611 drawBackground(gc, bounds.x, bounds.y, nameSpace, bounds.height);
1612
1613 // draw empty states space background
1614 gc.setBackground(getColorScheme().getColor(TimeGraphColorScheme.BACKGROUND));
1615 drawBackground(gc, bounds.x + nameSpace, bounds.y, bounds.width - nameSpace, bounds.height);
1616
1617 for (int i = fTopIndex; i < fItemData.fExpandedItems.length; i++) {
1618 Rectangle itemRect = getItemRect(bounds, i);
1619 if (itemRect.y >= bounds.y + bounds.height) {
1620 break;
1621 }
1622 Item item = fItemData.fExpandedItems[i];
1623 // draw the background of selected item and items with no time events
1624 if (! item.fEntry.hasTimeEvents()) {
1625 gc.setBackground(getColorScheme().getBkColorGroup(item.fSelected, fIsInFocus));
1626 gc.fillRectangle(itemRect);
1627 } else if (item.fSelected) {
1628 gc.setBackground(getColorScheme().getBkColor(true, fIsInFocus, true));
1629 gc.fillRectangle(itemRect.x, itemRect.y, nameSpace, itemRect.height);
1630 gc.setBackground(getColorScheme().getBkColor(true, fIsInFocus, false));
1631 gc.fillRectangle(nameSpace, itemRect.y, itemRect.width - nameSpace, itemRect.height);
1632 }
1633 // draw the name and middle line
1634 if (! item.fEntry.hasTimeEvents()) {
1635 drawName(item, itemRect, gc);
1636 } else {
1637 Rectangle nameRect = new Rectangle(itemRect.x, itemRect.y, nameSpace, itemRect.height);
1638 drawName(item, nameRect, gc);
1639 Rectangle rect = new Rectangle(nameSpace, itemRect.y, itemRect.width - nameSpace, itemRect.height);
1640 drawMidLine(rect, gc);
1641 }
1642 }
1643 }
1644
1645 /**
1646 * Draw the grid lines
1647 *
1648 * @param bounds
1649 * The bounds of the control
1650 * @param gc
1651 * Graphics context
1652 * @since 2.0
1653 */
1654 public void drawGridLines(Rectangle bounds, GC gc) {
1655 if (!fGridLinesVisible) {
1656 return;
1657 }
1658 gc.setForeground(fGridLineColor);
1659 gc.setAlpha(fGridLineColor.getAlpha());
1660 for (int x : fTimeGraphScale.getTickList()) {
1661 gc.drawLine(x, bounds.y, x, bounds.y + bounds.height);
1662 }
1663 gc.setAlpha(255);
1664 }
1665
1666 /**
1667 * Draw the markers
1668 *
1669 * @param bounds
1670 * The rectangle of the area
1671 * @param timeProvider
1672 * The time provider
1673 * @param markers
1674 * The list of markers
1675 * @param foreground
1676 * true to draw the foreground markers, false otherwise
1677 * @param nameSpace
1678 * The width reserved for the names
1679 * @param gc
1680 * Reference to the SWT GC object
1681 * @since 2.0
1682 */
1683 protected void drawMarkers(Rectangle bounds, ITimeDataProvider timeProvider, List<IMarkerEvent> markers, boolean foreground, int nameSpace, GC gc) {
1684 if (!fMarkersVisible || markers == null || markers.isEmpty()) {
1685 return;
1686 }
1687 gc.setClipping(new Rectangle(nameSpace, 0, bounds.width - nameSpace, bounds.height));
1688 /* the list can grow concurrently but cannot shrink */
1689 for (int i = 0; i < markers.size(); i++) {
1690 IMarkerEvent marker = markers.get(i);
1691 if (marker.isForeground() == foreground) {
1692 drawMarker(marker, bounds, timeProvider, nameSpace, gc);
1693 }
1694 }
1695 gc.setClipping((Rectangle) null);
1696 }
1697
1698 /**
1699 * Draw a single marker
1700 *
1701 * @param marker
1702 * The marker event
1703 * @param bounds
1704 * The bounds of the control
1705 * @param timeProvider
1706 * The time provider
1707 * @param nameSpace
1708 * The width reserved for the name
1709 * @param gc
1710 * Reference to the SWT GC object
1711 * @since 2.0
1712 */
1713 protected void drawMarker(IMarkerEvent marker, Rectangle bounds, ITimeDataProvider timeProvider, int nameSpace, GC gc) {
1714 Rectangle rect = Utils.clone(bounds);
1715 if (marker.getEntry() != null) {
1716 int index = fItemData.findItemIndex(marker.getEntry());
1717 if (index == -1) {
1718 return;
1719 }
1720 rect = getStatesRect(bounds, index, nameSpace);
1721 if (rect.y < 0 || rect.y > bounds.height) {
1722 return;
1723 }
1724 }
1725 int x0 = getXForTime(marker.getTime());
1726 int x1 = getXForTime(marker.getTime() + marker.getDuration());
1727 if (x0 > bounds.width || x1 < nameSpace) {
1728 return;
1729 }
1730 rect.x = Math.max(nameSpace, Math.min(bounds.width, x0));
1731 rect.width = Math.max(1, Math.min(bounds.width, x1) - rect.x);
1732
1733 Color color = getColorScheme().getColor(marker.getColor());
1734 gc.setBackground(color);
1735 gc.setAlpha(color.getAlpha());
1736 gc.fillRectangle(rect);
1737 gc.setAlpha(255);
1738 String label = marker.getLabel();
1739 if (label != null && marker.getEntry() != null) {
1740 label = label.substring(0, Math.min(label.indexOf('\n') != -1 ? label.indexOf('\n') : label.length(), MAX_LABEL_LENGTH));
1741 gc.setForeground(color);
1742 Utils.drawText(gc, label, rect.x - gc.textExtent(label).x, rect.y, true);
1743 }
1744 }
1745
1746 /**
1747 * Draw many items at once
1748 *
1749 * @param bounds
1750 * The bounds of the control
1751 * @param timeProvider
1752 * The time provider
1753 * @param items
1754 * The array items to draw
1755 * @param topIndex
1756 * The index of the first element to draw
1757 * @param nameSpace
1758 * The name space width
1759 * @param gc
1760 * Graphics context
1761 */
1762 public void drawItems(Rectangle bounds, ITimeDataProvider timeProvider,
1763 Item[] items, int topIndex, int nameSpace, GC gc) {
1764 for (int i = topIndex; i < items.length; i++) {
1765 Item item = items[i];
1766 drawItem(item, bounds, timeProvider, i, nameSpace, gc);
1767 }
1768 }
1769
1770 /**
1771 * Draws the item
1772 *
1773 * @param item
1774 * The item to draw
1775 * @param bounds
1776 * The bounds of the control
1777 * @param timeProvider
1778 * The time provider
1779 * @param i
1780 * The expanded item index
1781 * @param nameSpace
1782 * The name space width
1783 * @param gc
1784 * Graphics context
1785 */
1786 protected void drawItem(Item item, Rectangle bounds, ITimeDataProvider timeProvider, int i, int nameSpace, GC gc) {
1787 Rectangle itemRect = getItemRect(bounds, i);
1788 if (itemRect.y >= bounds.y + bounds.height) {
1789 return;
1790 }
1791
1792 ITimeGraphEntry entry = item.fEntry;
1793 long time0 = timeProvider.getTime0();
1794 long time1 = timeProvider.getTime1();
1795 long selectedTime = fTimeProvider.getSelectionEnd();
1796
1797 Rectangle rect = new Rectangle(nameSpace, itemRect.y, itemRect.width - nameSpace, itemRect.height);
1798 if (rect.isEmpty() || (time1 <= time0)) {
1799 fTimeGraphProvider.postDrawEntry(entry, rect, gc);
1800 return;
1801 }
1802
1803 boolean selected = item.fSelected;
1804 // K pixels per second
1805 double pixelsPerNanoSec = (rect.width <= RIGHT_MARGIN) ? 0 : (double) (rect.width - RIGHT_MARGIN) / (time1 - time0);
1806
1807 if (item.fEntry.hasTimeEvents()) {
1808 gc.setClipping(new Rectangle(nameSpace, 0, bounds.width - nameSpace, bounds.height));
1809 fillSpace(rect, gc, selected);
1810
1811 int margins = getMarginForHeight(rect.height);
1812 int height = rect.height - margins;
1813 int topMargin = (margins + 1) / 2;
1814 Rectangle stateRect = new Rectangle(rect.x, rect.y + topMargin, rect.width, height);
1815
1816 /* Set the font for this item */
1817 setFontForHeight(height, gc);
1818
1819 long maxDuration = (timeProvider.getTimeSpace() == 0) ? Long.MAX_VALUE : 1 * (time1 - time0) / timeProvider.getTimeSpace();
1820 Iterator<ITimeEvent> iterator = entry.getTimeEventsIterator(time0, time1, maxDuration);
1821
1822 int lastX = -1;
1823 while (iterator.hasNext()) {
1824 ITimeEvent event = iterator.next();
1825 int x = rect.x + (int) ((event.getTime() - time0) * pixelsPerNanoSec);
1826 int xEnd = rect.x + (int) ((event.getTime() + event.getDuration() - time0) * pixelsPerNanoSec);
1827 if (x >= rect.x + rect.width || xEnd < rect.x) {
1828 // event is out of bounds
1829 continue;
1830 }
1831 xEnd = Math.min(rect.x + rect.width, xEnd);
1832 stateRect.x = Math.max(rect.x, x);
1833 stateRect.width = Math.max(0, xEnd - stateRect.x + 1);
1834 if (stateRect.x == lastX) {
1835 stateRect.width -= 1;
1836 if (stateRect.width > 0) {
1837 gc.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLACK));
1838 gc.drawPoint(stateRect.x, stateRect.y - 2);
1839 stateRect.x += 1;
1840 }
1841 }
1842 boolean timeSelected = selectedTime >= event.getTime() && selectedTime < event.getTime() + event.getDuration();
1843 if (drawState(getColorScheme(), event, stateRect, gc, selected, timeSelected)) {
1844 lastX = stateRect.x;
1845 }
1846 }
1847 gc.setClipping((Rectangle) null);
1848 }
1849 fTimeGraphProvider.postDrawEntry(entry, rect, gc);
1850 }
1851
1852 /**
1853 * Draw the links
1854 *
1855 * @param bounds
1856 * The bounds of the control
1857 * @param timeProvider
1858 * The time provider
1859 * @param links
1860 * The list of link events
1861 * @param nameSpace
1862 * The name space width
1863 * @param gc
1864 * Graphics context
1865 */
1866 public void drawLinks(Rectangle bounds, ITimeDataProvider timeProvider,
1867 List<ILinkEvent> links, int nameSpace, GC gc) {
1868 if (fHideArrows) {
1869 return;
1870 }
1871 gc.setClipping(new Rectangle(nameSpace, 0, bounds.width - nameSpace, bounds.height));
1872 /* the list can grow concurrently but cannot shrink */
1873 for (int i = 0; i < links.size(); i++) {
1874 drawLink(links.get(i), bounds, timeProvider, nameSpace, gc);
1875 }
1876 gc.setClipping((Rectangle) null);
1877 }
1878
1879 /**
1880 * Draws a link type event
1881 *
1882 * @param event
1883 * The link event to draw
1884 * @param bounds
1885 * The bounds of the control
1886 * @param timeProvider
1887 * The time provider
1888 * @param nameSpace
1889 * The name space width
1890 * @param gc
1891 * Graphics context
1892 */
1893 protected void drawLink(ILinkEvent event, Rectangle bounds, ITimeDataProvider timeProvider, int nameSpace, GC gc) {
1894 drawArrow(getColorScheme(), event, getArrowRectangle(bounds, event), gc);
1895 }
1896
1897 private Rectangle getArrowRectangle(Rectangle bounds, ILinkEvent event) {
1898 int srcIndex = fItemData.findItemIndex(event.getEntry());
1899 int destIndex = fItemData.findItemIndex(event.getDestinationEntry());
1900
1901 if ((srcIndex == -1) || (destIndex == -1)) {
1902 return null;
1903 }
1904
1905 Rectangle src = getStatesRect(bounds, srcIndex, fTimeProvider.getNameSpace());
1906 Rectangle dst = getStatesRect(bounds, destIndex, fTimeProvider.getNameSpace());
1907
1908 int x0 = getXForTime(event.getTime());
1909 int x1 = getXForTime(event.getTime() + event.getDuration());
1910
1911 // limit the x-coordinates to prevent integer overflow in calculations
1912 // and also GC.drawLine doesn't draw properly with large coordinates
1913 final int limit = Integer.MAX_VALUE / 1024;
1914 x0 = Math.max(-limit, Math.min(x0, limit));
1915 x1 = Math.max(-limit, Math.min(x1, limit));
1916
1917 int y0 = src.y + src.height / 2;
1918 int y1 = dst.y + dst.height / 2;
1919 return new Rectangle(x0, y0, x1 - x0, y1 - y0);
1920 }
1921
1922 /**
1923 * Draw an arrow
1924 *
1925 * @param colors
1926 * Color scheme
1927 * @param event
1928 * Time event for which we're drawing the arrow
1929 * @param rect
1930 * The arrow rectangle
1931 * @param gc
1932 * Graphics context
1933 * @return true if the arrow was drawn
1934 */
1935 protected boolean drawArrow(TimeGraphColorScheme colors, ITimeEvent event,
1936 Rectangle rect, GC gc) {
1937
1938 if (rect == null) {
1939 return false;
1940 }
1941 int colorIdx = fTimeGraphProvider.getStateTableIndex(event);
1942 if (colorIdx < 0) {
1943 return false;
1944 }
1945 boolean visible = ((rect.height == 0) && (rect.width == 0)) ? false : true;
1946
1947 if (visible) {
1948 Color stateColor = null;
1949 if (colorIdx < fEventColorMap.length) {
1950 stateColor = fEventColorMap[colorIdx];
1951 } else {
1952 stateColor = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
1953 }
1954
1955 gc.setForeground(stateColor);
1956 gc.setBackground(stateColor);
1957
1958 /* Draw the arrow */
1959 gc.drawLine(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height);
1960 drawArrowHead(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, gc);
1961
1962 }
1963 fTimeGraphProvider.postDrawEvent(event, rect, gc);
1964 return visible;
1965 }
1966
1967 /*
1968 * @author Francis Giraldeau
1969 *
1970 * Inspiration:
1971 * http://stackoverflow.com/questions/3010803/draw-arrow-on-line-algorithm
1972 *
1973 * The algorithm was taken from this site, not the code itself
1974 */
1975 private static void drawArrowHead(int x0, int y0, int x1, int y1, GC gc)
1976 {
1977 int factor = 10;
1978 double cos = 0.9510;
1979 double sin = 0.3090;
1980 long lenx = x1 - x0;
1981 long leny = y1 - y0;
1982 double len = Math.sqrt(lenx * lenx + leny * leny);
1983
1984 double dx = factor * lenx / len;
1985 double dy = factor * leny / len;
1986 int end1X = (int) Math.round((x1 - (dx * cos + dy * -sin)));
1987 int end1Y = (int) Math.round((y1 - (dx * sin + dy * cos)));
1988 int end2X = (int) Math.round((x1 - (dx * cos + dy * sin)));
1989 int end2Y = (int) Math.round((y1 - (dx * -sin + dy * cos)));
1990 int[] arrow = new int[] { x1, y1, end1X, end1Y, end2X, end2Y, x1, y1 };
1991 gc.fillPolygon(arrow);
1992 }
1993
1994 /**
1995 * Draw the name of an item.
1996 *
1997 * @param item
1998 * Item object
1999 * @param bounds
2000 * The bounds of the item's name space
2001 * @param gc
2002 * Graphics context
2003 */
2004 protected void drawName(Item item, Rectangle bounds, GC gc) {
2005 boolean hasTimeEvents = item.fEntry.hasTimeEvents();
2006
2007 // No name to be drawn
2008 if (fTimeProvider.getNameSpace() == 0) {
2009 return;
2010 }
2011
2012 int height = bounds.height - getMarginForHeight(bounds.height);
2013 setFontForHeight(height, gc);
2014
2015 int leftMargin = MARGIN + item.fLevel * EXPAND_SIZE;
2016 if (item.fHasChildren) {
2017 gc.setForeground(getColorScheme().getFgColorGroup(false, false));
2018 gc.setBackground(getColorScheme().getBkColor(false, false, false));
2019 Rectangle rect = Utils.clone(bounds);
2020 rect.x += leftMargin;
2021 rect.y += (bounds.height - EXPAND_SIZE) / 2;
2022 rect.width = EXPAND_SIZE;
2023 rect.height = EXPAND_SIZE;
2024 gc.fillRectangle(rect);
2025 gc.drawRectangle(rect.x, rect.y, rect.width - 1, rect.height - 1);
2026 int midy = rect.y + rect.height / 2;
2027 gc.drawLine(rect.x + 2, midy, rect.x + rect.width - 3, midy);
2028 if (!item.fExpanded) {
2029 int midx = rect.x + rect.width / 2;
2030 gc.drawLine(midx, rect.y + 2, midx, rect.y + rect.height - 3);
2031 }
2032 }
2033 leftMargin += EXPAND_SIZE + MARGIN;
2034
2035 Image img = fTimeGraphProvider.getItemImage(item.fEntry);
2036 if (img != null) {
2037 // draw icon
2038 int imgHeight = img.getImageData().height;
2039 int imgWidth = img.getImageData().width;
2040 int x = leftMargin;
2041 int y = bounds.y + (bounds.height - imgHeight) / 2;
2042 gc.drawImage(img, x, y);
2043 leftMargin += imgWidth + MARGIN;
2044 }
2045 String name = item.fName;
2046 Point size = gc.stringExtent(name);
2047 if (fIdealNameSpace < leftMargin + size.x + MARGIN) {
2048 fIdealNameSpace = leftMargin + size.x + MARGIN;
2049 }
2050 if (hasTimeEvents) {
2051 // cut long string with "..."
2052 int width = bounds.width - leftMargin;
2053 int cuts = 0;
2054 while (size.x > width && name.length() > 1) {
2055 cuts++;
2056 name = name.substring(0, name.length() - 1);
2057 size = gc.stringExtent(name + "..."); //$NON-NLS-1$
2058 }
2059 if (cuts > 0) {
2060 name += "..."; //$NON-NLS-1$
2061 }
2062 }
2063 Rectangle rect = Utils.clone(bounds);
2064 rect.x += leftMargin;
2065 rect.width -= leftMargin;
2066 // draw text
2067 if (rect.width > 0) {
2068 rect.y += (bounds.height - gc.stringExtent(name).y) / 2;
2069 gc.setForeground(getColorScheme().getFgColor(item.fSelected, fIsInFocus));
2070 int textWidth = Utils.drawText(gc, name, rect, true);
2071 leftMargin += textWidth + MARGIN;
2072
2073 if (hasTimeEvents) {
2074 // draw middle line
2075 rect.x = bounds.x + leftMargin;
2076 rect.y = bounds.y;
2077 rect.width = bounds.width - rect.x;
2078 drawMidLine(rect, gc);
2079 }
2080 }
2081 }
2082
2083 /**
2084 * Draw the state (color fill)
2085 *
2086 * @param colors
2087 * Color scheme
2088 * @param event
2089 * Time event for which we're drawing the state
2090 * @param rect
2091 * The state rectangle
2092 * @param gc
2093 * Graphics context
2094 * @param selected
2095 * Is this time event currently selected (so it appears
2096 * highlighted)
2097 * @param timeSelected
2098 * Is the timestamp currently selected
2099 * @return true if the state was drawn
2100 */
2101 protected boolean drawState(TimeGraphColorScheme colors, ITimeEvent event,
2102 Rectangle rect, GC gc, boolean selected, boolean timeSelected) {
2103
2104 int colorIdx = fTimeGraphProvider.getStateTableIndex(event);
2105 if (colorIdx < 0 && colorIdx != ITimeGraphPresentationProvider.TRANSPARENT) {
2106 return false;
2107 }
2108 boolean visible = rect.width == 0 ? false : true;
2109 rect.width = Math.max(1, rect.width);
2110 Color black = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
2111 gc.setForeground(black);
2112
2113 if (colorIdx == ITimeGraphPresentationProvider.TRANSPARENT) {
2114 if (visible) {
2115 // Only draw the top and bottom borders
2116 gc.drawLine(rect.x, rect.y, rect.x + rect.width - 1, rect.y);
2117 gc.drawLine(rect.x, rect.y + rect.height - 1, rect.x + rect.width - 1, rect.y + rect.height - 1);
2118 if (rect.width == 1) {
2119 gc.drawPoint(rect.x, rect.y - 2);
2120 }
2121 }
2122 fTimeGraphProvider.postDrawEvent(event, rect, gc);
2123 return false;
2124 }
2125 Color stateColor = null;
2126 if (colorIdx < fEventColorMap.length) {
2127 stateColor = fEventColorMap[colorIdx];
2128 } else {
2129 stateColor = black;
2130 }
2131
2132 boolean reallySelected = timeSelected && selected;
2133 // fill all rect area
2134 gc.setBackground(stateColor);
2135 if (visible) {
2136 gc.fillRectangle(rect);
2137 } else if (fBlendSubPixelEvents) {
2138 gc.setAlpha(128);
2139 gc.fillRectangle(rect);
2140 gc.setAlpha(255);
2141 }
2142
2143 if (reallySelected) {
2144 gc.drawLine(rect.x, rect.y - 1, rect.x + rect.width - 1, rect.y - 1);
2145 gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width - 1, rect.y + rect.height);
2146 }
2147 if (!visible) {
2148 gc.drawPoint(rect.x, rect.y - 2);
2149 }
2150 fTimeGraphProvider.postDrawEvent(event, rect, gc);
2151 return visible;
2152 }
2153
2154 /**
2155 * Fill an item's states rectangle
2156 *
2157 * @param rect
2158 * The states rectangle
2159 * @param gc
2160 * Graphics context
2161 * @param selected
2162 * true if the item is selected
2163 */
2164 protected void fillSpace(Rectangle rect, GC gc, boolean selected) {
2165 /* Nothing to draw */
2166 }
2167
2168 /**
2169 * Draw a line at the middle height of a rectangle
2170 *
2171 * @param rect
2172 * The rectangle
2173 * @param gc
2174 * Graphics context
2175 */
2176 private void drawMidLine(Rectangle rect, GC gc) {
2177 gc.setForeground(getColorScheme().getColor(TimeGraphColorScheme.MID_LINE));
2178 int midy = rect.y + rect.height / 2;
2179 gc.drawLine(rect.x, midy, rect.x + rect.width, midy);
2180 }
2181
2182 private static int getMarginForHeight(int height) {
2183 /*
2184 * State rectangle is smaller than the item bounds when height is > 4.
2185 * Don't use any margin if the height is below or equal that threshold.
2186 * Use a maximum of 6 pixels for both margins, otherwise try to use 13
2187 * pixels for the state height, but with a minimum margin of 1.
2188 */
2189 final int MARGIN_THRESHOLD = 4;
2190 final int PREFERRED_HEIGHT = 13;
2191 final int MIN_MARGIN = 1;
2192 final int MAX_MARGIN = 6;
2193 return height <= MARGIN_THRESHOLD ? 0 :
2194 Math.max(Math.min(height - PREFERRED_HEIGHT, MAX_MARGIN), MIN_MARGIN);
2195 }
2196
2197 private void setFontForHeight(int pixels, GC gc) {
2198 /* convert font height from pixels to points */
2199 int height = Math.max(pixels * PPI / DPI, 1);
2200 Font font = fFonts.get(height);
2201 if (font == null) {
2202 FontData fontData = gc.getFont().getFontData()[0];
2203 fontData.setHeight(height);
2204 font = new Font(gc.getDevice(), fontData);
2205 fFonts.put(height, font);
2206 }
2207 gc.setFont(font);
2208 }
2209
2210 @Override
2211 public void keyTraversed(TraverseEvent e) {
2212 if ((e.detail == SWT.TRAVERSE_TAB_NEXT) || (e.detail == SWT.TRAVERSE_TAB_PREVIOUS)) {
2213 e.doit = true;
2214 }
2215 }
2216
2217 @Override
2218 public void keyPressed(KeyEvent e) {
2219 int idx = -1;
2220 if (fItemData.fExpandedItems.length == 0) {
2221 return;
2222 }
2223 if (SWT.HOME == e.keyCode) {
2224 idx = 0;
2225 } else if (SWT.END == e.keyCode) {
2226 idx = fItemData.fExpandedItems.length - 1;
2227 } else if (SWT.ARROW_DOWN == e.keyCode) {
2228 idx = getSelectedIndex();
2229 if (idx < 0) {
2230 idx = 0;
2231 } else if (idx < fItemData.fExpandedItems.length - 1) {
2232 idx++;
2233 }
2234 } else if (SWT.ARROW_UP == e.keyCode) {
2235 idx = getSelectedIndex();
2236 if (idx < 0) {
2237 idx = 0;
2238 } else if (idx > 0) {
2239 idx--;
2240 }
2241 } else if (SWT.ARROW_LEFT == e.keyCode && fDragState == DRAG_NONE) {
2242 boolean extend = (e.stateMask & SWT.SHIFT) != 0;
2243 selectPrevEvent(extend);
2244 } else if (SWT.ARROW_RIGHT == e.keyCode && fDragState == DRAG_NONE) {
2245 boolean extend = (e.stateMask & SWT.SHIFT) != 0;
2246 selectNextEvent(extend);
2247 } else if (SWT.PAGE_DOWN == e.keyCode) {
2248 int page = countPerPage();
2249 idx = getSelectedIndex();
2250 if (idx < 0) {
2251 idx = 0;
2252 }
2253 idx += page;
2254 if (idx >= fItemData.fExpandedItems.length) {
2255 idx = fItemData.fExpandedItems.length - 1;
2256 }
2257 } else if (SWT.PAGE_UP == e.keyCode) {
2258 int page = countPerPage();
2259 idx = getSelectedIndex();
2260 if (idx < 0) {
2261 idx = 0;
2262 }
2263 idx -= page;
2264 if (idx < 0) {
2265 idx = 0;
2266 }
2267 } else if (SWT.CR == e.keyCode) {
2268 idx = getSelectedIndex();
2269 if (idx >= 0) {
2270 if (fItemData.fExpandedItems[idx].fHasChildren) {
2271 toggle(idx);
2272 } else {
2273 fireDefaultSelection();
2274 }
2275 }
2276 idx = -1;
2277 } else if ((e.character == '+' || e.character == '=') && ((e.stateMask & SWT.CTRL) != 0)) {
2278 fVerticalZoomAlignEntry = getVerticalZoomAlignSelection();
2279 verticalZoom(true);
2280 if (fVerticalZoomAlignEntry != null) {
2281 setElementPosition(fVerticalZoomAlignEntry.getKey(), fVerticalZoomAlignEntry.getValue());
2282 }
2283 } else if (e.character == '-' && ((e.stateMask & SWT.CTRL) != 0)) {
2284 fVerticalZoomAlignEntry = getVerticalZoomAlignSelection();
2285 verticalZoom(false);
2286 if (fVerticalZoomAlignEntry != null) {
2287 setElementPosition(fVerticalZoomAlignEntry.getKey(), fVerticalZoomAlignEntry.getValue());
2288 }
2289 } else if (e.character == '0' && ((e.stateMask & SWT.CTRL) != 0)) {
2290 fVerticalZoomAlignEntry = getVerticalZoomAlignSelection();
2291 resetVerticalZoom();
2292 if (fVerticalZoomAlignEntry != null) {
2293 setElementPosition(fVerticalZoomAlignEntry.getKey(), fVerticalZoomAlignEntry.getValue());
2294 }
2295 }
2296 if (idx >= 0) {
2297 selectItem(idx, false);
2298 fireSelectionChanged();
2299 }
2300 int x = toControl(e.display.getCursorLocation()).x;
2301 updateCursor(x, e.stateMask | e.keyCode);
2302 }
2303
2304 @Override
2305 public void keyReleased(KeyEvent e) {
2306 int x = toControl(e.display.getCursorLocation()).x;
2307 updateCursor(x, e.stateMask & ~e.keyCode);
2308 }
2309
2310 @Override
2311 public void focusGained(FocusEvent e) {
2312 fIsInFocus = true;
2313 redraw();
2314 updateStatusLine(STATUS_WITHOUT_CURSOR_TIME);
2315 }
2316
2317 @Override
2318 public void focusLost(FocusEvent e) {
2319 fIsInFocus = false;
2320 if (DRAG_NONE != fDragState) {
2321 setCapture(false);
2322 fDragState = DRAG_NONE;
2323 }
2324 redraw();
2325 updateStatusLine(NO_STATUS);
2326 }
2327
2328 /**
2329 * @return If the current view is focused
2330 */
2331 public boolean isInFocus() {
2332 return fIsInFocus;
2333 }
2334
2335 /**
2336 * Provide the possibility to control the wait cursor externally e.g. data
2337 * requests in progress
2338 *
2339 * @param waitInd Should we wait indefinitely?
2340 */
2341 public void waitCursor(boolean waitInd) {
2342 // Update cursor as indicated
2343 if (waitInd) {
2344 setCursor(fWaitCursor);
2345 } else {
2346 setCursor(null);
2347 }
2348 }
2349
2350 private void updateCursor(int x, int stateMask) {
2351 // if Wait cursor not active, check for the need to change the cursor
2352 if (getCursor() == fWaitCursor) {
2353 return;
2354 }
2355 Cursor cursor = null;
2356 if (fDragState == DRAG_SPLIT_LINE) {
2357 } else if (fDragState == DRAG_SELECTION) {
2358 cursor = fResizeCursor;
2359 } else if (fDragState == DRAG_TRACE_ITEM) {
2360 cursor = fDragCursor;
2361 } else if (fDragState == DRAG_ZOOM) {
2362 cursor = fZoomCursor;
2363 } else if ((stateMask & SWT.MODIFIER_MASK) == SWT.CTRL) {
2364 cursor = fDragCursor;
2365 } else if ((stateMask & SWT.MODIFIER_MASK) == SWT.SHIFT) {
2366 cursor = fResizeCursor;
2367 } else if (!isOverSplitLine(x)) {
2368 long selectionBegin = fTimeProvider.getSelectionBegin();
2369 long selectionEnd = fTimeProvider.getSelectionEnd();
2370 int xBegin = getXForTime(selectionBegin);
2371 int xEnd = getXForTime(selectionEnd);
2372 if (Math.abs(x - xBegin) < SNAP_WIDTH || Math.abs(x - xEnd) < SNAP_WIDTH) {
2373 cursor = fResizeCursor;
2374 }
2375 }
2376 if (getCursor() != cursor) {
2377 setCursor(cursor);
2378 }
2379 }
2380
2381 /**
2382 * Update the status line following a change of selection.
2383 *
2384 * @since 2.0
2385 */
2386 public void updateStatusLine() {
2387 updateStatusLine(STATUS_WITHOUT_CURSOR_TIME);
2388 }
2389
2390 private void updateStatusLine(int x) {
2391 // use the time provider of the time graph scale for the status line
2392 ITimeDataProvider tdp = fTimeGraphScale.getTimeProvider();
2393 if (fStatusLineManager == null || null == tdp ||
2394 tdp.getTime0() == tdp.getTime1()) {
2395 return;
2396 }
2397 TimeFormat tf = tdp.getTimeFormat();
2398 Resolution res = Resolution.NANOSEC;
2399 StringBuilder message = new StringBuilder();
2400 if ((x >= 0 || x == STATUS_WITHOUT_CURSOR_TIME) && fDragState == DRAG_NONE) {
2401 if (x != STATUS_WITHOUT_CURSOR_TIME) {
2402 long time = getTimeAtX(x);
2403 if (time >= 0) {
2404 if (tdp instanceof ITimeDataProviderConverter) {
2405 time = ((ITimeDataProviderConverter) tdp).convertTime(time);
2406 }
2407 message.append(NLS.bind("T: {0}{1} ", //$NON-NLS-1$
2408 new Object[] {
2409 tf == TimeFormat.CALENDAR ? Utils.formatDate(time) + ' ' : "", //$NON-NLS-1$
2410 Utils.formatTime(time, tf, res)
2411 }));
2412 }
2413 }
2414 long selectionBegin = tdp.getSelectionBegin();
2415 long selectionEnd = tdp.getSelectionEnd();
2416 message.append(NLS.bind("T1: {0}{1}", //$NON-NLS-1$
2417 new Object[] {
2418 tf == TimeFormat.CALENDAR ? Utils.formatDate(selectionBegin) + ' ' : "", //$NON-NLS-1$
2419 Utils.formatTime(selectionBegin, tf, res)
2420 }));
2421 if (selectionBegin != selectionEnd) {
2422 message.append(NLS.bind(" T2: {0}{1} \u0394: {2}", //$NON-NLS-1$
2423 new Object[] {
2424 tf == TimeFormat.CALENDAR ? Utils.formatDate(selectionEnd) + ' ' : "", //$NON-NLS-1$
2425 Utils.formatTime(selectionEnd, tf, res),
2426 Utils.formatDelta(selectionEnd - selectionBegin, tf, res)
2427 }));
2428 }
2429 } else if (fDragState == DRAG_SELECTION || fDragState == DRAG_ZOOM) {
2430 long time0 = fDragBeginMarker ? getTimeAtX(fDragX0) : fDragTime0;
2431 long time = fDragBeginMarker ? fDragTime0 : getTimeAtX(fDragX);
2432 if (tdp instanceof ITimeDataProviderConverter) {
2433 time0 = ((ITimeDataProviderConverter) tdp).convertTime(time0);
2434 time = ((ITimeDataProviderConverter) tdp).convertTime(time);
2435 }
2436 message.append(NLS.bind("T1: {0}{1} T2: {2}{3} \u0394: {4}", //$NON-NLS-1$
2437 new Object[] {
2438 tf == TimeFormat.CALENDAR ? Utils.formatDate(time0) + ' ' : "", //$NON-NLS-1$
2439 Utils.formatTime(time0, tf, res),
2440 tf == TimeFormat.CALENDAR ? Utils.formatDate(time) + ' ' : "", //$NON-NLS-1$
2441 Utils.formatTime(time, tf, res),
2442 Utils.formatDelta(time - time0, tf, res)
2443 }));
2444 }
2445 fStatusLineManager.setMessage(message.toString());
2446 }
2447
2448 @Override
2449 public void mouseMove(MouseEvent e) {
2450 if (null == fTimeProvider) {
2451 return;
2452 }
2453 Point size = getSize();
2454 if (DRAG_TRACE_ITEM == fDragState) {
2455 int nameWidth = fTimeProvider.getNameSpace();
2456 if (e.x > nameWidth && size.x > nameWidth && fDragX != e.x) {
2457 fDragX = e.x;
2458 double pixelsPerNanoSec = (size.x - nameWidth <= RIGHT_MARGIN) ? 0 : (double) (size.x - nameWidth - RIGHT_MARGIN) / (fTime1bak - fTime0bak);
2459 long timeDelta = (long) ((pixelsPerNanoSec == 0) ? 0 : ((fDragX - fDragX0) / pixelsPerNanoSec));
2460 long time1 = fTime1bak - timeDelta;
2461 long maxTime = fTimeProvider.getMaxTime();
2462 if (time1 > maxTime) {
2463 time1 = maxTime;
2464 }
2465 long time0 = time1 - (fTime1bak - fTime0bak);
2466 if (time0 < fTimeProvider.getMinTime()) {
2467 time0 = fTimeProvider.getMinTime();
2468 time1 = time0 + (fTime1bak - fTime0bak);
2469 }
2470 fTimeProvider.setStartFinishTimeNotify(time0, time1);
2471 }
2472 } else if (DRAG_SPLIT_LINE == fDragState) {
2473 fDragX = e.x;
2474 fTimeProvider.setNameSpace(e.x);
2475 TmfSignalManager.dispatchSignal(new TmfTimeViewAlignmentSignal(this, getTimeViewAlignmentInfo()));
2476 } else if (DRAG_SELECTION == fDragState) {
2477 if (fDragBeginMarker) {
2478 fDragX0 = Math.min(Math.max(e.x, fTimeProvider.getNameSpace()), size.x - RIGHT_MARGIN);
2479 } else {
2480 fDragX = Math.min(Math.max(e.x, fTimeProvider.getNameSpace()), size.x - RIGHT_MARGIN);
2481 }
2482 redraw();
2483 fTimeGraphScale.setDragRange(fDragX0, fDragX);
2484 fireDragSelectionChanged(getTimeAtX(fDragX0), getTimeAtX(fDragX));
2485 } else if (DRAG_ZOOM == fDragState) {
2486 fDragX = Math.min(Math.max(e.x, fTimeProvider.getNameSpace()), size.x - RIGHT_MARGIN);
2487 redraw();
2488 fTimeGraphScale.setDragRange(fDragX0, fDragX);
2489 } else if (DRAG_NONE == fDragState) {
2490 boolean mouseOverSplitLine = isOverSplitLine(e.x);
2491 if (fMouseOverSplitLine != mouseOverSplitLine) {
2492 redraw();
2493 }
2494 fMouseOverSplitLine = mouseOverSplitLine;
2495 }
2496 updateCursor(e.x, e.stateMask);
2497 updateStatusLine(e.x);
2498 }
2499
2500 @Override
2501 public void mouseDoubleClick(MouseEvent e) {
2502 if (null == fTimeProvider) {
2503 return;
2504 }
2505 if (1 == e.button && (e.stateMask & SWT.BUTTON_MASK) == 0) {
2506 if (isOverSplitLine(e.x) && fTimeProvider.getNameSpace() != 0) {
2507 fTimeProvider.setNameSpace(fIdealNameSpace);
2508 boolean mouseOverSplitLine = isOverSplitLine(e.x);
2509 if (fMouseOverSplitLine != mouseOverSplitLine) {
2510 redraw();
2511 }
2512 fMouseOverSplitLine = mouseOverSplitLine;
2513 TmfSignalManager.dispatchSignal(new TmfTimeViewAlignmentSignal(this, getTimeViewAlignmentInfo()));
2514 return;
2515 }
2516 int idx = getItemIndexAtY(e.y);
2517 if (idx >= 0) {
2518 selectItem(idx, false);
2519 fireDefaultSelection();
2520 }
2521 }
2522 }
2523
2524 @Override
2525 public void mouseDown(MouseEvent e) {
2526 if (fDragState != DRAG_NONE || null == fTimeProvider ||
2527 fTimeProvider.getTime0() == fTimeProvider.getTime1() ||
2528 getSize().x - fTimeProvider.getNameSpace() <= 0) {
2529 return;
2530 }
2531 int idx;
2532 if (1 == e.button && (e.stateMask & SWT.MODIFIER_MASK) == 0) {
2533 int nameSpace = fTimeProvider.getNameSpace();
2534 if (nameSpace != 0 && isOverSplitLine(e.x)) {
2535 fDragState = DRAG_SPLIT_LINE;
2536 fDragButton = e.button;
2537 fDragX = e.x;
2538 fDragX0 = fDragX;
2539 fTime0bak = fTimeProvider.getTime0();
2540 fTime1bak = fTimeProvider.getTime1();
2541 redraw();
2542 updateCursor(e.x, e.stateMask);
2543 return;
2544 }
2545 }
2546 if (1 == e.button && ((e.stateMask & SWT.MODIFIER_MASK) == 0 || (e.stateMask & SWT.MODIFIER_MASK) == SWT.SHIFT)) {
2547 int nameSpace = fTimeProvider.getNameSpace();
2548 idx = getItemIndexAtY(e.y);
2549 if (idx >= 0) {
2550 Item item = fItemData.fExpandedItems[idx];
2551 if (item.fHasChildren && e.x < nameSpace && e.x < MARGIN + (item.fLevel + 1) * EXPAND_SIZE) {
2552 toggle(idx);
2553 return;
2554 }
2555 selectItem(idx, false);
2556 fireSelectionChanged();
2557 } else {
2558 selectItem(idx, false); // clear selection
2559 fireSelectionChanged();
2560 }
2561 long hitTime = getTimeAtX(e.x);
2562 if (hitTime >= 0) {
2563 setCapture(true);
2564
2565 fDragState = DRAG_SELECTION;
2566 fDragBeginMarker = false;
2567 fDragButton = e.button;
2568 fDragX = e.x;
2569 fDragX0 = fDragX;
2570 fDragTime0 = getTimeAtX(fDragX0);
2571 long selectionBegin = fTimeProvider.getSelectionBegin();
2572 long selectionEnd = fTimeProvider.getSelectionEnd();
2573 int xBegin = getXForTime(selectionBegin);
2574 int xEnd = getXForTime(selectionEnd);
2575 if ((e.stateMask & SWT.MODIFIER_MASK) == SWT.SHIFT) {
2576 long time = getTimeAtX(e.x);
2577 if (Math.abs(time - selectionBegin) < Math.abs(time - selectionEnd)) {
2578 fDragBeginMarker = true;
2579 fDragX = xEnd;
2580 fDragX0 = e.x;
2581 fDragTime0 = selectionEnd;
2582 } else {
2583 fDragX0 = xBegin;
2584 fDragTime0 = selectionBegin;
2585 }
2586 } else {
2587 long time = getTimeAtX(e.x);
2588 if (Math.abs(e.x - xBegin) < SNAP_WIDTH && Math.abs(time - selectionBegin) <= Math.abs(time - selectionEnd)) {
2589 fDragBeginMarker = true;
2590 fDragX = xEnd;
2591 fDragX0 = e.x;
2592 fDragTime0 = selectionEnd;
2593 } else if (Math.abs(e.x - xEnd) < SNAP_WIDTH && Math.abs(time - selectionEnd) <= Math.abs(time - selectionBegin)) {
2594 fDragX0 = xBegin;
2595 fDragTime0 = selectionBegin;
2596 }
2597 }
2598 fTime0bak = fTimeProvider.getTime0();
2599 fTime1bak = fTimeProvider.getTime1();
2600 redraw();
2601 updateCursor(e.x, e.stateMask);
2602 fTimeGraphScale.setDragRange(fDragX0, fDragX);
2603 }
2604 } else if (2 == e.button || (1 == e.button && (e.stateMask & SWT.MODIFIER_MASK) == SWT.CTRL)) {
2605 long hitTime = getTimeAtX(e.x);
2606 if (hitTime > 0) {
2607 setCapture(true);
2608 fDragState = DRAG_TRACE_ITEM;
2609 fDragButton = e.button;
2610 fDragX = e.x;
2611 fDragX0 = fDragX;
2612 fTime0bak = fTimeProvider.getTime0();
2613 fTime1bak = fTimeProvider.getTime1();
2614 updateCursor(e.x, e.stateMask);
2615 }
2616 } else if (3 == e.button) {
2617 if (e.x >= fTimeProvider.getNameSpace()) {
2618 setCapture(true);
2619 fDragX = Math.min(Math.max(e.x, fTimeProvider.getNameSpace()), getSize().x - RIGHT_MARGIN);
2620 fDragX0 = fDragX;
2621 fDragTime0 = getTimeAtX(fDragX0);
2622 fDragState = DRAG_ZOOM;
2623 fDragButton = e.button;
2624 redraw();
2625 updateCursor(e.x, e.stateMask);
2626 fTimeGraphScale.setDragRange(fDragX0, fDragX);
2627 } else {
2628 idx = getItemIndexAtY(e.y);
2629 selectItem(idx, false);
2630 fireSelectionChanged();
2631 }
2632 }
2633 }
2634
2635 @Override
2636 public void mouseUp(MouseEvent e) {
2637 if (fPendingMenuDetectEvent != null && e.button == 3) {
2638 menuDetected(fPendingMenuDetectEvent);
2639 }
2640 if (DRAG_NONE != fDragState) {
2641 setCapture(false);
2642 if (e.button == fDragButton && DRAG_TRACE_ITEM == fDragState) {
2643 if (fDragX != fDragX0) {
2644 fTimeProvider.notifyStartFinishTime();
2645 }
2646 fDragState = DRAG_NONE;
2647 } else if (e.button == fDragButton && DRAG_SPLIT_LINE == fDragState) {
2648 fDragState = DRAG_NONE;
2649 redraw();
2650 } else if (e.button == fDragButton && DRAG_SELECTION == fDragState) {
2651 if (fDragX == fDragX0) { // click without selecting anything
2652 long time = getTimeAtX(e.x);
2653 fTimeProvider.setSelectedTimeNotify(time, false);
2654 } else {
2655 long time0 = fDragBeginMarker ? getTimeAtX(fDragX0) : fDragTime0;
2656 long time1 = fDragBeginMarker ? fDragTime0 : getTimeAtX(fDragX);
2657 fTimeProvider.setSelectionRangeNotify(time0, time1, false);
2658 }
2659 fDragState = DRAG_NONE;
2660 redraw();
2661 fTimeGraphScale.setDragRange(-1, -1);
2662 } else if (e.button == fDragButton && DRAG_ZOOM == fDragState) {
2663 int nameWidth = fTimeProvider.getNameSpace();
2664 if (Math.max(fDragX, fDragX0) > nameWidth && fDragX != fDragX0) {
2665 long time0 = getTimeAtX(fDragX0);
2666 long time1 = getTimeAtX(fDragX);
2667 if (time0 < time1) {
2668 fTimeProvider.setStartFinishTimeNotify(time0, time1);
2669 } else {
2670 fTimeProvider.setStartFinishTimeNotify(time1, time0);
2671 }
2672 } else {
2673 redraw();
2674 }
2675 fDragState = DRAG_NONE;
2676 fTimeGraphScale.setDragRange(-1, -1);
2677 }
2678 }
2679 updateCursor(e.x, e.stateMask);
2680 updateStatusLine(e.x);
2681 }
2682
2683 @Override
2684 public void mouseEnter(MouseEvent e) {
2685 }
2686
2687 @Override
2688 public void mouseExit(MouseEvent e) {
2689 if (fMouseOverSplitLine) {
2690 fMouseOverSplitLine = false;
2691 redraw();
2692 }
2693 updateStatusLine(STATUS_WITHOUT_CURSOR_TIME);
2694 }
2695
2696 @Override
2697 public void mouseHover(MouseEvent e) {
2698 }
2699
2700 @Override
2701 public void mouseScrolled(MouseEvent e) {
2702 if (fDragState != DRAG_NONE || e.count == 0) {
2703 return;
2704 }
2705
2706 /*
2707 * On some platforms the mouse scroll event is sent to the
2708 * control that has focus even if it is not under the cursor.
2709 * Handle the event only if over the time graph control.
2710 */
2711 Point size = getSize();
2712 Rectangle bounds = new Rectangle(0, 0, size.x, size.y);
2713 if (!bounds.contains(e.x, e.y)) {
2714 return;
2715 }
2716
2717 boolean horizontalZoom = false;
2718 boolean horizontalScroll = false;
2719 boolean verticalZoom = false;
2720 boolean verticalScroll = false;
2721
2722 // over the time graph control
2723 if ((e.stateMask & SWT.MODIFIER_MASK) == (SWT.SHIFT | SWT.CTRL)) {
2724 verticalZoom = true;
2725 } else if (e.x < fTimeProvider.getNameSpace()) {
2726 // over the name space
2727 verticalScroll = true;
2728 } else {
2729 // over the state area
2730 if ((e.stateMask & SWT.MODIFIER_MASK) == SWT.CTRL) {
2731 // over the state area, CTRL pressed
2732 horizontalZoom = true;
2733 } else if ((e.stateMask & SWT.MODIFIER_MASK) == SWT.SHIFT) {
2734 // over the state area, SHIFT pressed
2735 horizontalScroll = true;
2736 } else {
2737 // over the state area, no modifier pressed
2738 verticalScroll = true;
2739 }
2740 }
2741 if (verticalZoom) {
2742 fVerticalZoomAlignEntry = getVerticalZoomAlignCursor(e.y);
2743 verticalZoom(e.count > 0);
2744 if (fVerticalZoomAlignEntry != null) {
2745 setElementPosition(fVerticalZoomAlignEntry.getKey(), fVerticalZoomAlignEntry.getValue());
2746 }
2747 } else if (horizontalZoom && fTimeProvider.getTime0() != fTimeProvider.getTime1()) {
2748 zoom(e.count > 0);
2749 } else if (horizontalScroll) {
2750 horizontalScroll(e.count > 0);
2751 } else if (verticalScroll){
2752 setTopIndex(getTopIndex() - e.count);
2753 }
2754 }
2755
2756 /**
2757 * Get the vertical zoom alignment entry and position based on the current
2758 * selection. If there is no selection or if the selection is not visible,
2759 * return an alignment entry with a null time graph entry.
2760 *
2761 * @return a map entry where the key is the selection's time graph entry and
2762 * the value is the center y-coordinate of that entry, or null
2763 */
2764 private Entry<ITimeGraphEntry, Integer> getVerticalZoomAlignSelection() {
2765 Entry<ITimeGraphEntry, Integer> alignEntry = getVerticalZoomAlignOngoing();
2766 if (alignEntry != null) {
2767 return alignEntry;
2768 }
2769 int index = getSelectedIndex();
2770 if (index == -1 || index >= getExpandedElementCount()) {
2771 return new SimpleEntry<>(null, 0);
2772 }
2773 Rectangle bounds = getClientArea();
2774 Rectangle itemRect = getItemRect(bounds, index);
2775 if (itemRect.y < bounds.y || itemRect.y > bounds.y + bounds.height) {
2776 /* selection is not visible */
2777 return new SimpleEntry<>(null, 0);
2778 }
2779 ITimeGraphEntry entry = getExpandedElement(index);
2780 int y = itemRect.y + itemRect.height / 2;
2781 return new SimpleEntry<>(entry, y);
2782 }
2783
2784 /**
2785 * Get the vertical zoom alignment entry and position at the specified
2786 * cursor position.
2787 *
2788 * @param y
2789 * the cursor y-coordinate
2790 * @return a map entry where the key is the time graph entry under the
2791 * cursor and the value is the cursor y-coordinate
2792 */
2793 private Entry<ITimeGraphEntry, Integer> getVerticalZoomAlignCursor(int y) {
2794 Entry<ITimeGraphEntry, Integer> alignEntry = getVerticalZoomAlignOngoing();
2795 if (alignEntry != null) {
2796 return alignEntry;
2797 }
2798 int index = getItemIndexAtY(y);
2799 if (index == -1) {
2800 index = getExpandedElementCount() - 1;
2801 }
2802 ITimeGraphEntry entry = getExpandedElement(index);
2803 return new SimpleEntry<>(entry, y);
2804 }
2805
2806 /**
2807 * Get the vertical zoom alignment entry and position if there is an ongoing
2808 * one and we are within the vertical zoom delay, or otherwise return null.
2809 *
2810 * @return a map entry where the key is a time graph entry and the value is
2811 * a y-coordinate, or null
2812 */
2813 private Entry<ITimeGraphEntry, Integer> getVerticalZoomAlignOngoing() {
2814 long currentTimeMillis = System.currentTimeMillis();
2815 if (currentTimeMillis < fVerticalZoomAlignTime + VERTICAL_ZOOM_DELAY) {
2816 /*
2817 * If the vertical zoom is triggered repeatedly in a short amount of
2818 * time, use the initial event's entry and position.
2819 */
2820 fVerticalZoomAlignTime = currentTimeMillis;
2821 return fVerticalZoomAlignEntry;
2822 }
2823 fVerticalZoomAlignTime = currentTimeMillis;
2824 return null;
2825 }
2826
2827 @Override
2828 public void handleEvent(Event event) {
2829 if (event.type == SWT.MouseWheel) {
2830 // prevent horizontal scrolling when the mouse wheel is used to
2831 // scroll vertically or zoom
2832 event.doit = false;
2833 }
2834 }
2835
2836 @Override
2837 public int getBorderWidth() {
2838 return fBorderWidth;
2839 }
2840
2841 /**
2842 * Set the border width
2843 *
2844 * @param borderWidth
2845 * The width
2846 */
2847 public void setBorderWidth(int borderWidth) {
2848 this.fBorderWidth = borderWidth;
2849 }
2850
2851 /**
2852 * @return The current height of the header row
2853 */
2854 public int getHeaderHeight() {
2855 return fHeaderHeight;
2856 }
2857
2858 /**
2859 * Set the height of the header row
2860 *
2861 * @param headerHeight
2862 * The height
2863 */
2864 public void setHeaderHeight(int headerHeight) {
2865 this.fHeaderHeight = headerHeight;
2866 }
2867
2868 /**
2869 * @return The default height of regular item rows
2870 */
2871 public int getItemHeight() {
2872 return fGlobalItemHeight;
2873 }
2874
2875 /**
2876 * Set the default height of regular item rows.
2877 *
2878 * @param rowHeight
2879 * The height
2880 */
2881 public void setItemHeight(int rowHeight) {
2882 this.fGlobalItemHeight = rowHeight;
2883 for (Item item : fItemData.fItems) {
2884 item.fItemHeight = rowHeight;
2885 }
2886 }
2887
2888 /**
2889 * Set the height of a specific item. Overrides the default item height.
2890 *
2891 * @param entry
2892 * A time graph entry
2893 * @param rowHeight
2894 * The height
2895 * @return true if the height is successfully stored, false otherwise
2896 */
2897 public boolean setItemHeight(ITimeGraphEntry entry, int rowHeight) {
2898 Item item = fItemData.findItem(entry);
2899 if (item != null) {
2900 item.fItemHeight = rowHeight;
2901 return true;
2902 }
2903 return false;
2904 }
2905
2906 /**
2907 * Set the minimum item width
2908 *
2909 * @param width The minimum width
2910 */
2911 public void setMinimumItemWidth(int width) {
2912 this.fMinimumItemWidth = width;
2913 }
2914
2915 /**
2916 * @return The minimum item width
2917 */
2918 public int getMinimumItemWidth() {
2919 return fMinimumItemWidth;
2920 }
2921
2922 /**
2923 * Set whether all time events with a duration shorter than one pixel should
2924 * be blended in. If false, only the first such time event will be drawn and
2925 * the subsequent time events in the same pixel will be discarded. The
2926 * default value is false.
2927 *
2928 * @param blend
2929 * true if sub-pixel events should be blended, false otherwise.
2930 * @since 1.1
2931 */
2932 public void setBlendSubPixelEvents(boolean blend) {
2933 fBlendSubPixelEvents = blend;
2934 }
2935
2936 @Override
2937 public void addSelectionChangedListener(ISelectionChangedListener listener) {
2938 if (listener != null && !fSelectionChangedListeners.contains(listener)) {
2939 fSelectionChangedListeners.add(listener);
2940 }
2941 }
2942
2943 @Override
2944 public void removeSelectionChangedListener(ISelectionChangedListener listener) {
2945 if (listener != null) {
2946 fSelectionChangedListeners.remove(listener);
2947 }
2948 }
2949
2950 @Override
2951 public void setSelection(ISelection selection) {
2952 if (selection instanceof TimeGraphSelection) {
2953 TimeGraphSelection sel = (TimeGraphSelection) selection;
2954 Object ob = sel.getFirstElement();
2955 if (ob instanceof ITimeGraphEntry) {
2956 ITimeGraphEntry trace = (ITimeGraphEntry) ob;
2957 selectItem(trace, false);
2958 }
2959 }
2960
2961 }
2962
2963 /**
2964 * @param filter The filter object to be attached to the view
2965 */
2966 public void addFilter(@NonNull ViewerFilter filter) {
2967 if (!fFilters.contains(filter)) {
2968 fFilters.add(filter);
2969 }
2970 }
2971
2972 /**
2973 * @param filter The filter object to be attached to the view
2974 */
2975 public void removeFilter(@NonNull ViewerFilter filter) {
2976 fFilters.remove(filter);
2977 }
2978
2979 /**
2980 * Returns this control's filters.
2981 *
2982 * @return an array of viewer filters
2983 * @since 2.0
2984 */
2985 public @NonNull ViewerFilter[] getFilters() {
2986 return Iterables.toArray(fFilters, ViewerFilter.class);
2987 }
2988
2989 /**
2990 * Sets the filters, replacing any previous filters.
2991 *
2992 * @param filters
2993 * an array of viewer filters, or null
2994 * @since 2.0
2995 */
2996 public void setFilters(@NonNull ViewerFilter[] filters) {
2997 fFilters.clear();
2998 if (filters != null) {
2999 fFilters.addAll(Arrays.asList(filters));
3000 }
3001 }
3002
3003 @Override
3004 public void colorSettingsChanged(StateItem[] stateItems) {
3005 /* Destroy previous colors from the resource manager */
3006 if (fEventColorMap != null) {
3007 for (Color color : fEventColorMap) {
3008 fResourceManager.destroyColor(color.getRGB());
3009 }
3010 }
3011 if (stateItems != null) {
3012 fEventColorMap = new Color[stateItems.length];
3013 for (int i = 0; i < stateItems.length; i++) {
3014 fEventColorMap[i] = fResourceManager.createColor(stateItems[i].getStateColor());
3015 }
3016 } else {
3017 fEventColorMap = new Color[] { };
3018 }
3019 redraw();
3020 }
3021
3022 private class ItemData {
3023 private Map<ITimeGraphEntry, Item> fItemMap = new LinkedHashMap<>();
3024 private Item[] fExpandedItems = new Item[0];
3025 private Item[] fItems = new Item[0];
3026 private ITimeGraphEntry fRootEntries[] = new ITimeGraphEntry[0];
3027 private List<ILinkEvent> fLinks = new ArrayList<>();
3028
3029 public ItemData() {
3030 }
3031
3032 public Item findItem(ITimeGraphEntry entry) {
3033 return fItemMap.get(entry);
3034 }
3035
3036 public int findItemIndex(ITimeGraphEntry entry) {
3037 Item item = fItemMap.get(entry);
3038 if (item == null) {
3039 return -1;
3040 }
3041 return item.fExpandedIndex;
3042 }
3043
3044 public void refreshData() {
3045 ITimeGraphEntry selection = getSelectedTrace();
3046 Map<ITimeGraphEntry, Item> itemMap = new LinkedHashMap<>();
3047 for (int i = 0; i < fRootEntries.length; i++) {
3048 ITimeGraphEntry entry = fRootEntries[i];
3049 refreshData(itemMap, null, 0, entry);
3050 }
3051 fItemMap = itemMap;
3052 fItems = fItemMap.values().toArray(new Item[0]);
3053 updateExpandedItems();
3054 if (selection != null) {
3055 for (Item item : fExpandedItems) {
3056 if (item.fEntry == selection) {
3057 item.fSelected = true;
3058 break;
3059 }
3060 }
3061 }
3062 }
3063
3064 private void refreshData(Map<ITimeGraphEntry, Item> itemMap, Item parent, int level, ITimeGraphEntry entry) {
3065 Item item = new Item(entry, entry.getName(), level);
3066 if (parent != null) {
3067 parent.fChildren.add(item);
3068 }
3069 if (fGlobalItemHeight == CUSTOM_ITEM_HEIGHT) {
3070 item.fItemHeight = fTimeGraphProvider.getItemHeight(entry);
3071 } else {
3072 item.fItemHeight = fGlobalItemHeight;
3073 }
3074 item.fItemHeight = Math.max(1, item.fItemHeight + fHeightAdjustment);
3075 itemMap.put(entry, item);
3076 if (entry.hasChildren()) {
3077 Item oldItem = fItemMap.get(entry);
3078 if (oldItem != null && oldItem.fHasChildren && level == oldItem.fLevel && entry.getParent() == oldItem.fEntry.getParent()) {
3079 /* existing items keep their old expanded state */
3080 item.fExpanded = oldItem.fExpanded;
3081 } else {
3082 /* new items set the expanded state according to auto-expand level */
3083 item.fExpanded = fAutoExpandLevel == ALL_LEVELS || level < fAutoExpandLevel;
3084 }
3085 item.fHasChildren = true;
3086 for (ITimeGraphEntry child : entry.getChildren()) {
3087 refreshData(itemMap, item, level + 1, child);
3088 }
3089 }
3090 }
3091
3092 public void updateExpandedItems() {
3093 for (Item item : fItems) {
3094 item.fExpandedIndex = -1;
3095 }
3096 List<Item> expandedItemList = new ArrayList<>();
3097 for (int i = 0; i < fRootEntries.length; i++) {
3098 ITimeGraphEntry entry = fRootEntries[i];
3099 Item item = findItem(entry);
3100 refreshExpanded(expandedItemList, item);
3101 }
3102 fExpandedItems = expandedItemList.toArray(new Item[0]);
3103 fTopIndex = Math.min(fTopIndex, Math.max(0, fExpandedItems.length - 1));
3104 }
3105
3106 private void refreshExpanded(List<Item> expandedItemList, Item item) {
3107 // Check for filters
3108 boolean display = true;
3109 for (ViewerFilter filter : fFilters) {
3110 if (!filter.select(null, item.fEntry.getParent(), item.fEntry)) {
3111 display = false;
3112 break;
3113 }
3114 }
3115 if (display) {
3116 item.fExpandedIndex = expandedItemList.size();
3117 expandedItemList.add(item);
3118 if (item.fHasChildren && item.fExpanded) {
3119 for (Item child : item.fChildren) {
3120 refreshExpanded(expandedItemList, child);
3121 }
3122 }
3123 }
3124 }
3125
3126 public void refreshData(ITimeGraphEntry[] entries) {
3127 if (entries == null) {
3128 fRootEntries = null;
3129 } else {
3130 fRootEntries = Arrays.copyOf(entries, entries.length);
3131 }
3132
3133 refreshData();
3134 }
3135
3136 public void refreshArrows(List<ILinkEvent> events) {
3137 /* If links are null, reset the list */
3138 if (events != null) {
3139 fLinks = events;
3140 } else {
3141 fLinks = new ArrayList<>();
3142 }
3143 }
3144
3145 public ITimeGraphEntry[] getEntries() {
3146 return fRootEntries;
3147 }
3148 }
3149
3150 private class Item {
3151 private boolean fExpanded;
3152 private int fExpandedIndex;
3153 private boolean fSelected;
3154 private boolean fHasChildren;
3155 private int fItemHeight;
3156 private final int fLevel;
3157 private final List<Item> fChildren;
3158 private final String fName;
3159 private final ITimeGraphEntry fEntry;
3160
3161 public Item(ITimeGraphEntry entry, String name, int level) {
3162 this.fEntry = entry;
3163 this.fName = name;
3164 this.fLevel = level;
3165 this.fChildren = new ArrayList<>();
3166 }
3167
3168 @Override
3169 public String toString() {
3170 return fName;
3171 }
3172 }
3173
3174 @Override
3175 public void menuDetected(MenuDetectEvent e) {
3176 if (null == fTimeProvider) {
3177 return;
3178 }
3179 if (e.detail == SWT.MENU_MOUSE) {
3180 if (fPendingMenuDetectEvent == null) {
3181 /* Feature in Linux. The MenuDetectEvent is received before mouseDown.
3182 * Store the event and trigger it later just before handling mouseUp.
3183 * This allows for the method to detect if mouse is used to drag zoom.
3184 */
3185 fPendingMenuDetectEvent = e;
3186 return;
3187 }
3188 fPendingMenuDetectEvent = null;
3189 if (fDragState != DRAG_ZOOM || fDragX != fDragX0) {
3190 return;
3191 }
3192 } else {
3193 if (fDragState != DRAG_NONE) {
3194 return;
3195 }
3196 }
3197 Point p = toControl(e.x, e.y);
3198 int idx = getItemIndexAtY(p.y);
3199 if (idx >= 0 && idx < fItemData.fExpandedItems.length) {
3200 Item item = fItemData.fExpandedItems[idx];
3201 ITimeGraphEntry entry = item.fEntry;
3202 if (entry.hasTimeEvents()) {
3203 ITimeEvent event = Utils.findEvent(entry, getTimeAtX(p.x), 2);
3204 if (event != null) {
3205 e.data = event;
3206 fireMenuEventOnTimeEvent(e);
3207 return;
3208 }
3209 }
3210 e.data = entry;
3211 fireMenuEventOnTimeGraphEntry(e);
3212 }
3213 }
3214
3215 /**
3216 * Perform the alignment operation.
3217 *
3218 * @param offset
3219 * the alignment offset
3220 *
3221 * @see ITmfTimeAligned
3222 *
3223 * @since 1.0
3224 */
3225 public void performAlign(int offset) {
3226 fTimeProvider.setNameSpace(offset);
3227 }
3228
3229 /**
3230 * Return the time alignment information
3231 *
3232 * @return the time alignment information
3233 *
3234 * @see ITmfTimeAligned
3235 *
3236 * @since 1.0
3237 */
3238 public TmfTimeViewAlignmentInfo getTimeViewAlignmentInfo() {
3239 return new TmfTimeViewAlignmentInfo(getShell(), toDisplay(0, 0), fTimeProvider.getNameSpace());
3240 }
3241 }
This page took 0.11051 seconds and 6 git commands to generate.