tmf.ui: Return minimal number of X values in XY viewer
[deliverable/tracecompass.git] / tmf / org.eclipse.tracecompass.tmf.ui / src / org / eclipse / tracecompass / tmf / ui / viewers / xycharts / linecharts / TmfCommonXLineChartViewer.java
CommitLineData
2e427755 1/*******************************************************************************
4e72adee 2 * Copyright (c) 2014, 2015 École Polytechnique de Montréal and others.
2e427755
GB
3 *
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 *
9 * Contributors:
10 * Geneviève Bastien - Initial API and implementation
11 *******************************************************************************/
12
2bdf0193 13package org.eclipse.tracecompass.tmf.ui.viewers.xycharts.linecharts;
2e427755
GB
14
15import java.util.LinkedHashMap;
16import java.util.Map;
17import java.util.Map.Entry;
18
00968516
GB
19import org.eclipse.core.runtime.IProgressMonitor;
20import org.eclipse.core.runtime.NullProgressMonitor;
c85a741e 21import org.eclipse.swt.SWT;
54404589 22import org.eclipse.swt.graphics.Point;
2e427755
GB
23import org.eclipse.swt.widgets.Composite;
24import org.eclipse.swt.widgets.Display;
54404589 25import org.eclipse.tracecompass.tmf.core.signal.TmfSignalManager;
2bdf0193 26import org.eclipse.tracecompass.tmf.core.trace.ITmfTrace;
54404589
MAL
27import org.eclipse.tracecompass.tmf.ui.signal.TmfTimeViewAlignmentInfo;
28import org.eclipse.tracecompass.tmf.ui.signal.TmfTimeViewAlignmentSignal;
2bdf0193
AM
29import org.eclipse.tracecompass.tmf.ui.viewers.xycharts.TmfChartTimeStampFormat;
30import org.eclipse.tracecompass.tmf.ui.viewers.xycharts.TmfXYChartViewer;
2e427755
GB
31import org.swtchart.IAxisTick;
32import org.swtchart.ILineSeries;
33import org.swtchart.ILineSeries.PlotSymbolType;
34import org.swtchart.ISeries;
35import org.swtchart.ISeries.SeriesType;
c85a741e 36import org.swtchart.ISeriesSet;
2e427755
GB
37import org.swtchart.LineStyle;
38import org.swtchart.Range;
39
40/**
41 * Abstract line chart viewer class implementation. All series in this viewer
42 * use the same X axis values. They are automatically created as values are
43 * provided for a key. Series by default will be displayed as a line. Each
44 * series appearance can be overridden when creating it.
45 *
46 * @author - Geneviève Bastien
2e427755
GB
47 */
48public abstract class TmfCommonXLineChartViewer extends TmfXYChartViewer {
49
50 private static final double DEFAULT_MAXY = Double.MIN_VALUE;
51 private static final double DEFAULT_MINY = Double.MAX_VALUE;
52
53 /* The desired number of points per pixel */
54 private static final double RESOLUTION = 1.0;
55
c85a741e
GB
56 private static final int[] LINE_COLORS = { SWT.COLOR_BLUE, SWT.COLOR_RED, SWT.COLOR_GREEN,
57 SWT.COLOR_MAGENTA, SWT.COLOR_CYAN,
58 SWT.COLOR_DARK_BLUE, SWT.COLOR_DARK_RED, SWT.COLOR_DARK_GREEN,
59 SWT.COLOR_DARK_MAGENTA, SWT.COLOR_DARK_CYAN, SWT.COLOR_DARK_YELLOW,
60 SWT.COLOR_BLACK, SWT.COLOR_GRAY };
61 private static final LineStyle[] LINE_STYLES = { LineStyle.SOLID, LineStyle.DASH, LineStyle.DOT, LineStyle.DASHDOT };
62
2e427755
GB
63 private final Map<String, double[]> fSeriesValues = new LinkedHashMap<>();
64 private double[] fXValues;
9392459a 65 private double fResolution;
2e427755 66
00968516
GB
67 private UpdateThread fUpdateThread;
68
2e427755
GB
69 /**
70 * Constructor
71 *
72 * @param parent
73 * The parent composite
74 * @param title
75 * The title of the viewer
76 * @param xLabel
77 * The label of the xAxis
78 * @param yLabel
79 * The label of the yAXIS
80 */
81 public TmfCommonXLineChartViewer(Composite parent, String title, String xLabel, String yLabel) {
82 super(parent, title, xLabel, yLabel);
83
9392459a 84 setResolution(RESOLUTION);
2e427755
GB
85 setTooltipProvider(new TmfCommonXLineChartTooltipProvider(this));
86 }
87
9392459a
GB
88 /**
89 * Set the number of requests per pixel that should be done on this chart
90 *
91 * @param resolution
92 * The number of points per pixels
93 */
94 protected void setResolution(double resolution) {
95 fResolution = resolution;
96 }
97
2e427755
GB
98 @Override
99 public void loadTrace(ITmfTrace trace) {
100 super.loadTrace(trace);
47cb22a7
GB
101 reinitialize();
102 }
103
104 /**
105 * Forces a reinitialization of the data sources, even if it has already
106 * been initialized for this trace before
47cb22a7
GB
107 */
108 protected void reinitialize() {
2e427755
GB
109 fSeriesValues.clear();
110 Thread thread = new Thread() {
5048e376 111 // Don't use TmfUiRefreshHandler (bug 467751)
2e427755
GB
112 @Override
113 public void run() {
114 initializeDataSource();
5048e376
BH
115 if (!getSwtChart().isDisposed()) {
116 getDisplay().asyncExec(new Runnable() {
117 @Override
118 public void run() {
119 if (!getSwtChart().isDisposed()) {
120 /* Delete the old series */
121 clearContent();
122 createSeries();
123 }
0573bfec 124 }
5048e376
BH
125 });
126 }
2e427755
GB
127 }
128 };
129 thread.start();
130 }
131
132 /**
133 * Initialize the source of the data for this viewer. This method is run in
134 * a separate thread, so this is where for example one can execute an
135 * analysis module and wait for its completion to initialize the series
136 */
137 protected void initializeDataSource() {
138
139 }
140
00968516
GB
141 private class UpdateThread extends Thread {
142 private final IProgressMonitor fMonitor;
143 private final int fNumRequests;
144
145 public UpdateThread(int numRequests) {
146 super("Line chart update"); //$NON-NLS-1$
147 fNumRequests = numRequests;
148 fMonitor = new NullProgressMonitor();
149 }
150
151 @Override
152 public void run() {
0573bfec
MK
153 Display.getDefault().syncExec(new Runnable() {
154 @Override
155 public void run() {
156 updateData(getWindowStartTime(), getWindowEndTime(), fNumRequests, fMonitor);
157 }
158 });
00968516
GB
159 updateThreadFinished(this);
160 }
161
162 public void cancel() {
163 fMonitor.setCanceled(true);
164 }
165 }
166
167 private synchronized void newUpdateThread() {
168 cancelUpdate();
8a328018
FLN
169 if (!getSwtChart().isDisposed()) {
170 final int numRequests = (int) (getSwtChart().getPlotArea().getBounds().width * fResolution);
171 fUpdateThread = new UpdateThread(numRequests);
172 fUpdateThread.start();
173 }
00968516
GB
174 }
175
176 private synchronized void updateThreadFinished(UpdateThread thread) {
177 if (thread == fUpdateThread) {
178 fUpdateThread = null;
179 }
180 }
181
182 /**
183 * Cancels the currently running update thread. It is automatically called
184 * when the content is updated, but child viewers may want to call it
185 * manually to do some operations before calling
186 * {@link TmfCommonXLineChartViewer#updateContent}
187 */
188 protected synchronized void cancelUpdate() {
189 if (fUpdateThread != null) {
190 fUpdateThread.cancel();
191 }
192 }
193
2e427755
GB
194 @Override
195 protected void updateContent() {
196 getDisplay().asyncExec(new Runnable() {
2e427755
GB
197 @Override
198 public void run() {
00968516 199 newUpdateThread();
2e427755
GB
200 }
201 });
202 }
203
204 /**
205 * Convenience method to compute the values of the X axis for a given time
5c75d7d2
GB
206 * range. This method will return at most nb values, equally separated from
207 * start to end. The step between values will be at least 1.0, so the number
208 * of values returned can be lower than nb.
2e427755
GB
209 *
210 * The returned time values are in internal time, ie to get trace time, the
211 * time offset needs to be added to those values.
212 *
213 * @param start
214 * The start time of the time range
215 * @param end
216 * End time of the range
217 * @param nb
5c75d7d2 218 * The maximum number of steps in the x axis.
2e427755
GB
219 * @return The time values (converted to double) to match every step.
220 */
5637b809 221 protected static final double[] getXAxis(long start, long end, int nb) {
2e427755 222 long steps = (end - start);
5c75d7d2
GB
223 int nbVals = nb;
224 if (steps < nb) {
225 nbVals = (int) steps;
226 if (nbVals <= 0) {
227 nbVals = 1;
228 }
229 }
230 double step = steps / (double) nbVals;
2e427755 231
5c75d7d2 232 double timestamps[] = new double[nbVals];
2e427755 233 double curTime = 1;
5c75d7d2 234 for (int i = 0; i < nbVals; i++) {
2e427755
GB
235 timestamps[i] = curTime;
236 curTime += step;
237 }
238 return timestamps;
239 }
240
241 /**
242 * Set the values of the x axis. There is only one array of values for the x
243 * axis for all series of a line chart so it needs to be set once here.
244 *
245 * @param xaxis
246 * The values for the x axis. The values must be in internal
247 * time, ie time offset have been subtracted from trace time
248 * values.
249 */
250 protected final void setXAxis(double[] xaxis) {
251 fXValues = xaxis;
252 }
253
254 /**
255 * Update the series data because the time range has changed. The x axis
256 * values for this data update can be computed using the
c85a741e
GB
257 * {@link TmfCommonXLineChartViewer#getXAxis(long, long, int)} method which
258 * will return a list of uniformely separated time values.
2e427755
GB
259 *
260 * Each series values should be set by calling the
261 * {@link TmfCommonXLineChartViewer#setSeries(String, double[])}.
262 *
263 * This method is responsible for calling the
c85a741e
GB
264 * {@link TmfCommonXLineChartViewer#updateDisplay()} when needed for the new
265 * values to be displayed.
2e427755
GB
266 *
267 * @param start
268 * The start time of the range for which the get the data
269 * @param end
270 * The end time of the range
271 * @param nb
272 * The number of 'points' in the chart.
00968516
GB
273 * @param monitor
274 * The progress monitor object
2e427755 275 */
00968516 276 protected abstract void updateData(long start, long end, int nb, IProgressMonitor monitor);
2e427755
GB
277
278 /**
279 * Set the data for a given series of the graph. The series does not need to
280 * be created before calling this, but it needs to have at least as many
281 * values as the x axis.
282 *
283 * If the series does not exist, it will automatically be created at display
284 * time, with the default values.
285 *
286 * @param seriesName
287 * The name of the series for which to set the values
288 * @param seriesValues
289 * The array of values for the series
290 */
291 protected void setSeries(String seriesName, double[] seriesValues) {
292 if (fXValues.length > seriesValues.length) {
293 throw new IllegalStateException();
294 }
295 fSeriesValues.put(seriesName, seriesValues);
296 }
297
298 /**
299 * Add a new series to the XY line chart. By default, it is a simple solid
300 * line.
301 *
2e427755
GB
302 * @param seriesName
303 * The name of the series to create
304 * @return The series so that the concrete viewer can modify its properties
305 * if required
306 */
307 protected ILineSeries addSeries(String seriesName) {
c85a741e
GB
308 ISeriesSet seriesSet = getSwtChart().getSeriesSet();
309 int seriesCount = seriesSet.getSeries().length;
310 ILineSeries series = (ILineSeries) seriesSet.createSeries(SeriesType.LINE, seriesName);
2e427755
GB
311 series.setVisible(true);
312 series.enableArea(false);
c85a741e 313 series.setLineStyle(LINE_STYLES[(seriesCount / (LINE_COLORS.length)) % LINE_STYLES.length]);
2e427755 314 series.setSymbolType(PlotSymbolType.NONE);
c85a741e 315 series.setLineColor(Display.getDefault().getSystemColor(LINE_COLORS[seriesCount % LINE_COLORS.length]));
2e427755
GB
316 return series;
317 }
318
319 /**
320 * Delete a series from the chart and its values from the viewer.
321 *
322 * @param seriesName
323 * Name of the series to delete
324 */
325 protected void deleteSeries(String seriesName) {
326 ISeries series = getSwtChart().getSeriesSet().getSeries(seriesName);
327 if (series != null) {
328 getSwtChart().getSeriesSet().deleteSeries(series.getId());
329 }
330 fSeriesValues.remove(seriesName);
331 }
332
333 /**
334 * Update the chart's values before refreshing the viewer
335 */
336 protected void updateDisplay() {
337 Display.getDefault().asyncExec(new Runnable() {
338 final TmfChartTimeStampFormat tmfChartTimeStampFormat = new TmfChartTimeStampFormat(getTimeOffset());
339
340 @Override
341 public void run() {
342 if (!getSwtChart().isDisposed()) {
3db04143
FLN
343 double[] xValues = fXValues;
344 if (xValues.length < 1) {
345 return;
346 }
2e427755
GB
347 double maxy = DEFAULT_MAXY;
348 double miny = DEFAULT_MINY;
349 for (Entry<String, double[]> entry : fSeriesValues.entrySet()) {
350 ILineSeries series = (ILineSeries) getSwtChart().getSeriesSet().getSeries(entry.getKey());
351 if (series == null) {
352 series = addSeries(entry.getKey());
353 }
3db04143 354 series.setXSeries(xValues);
2e427755
GB
355 /* Find the minimal and maximum values in this series */
356 for (double value : entry.getValue()) {
357 maxy = Math.max(maxy, value);
358 miny = Math.min(miny, value);
359 }
360 series.setYSeries(entry.getValue());
361 }
9392459a
GB
362 if (maxy == DEFAULT_MAXY) {
363 maxy = 1.0;
364 }
2e427755
GB
365
366 IAxisTick xTick = getSwtChart().getAxisSet().getXAxis(0).getTick();
367 xTick.setFormat(tmfChartTimeStampFormat);
368
3db04143
FLN
369 final double start = xValues[0];
370 int lastX = xValues.length - 1;
371 double end = (start == xValues[lastX]) ? start + 1 : xValues[lastX];
2e427755 372 getSwtChart().getAxisSet().getXAxis(0).setRange(new Range(start, end));
2e427755
GB
373 if (maxy > miny) {
374 getSwtChart().getAxisSet().getYAxis(0).setRange(new Range(miny, maxy));
375 }
376 getSwtChart().redraw();
54404589
MAL
377
378 if (isSendTimeAlignSignals()) {
0573bfec
MK
379 // The width of the chart might have changed and its
380 // time axis might be misaligned with the other views
54404589
MAL
381 Point viewPos = TmfCommonXLineChartViewer.this.getParent().getParent().toDisplay(0, 0);
382 int axisPos = getSwtChart().toDisplay(0, 0).x + getPointAreaOffset();
383 int timeAxisOffset = axisPos - viewPos.x;
384 TmfTimeViewAlignmentInfo timeAlignmentInfo = new TmfTimeViewAlignmentInfo(getControl().getShell(), viewPos, timeAxisOffset);
385 TmfSignalManager.dispatchSignal(new TmfTimeViewAlignmentSignal(TmfCommonXLineChartViewer.this, timeAlignmentInfo, true));
386 }
2e427755
GB
387 }
388 }
389 });
390 }
391
392 /**
393 * Create the series once the initialization of the viewer's data source is
394 * done. Series do not need to be created before setting their values, but
395 * if their appearance needs to be customized, this method is a good place
396 * to do so. It is called only once per trace.
397 */
398 protected void createSeries() {
399
400 }
401
bf06b33c
MK
402 @Override
403 protected void clearContent() {
404 getSwtChart().getAxisSet().getXAxis(0).getTick().setFormat(null);
405 super.clearContent();
406 }
407
2e427755 408}
This page took 0.097286 seconds and 5 git commands to generate.