1 /*****************************************************************************
2 * Copyright (c) 2007, 2017 Intel Corporation, Ericsson
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
9 * Intel Corporation - Initial API and implementation
10 * Ruslan A. Scherbakov, Intel - Initial API and implementation
11 * Alvaro Sanchez-Leon - Udpated for TMF
12 * Patrick Tasse - Refactoring
13 * Marc-Andre Laperle - Add time zone preference
14 *****************************************************************************/
16 package org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.widgets
;
18 import java
.text
.NumberFormat
;
19 import java
.text
.SimpleDateFormat
;
20 import java
.util
.Date
;
21 import java
.util
.Iterator
;
22 import java
.util
.TimeZone
;
23 import java
.util
.concurrent
.TimeUnit
;
25 import org
.eclipse
.jdt
.annotation
.NonNull
;
26 import org
.eclipse
.swt
.SWT
;
27 import org
.eclipse
.swt
.graphics
.Color
;
28 import org
.eclipse
.swt
.graphics
.Device
;
29 import org
.eclipse
.swt
.graphics
.GC
;
30 import org
.eclipse
.swt
.graphics
.Point
;
31 import org
.eclipse
.swt
.graphics
.RGB
;
32 import org
.eclipse
.swt
.graphics
.Rectangle
;
33 import org
.eclipse
.swt
.widgets
.Display
;
34 import org
.eclipse
.tracecompass
.common
.core
.format
.DecimalUnitFormat
;
35 import org
.eclipse
.tracecompass
.internal
.tmf
.ui
.Messages
;
36 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimePreferences
;
37 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.model
.ITimeEvent
;
38 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.model
.ITimeGraphEntry
;
41 * General utilities and definitions used by the time graph widget
43 * @author Alvaro Sanchez-Leon
44 * @author Patrick Tasse
51 /** Time format for dates and timestamp */
52 public enum TimeFormat
{
53 /** Relative to the start of the trace */
57 * Absolute timestamp (ie, relative to the Unix epoch)
62 * Timestamp displayed as a simple number
67 * Timestamp displayed as cycles
73 * Timestamp resolution
75 public static enum Resolution
{
90 * Ellipsis character, used to shorten strings that don't fit in their
95 public static final String ELLIPSIS
= "…"; //$NON-NLS-1$
97 private static final SimpleDateFormat TIME_FORMAT
= new SimpleDateFormat("HH:mm:ss"); //$NON-NLS-1$
98 private static final SimpleDateFormat DATE_FORMAT
= new SimpleDateFormat("yyyy-MM-dd"); //$NON-NLS-1$
99 private static final long HOURS_PER_DAY
= 24;
100 private static final long MIN_PER_HOUR
= 60;
101 private static final long SEC_PER_MIN
= 60;
102 private static final long SEC_IN_NS
= 1000000000;
103 private static final long MILLISEC_IN_NS
= 1000000;
106 * Update the time and date formats to use the current time zone
108 public static void updateTimeZone() {
109 TimeZone timeZone
= TmfTimePreferences
.getTimeZone();
110 TIME_FORMAT
.setTimeZone(timeZone
);
111 DATE_FORMAT
.setTimeZone(timeZone
);
114 static Rectangle
clone(Rectangle source
) {
115 return new Rectangle(source
.x
, source
.y
, source
.width
, source
.height
);
119 * Initialize a Rectangle object to default values (all equal to 0)
122 * The Rectangle to initialize
124 public static void init(Rectangle rect
) {
132 * Initialize a Rectangle object with all the given values
135 * The Rectangle object to initialize
141 * The width of the rectangle
143 * The height of the rectangle
145 public static void init(Rectangle rect
, int x
, int y
, int width
, int height
) {
149 rect
.height
= height
;
153 * Initialize a Rectangle object to another existing Rectangle's values.
156 * The Rectangle to initialize
158 * The reference Rectangle to copy
160 public static void init(Rectangle rect
, Rectangle source
) {
163 rect
.width
= source
.width
;
164 rect
.height
= source
.height
;
168 * Reduce the size of a given rectangle by the given amounts.
171 * The rectangle to modify
173 * The reduction in width
175 * The reduction in height
177 public static void deflate(Rectangle rect
, int x
, int y
) {
181 rect
.height
-= y
+ y
;
185 * Increase the size of a given rectangle by the given amounts.
188 * The rectangle to modify
190 * The augmentation in width
192 * The augmentation in height
194 public static void inflate(Rectangle rect
, int x
, int y
) {
198 rect
.height
+= y
+ y
;
201 static void dispose(Color col
) {
208 * Get the resulting color from a mix of two existing ones for a given
212 * The display device (which might affect the color conversion)
218 * The gamma level for color 1
220 * The gamma level for color 2
221 * @return The resulting color
223 public static Color
mixColors(Device display
, Color c1
, Color c2
, int w1
,
225 return new Color(display
, (w1
* c1
.getRed() + w2
* c2
.getRed())
226 / (w1
+ w2
), (w1
* c1
.getGreen() + w2
* c2
.getGreen())
227 / (w1
+ w2
), (w1
* c1
.getBlue() + w2
* c2
.getBlue())
232 * Get the system color with the given ID.
236 * @return The resulting color
238 public static Color
getSysColor(int id
) {
239 Color col
= Display
.getCurrent().getSystemColor(id
);
240 return new Color(col
.getDevice(), col
.getRGB());
244 * Get the resulting color from a mix of two existing ones for the current
252 * The gamma level for color 1
254 * The gamma level for color 2
255 * @return The resulting color
257 public static Color
mixColors(Color col1
, Color col2
, int w1
, int w2
) {
258 return mixColors(Display
.getCurrent(), col1
, col2
, w1
, w2
);
262 * Get a distinct color from the specified RGB color, based on its
263 * relative luminance.
267 * @return The black or white system color, whichever is more distinct.
270 public static Color
getDistinctColor(RGB rgb
) {
271 /* Calculate the relative luminance of the color, high value is bright */
272 final int luminanceThreshold
= 128;
273 /* Relative luminance (Y) coefficients as defined in ITU.R Rec. 709 */
274 final double redCoefficient
= 0.2126;
275 final double greenCoefficient
= 0.7152;
276 final double blueCoefficient
= 0.0722;
277 int luminance
= (int) (redCoefficient
* rgb
.red
+ greenCoefficient
* rgb
.green
+ blueCoefficient
* rgb
.blue
);
278 /* Use black over bright colors and white over dark colors */
279 return Display
.getDefault().getSystemColor(
280 luminance
> luminanceThreshold ? SWT
.COLOR_BLACK
: SWT
.COLOR_WHITE
);
284 * Draw text in a rectangle.
291 * The rectangle object which is being drawn
293 * If true the background will be transparent
294 * @return The width of the written text
296 public static int drawText(GC gc
, String text
, Rectangle rect
, boolean transp
) {
297 Point size
= gc
.stringExtent(text
);
298 gc
.drawText(text
, rect
.x
, rect
.y
, transp
);
303 * Draw text at a given location.
310 * The X coordinate of the starting point
312 * the Y coordinate of the starting point
314 * If true the background will be transparent
315 * @return The width of the written text
317 public static int drawText(GC gc
, String text
, int x
, int y
, boolean transp
) {
318 Point size
= gc
.stringExtent(text
);
319 gc
.drawText(text
, x
, y
, transp
);
324 * Draw text in a rectangle, trimming the text to prevent exceeding the specified width.
329 * The string to be drawn
331 * The x coordinate of the top left corner of the rectangular area where the text is to be drawn
333 * The y coordinate of the top left corner of the rectangular area where the text is to be drawn
335 * The width of the area to be drawn
337 * The height of the area to be drawn
339 * If <code>true</code> the text will be centered in the available area if space permits
340 * @param isTransparent
341 * If <code>true</code> the background will be transparent, otherwise it will be opaque
342 * @return The number of characters written
345 public static int drawText(GC gc
, String text
, int x
, int y
, int width
, int height
, boolean isCentered
, boolean isTransparent
) {
346 if (width
< 1 || text
.isEmpty()) {
350 String stringToDisplay
;
353 boolean isCenteredWidth
= isCentered
;
357 /* First check if the whole string fits */
358 Point textExtent
= gc
.textExtent(text
);
359 if (textExtent
.x
<= width
) {
361 stringToDisplay
= text
;
364 * The full string doesn't fit, try to find the longest one with
365 * "..." at the end that does fit.
367 * Iterate on the string length sizes, starting from 1 going up,
368 * until we find a string that does not fit. Once we do, we keep the
369 * one just before that did fit.
371 isCenteredWidth
= false;
374 while (len
<= text
.length()) {
375 textExtent
= gc
.textExtent(text
.substring(0, len
) + ELLIPSIS
);
376 if (textExtent
.x
> width
) {
378 * Here is the first length that does not fit, the one from
379 * the previous iteration is the one we will use.
384 /* This string would fit, try the next one */
388 stringToDisplay
= text
.substring(0, len
) + ELLIPSIS
;
392 /* Nothing fits, we end up drawing nothing */
396 if (isCenteredWidth
) {
397 realX
+= (width
- textExtent
.x
) / 2;
400 realY
+= (height
- textExtent
.y
) / 2 - 1;
402 gc
.drawText(stringToDisplay
, realX
, realY
, isTransparent
);
408 * Formats time in format: MM:SS:NNN
411 * @param format 0: MMMM:ss:nnnnnnnnn, 1: HH:MM:ss MMM.mmmm.nnn
412 * @param resolution the resolution
413 * @return the formatted time
415 public static String
formatTime(long time
, TimeFormat format
, Resolution resolution
) {
418 return formatTimeAbs(time
, resolution
);
420 return NumberFormat
.getInstance().format(time
);
422 return NumberFormat
.getInstance().format(time
) + Messages
.Utils_ClockCyclesUnit
;
427 StringBuffer str
= new StringBuffer();
435 long sec
= t
/ SEC_IN_NS
;
437 String ns
= formatNs(t
, resolution
);
438 if (!ns
.equals("")) { //$NON-NLS-1$
443 return str
.toString();
447 * From input time in nanoseconds, convert to Date format YYYY-MM-dd
450 * The source time, in ns
451 * @return the formatted date
453 public static String
formatDate(long absTime
) {
454 String sdate
= DATE_FORMAT
.format(new Date(absTime
/ MILLISEC_IN_NS
));
459 * Formats time in ns to Calendar format: HH:MM:SS MMM.mmm.nnn
462 * The source time, in ns
464 * The resolution to use
465 * @return the formatted time
467 public static String
formatTimeAbs(long time
, Resolution res
) {
468 StringBuffer str
= new StringBuffer();
470 // format time from nanoseconds to calendar time HH:MM:SS
471 String stime
= TIME_FORMAT
.format(new Date(time
/ MILLISEC_IN_NS
));
473 String ns
= formatNs(time
, res
);
477 * append the Milliseconds, MicroSeconds and NanoSeconds as
478 * specified in the Resolution
482 return str
.toString();
489 * The time delta, in ns
491 * The time format to use
493 * The resolution to use
494 * @return the formatted time delta
496 public static String
formatDelta(long delta
, TimeFormat format
, Resolution resolution
) {
497 if (format
== TimeFormat
.CALENDAR
) {
498 return formatDeltaAbs(delta
, resolution
);
500 return formatTime(delta
, format
, resolution
);
504 * Formats time delta in ns to Calendar format, only formatting the years,
505 * days, hours or minutes if necessary.
508 * The time delta, in ns
510 * The resolution to use
511 * @return the formatted time delta
513 public static String
formatDeltaAbs(long delta
, Resolution resolution
) {
514 StringBuffer str
= new StringBuffer();
518 long ns
= Math
.abs(delta
);
519 long seconds
= TimeUnit
.NANOSECONDS
.toSeconds(ns
);
520 long minutes
= TimeUnit
.NANOSECONDS
.toMinutes(ns
);
521 long hours
= TimeUnit
.NANOSECONDS
.toHours(ns
);
522 long days
= TimeUnit
.NANOSECONDS
.toDays(ns
);
525 str
.append("d "); //$NON-NLS-1$
528 str
.append(hours
% HOURS_PER_DAY
);
529 str
.append("h "); //$NON-NLS-1$
532 str
.append(minutes
% MIN_PER_HOUR
);
533 str
.append("m "); //$NON-NLS-1$
535 str
.append(seconds
% SEC_PER_MIN
);
537 // append the ms, us and ns as specified in the resolution
538 str
.append(formatNs(delta
, resolution
));
539 str
.append("s"); //$NON-NLS-1$
541 str
.append(" ("); //$NON-NLS-1$
542 str
.append(new DecimalUnitFormat(1.0 / SEC_IN_NS
).format(delta
));
543 str
.append("s)"); //$NON-NLS-1$
545 return str
.toString();
549 * Obtains the remainder fraction on unit Seconds of the entered value in
550 * nanoseconds. e.g. input: 1241207054171080214 ns The number of fraction
551 * seconds can be obtained by removing the last 9 digits: 1241207054 the
552 * fractional portion of seconds, expressed in ns is: 171080214
555 * The source time in ns
557 * The Resolution to use
558 * @return the formatted nanosec
560 public static String
formatNs(long srcTime
, Resolution res
) {
561 StringBuffer str
= new StringBuffer();
562 long ns
= Math
.abs(srcTime
% SEC_IN_NS
);
563 String nanos
= Long
.toString(ns
);
564 str
.append("000000000".substring(nanos
.length())); //$NON-NLS-1$
567 if (res
== Resolution
.MILLISEC
) {
568 return str
.substring(0, 3);
569 } else if (res
== Resolution
.MICROSEC
) {
570 return str
.substring(0, 6);
571 } else if (res
== Resolution
.NANOSEC
) {
572 return str
.substring(0, 9);
574 return ""; //$NON-NLS-1$
578 * FIXME Currently does nothing.
585 * The minimal accepted value
587 * The maximal accepted value
588 * @return The value that was read
590 public static int loadIntOption(String opt
, int def
, int min
, int max
) {
595 * FIXME currently does nothing
602 public static void saveIntOption(String opt
, int val
) {
605 static ITimeEvent
getFirstEvent(ITimeGraphEntry entry
) {
606 if (null == entry
|| ! entry
.hasTimeEvents()) {
609 Iterator
<?
extends ITimeEvent
> iterator
= entry
.getTimeEventsIterator();
610 if (iterator
!= null && iterator
.hasNext()) {
611 return iterator
.next();
617 * Gets the {@link ITimeEvent} at the given time from the given
618 * {@link ITimeGraphEntry}.
621 * a {@link ITimeGraphEntry}
625 * this parameter means: <list> <li>-1: Previous Event</li> <li>
626 * 0: Current Event</li> <li>
627 * 1: Next Event</li> <li>2: Previous Event when located in a non
629 * @return a {@link ITimeEvent}, or <code>null</code>.
631 public static ITimeEvent
findEvent(ITimeGraphEntry entry
, long time
, int n
) {
632 if (null == entry
|| ! entry
.hasTimeEvents()) {
635 Iterator
<@NonNull ?
extends ITimeEvent
> iterator
= entry
.getTimeEventsIterator();
636 if (iterator
== null) {
639 ITimeEvent nextEvent
= null;
640 ITimeEvent currEvent
= null;
641 ITimeEvent prevEvent
= null;
643 while (iterator
.hasNext()) {
644 nextEvent
= iterator
.next();
645 long nextStartTime
= nextEvent
.getTime();
647 if (nextStartTime
> time
) {
651 if (currEvent
== null || currEvent
.getTime() != nextStartTime
||
652 (nextStartTime
!= time
&& currEvent
.getDuration() != nextEvent
.getDuration())) {
653 prevEvent
= currEvent
;
654 currEvent
= nextEvent
;
658 if (n
== -1) { //previous
659 if (currEvent
!= null && currEvent
.getTime() + currEvent
.getDuration() >= time
) {
663 } else if (n
== 0) { //current
664 if (currEvent
!= null && currEvent
.getTime() + currEvent
.getDuration() >= time
) {
668 } else if (n
== 1) { //next
669 if (nextEvent
!= null && nextEvent
.getTime() > time
) {
673 } else if (n
== 2) { //current or previous when in empty space
681 * Pretty-print a method signature.
684 * The original signature
685 * @return The pretty signature
687 public static String
fixMethodSignature(String origSig
) {
688 String sig
= origSig
;
689 int pos
= sig
.indexOf('(');
691 String ret
= sig
.substring(0, pos
);
692 sig
= sig
.substring(pos
);
693 sig
= sig
+ " " + ret
; //$NON-NLS-1$
699 * Restore an original method signature from a pretty-printed one.
702 * The pretty-printed signature
703 * @return The original method signature
705 public static String
restoreMethodSignature(String ppSig
) {
706 String ret
= ""; //$NON-NLS-1$
709 int pos
= sig
.indexOf('(');
711 ret
= sig
.substring(0, pos
);
712 sig
= sig
.substring(pos
+ 1);
714 pos
= sig
.indexOf(')');
716 sig
= sig
.substring(0, pos
);
718 String args
[] = sig
.split(","); //$NON-NLS-1$
719 StringBuffer result
= new StringBuffer("("); //$NON-NLS-1$
720 for (int i
= 0; i
< args
.length
; i
++) {
721 String arg
= args
[i
].trim();
722 if (arg
.length() == 0 && args
.length
== 1) {
725 result
.append(getTypeSignature(arg
));
727 result
.append(")").append(getTypeSignature(ret
)); //$NON-NLS-1$
728 return result
.toString();
732 * Get the mangled type information from an array of types.
735 * The types to convert. See method implementation for what it
737 * @return The mangled string of types
739 public static String
getTypeSignature(String typeStr
) {
741 String type
= typeStr
;
742 for (int j
= 0; j
< type
.length(); j
++) {
743 if (type
.charAt(j
) == '[') {
747 int pos
= type
.indexOf('[');
749 type
= type
.substring(0, pos
);
751 StringBuffer sig
= new StringBuffer(""); //$NON-NLS-1$
752 for (int j
= 0; j
< dim
; j
++)
754 sig
.append("["); //$NON-NLS-1$
756 if (type
.equals("boolean")) { //$NON-NLS-1$
758 } else if (type
.equals("byte")) { //$NON-NLS-1$
760 } else if (type
.equals("char")) { //$NON-NLS-1$
762 } else if (type
.equals("short")) { //$NON-NLS-1$
764 } else if (type
.equals("int")) { //$NON-NLS-1$
766 } else if (type
.equals("long")) { //$NON-NLS-1$
768 } else if (type
.equals("float")) { //$NON-NLS-1$
770 } else if (type
.equals("double")) { //$NON-NLS-1$
772 } else if (type
.equals("void")) { //$NON-NLS-1$
776 sig
.append('L').append(type
.replace('.', '/')).append(';');
778 return sig
.toString();
782 * Compare two doubles together.
788 * @return 1 if they are different, and 0 if they are *exactly* the same.
789 * Because of the way doubles are stored, it's possible for the
790 * same number obtained in two different ways to actually look
793 public static int compare(double d1
, double d2
) {
804 * Compare two character strings alphabetically. This is simply a wrapper
805 * around String.compareToIgnoreCase but that will handle cases where
806 * strings can be null
812 * @return A number below, equal, or greater than zero if the first string
813 * is smaller, equal, or bigger (alphabetically) than the second
816 public static int compare(String s1
, String s2
) {
817 if (s1
!= null && s2
!= null) {
818 return s1
.compareToIgnoreCase(s2
);
830 * Calculates the square of the distance between two points.
833 * x-coordinate of point 1
835 * y-coordinate of point 1
837 * x-coordinate of point 2
839 * y-coordinate of point 2
841 * @return the square of the distance in pixels^2
843 public static double distance2(int x1
, int y1
, int x2
, int y2
) {
846 int d2
= dx
* dx
+ dy
* dy
;
851 * Calculates the distance between a point and a line segment. If the point
852 * is in the perpendicular region between the segment points, return the
853 * distance from the point to its projection on the segment. Otherwise
854 * return the distance from the point to its closest segment point.
857 * x-coordinate of the point
859 * y-coordinate of the point
861 * x-coordinate of segment point 1
863 * y-coordinate of segment point 1
865 * x-coordinate of segment point 2
867 * y-coordinate of segment point 2
869 * @return the distance in pixels
871 public static double distance(int px
, int py
, int x1
, int y1
, int x2
, int y2
) {
872 double length2
= distance2(x1
, y1
, x2
, y2
);
874 return Math
.sqrt(distance2(px
, py
, x1
, y1
));
876 // 'r' is the ratio of the position, between segment point 1 and segment
877 // point 2, of the projection of the point on the segment
878 double r
= ((px
- x1
) * (x2
- x1
) + (py
- y1
) * (y2
- y1
)) / length2
;
880 // the projection is before segment point 1, return distance from
881 // the point to segment point 1
882 return Math
.sqrt(distance2(px
, py
, x1
, y1
));
885 // the projection is after segment point 2, return distance from
886 // the point to segment point 2
887 return Math
.sqrt(distance2(px
, py
, x2
, y2
));
889 // the projection is between the segment points, return distance from
890 // the point to its projection on the segment
891 int x
= (int) (x1
+ r
* (x2
- x1
));
892 int y
= (int) (y1
+ r
* (y2
- y1
));
893 return Math
.sqrt(distance2(px
, py
, x
, y
));