Skip to main content
summaryrefslogtreecommitdiffstats
blob: b2882d7ea10e28971ff478dbfb1dfb87d782ab74 (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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
/*******************************************************************************
 * Copyright (c) 2011, 2013 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 - Reformat histogram labels on format change
 *   Patrick Tasse - Support selection range
 *******************************************************************************/

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

import org.eclipse.linuxtools.tmf.core.signal.TmfSignalHandler;
import org.eclipse.linuxtools.tmf.core.signal.TmfSignalManager;
import org.eclipse.linuxtools.tmf.core.signal.TmfTimestampFormatUpdateSignal;
import org.eclipse.linuxtools.tmf.core.timestamp.ITmfTimestamp;
import org.eclipse.linuxtools.tmf.core.timestamp.TmfTimestamp;
import org.eclipse.linuxtools.tmf.core.timestamp.TmfTimestampDelta;
import org.eclipse.linuxtools.tmf.core.timestamp.TmfTimestampFormat;
import org.eclipse.linuxtools.tmf.ui.views.TmfView;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
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.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.MouseWheelListener;
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.FillLayout;
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.Label;
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.1
 * @author Francois Chouinard
 */
public abstract class Histogram implements ControlListener, PaintListener, KeyListener, MouseListener, MouseMoveListener, MouseTrackListener, IHistogramModelListener {

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

    // Histogram colors
    private final Color fBackgroundColor = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE);
    private final Color fSelectionForegroundColor = Display.getCurrent().getSystemColor(SWT.COLOR_BLUE);
    private final Color fSelectionBackgroundColor = Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
    private final Color fLastEventColor = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_RED);
    private final Color fHistoBarColor = new Color(Display.getDefault(), 74, 112, 139);
    private final Color fLostEventColor = new Color(Display.getCurrent(), 208, 62, 120);
    private final Color fFillColor = Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
    private final Color fTimeRangeColor = new Color(Display.getCurrent(), 255, 128, 0);

    // Drag states
    /**
     * No drag in progress
     * @since 2.2
     */
    protected final int DRAG_NONE = 0;
    /**
     * Drag the selection
     * @since 2.2
     */
    protected final int DRAG_SELECTION = 1;
    /**
     * Drag the time range
     * @since 2.2
     */
    protected final int DRAG_RANGE = 2;
    /**
     * Drag the zoom range
     * @since 2.2
     */
    protected final int DRAG_ZOOM = 3;

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

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

    private Composite fComposite;
    private Font fFont;

    // 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;

    /**
     * The current event value
     */
    protected long fCurrentEventTime = 0L;

    /**
     * The current selection begin time
     */
    private long fSelectionBegin = 0L;

    /**
     * The current selection end time
     */
    private long fSelectionEnd = 0L;

    /**
     * The drag state
     * @see #DRAG_NONE
     * @see #DRAG_SELECTION
     * @see #DRAG_RANGE
     * @see #DRAG_ZOOM
     * @since 2.2
     */
    protected int fDragState = DRAG_NONE;

    /**
     * The button that started a mouse drag, or 0 if no drag in progress
     * @since 2.2
     */
    protected int fDragButton = 0;

    /**
     * The bucket display offset
     */
    private int fOffset = 0;

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

    /**
     * Full 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;

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

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

        TmfSignalManager.register(this);
    }

    /**
     * Dispose resources and unregisters listeners.
     */
    public void dispose() {
        TmfSignalManager.deregister(this);

        fHistoBarColor.dispose();
        fLastEventColor.dispose();
        fTimeRangeColor.dispose();
        fDataModel.removeHistogramListener(this);
    }

    private Composite createWidget(final Composite parent) {

        final Color labelColor = parent.getBackground();
        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;
        gridData.grabExcessVerticalSpace = 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
        Composite canvasComposite = new Composite(composite, SWT.BORDER);
        gridData = new GridData();
        gridData.horizontalSpan = 2;
        gridData.verticalSpan = 2;
        gridData.horizontalAlignment = SWT.FILL;
        gridData.verticalAlignment = SWT.FILL;
        gridData.heightHint = 0;
        gridData.widthHint = 0;
        gridData.grabExcessHorizontalSpace = true;
        gridData.grabExcessVerticalSpace = true;
        canvasComposite.setLayoutData(gridData);
        canvasComposite.setLayout(new FillLayout());
        fCanvas = new Canvas(canvasComposite, SWT.DOUBLE_BUFFERED);

        // 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 Label dummyLabel = new Label(composite, SWT.NONE);
        dummyLabel.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.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.setLayoutData(gridData);

        FocusListener listener = new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                fCanvas.setFocus();
            }
        };
        fMaxNbEventsText.addFocusListener(listener);
        fMinNbEventsText.addFocusListener(listener);
        fTimeRangeStartText.addFocusListener(listener);
        fTimeRangeEndText.addFocusListener(listener);

        return composite;
    }

    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;
    }

    /**
     * Returns the text control for the maximum of events in one bar
     *
     * @return the text control
     * @since 2.2
     */
    public Text getMaxNbEventsText() {
        return fMaxNbEventsText;
    }

    // ------------------------------------------------------------------------
    // Operations
    // ------------------------------------------------------------------------
    /**
     * Updates the time range.
     * @param startTime A start time
     * @param endTime A end time.
     */
    public void updateTimeRange(long startTime, long endTime) {
        if (fDragState == DRAG_NONE) {
            ((HistogramView) fParentView).updateTimeRange(startTime, endTime);
        }
    }

    /**
     * Clear the histogram and reset the data
     */
    public void clear() {
        fDataModel.clear();
        synchronized (fDataModel) {
            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
     * @deprecated As of 2.1, use {@link #setSelection(long, long)}
     */
    @Deprecated
    public void setCurrentEvent(final long timestamp) {
        fSelectionBegin = (timestamp > 0) ? timestamp : 0;
        fSelectionEnd = (timestamp > 0) ? timestamp : 0;
        fDataModel.setSelectionNotifyListeners(timestamp, timestamp);
    }

    /**
     * Sets the current selection time range and refresh the display
     *
     * @param beginTime The begin time of the current selection
     * @param endTime The end time of the current selection
     * @since 2.1
     */
    public void setSelection(final long beginTime, final long endTime) {
        fSelectionBegin = (beginTime > 0) ? beginTime : 0;
        fSelectionEnd = (endTime > 0) ? endTime : 0;
        fDataModel.setSelectionNotifyListeners(beginTime, endTime);
    }

    /**
     * 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 fScaledData.fFirstBucketTime + 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);
    }

    /**
     * Set the bucket display offset
     *
     * @param offset
     *            the bucket display offset
     * @since 2.2
     */
    protected void setOffset(final int offset) {
        fOffset = offset;
    }

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

        int index;
        switch (keyCode) {

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

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

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

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

        default:
            return;
        }

        fScaledData.fSelectionEndBucket = fScaledData.fSelectionBeginBucket;
        fSelectionBegin = getTimestamp(fScaledData.fSelectionBeginBucket);
        fSelectionEnd = fSelectionBegin;
        updateSelectionTime();
    }

    /**
     * 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.setSelection(fSelectionBegin, fSelectionEnd);
                        fScaledData = fDataModel.scaleTo(canvasWidth, canvasHeight, 1);
                        synchronized (fDataModel) {
                            if (fScaledData != null) {
                                fCanvas.redraw();
                                // Display histogram and update X-,Y-axis labels
                                updateRangeTextControls();
                                long maxNbEvents = HistogramScaledData.hideLostEvents ? fScaledData.fMaxValue : fScaledData.fMaxCombinedValue;
                                fMaxNbEventsText.setText(Long.toString(maxNbEvents));
                                // The Y-axis area might need to be re-sized
                                GridData gd = (GridData) fMaxNbEventsText.getLayoutData();
                                gd.widthHint = Math.max(gd.widthHint, fMaxNbEventsText.computeSize(SWT.DEFAULT, SWT.DEFAULT).x);
                                fMaxNbEventsText.getParent().layout();
                            }
                        }
                    }
                }
            });
        }
    }

    /**
     * Add a mouse wheel listener to the histogram
     * @param listener the mouse wheel listener
     * @since 2.0
     */
    public void addMouseWheelListener(MouseWheelListener listener) {
        fCanvas.addMouseWheelListener(listener);
    }

    /**
     * Remove a mouse wheel listener from the histogram
     * @param listener the mouse wheel listener
     * @since 2.0
     */
    public void removeMouseWheelListener(MouseWheelListener listener) {
        fCanvas.removeMouseWheelListener(listener);
    }

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

    private void updateSelectionTime() {
        if (fSelectionBegin > fSelectionEnd) {
            long end = fSelectionBegin;
            fSelectionBegin = fSelectionEnd;
            fSelectionEnd = end;
        }
        ((HistogramView) fParentView).updateSelectionTime(fSelectionBegin, fSelectionEnd);
    }

    /**
     * Update the range text controls
     */
    private void updateRangeTextControls() {
        if (fDataModel != null && fDataModel.getStartTime() < fDataModel.getEndTime()) {
            fTimeRangeStartText.setText(TmfTimestampFormat.getDefaulTimeFormat().format(fDataModel.getStartTime()));
            fTimeRangeEndText.setText(TmfTimestampFormat.getDefaulTimeFormat().format(fDataModel.getEndTime()));
        } else {
            fTimeRangeStartText.setText(""); //$NON-NLS-1$
            fTimeRangeEndText.setText(""); //$NON-NLS-1$
        }
    }

    // ------------------------------------------------------------------------
    // 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;

            // Turn off anti-aliasing
            int aliasing = imageGC.getAntialias();
            imageGC.setAntialias(SWT.OFF);

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

            // Draw the histogram bars
            final int limit = width < scaledData.fWidth ? width : scaledData.fWidth;
            double factor = HistogramScaledData.hideLostEvents ? scaledData.fScalingFactor : scaledData.fScalingFactorCombined;
            for (int i = 0; i < limit; i++) {
                final int value = (int) Math.ceil(scaledData.fData[i] * factor);
                int x = i + fOffset;

                // in Linux, the last pixel in a line is not drawn,
                // so draw lost events first, one pixel too far
                if (!HistogramScaledData.hideLostEvents) {
                    imageGC.setForeground(fLostEventColor);
                    final int lostEventValue = (int) Math.ceil(scaledData.fLostEventsData[i] * factor);
                    if (lostEventValue != 0) {
                        // drawing a line is inclusive, so we should remove 1 from y2
                        // but we don't because Linux
                        imageGC.drawLine(x, height - value - lostEventValue, x, height - value);
                    }
                }

                // then draw normal events second, to overwrite that extra pixel
                imageGC.setForeground(fHistoBarColor);
                imageGC.drawLine(x, height - value, x, height);
            }

            // Draw the selection bars
            int alpha = imageGC.getAlpha();
            imageGC.setAlpha(100);
            imageGC.setForeground(fSelectionForegroundColor);
            imageGC.setBackground(fSelectionBackgroundColor);
            final int beginBucket = scaledData.fSelectionBeginBucket + fOffset;
            if (beginBucket >= 0 && beginBucket < limit) {
                imageGC.drawLine(beginBucket, 0, beginBucket, height);
            }
            final int endBucket = scaledData.fSelectionEndBucket + fOffset;
            if (endBucket >= 0 && endBucket < limit && endBucket != beginBucket) {
                imageGC.drawLine(endBucket, 0, endBucket, height);
            }
            if (Math.abs(endBucket - beginBucket) > 1) {
                if (endBucket > beginBucket) {
                    imageGC.fillRectangle(beginBucket + 1, 0, endBucket - beginBucket - 1, height);
                } else {
                    imageGC.fillRectangle(endBucket + 1, 0, beginBucket - endBucket - 1, height);
                }
            }
            imageGC.setAlpha(alpha);

            // Add a dashed line as a delimiter
            int delimiterIndex = (int) ((getDataModel().getEndTime() - scaledData.getFirstBucketTime()) / scaledData.fBucketDuration) + 1;
            drawDelimiter(imageGC, fLastEventColor, height, delimiterIndex);

            // Fill the area to the right of delimiter with background color
            imageGC.setBackground(fFillColor);
            imageGC.fillRectangle(delimiterIndex + 1, 0, width - (delimiterIndex + 1), height);

            // Restore anti-aliasing
            imageGC.setAntialias(aliasing);

        } 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);
    }

    /**
     * Draw a time range window
     *
     * @param imageGC
     *            the GC
     * @param rangeStartTime
     *            the range start time
     * @param rangeDuration
     *            the range duration
     * @since 2.2
     */
    protected void drawTimeRangeWindow(GC imageGC, long rangeStartTime, long rangeDuration) {

        if (fScaledData == null) {
            return;
        }

        // Map times to histogram coordinates
        long bucketSpan = Math.max(fScaledData.fBucketDuration, 1);
        long startTime = Math.min(rangeStartTime, rangeStartTime + rangeDuration);
        int rangeWidth = (int) (Math.abs(rangeDuration) / bucketSpan);

        int left = (int) ((startTime - fDataModel.getFirstBucketTime()) / bucketSpan);
        int right = left + rangeWidth;
        int center = (left + right) / 2;
        int height = fCanvas.getSize().y;
        int arc = Math.min(15, rangeWidth);

        // Draw the selection window
        imageGC.setForeground(fTimeRangeColor);
        imageGC.setLineWidth(1);
        imageGC.setLineStyle(SWT.LINE_SOLID);
        imageGC.drawRoundRectangle(left, 0, rangeWidth, height - 1, arc, arc);

        // Fill the selection window
        imageGC.setBackground(fTimeRangeColor);
        imageGC.setAlpha(35);
        imageGC.fillRoundRectangle(left + 1, 1, rangeWidth - 1, height - 2, arc, arc);
        imageGC.setAlpha(255);

        // Draw the cross hair
        imageGC.setForeground(fTimeRangeColor);
        imageGC.setLineWidth(1);
        imageGC.setLineStyle(SWT.LINE_SOLID);

        int chHalfWidth = ((rangeWidth < 60) ? (rangeWidth * 2) / 3 : 40) / 2;
        imageGC.drawLine(center - chHalfWidth, height / 2, center + chHalfWidth, height / 2);
        imageGC.drawLine(center, (height / 2) - chHalfWidth, center, (height / 2) + chHalfWidth);
    }

    // ------------------------------------------------------------------------
    // 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 (fScaledData != null && event.button == 1 && fDragState == DRAG_NONE && fDataModel.getNbEvents() != 0) {
            fDragState = DRAG_SELECTION;
            fDragButton = event.button;
            if ((event.stateMask & SWT.MODIFIER_MASK) == SWT.SHIFT) {
                if (Math.abs(event.x - fScaledData.fSelectionBeginBucket) < Math.abs(event.x - fScaledData.fSelectionEndBucket)) {
                    fScaledData.fSelectionBeginBucket = fScaledData.fSelectionEndBucket;
                    fSelectionBegin = fSelectionEnd;
                }
                fSelectionEnd = Math.min(getTimestamp(event.x), getEndTime());
                fScaledData.fSelectionEndBucket = (int) ((fSelectionEnd - fScaledData.fFirstBucketTime) / fScaledData.fBucketDuration);
            } else {
                fSelectionBegin = Math.min(getTimestamp(event.x), getEndTime());
                fScaledData.fSelectionBeginBucket = (int) ((fSelectionBegin - fScaledData.fFirstBucketTime) / fScaledData.fBucketDuration);
                fSelectionEnd = fSelectionBegin;
                fScaledData.fSelectionEndBucket = fScaledData.fSelectionBeginBucket;
            }
            fCanvas.redraw();
        }
    }

    @Override
    public void mouseUp(final MouseEvent event) {
        if (fDragState == DRAG_SELECTION && event.button == fDragButton) {
            fDragState = DRAG_NONE;
            fDragButton = 0;
            updateSelectionTime();
        }
    }

    // ------------------------------------------------------------------------
    // MouseMoveListener
    // ------------------------------------------------------------------------

    /**
     * @since 2.2
     */
    @Override
    public void mouseMove(MouseEvent event) {
        if (fDragState == DRAG_SELECTION && fDataModel.getNbEvents() > 0) {
            fSelectionEnd = Math.max(getStartTime(), Math.min(getEndTime(), getTimestamp(event.x)));
            fScaledData.fSelectionEndBucket = (int) ((fSelectionEnd - fScaledData.fFirstBucketTime) / fScaledData.fBucketDuration);
            fCanvas.redraw();
        }
    }

    // ------------------------------------------------------------------------
    // 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) {
            int delimiterIndex = (int) ((fDataModel.getEndTime() - fScaledData.getFirstBucketTime()) / fScaledData.fBucketDuration) + 1;
            if (event.x < delimiterIndex) {
                final String tooltip = formatToolTipLabel(event.x - fOffset);
                fCanvas.setToolTipText(tooltip);
                return;
            }
        }
        fCanvas.setToolTipText(null);
    }

    private String formatToolTipLabel(final int index) {
        long startTime = fScaledData.getBucketStartTime(index);
        // negative values are possible if time values came into the model in decreasing order
        if (startTime < 0) {
            startTime = 0;
        }
        final long endTime = fScaledData.getBucketEndTime(index);
        final int nbEvents = (index >= 0) ? fScaledData.fData[index] : 0;
        final String newLine = System.getProperty("line.separator"); //$NON-NLS-1$
        final StringBuffer buffer = new StringBuffer();
        int selectionBeginBucket = Math.min(fScaledData.fSelectionBeginBucket, fScaledData.fSelectionEndBucket);
        int selectionEndBucket = Math.max(fScaledData.fSelectionBeginBucket, fScaledData.fSelectionEndBucket);
        if (selectionBeginBucket <= index && index <= selectionEndBucket && fSelectionBegin != fSelectionEnd) {
            TmfTimestampDelta delta = new TmfTimestampDelta(Math.abs(fSelectionEnd - fSelectionBegin), ITmfTimestamp.NANOSECOND_SCALE);
            buffer.append(NLS.bind(Messages.Histogram_selectionSpanToolTip, delta.toString()));
            buffer.append(newLine);
        }
        buffer.append(NLS.bind(Messages.Histogram_bucketRangeToolTip,
                new TmfTimestamp(startTime, ITmfTimestamp.NANOSECOND_SCALE).toString(),
                new TmfTimestamp(endTime, ITmfTimestamp.NANOSECOND_SCALE).toString()));
        buffer.append(newLine);
        buffer.append(NLS.bind(Messages.Histogram_eventCountToolTip, nbEvents));
        if (!HistogramScaledData.hideLostEvents) {
            final int nbLostEvents = (index >= 0) ? fScaledData.fLostEventsData[index] : 0;
            buffer.append(newLine);
            buffer.append(NLS.bind(Messages.Histogram_lostEventCountToolTip, nbLostEvents));
        }
        return buffer.toString();
    }

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

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

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

    // ------------------------------------------------------------------------
    // Signal Handlers
    // ------------------------------------------------------------------------

    /**
     * Format the timestamp and update the display
     *
     * @param signal
     *            the incoming signal
     * @since 2.0
     */
    @TmfSignalHandler
    public void timestampFormatUpdated(TmfTimestampFormatUpdateSignal signal) {
        if (fDataModel.getNbEvents() == 0) {
            return;
        }

        updateRangeTextControls();

        fComposite.layout();
    }

}

Back to the top