1 /*******************************************************************************
2 * Copyright (c) 2012, 2015 Ericsson
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * Mathieu Denis <mathieu.denis@polymtl.ca> - Initial API and implementation
11 * Alexandre Montplaisir - Port to ITmfStatistics provider
12 * Patrick Tasse - Support selection range
13 * Bernd Hufmann - Fix range selection updates
14 *******************************************************************************/
16 package org
.eclipse
.tracecompass
.tmf
.ui
.viewers
.statistics
;
18 import static org
.eclipse
.tracecompass
.common
.core
.NonNullUtils
.checkNotNull
;
20 import java
.util
.Collection
;
21 import java
.util
.HashMap
;
22 import java
.util
.List
;
25 import org
.eclipse
.core
.runtime
.jobs
.Job
;
26 import org
.eclipse
.jface
.viewers
.TreeViewer
;
27 import org
.eclipse
.jface
.viewers
.TreeViewerColumn
;
28 import org
.eclipse
.jface
.viewers
.Viewer
;
29 import org
.eclipse
.jface
.viewers
.ViewerComparator
;
30 import org
.eclipse
.swt
.SWT
;
31 import org
.eclipse
.swt
.custom
.SashForm
;
32 import org
.eclipse
.swt
.events
.SelectionAdapter
;
33 import org
.eclipse
.swt
.events
.SelectionEvent
;
34 import org
.eclipse
.swt
.graphics
.Color
;
35 import org
.eclipse
.swt
.graphics
.Cursor
;
36 import org
.eclipse
.swt
.widgets
.Composite
;
37 import org
.eclipse
.swt
.widgets
.Control
;
38 import org
.eclipse
.swt
.widgets
.Display
;
39 import org
.eclipse
.swt
.widgets
.Event
;
40 import org
.eclipse
.swt
.widgets
.Listener
;
41 import org
.eclipse
.tracecompass
.tmf
.core
.component
.TmfComponent
;
42 import org
.eclipse
.tracecompass
.tmf
.core
.request
.ITmfEventRequest
;
43 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfSelectionRangeUpdatedSignal
;
44 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfSignalHandler
;
45 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceRangeUpdatedSignal
;
46 import org
.eclipse
.tracecompass
.tmf
.core
.statistics
.TmfStatisticsModule
;
47 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.ITmfTimestamp
;
48 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimeRange
;
49 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfTrace
;
50 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceContext
;
51 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceManager
;
52 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceUtils
;
53 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.experiment
.TmfExperiment
;
54 import org
.eclipse
.tracecompass
.tmf
.ui
.viewers
.TmfViewer
;
55 import org
.eclipse
.tracecompass
.tmf
.ui
.viewers
.piecharts
.TmfPieChartViewer
;
56 import org
.eclipse
.tracecompass
.tmf
.ui
.viewers
.piecharts
.model
.TmfPieChartStatisticsModel
;
57 import org
.eclipse
.tracecompass
.tmf
.ui
.viewers
.statistics
.model
.TmfBaseColumnData
;
58 import org
.eclipse
.tracecompass
.tmf
.ui
.viewers
.statistics
.model
.TmfBaseColumnDataProvider
;
59 import org
.eclipse
.tracecompass
.tmf
.ui
.viewers
.statistics
.model
.TmfStatisticsFormatter
;
60 import org
.eclipse
.tracecompass
.tmf
.ui
.viewers
.statistics
.model
.TmfStatisticsTree
;
61 import org
.eclipse
.tracecompass
.tmf
.ui
.viewers
.statistics
.model
.TmfStatisticsTreeManager
;
62 import org
.eclipse
.tracecompass
.tmf
.ui
.viewers
.statistics
.model
.TmfStatisticsTreeNode
;
63 import org
.eclipse
.tracecompass
.tmf
.ui
.viewers
.statistics
.model
.TmfTreeContentProvider
;
66 * A basic viewer to display statistics in the statistics view.
68 * It is linked to a single ITmfTrace until its disposal.
70 * @author Mathieu Denis
72 public class TmfStatisticsViewer
extends TmfViewer
{
74 /** The actual tree viewer to display */
75 private TreeViewer fTreeViewer
;
77 /** Update range synchronization object */
78 private final Object fStatisticsRangeUpdateSyncObj
= new Object();
80 /** The statistics tree linked to this viewer */
81 private TmfStatisticsTree fStatisticsData
;
83 /** The trace that is displayed by this viewer */
84 private ITmfTrace fTrace
;
86 /** Indicates to process all events */
87 private boolean fProcessAll
;
89 /** View instance counter (for multiple statistics views) */
90 private static int fCountInstance
= 0;
92 /** Number of this instance. Used as an instance ID. */
93 private int fInstanceNb
;
95 /** Object to store the cursor while waiting for the trace to load */
96 private Cursor fWaitCursor
= null;
99 * Counts the number of times waitCursor() has been called. It avoids
100 * removing the waiting cursor, since there may be multiple requests running
103 private int fWaitCursorCount
= 0;
105 /** Tells to send a time range request when the trace gets updated. */
106 private boolean fSendRangeRequest
= true;
108 private final Map
<ITmfTrace
, Job
> fUpdateJobsPartial
= new HashMap
<>();
109 private final Map
<ITmfTrace
, Job
> fUpdateJobsGlobal
= new HashMap
<>();
111 private TmfPieChartViewer fPieChartViewer
;
113 private SashForm fSash
;
115 private TmfPieChartStatisticsModel fPieChartModel
;
118 * Create a basic statistics viewer. To be used in conjunction with
119 * {@link TmfStatisticsViewer#init(Composite, String, ITmfTrace)}
122 * The parent composite that will hold the viewer
124 * The name that will be assigned to this viewer
126 * The trace that is displayed by this viewer
129 public TmfStatisticsViewer(Composite parent
, String viewerName
, ITmfTrace trace
) {
130 init(parent
, viewerName
, trace
);
134 * Initialize the statistics viewer.
137 * The parent component of the viewer.
139 * The name to give to the viewer.
141 * The trace that will be displayed by the viewer.
143 public void init(Composite parent
, String viewerName
, ITmfTrace trace
) {
144 super.init(parent
, viewerName
);
145 // Increment a counter to make sure the tree ID is unique.
147 fInstanceNb
= fCountInstance
;
150 // The viewer will process all events if he is assigned to an experiment
151 fProcessAll
= (trace
instanceof TmfExperiment
);
158 public void dispose() {
160 if (fWaitCursor
!= null) {
161 fWaitCursor
.dispose();
164 for (Job j
: fUpdateJobsGlobal
.values()) {
168 for (Job j
: fUpdateJobsPartial
.values()) {
172 // Clean the model for this viewer
173 TmfStatisticsTreeManager
.removeStatTreeRoot(getTreeID());
174 fPieChartViewer
.reinitializeCharts();
177 // ------------------------------------------------------------------------
179 // ------------------------------------------------------------------------
182 * Handles the signal about new trace range.
185 * The trace range updated signal
188 public void traceRangeUpdated(TmfTraceRangeUpdatedSignal signal
) {
189 ITmfTrace trace
= signal
.getTrace();
191 if (!isListeningTo(trace
)) {
195 synchronized (fStatisticsRangeUpdateSyncObj
) {
196 // Sends the time range request only once from this method.
197 if (fSendRangeRequest
) {
198 fSendRangeRequest
= false;
200 TmfTraceContext ctx
= TmfTraceManager
.getInstance().getCurrentTraceContext();
201 TmfTimeRange timeRange
= ctx
.getSelectionRange();
202 requestTimeRangeData(trace
, timeRange
);
205 requestData(trace
, signal
.getRange());
209 * Handles the time synch updated signal. It updates the time range
213 * Contains the information about the new selected time range.
217 public void timeSynchUpdated(TmfSelectionRangeUpdatedSignal signal
) {
218 if (fTrace
== null) {
221 ITmfTimestamp begin
= signal
.getBeginTime();
222 ITmfTimestamp end
= signal
.getEndTime();
223 TmfTimeRange timeRange
= new TmfTimeRange(begin
, end
);
224 requestTimeRangeData(fTrace
, timeRange
);
227 // ------------------------------------------------------------------------
229 // ------------------------------------------------------------------------
232 * Returns the primary control associated with this viewer.
234 * @return the SWT control which displays this viewer's content
237 public Control
getControl() {
242 * Get the input of the viewer.
244 * @return an object representing the input of the statistics viewer.
246 public Object
getInput() {
247 return fTreeViewer
.getInput();
251 * This method can be overridden to implement another way of representing
252 * the statistics data and to retrieve the information for display.
254 * @return a TmfStatisticsData object.
256 public TmfStatisticsTree
getStatisticData() {
257 if (fStatisticsData
== null) {
258 fStatisticsData
= new TmfStatisticsTree();
260 return fStatisticsData
;
264 * @return the model of the piecharts in this viewer
267 public TmfPieChartStatisticsModel
getPieChartModel(){
268 if (fPieChartModel
== null) {
269 fPieChartModel
= new TmfPieChartStatisticsModel();
271 return fPieChartModel
;
275 * Returns a unique ID based on name to be associated with the statistics
276 * tree for this viewer. For a same name, it will always return the same ID.
278 * @return a unique statistics tree ID.
280 public String
getTreeID() {
281 return getName() + fInstanceNb
;
285 public void refresh() {
286 final Control viewerControl
= getControl();
287 // Ignore update if disposed
288 if (viewerControl
.isDisposed()) {
292 refreshPieCharts(true, true);
296 * Only refreshes the Tree viewer
298 private void refreshTree(){
299 final Control viewerControl
= getControl();
300 // Ignore update if disposed
301 if (viewerControl
.isDisposed()) {
305 Display
.getDefault().asyncExec(new Runnable() {
308 if (!viewerControl
.isDisposed()) {
309 fTreeViewer
.refresh();
316 * Only refreshes the piecharts depending on the parameters
317 * @param refreshGlobal if we have to refresh the global piechart
318 * @param refreshSelection if we have to refresh the selection piechart
321 protected void refreshPieCharts(final boolean refreshGlobal
, final boolean refreshSelection
) {
322 final Control viewerControl
= getControl();
323 // Ignore update if disposed
324 if (viewerControl
.isDisposed()) {
328 Display
.getDefault().asyncExec(new Runnable() {
331 if (!viewerControl
.isDisposed()) {
332 fPieChartViewer
.refresh(refreshGlobal
, refreshSelection
);
339 * Will force a request on the partial event count if one is needed.
341 public void sendPartialRequestOnNextUpdate() {
342 synchronized (fStatisticsRangeUpdateSyncObj
) {
343 fSendRangeRequest
= true;
348 * Focus on the statistics tree of the viewer
350 public void setFocus() {
351 fTreeViewer
.getTree().setFocus();
355 * Cancels the request if it is not already completed
358 * The request to be canceled
360 protected void cancelOngoingRequest(ITmfEventRequest request
) {
361 if (request
!= null && !request
.isCompleted()) {
367 * This method can be overridden to change the representation of the data in
370 * @return An object of type {@link TmfBaseColumnDataProvider}.
372 protected TmfBaseColumnDataProvider
getColumnDataProvider() {
373 return new TmfBaseColumnDataProvider();
377 * Initialize the content that will be drawn in this viewer
380 * The parent of the control to create
382 protected void initContent(Composite parent
) {
384 final List
<TmfBaseColumnData
> columnDataList
= getColumnDataProvider().getColumnData();
386 fSash
= new SashForm(parent
, SWT
.HORIZONTAL
);
388 fTreeViewer
= new TreeViewer(fSash
, SWT
.BORDER
| SWT
.H_SCROLL
| SWT
.V_SCROLL
);
389 fPieChartViewer
= new TmfPieChartViewer(fSash
);
390 fSash
.setWeights(new int[]{100,100});
392 fTreeViewer
.setContentProvider(new TmfTreeContentProvider());
393 fTreeViewer
.getTree().setHeaderVisible(true);
394 fTreeViewer
.setUseHashlookup(true);
396 // Creates the columns defined by the column data provider
397 for (final TmfBaseColumnData columnData
: columnDataList
) {
398 final TreeViewerColumn treeColumn
= new TreeViewerColumn(fTreeViewer
, columnData
.getAlignment());
399 treeColumn
.getColumn().setText(columnData
.getHeader());
400 treeColumn
.getColumn().setWidth(columnData
.getWidth());
401 treeColumn
.getColumn().setToolTipText(columnData
.getTooltip());
403 // If is dummy column
404 if (columnData
== columnDataList
.get(TmfBaseColumnDataProvider
.StatsColumn
.DUMMY
.getIndex())) {
405 treeColumn
.getColumn().setResizable(false);
408 // A comparator is defined.
409 if (columnData
.getComparator() != null) {
410 // Adds a listener on the columns header for sorting purpose.
411 treeColumn
.getColumn().addSelectionListener(new SelectionAdapter() {
413 private ViewerComparator reverseComparator
;
416 public void widgetSelected(SelectionEvent e
) {
417 // Initializes the reverse comparator once.
418 if (reverseComparator
== null) {
419 reverseComparator
= new ViewerComparator() {
421 public int compare(Viewer viewer
, Object e1
, Object e2
) {
422 return -1 * columnData
.getComparator().compare(viewer
, e1
, e2
);
427 if (fTreeViewer
.getTree().getSortDirection() == SWT
.UP
428 || fTreeViewer
.getTree().getSortColumn() != treeColumn
.getColumn()) {
430 * Puts the descendant order if the old order was up
431 * or if the selected column has changed.
433 fTreeViewer
.setComparator(columnData
.getComparator());
434 fTreeViewer
.getTree().setSortDirection(SWT
.DOWN
);
437 * Puts the ascendant ordering if the selected
438 * column hasn't changed.
440 fTreeViewer
.setComparator(reverseComparator
);
441 fTreeViewer
.getTree().setSortDirection(SWT
.UP
);
443 fTreeViewer
.getTree().setSortColumn(treeColumn
.getColumn());
447 treeColumn
.setLabelProvider(columnData
.getLabelProvider());
450 // Handler that will draw the percentages and the bar charts.
451 fTreeViewer
.getTree().addListener(SWT
.EraseItem
, new Listener() {
453 public void handleEvent(Event event
) {
454 if (columnDataList
.get(event
.index
).getPercentageProvider() != null) {
456 TmfStatisticsTreeNode node
= (TmfStatisticsTreeNode
) event
.item
.getData();
458 // If node is hidden, exit immediately.
459 if (TmfBaseColumnDataProvider
.HIDDEN_FOLDER_LEVELS
.contains(node
.getName())) {
463 // Otherwise, get percentage and draw bar and text if applicable.
464 double percentage
= columnDataList
.get(event
.index
).getPercentageProvider().getPercentage(node
);
466 // The item is selected.
467 if ((event
.detail
& SWT
.SELECTED
) > 0) {
468 // Draws our own background to avoid overwriting the bar.
469 event
.gc
.fillRectangle(event
.x
, event
.y
, event
.width
, event
.height
);
470 event
.detail
&= ~SWT
.SELECTED
;
473 // Drawing the percentage text
474 // if events are present in top node
475 // and the current node is not the top node
476 // and if is total or partial events column.
477 // If not, exit the method.
478 if (!((event
.index
== TmfBaseColumnDataProvider
.StatsColumn
.TOTAL
.getIndex() || event
.index
== TmfBaseColumnDataProvider
.StatsColumn
.PARTIAL
.getIndex())
479 && node
!= node
.getTop())) {
483 long eventValue
= event
.index
== TmfBaseColumnDataProvider
.StatsColumn
.TOTAL
.getIndex() ?
484 node
.getTop().getValues().getTotal() : node
.getTop().getValues().getPartial();
486 if (eventValue
!= 0) {
488 int oldAlpha
= event
.gc
.getAlpha();
489 Color oldForeground
= event
.gc
.getForeground();
490 Color oldBackground
= event
.gc
.getBackground();
493 if (percentage
!= 0) {
495 * Draws a transparent gradient rectangle from the
496 * color of foreground and background.
498 int barWidth
= (int) ((fTreeViewer
.getTree().getColumn(event
.index
).getWidth() - 8) * percentage
);
499 event
.gc
.setAlpha(64);
500 event
.gc
.setForeground(event
.item
.getDisplay().getSystemColor(SWT
.COLOR_BLUE
));
501 event
.gc
.setBackground(event
.item
.getDisplay().getSystemColor(SWT
.COLOR_LIST_BACKGROUND
));
502 event
.gc
.fillGradientRectangle(event
.x
, event
.y
, barWidth
, event
.height
, true);
503 event
.gc
.drawRectangle(event
.x
, event
.y
, barWidth
, event
.height
);
505 // Restore old values
506 event
.gc
.setBackground(oldBackground
);
507 event
.gc
.setAlpha(oldAlpha
);
508 event
.detail
&= ~SWT
.BACKGROUND
;
512 String percentageText
= TmfStatisticsFormatter
.toPercentageText(percentage
);
513 String absoluteNumberText
= TmfStatisticsFormatter
.toColumnData(node
, TmfBaseColumnDataProvider
.StatsColumn
.getColumn(event
.index
));
515 if (event
.width
> event
.gc
.stringExtent(percentageText
).x
+ event
.gc
.stringExtent(absoluteNumberText
).x
) {
516 int textHeight
= event
.gc
.stringExtent(percentageText
).y
;
517 event
.gc
.setForeground(event
.item
.getDisplay().getSystemColor(SWT
.COLOR_DARK_GRAY
));
518 event
.gc
.drawText(percentageText
, event
.x
, event
.y
+ (event
.height
- textHeight
) / 2, true);
521 // Restores old values
522 event
.gc
.setForeground(oldForeground
);
530 // Initializes the comparator parameters
531 fTreeViewer
.setComparator(columnDataList
.get(0).getComparator());
532 fTreeViewer
.getTree().setSortColumn(fTreeViewer
.getTree().getColumn(0));
533 fTreeViewer
.getTree().setSortDirection(SWT
.DOWN
);
537 * Initializes the input for the tree viewer.
539 protected void initInput() {
540 String treeID
= getTreeID();
541 TmfStatisticsTreeNode statisticsTreeNode
;
542 if (TmfStatisticsTreeManager
.containsTreeRoot(treeID
)) {
543 // The statistics root is already present
544 statisticsTreeNode
= TmfStatisticsTreeManager
.getStatTreeRoot(treeID
);
546 // Checks if the trace is already in the statistics tree.
547 int numNodeTraces
= statisticsTreeNode
.getNbChildren();
549 Collection
<ITmfTrace
> traces
= TmfTraceManager
.getTraceSet(fTrace
);
550 int numTraces
= traces
.size();
552 if (numTraces
== numNodeTraces
) {
555 * Checks if the experiment contains the same traces as when
556 * previously selected.
558 for (ITmfTrace trace
: traces
) {
559 String traceName
= trace
.getName();
560 if (!statisticsTreeNode
.containsChild(traceName
)) {
567 // No need to reload data, all traces are already loaded
568 fTreeViewer
.setInput(statisticsTreeNode
);
571 // Clears the old content to start over
572 statisticsTreeNode
.reset();
575 // Creates a new tree
576 statisticsTreeNode
= TmfStatisticsTreeManager
.addStatsTreeRoot(treeID
, getStatisticData());
579 // Sets the input to a clean data model
580 fTreeViewer
.setInput(statisticsTreeNode
);
581 /* Set a new model for the piecharts and keep a reference */
582 fPieChartViewer
.setInput(getPieChartModel());
586 * Tells if the viewer is listening to a trace.
589 * The trace that the viewer may be listening
590 * @return true if the viewer is listening to the trace, false otherwise
592 protected boolean isListeningTo(ITmfTrace trace
) {
593 if (fProcessAll
|| trace
== fTrace
) {
600 * Called when an trace request has been completed successfully.
603 * Tells if the request is a global or time range (partial)
606 protected void modelComplete(boolean global
) {
612 * Sends the request to the trace for the whole trace
615 * The trace used to send the request
617 * The range to request to the trace
619 protected void requestData(final ITmfTrace trace
, final TmfTimeRange timeRange
) {
620 buildStatisticsTree(trace
, timeRange
, true);
624 * Sends the time range request from the trace
627 * The trace used to send the request
629 * The range to request to the trace
631 protected void requestTimeRangeData(final ITmfTrace trace
, final TmfTimeRange timeRange
) {
632 buildStatisticsTree(trace
, timeRange
, false);
636 * Requests all the data of the trace to the state system which contains
637 * information about the statistics.
639 * Since the viewer may be listening to multiple traces, it may receive an
640 * experiment rather than a single trace. The filtering is done with the
641 * method {@link #isListeningTo(String trace)}.
644 * The trace for which a request must be done
646 * The time range that will be requested to the state system
648 * Tells if the request is for the global event count or the
651 private void buildStatisticsTree(final ITmfTrace trace
, final TmfTimeRange timeRange
, final boolean isGlobal
) {
652 final TmfStatisticsTree statsData
= TmfStatisticsTreeManager
.getStatTree(getTreeID());
653 if (statsData
== null) {
657 Map
<ITmfTrace
, Job
> updateJobs
;
659 updateJobs
= fUpdateJobsGlobal
;
661 updateJobs
= fUpdateJobsPartial
;
664 for (ITmfTrace aTrace
: TmfTraceManager
.getTraceSet(trace
)) {
665 aTrace
= checkNotNull(aTrace
);
666 if (!isListeningTo(aTrace
)) {
670 /* Retrieve the statistics object */
671 final TmfStatisticsModule statsMod
= TmfTraceUtils
.getAnalysisModuleOfClass(aTrace
, TmfStatisticsModule
.class, TmfStatisticsModule
.ID
);
672 if (statsMod
== null) {
673 /* No statistics module available for this trace */
677 Job job
= updateJobs
.get(aTrace
);
679 job
= new StatisticsUpdateJob("Statistics update", aTrace
, isGlobal
, timeRange
, statsMod
, this); //$NON-NLS-1$
680 updateJobs
.put(aTrace
, job
);
688 * Resets the number of events within the time range
690 protected void resetTimeRangeValue() {
691 TmfStatisticsTreeNode treeModelRoot
= TmfStatisticsTreeManager
.getStatTreeRoot(getTreeID());
692 if (treeModelRoot
!= null && treeModelRoot
.hasChildren()) {
693 treeModelRoot
.resetTimeRangeValue();
698 * When the trace is loading the cursor will be different so the user knows
699 * that the processing is not finished yet.
701 * Calls to this method are stacked.
703 * @param waitRequested
704 * Indicates if we need to show the waiting cursor, or the
707 protected void waitCursor(final boolean waitRequested
) {
708 if ((fTreeViewer
== null) || (fTreeViewer
.getTree().isDisposed())) {
712 boolean needsUpdate
= false;
713 Display display
= fTreeViewer
.getControl().getDisplay();
716 if (fWaitCursor
== null) { // The cursor hasn't been initialized yet
717 fWaitCursor
= new Cursor(display
, SWT
.CURSOR_WAIT
);
719 if (fWaitCursorCount
== 1) { // The cursor is not in waiting mode
723 if (fWaitCursorCount
> 0) { // The cursor is in waiting mode
725 if (fWaitCursorCount
== 0) { // No more reason to wait
726 // Put back the default cursor
733 // Performs the updates on the UI thread
734 display
.asyncExec(new Runnable() {
737 if ((fTreeViewer
!= null)
738 && (!fTreeViewer
.getTree().isDisposed())) {
739 Cursor cursor
= null; // indicates default
741 cursor
= fWaitCursor
;
743 fTreeViewer
.getControl().setCursor(cursor
);
751 * @param isGlobal if the job to remove is global or partial
752 * @param jobTrace The trace
754 void removeFromJobs(boolean isGlobal
, ITmfTrace jobTrace
) {
755 Map
<ITmfTrace
, Job
> updateJobs
= isGlobal ? fUpdateJobsGlobal
: fUpdateJobsPartial
;
756 Job job
= updateJobs
.remove(jobTrace
);