1 /*******************************************************************************
2 * Copyright (c) 2014, 2015 École Polytechnique de Montréal and others.
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 * Geneviève Bastien - Initial API and implementation
11 *******************************************************************************/
13 package org
.eclipse
.tracecompass
.tmf
.ui
.viewers
.xycharts
.linecharts
;
15 import java
.util
.LinkedHashMap
;
17 import java
.util
.Map
.Entry
;
18 import java
.util
.logging
.Logger
;
20 import org
.eclipse
.core
.runtime
.IProgressMonitor
;
21 import org
.eclipse
.core
.runtime
.NullProgressMonitor
;
22 import org
.eclipse
.jdt
.annotation
.Nullable
;
23 import org
.eclipse
.swt
.SWT
;
24 import org
.eclipse
.swt
.graphics
.Point
;
25 import org
.eclipse
.swt
.widgets
.Composite
;
26 import org
.eclipse
.swt
.widgets
.Display
;
27 import org
.eclipse
.tracecompass
.common
.core
.log
.TraceCompassLog
;
28 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfSignalManager
;
29 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfTrace
;
30 import org
.eclipse
.tracecompass
.tmf
.ui
.signal
.TmfTimeViewAlignmentInfo
;
31 import org
.eclipse
.tracecompass
.tmf
.ui
.signal
.TmfTimeViewAlignmentSignal
;
32 import org
.eclipse
.tracecompass
.tmf
.ui
.viewers
.xycharts
.TmfChartTimeStampFormat
;
33 import org
.eclipse
.tracecompass
.tmf
.ui
.viewers
.xycharts
.TmfXYChartViewer
;
34 import org
.swtchart
.IAxisTick
;
35 import org
.swtchart
.ILineSeries
;
36 import org
.swtchart
.ILineSeries
.PlotSymbolType
;
37 import org
.swtchart
.ISeries
;
38 import org
.swtchart
.ISeries
.SeriesType
;
39 import org
.swtchart
.ISeriesSet
;
40 import org
.swtchart
.LineStyle
;
41 import org
.swtchart
.Range
;
44 * Abstract line chart viewer class implementation. All series in this viewer
45 * use the same X axis values. They are automatically created as values are
46 * provided for a key. Series by default will be displayed as a line. Each
47 * series appearance can be overridden when creating it.
49 * @author - Geneviève Bastien
51 public abstract class TmfCommonXLineChartViewer
extends TmfXYChartViewer
{
53 private static final double DEFAULT_MAXY
= Double
.MIN_VALUE
;
54 private static final double DEFAULT_MINY
= Double
.MAX_VALUE
;
56 /* The desired number of points per pixel */
57 private static final double RESOLUTION
= 1.0;
58 private static final Logger LOGGER
= TraceCompassLog
.getLogger(TmfCommonXLineChartViewer
.class);
59 private static final String LOG_STRING_WITH_PARAM
= "[TmfCommonXLineChart:%s] viewerId=%s, %s"; //$NON-NLS-1$
60 private static final String LOG_STRING
= "[TmfCommonXLineChart:%s] viewerId=%s"; //$NON-NLS-1$
62 private static final int[] LINE_COLORS
= { SWT
.COLOR_BLUE
, SWT
.COLOR_RED
, SWT
.COLOR_GREEN
,
63 SWT
.COLOR_MAGENTA
, SWT
.COLOR_CYAN
,
64 SWT
.COLOR_DARK_BLUE
, SWT
.COLOR_DARK_RED
, SWT
.COLOR_DARK_GREEN
,
65 SWT
.COLOR_DARK_MAGENTA
, SWT
.COLOR_DARK_CYAN
, SWT
.COLOR_DARK_YELLOW
,
66 SWT
.COLOR_BLACK
, SWT
.COLOR_GRAY
};
67 private static final LineStyle
[] LINE_STYLES
= { LineStyle
.SOLID
, LineStyle
.DASH
, LineStyle
.DOT
, LineStyle
.DASHDOT
};
69 private final Map
<String
, double[]> fSeriesValues
= new LinkedHashMap
<>();
70 private double[] fXValues
;
71 private double fResolution
;
73 private UpdateThread fUpdateThread
;
79 * The parent composite
81 * The title of the viewer
83 * The label of the xAxis
85 * The label of the yAXIS
87 public TmfCommonXLineChartViewer(Composite parent
, String title
, String xLabel
, String yLabel
) {
88 super(parent
, title
, xLabel
, yLabel
);
89 getSwtChart().getTitle().setVisible(false);
90 getSwtChart().getLegend().setPosition(SWT
.BOTTOM
);
91 getSwtChart().getAxisSet().getXAxes()[0].getTitle().setVisible(false);
92 setResolution(RESOLUTION
);
93 setTooltipProvider(new TmfCommonXLineChartTooltipProvider(this));
97 * Set the number of requests per pixel that should be done on this chart
100 * The number of points per pixels
102 protected void setResolution(double resolution
) {
103 fResolution
= resolution
;
107 public void loadTrace(ITmfTrace trace
) {
108 super.loadTrace(trace
);
113 * Formats a log message for this class
116 * The event to log, that will be appended to the class name to
117 * make the full event name
119 * The string of extra parameters to add to the log message, in
120 * the format name=value[, name=value]*, or <code>null</code> for
122 * @return The complete log message for this class
124 private String
getLogMessage(String event
, @Nullable String parameters
) {
125 if (parameters
== null) {
126 return String
.format(LOG_STRING
, event
, getClass().getName());
128 return String
.format(LOG_STRING_WITH_PARAM
, event
, getClass().getName(), parameters
);
132 * Forces a reinitialization of the data sources, even if it has already
133 * been initialized for this trace before
135 protected void reinitialize() {
136 fSeriesValues
.clear();
137 Thread thread
= new Thread() {
138 // Don't use TmfUiRefreshHandler (bug 467751)
141 LOGGER
.info(() -> getLogMessage("InitializeThreadStart", "tid=" + getId())); //$NON-NLS-1$ //$NON-NLS-2$
142 initializeDataSource();
143 if (!getSwtChart().isDisposed()) {
144 getDisplay().asyncExec(new Runnable() {
147 if (!getSwtChart().isDisposed()) {
148 /* Delete the old series */
155 LOGGER
.info(() -> getLogMessage("InitializeThreadEnd", "tid=" + getId())); //$NON-NLS-1$ //$NON-NLS-2$
162 * Initialize the source of the data for this viewer. This method is run in
163 * a separate thread, so this is where for example one can execute an
164 * analysis module and wait for its completion to initialize the series
166 protected void initializeDataSource() {
170 private class UpdateThread
extends Thread
{
171 private final IProgressMonitor fMonitor
;
172 private final int fNumRequests
;
174 public UpdateThread(int numRequests
) {
175 super("Line chart update"); //$NON-NLS-1$
176 fNumRequests
= numRequests
;
177 fMonitor
= new NullProgressMonitor();
182 LOGGER
.info(() -> getLogMessage("UpdateThreadStart", "numRequests=" + fNumRequests
+ ", tid=" + getId())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
183 Display
.getDefault().syncExec(new Runnable() {
186 LOGGER
.info(() -> getLogMessage("UpdateDataStart", "tid=" + getId())); //$NON-NLS-1$ //$NON-NLS-2$
187 updateData(getWindowStartTime(), getWindowEndTime(), fNumRequests
, fMonitor
);
188 LOGGER
.info(() -> getLogMessage("UpdateDataEnd", "tid=" + getId())); //$NON-NLS-1$ //$NON-NLS-2$
191 updateThreadFinished(this);
192 LOGGER
.info(() -> getLogMessage("UpdateThreadEnd", "tid=" + getId())); //$NON-NLS-1$ //$NON-NLS-2$
195 public void cancel() {
196 LOGGER
.info(() -> getLogMessage("UpdateThreadCanceled", "tid=" + getId())); //$NON-NLS-1$ //$NON-NLS-2$
197 fMonitor
.setCanceled(true);
201 private synchronized void newUpdateThread() {
203 if (!getSwtChart().isDisposed()) {
204 final int numRequests
= (int) (getSwtChart().getPlotArea().getBounds().width
* fResolution
);
205 fUpdateThread
= new UpdateThread(numRequests
);
206 fUpdateThread
.start();
210 private synchronized void updateThreadFinished(UpdateThread thread
) {
211 if (thread
== fUpdateThread
) {
212 fUpdateThread
= null;
217 * Cancels the currently running update thread. It is automatically called
218 * when the content is updated, but child viewers may want to call it
219 * manually to do some operations before calling
220 * {@link TmfCommonXLineChartViewer#updateContent}
222 protected synchronized void cancelUpdate() {
223 if (fUpdateThread
!= null) {
224 fUpdateThread
.cancel();
229 protected void updateContent() {
230 getDisplay().asyncExec(new Runnable() {
239 * Convenience method to compute the values of the X axis for a given time
240 * range. This method will return at most nb values, equally separated from
241 * start to end. The step between values will be at least 1.0, so the number
242 * of values returned can be lower than nb.
244 * The returned time values are in internal time, ie to get trace time, the
245 * time offset needs to be added to those values.
248 * The start time of the time range
250 * End time of the range
252 * The maximum number of steps in the x axis.
253 * @return The time values (converted to double) to match every step.
255 protected static final double[] getXAxis(long start
, long end
, int nb
) {
256 long steps
= (end
- start
);
259 nbVals
= (int) steps
;
264 double step
= steps
/ (double) nbVals
;
266 double timestamps
[] = new double[nbVals
];
268 for (int i
= 0; i
< nbVals
; i
++) {
269 timestamps
[i
] = curTime
;
276 * Set the values of the x axis. There is only one array of values for the x
277 * axis for all series of a line chart so it needs to be set once here.
280 * The values for the x axis. The values must be in internal
281 * time, ie time offset have been subtracted from trace time
284 protected final void setXAxis(double[] xaxis
) {
289 * Update the series data because the time range has changed. The x axis
290 * values for this data update can be computed using the
291 * {@link TmfCommonXLineChartViewer#getXAxis(long, long, int)} method which
292 * will return a list of uniformely separated time values.
294 * Each series values should be set by calling the
295 * {@link TmfCommonXLineChartViewer#setSeries(String, double[])}.
297 * This method is responsible for calling the
298 * {@link TmfCommonXLineChartViewer#updateDisplay()} when needed for the new
299 * values to be displayed.
302 * The start time of the range for which the get the data
304 * The end time of the range
306 * The number of 'points' in the chart.
308 * The progress monitor object
310 protected abstract void updateData(long start
, long end
, int nb
, IProgressMonitor monitor
);
313 * Set the data for a given series of the graph. The series does not need to
314 * be created before calling this, but it needs to have at least as many
315 * values as the x axis.
317 * If the series does not exist, it will automatically be created at display
318 * time, with the default values.
321 * The name of the series for which to set the values
322 * @param seriesValues
323 * The array of values for the series
325 protected void setSeries(String seriesName
, double[] seriesValues
) {
326 if (fXValues
.length
!= seriesValues
.length
) {
327 throw new IllegalStateException("All series in list must be of length : " + fXValues
.length
); //$NON-NLS-1$
329 fSeriesValues
.put(seriesName
, seriesValues
);
333 * Add a new series to the XY line chart. By default, it is a simple solid
337 * The name of the series to create
338 * @return The series so that the concrete viewer can modify its properties
341 protected ILineSeries
addSeries(String seriesName
) {
342 ISeriesSet seriesSet
= getSwtChart().getSeriesSet();
343 int seriesCount
= seriesSet
.getSeries().length
;
344 ILineSeries series
= (ILineSeries
) seriesSet
.createSeries(SeriesType
.LINE
, seriesName
);
345 series
.setVisible(true);
346 series
.enableArea(false);
347 series
.setLineStyle(LINE_STYLES
[(seriesCount
/ (LINE_COLORS
.length
)) % LINE_STYLES
.length
]);
348 series
.setSymbolType(PlotSymbolType
.NONE
);
349 series
.setLineColor(Display
.getDefault().getSystemColor(LINE_COLORS
[seriesCount
% LINE_COLORS
.length
]));
354 * Delete a series from the chart and its values from the viewer.
357 * Name of the series to delete
359 protected void deleteSeries(String seriesName
) {
360 ISeries series
= getSwtChart().getSeriesSet().getSeries(seriesName
);
361 if (series
!= null) {
362 getSwtChart().getSeriesSet().deleteSeries(series
.getId());
364 fSeriesValues
.remove(seriesName
);
368 * Update the chart's values before refreshing the viewer
370 protected void updateDisplay() {
371 Display
.getDefault().asyncExec(new Runnable() {
372 final TmfChartTimeStampFormat tmfChartTimeStampFormat
= new TmfChartTimeStampFormat(getTimeOffset());
376 if (!getSwtChart().isDisposed()) {
377 double[] xValues
= fXValues
;
378 if (xValues
.length
< 1) {
381 double maxy
= DEFAULT_MAXY
;
382 double miny
= DEFAULT_MINY
;
383 for (Entry
<String
, double[]> entry
: fSeriesValues
.entrySet()) {
384 ILineSeries series
= (ILineSeries
) getSwtChart().getSeriesSet().getSeries(entry
.getKey());
385 if (series
== null) {
386 series
= addSeries(entry
.getKey());
388 series
.setXSeries(xValues
);
389 /* Find the minimal and maximum values in this series */
390 for (double value
: entry
.getValue()) {
391 maxy
= Math
.max(maxy
, value
);
392 miny
= Math
.min(miny
, value
);
394 series
.setYSeries(entry
.getValue());
396 if (maxy
== DEFAULT_MAXY
) {
400 IAxisTick xTick
= getSwtChart().getAxisSet().getXAxis(0).getTick();
401 xTick
.setFormat(tmfChartTimeStampFormat
);
403 final double start
= 0.0;
404 double end
= getWindowEndTime() - getWindowStartTime();
405 getSwtChart().getAxisSet().getXAxis(0).setRange(new Range(start
, end
));
407 getSwtChart().getAxisSet().getYAxis(0).setRange(new Range(miny
, maxy
));
409 getSwtChart().redraw();
411 if (isSendTimeAlignSignals()) {
412 // The width of the chart might have changed and its
413 // time axis might be misaligned with the other views
414 Point viewPos
= TmfCommonXLineChartViewer
.this.getParent().getParent().toDisplay(0, 0);
415 int axisPos
= getSwtChart().toDisplay(0, 0).x
+ getPointAreaOffset();
416 int timeAxisOffset
= axisPos
- viewPos
.x
;
417 TmfTimeViewAlignmentInfo timeAlignmentInfo
= new TmfTimeViewAlignmentInfo(getControl().getShell(), viewPos
, timeAxisOffset
);
418 TmfSignalManager
.dispatchSignal(new TmfTimeViewAlignmentSignal(TmfCommonXLineChartViewer
.this, timeAlignmentInfo
, true));
426 * Create the series once the initialization of the viewer's data source is
427 * done. Series do not need to be created before setting their values, but
428 * if their appearance needs to be customized, this method is a good place
429 * to do so. It is called only once per trace.
431 protected void createSeries() {
436 protected void clearContent() {
437 getSwtChart().getAxisSet().getXAxis(0).getTick().setFormat(null);
438 super.clearContent();