Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: ec41e4807751ae5cd9c5d7b5aab9b88149dfb57e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
/*******************************************************************************
 * Copyright (c) 2011, 2012 Ericsson
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Francois Chouinard - Initial API and implementation
 *   Bernd Hufmann - Changed to updated histogram data model
 *   Francois Chouinard - Initial API and implementation
 *******************************************************************************/

package org.eclipse.linuxtools.tmf.ui.views.histogram;

import org.eclipse.linuxtools.tmf.ui.views.TmfView;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;

/**
 * Re-usable histogram widget.
 *
 * It has the following features:
 * <ul>
 * <li>Y-axis labels displaying min/max count values
 * <li>X-axis labels displaying time range
 * <li>a histogram displaying the distribution of values over time (note that
 * the histogram might not necessarily fill the whole canvas)
 * </ul>
 * The widget also has 2 'markers' to identify:
 * <ul>
 * <li>a red dashed line over the bar that contains the currently selected event
 * <li>a dark red dashed line that delimits the right end of the histogram (if
 * it doesn't fill the canvas)
 * </ul>
 * Clicking on the histogram will select the current event at the mouse
 * location.
 * <p>
 * Once the histogram is selected, there is some limited keyboard support:
 * <ul>
 * <li>Home: go to the first histogram bar
 * <li>End: go to the last histogram bar
 * <li>Left: go to the previous histogram
 * <li>Right: go to the next histogram bar
 * </ul>
 * Finally, when the mouse hovers over the histogram, a tool tip showing the
 * following information about the corresponding histogram bar time range:
 * <ul>
 * <li>start of the time range
 * <li>end of the time range
 * <li>number of events in that time range
 * </ul>
 *
 * @version 1.0
 * @author Francois Chouinard
 */
public abstract class Histogram implements ControlListener, PaintListener, KeyListener, MouseListener, MouseTrackListener, IHistogramModelListener {

    // ------------------------------------------------------------------------
    // Constants
    // ------------------------------------------------------------------------

    // Histogram colors
    private final Color fBackgroundColor = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE);
    private final Color fCurrentEventColor = Display.getCurrent().getSystemColor(SWT.COLOR_RED);
    private final Color fLastEventColor = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_RED);
    private final Color fHistoBarColor = new Color(Display.getDefault(), 74, 112, 139);

    // Timestamp scale (nanosecond)
    /**
     * The time scale of the histogram (nano seconds)
     */
    public static final byte TIME_SCALE = -9;

    /**
     * The histogram bar width (number of pixels).
     */
    public static final int HISTOGRAM_BAR_WIDTH = 1;

    // ------------------------------------------------------------------------
    // Attributes
    // ------------------------------------------------------------------------

    // Owner view
    /**
     * The parent TMF view.
     */
    protected TmfView fParentView;

    // Histogram text fields
    private Text fMaxNbEventsText;
    private Text fMinNbEventsText;
    private Text fTimeRangeStartText;
    private Text fTimeRangeEndText;

    /**
     *  Histogram drawing area
     */
    protected Canvas fCanvas;
    /**
     *  The histogram data model.
     */
    protected final HistogramDataModel fDataModel;
    /**
     * The histogram data model scaled to current resolution and screen width.
     */
    protected HistogramScaledData fScaledData;

    protected long fCurrentEventTime = 0;

    // ------------------------------------------------------------------------
    // Construction
    // ------------------------------------------------------------------------

    /**
     * Standard constructor.
     *
     * @param view A reference to the parent TMF view.
     * @param parent A parent composite
     */
    public Histogram(final TmfView view, final Composite parent) {
        fParentView = view;

        createWidget(parent);
        fDataModel = new HistogramDataModel();
        fDataModel.addHistogramListener(this);
        clear();

        fCanvas.addControlListener(this);
        fCanvas.addPaintListener(this);
        fCanvas.addKeyListener(this);
        fCanvas.addMouseListener(this);
        fCanvas.addMouseTrackListener(this);
    }

    /**
     * Dispose resources and deregisters listeners.
     */
    public void dispose() {
        fHistoBarColor.dispose();
        fDataModel.removeHistogramListener(this);
    }

    private void createWidget(final Composite parent) {

        final Color labelColor = parent.getBackground();
        final Font fFont = adjustFont(parent);

        final int initalWidth = 10;

        // --------------------------------------------------------------------
        // Define the histogram
        // --------------------------------------------------------------------

        final GridLayout gridLayout = new GridLayout();
        gridLayout.numColumns = 3;
        gridLayout.marginHeight = 0;
        gridLayout.marginWidth = 0;
        gridLayout.marginTop = 0;
        gridLayout.horizontalSpacing = 0;
        gridLayout.verticalSpacing = 0;
        gridLayout.marginLeft = 0;
        gridLayout.marginRight = 0;
        final Composite composite = new Composite(parent, SWT.FILL);
        composite.setLayout(gridLayout);

        // Use all the horizontal space
        GridData gridData = new GridData();
        gridData.horizontalAlignment = SWT.FILL;
        gridData.verticalAlignment = SWT.FILL;
        gridData.grabExcessHorizontalSpace = true;
        composite.setLayoutData(gridData);

        // Y-axis max event
        gridData = new GridData();
        gridData.horizontalAlignment = SWT.RIGHT;
        gridData.verticalAlignment = SWT.TOP;
        fMaxNbEventsText = new Text(composite, SWT.READ_ONLY | SWT.RIGHT);
        fMaxNbEventsText.setFont(fFont);
        fMaxNbEventsText.setBackground(labelColor);
        fMaxNbEventsText.setEditable(false);
        fMaxNbEventsText.setText("0"); //$NON-NLS-1$
        fMaxNbEventsText.setLayoutData(gridData);

        // Histogram itself
        gridData = new GridData();
        gridData.horizontalSpan = 2;
        gridData.verticalSpan = 2;
        gridData.horizontalAlignment = SWT.FILL;
        gridData.verticalAlignment = SWT.FILL;
        gridData.grabExcessHorizontalSpace = true;
        fCanvas = new Canvas(composite, SWT.BORDER | SWT.DOUBLE_BUFFERED);
        fCanvas.setLayoutData(gridData);

        // Y-axis min event (always 0...)
        gridData = new GridData();
        gridData.horizontalAlignment = SWT.RIGHT;
        gridData.verticalAlignment = SWT.BOTTOM;
        fMinNbEventsText = new Text(composite, SWT.READ_ONLY | SWT.RIGHT);
        fMinNbEventsText.setFont(fFont);
        fMinNbEventsText.setBackground(labelColor);
        fMinNbEventsText.setEditable(false);
        fMinNbEventsText.setText("0"); //$NON-NLS-1$
        fMinNbEventsText.setLayoutData(gridData);

        // Dummy cell
        gridData = new GridData(initalWidth, SWT.DEFAULT);
        gridData.horizontalAlignment = SWT.RIGHT;
        gridData.verticalAlignment = SWT.BOTTOM;
        final Text dummyText = new Text(composite, SWT.READ_ONLY);
        dummyText.setFont(fFont);
        dummyText.setBackground(labelColor);
        dummyText.setEditable(false);
        dummyText.setText(""); //$NON-NLS-1$
        dummyText.setLayoutData(gridData);

        // Window range start time
        gridData = new GridData();
        gridData.horizontalAlignment = SWT.LEFT;
        gridData.verticalAlignment = SWT.BOTTOM;
        fTimeRangeStartText = new Text(composite, SWT.READ_ONLY);
        fTimeRangeStartText.setFont(fFont);
        fTimeRangeStartText.setBackground(labelColor);
        fTimeRangeStartText.setText(HistogramUtils.nanosecondsToString(0));
        fTimeRangeStartText.setLayoutData(gridData);

        // Window range end time
        gridData = new GridData();
        gridData.horizontalAlignment = SWT.RIGHT;
        gridData.verticalAlignment = SWT.BOTTOM;
        fTimeRangeEndText = new Text(composite, SWT.READ_ONLY);
        fTimeRangeEndText.setFont(fFont);
        fTimeRangeEndText.setBackground(labelColor);
        fTimeRangeEndText.setText(HistogramUtils.nanosecondsToString(0));
        fTimeRangeEndText.setLayoutData(gridData);
    }

    private static Font adjustFont(final Composite composite) {
        // Reduce font size for a more pleasing rendering
        final int fontSizeAdjustment = -2;
        final Font font = composite.getFont();
        final FontData fontData = font.getFontData()[0];
        return new Font(font.getDevice(), fontData.getName(), fontData.getHeight() + fontSizeAdjustment, fontData.getStyle());
    }

    // ------------------------------------------------------------------------
    // Accessors
    // ------------------------------------------------------------------------

    /**
     * Returns the start time (equal first bucket time).
     * @return the start time.
     */
    public long getStartTime() {
        return fDataModel.getFirstBucketTime();
    }

    /**
     * Returns the end time.
     * @return the end time.
     */
    public long getEndTime() {
        return fDataModel.getEndTime();
    }

    /**
     * Returns the time limit (end of last bucket)
     * @return the time limit.
     */
    public long getTimeLimit() {
        return fDataModel.getTimeLimit();
    }

    /**
     * Returns a data model reference.
     * @return data model.
     */
    public HistogramDataModel getDataModel() {
        return fDataModel;
    }

    // ------------------------------------------------------------------------
    // Operations
    // ------------------------------------------------------------------------
    /**
     * Updates the time range.
     * @param startTime A start time
     * @param endTime A end time.
     */
    public abstract void updateTimeRange(long startTime, long endTime);

    /**
     * Clear the histogram and reset the data
     */
    public void clear() {
        fDataModel.clear();
        fScaledData = null;
    }

    /**
     * Increase the histogram bucket corresponding to [timestamp]
     *
     * @param eventCount
     *            The new event count
     * @param timestamp
     *            The latest timestamp
     */
    public void countEvent(final long eventCount, final long timestamp) {
        fDataModel.countEvent(eventCount, timestamp);
    }

    /**
     * Sets the current event time and refresh the display
     *
     * @param timestamp
     *            The time of the current event
     */
    public void setCurrentEvent(final long timestamp) {
        fCurrentEventTime = (timestamp > 0) ? timestamp : 0;
        fDataModel.setCurrentEventNotifyListeners(timestamp);
    }

    /**
     * Computes the timestamp of the bucket at [offset]
     *
     * @param offset offset from the left on the histogram
     * @return the start timestamp of the corresponding bucket
     */
    public synchronized long getTimestamp(final int offset) {
        assert offset > 0 && offset < fScaledData.fWidth;
        try {
            return fDataModel.getFirstBucketTime() + fScaledData.fBucketDuration * offset;
        } catch (final Exception e) {
            return 0; // TODO: Fix that racing condition (NPE)
        }
    }

    /**
     * Computes the offset of the timestamp in the histogram
     *
     * @param timestamp the timestamp
     * @return the offset of the corresponding bucket (-1 if invalid)
     */
    public synchronized int getOffset(final long timestamp) {
        if (timestamp < fDataModel.getFirstBucketTime() || timestamp > fDataModel.getEndTime()) {
            return -1;
        }
        return (int) ((timestamp - fDataModel.getFirstBucketTime()) / fScaledData.fBucketDuration);
    }

    /**
     * Move the currently selected bar cursor to a non-empty bucket.
     *
     * @param keyCode the SWT key code
     */
    protected void moveCursor(final int keyCode) {

        if (fScaledData.fCurrentBucket == HistogramScaledData.OUT_OF_RANGE_BUCKET) {
            return;
        }

        int index;
        switch (keyCode) {

            case SWT.HOME:
                index = 0;
                while (index < fScaledData.fLastBucket && fScaledData.fData[index] == 0) {
                    index++;
                }
                if (index < fScaledData.fLastBucket) {
                    fScaledData.fCurrentBucket = index;
                }
                break;

            case SWT.ARROW_RIGHT:
                index = fScaledData.fCurrentBucket + 1;
                while (index < fScaledData.fWidth && fScaledData.fData[index] == 0) {
                    index++;
                }
                if (index < fScaledData.fLastBucket) {
                    fScaledData.fCurrentBucket = index;
                }
                break;

            case SWT.END:
                index = fScaledData.fLastBucket;
                while (index >= 0 && fScaledData.fData[index] == 0) {
                    index--;
                }
                if (index >= 0) {
                    fScaledData.fCurrentBucket = index;
                }
                break;

            case SWT.ARROW_LEFT:
                index = fScaledData.fCurrentBucket - 1;
                while (index >= 0 && fScaledData.fData[index] == 0) {
                    index--;
                }
                if (index >= 0) {
                    fScaledData.fCurrentBucket = index;
                }
                break;

            default:
                return;
        }

        updateCurrentEventTime();
    }

    /**
     * Refresh the histogram display
     */
    @Override
    public void modelUpdated() {
        if (!fCanvas.isDisposed() && fCanvas.getDisplay() != null) {
            fCanvas.getDisplay().asyncExec(new Runnable() {
                @Override
                public void run() {
                    if (!fCanvas.isDisposed()) {
                        // Retrieve and normalize the data
                        final int canvasWidth = fCanvas.getBounds().width;
                        final int canvasHeight = fCanvas.getBounds().height;
                        if (canvasWidth <= 0 || canvasHeight <= 0) {
                            return;
                        }
                        fDataModel.setCurrentEvent(fCurrentEventTime);
                        fScaledData = fDataModel.scaleTo(canvasWidth, canvasHeight, HISTOGRAM_BAR_WIDTH);
                        synchronized(fScaledData) {
                            if (fScaledData != null) {
                                fCanvas.redraw();
                                // Display histogram and update X-,Y-axis labels
                                fTimeRangeStartText.setText(HistogramUtils.nanosecondsToString(fDataModel.getFirstBucketTime()));
                                fTimeRangeEndText.setText(HistogramUtils.nanosecondsToString(fDataModel.getEndTime()));
                                fMaxNbEventsText.setText(Long.toString(fScaledData.fMaxValue));
                                // The Y-axis area might need to be re-sized
                                fMaxNbEventsText.getParent().layout();
                            }
                        }
                    }
                }
            });
        }
    }

    // ------------------------------------------------------------------------
    // Helper functions
    // ------------------------------------------------------------------------

    private void updateCurrentEventTime() {
        final long bucketStartTime = getTimestamp(fScaledData.fCurrentBucket);
        ((HistogramView) fParentView).updateCurrentEventTime(bucketStartTime);
    }

    // ------------------------------------------------------------------------
    // PaintListener
    // ------------------------------------------------------------------------
    /**
     * Image key string for the canvas.
     */
    protected final String IMAGE_KEY = "double-buffer-image"; //$NON-NLS-1$

    @Override
    public void paintControl(final PaintEvent event) {

        // Get the geometry
        final int canvasWidth = fCanvas.getBounds().width;
        final int canvasHeight = fCanvas.getBounds().height;

        // Make sure we have something to draw upon
        if (canvasWidth <= 0 || canvasHeight <= 0) {
            return;
        }

        // Retrieve image; re-create only if necessary
        Image image = (Image) fCanvas.getData(IMAGE_KEY);
        if (image == null || image.getBounds().width != canvasWidth || image.getBounds().height != canvasHeight) {
            image = new Image(event.display, canvasWidth, canvasHeight);
            fCanvas.setData(IMAGE_KEY, image);
        }

        // Draw the histogram on its canvas
        final GC imageGC = new GC(image);
        formatImage(imageGC, image);
        event.gc.drawImage(image, 0, 0);
        imageGC.dispose();
    }

    private void formatImage(final GC imageGC, final Image image) {

        if (fScaledData == null) {
            return;
        }

        final HistogramScaledData scaledData = new HistogramScaledData(fScaledData);

        try {
            // Get drawing boundaries
            final int width = image.getBounds().width;
            final int height = image.getBounds().height;

            // Clear the drawing area
            imageGC.setBackground(fBackgroundColor);
            imageGC.fillRectangle(0, 0, image.getBounds().width + 1, image.getBounds().height + 1);

            // Draw the histogram bars
            imageGC.setBackground(fHistoBarColor);
            final int limit = width < scaledData.fWidth ? width : scaledData.fWidth;
            for (int i = 1; i < limit; i++) {
                final int value = (int) (scaledData.fData[i] * scaledData.fScalingFactor);
                imageGC.fillRectangle(i, height - value, 1, value);
            }

            // Draw the current event bar
            final int currentBucket = scaledData.fCurrentBucket;
            if (currentBucket >= 0 && currentBucket < limit) {
                drawDelimiter(imageGC, fCurrentEventColor, height, currentBucket);
            }

            // Add a dashed line as a delimiter (at the right of the last bar)
            int lastEventIndex = limit - 1;
            while (lastEventIndex >= 0 && scaledData.fData[lastEventIndex] == 0) {
                lastEventIndex--;
            }
            lastEventIndex += (lastEventIndex < limit - 1) ? 1 : 0;
            drawDelimiter(imageGC, fLastEventColor, height, lastEventIndex);
        } catch (final Exception e) {
            // Do nothing
        }
    }

    private static void drawDelimiter(final GC imageGC, final Color color,
            final int height, final int index) {
        imageGC.setBackground(color);
        final int dash = height / 4;
        imageGC.fillRectangle(index, 0 * dash, 1, dash - 1);
        imageGC.fillRectangle(index, 1 * dash, 1, dash - 1);
        imageGC.fillRectangle(index, 2 * dash, 1, dash - 1);
        imageGC.fillRectangle(index, 3 * dash, 1, height - 3 * dash);
    }

    // ------------------------------------------------------------------------
    // KeyListener
    // ------------------------------------------------------------------------

    @Override
    public void keyPressed(final KeyEvent event) {
        moveCursor(event.keyCode);
    }

    @Override
    public void keyReleased(final KeyEvent event) {
    }

    // ------------------------------------------------------------------------
    // MouseListener
    // ------------------------------------------------------------------------

    @Override
    public void mouseDoubleClick(final MouseEvent event) {
    }

    @Override
    public void mouseDown(final MouseEvent event) {
        if (fDataModel.getNbEvents() > 0 && fScaledData.fLastBucket >= event.x) {
            fScaledData.fCurrentBucket = event.x;
            updateCurrentEventTime();
        }
    }

    @Override
    public void mouseUp(final MouseEvent event) {
    }

    // ------------------------------------------------------------------------
    // MouseTrackListener
    // ------------------------------------------------------------------------

    @Override
    public void mouseEnter(final MouseEvent event) {
    }

    @Override
    public void mouseExit(final MouseEvent event) {
    }

    @Override
    public void mouseHover(final MouseEvent event) {
        if (fDataModel.getNbEvents() > 0 && fScaledData != null && fScaledData.fLastBucket >= event.x) {
            final String tooltip = formatToolTipLabel(event.x);
            fCanvas.setToolTipText(tooltip);
        }
    }

    private String formatToolTipLabel(final int index) {
        long startTime = fScaledData.getBucketStartTime(fScaledData.fCurrentBucket);
        // negative values are possible if time values came into the model in decreasing order
        if (startTime < 0) {
            startTime = 0;
        }
        final long endTime = fScaledData.getBucketEndTime(fScaledData.fCurrentBucket);
        final int nbEvents = (index >= 0) ? fScaledData.fData[index] : 0;

        final StringBuffer buffer = new StringBuffer();
        buffer.append("Range = ["); //$NON-NLS-1$
        buffer.append(HistogramUtils.nanosecondsToString(startTime));
        buffer.append(","); //$NON-NLS-1$
        buffer.append(HistogramUtils.nanosecondsToString(endTime));
        buffer.append(")\n"); //$NON-NLS-1$
        buffer.append("Event count = "); //$NON-NLS-1$
        buffer.append(nbEvents);
        return buffer.toString();
    }

    // ------------------------------------------------------------------------
    // ControlListener
    // ------------------------------------------------------------------------

    @Override
    public void controlMoved(final ControlEvent event) {
        fDataModel.complete();
    }

    @Override
    public void controlResized(final ControlEvent event) {
        fDataModel.complete();
    }
}

Back to the top