1 /*****************************************************************************
2 * Copyright (c) 2007, 2014 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
.graphics
.Color
;
27 import org
.eclipse
.swt
.graphics
.Device
;
28 import org
.eclipse
.swt
.graphics
.GC
;
29 import org
.eclipse
.swt
.graphics
.Point
;
30 import org
.eclipse
.swt
.graphics
.Rectangle
;
31 import org
.eclipse
.swt
.widgets
.Display
;
32 import org
.eclipse
.tracecompass
.internal
.tmf
.ui
.Messages
;
33 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimePreferences
;
34 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.model
.ITimeEvent
;
35 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.model
.ITimeGraphEntry
;
38 * General utilities and definitions used by the time graph widget
40 * @author Alvaro Sanchez-Leon
41 * @author Patrick Tasse
48 /** Time format for dates and timestamp */
49 public enum TimeFormat
{
50 /** Relative to the start of the trace */
54 * Absolute timestamp (ie, relative to the Unix epoch)
59 * Timestamp displayed as a simple number
64 * Timestamp displayed as cycles
70 * Timestamp resolution
72 public static enum Resolution
{
87 * Ellipsis character, used to shorten strings that don't fit in their
92 public static final String ELLIPSIS
= "…"; //$NON-NLS-1$
94 private static final SimpleDateFormat TIME_FORMAT
= new SimpleDateFormat("HH:mm:ss"); //$NON-NLS-1$
95 private static final SimpleDateFormat DATE_FORMAT
= new SimpleDateFormat("yyyy-MM-dd"); //$NON-NLS-1$
96 private static final long HOURS_PER_DAY
= 24;
97 private static final long MIN_PER_HOUR
= 60;
98 private static final long SEC_PER_MIN
= 60;
99 private static final long SEC_IN_NS
= 1000000000;
100 private static final long MILLISEC_IN_NS
= 1000000;
103 * Update the time and date formats to use the current time zone
105 public static void updateTimeZone() {
106 TimeZone timeZone
= TmfTimePreferences
.getTimeZone();
107 TIME_FORMAT
.setTimeZone(timeZone
);
108 DATE_FORMAT
.setTimeZone(timeZone
);
111 static Rectangle
clone(Rectangle source
) {
112 return new Rectangle(source
.x
, source
.y
, source
.width
, source
.height
);
116 * Initialize a Rectangle object to default values (all equal to 0)
119 * The Rectangle to initialize
121 public static void init(Rectangle rect
) {
129 * Initialize a Rectangle object with all the given values
132 * The Rectangle object to initialize
138 * The width of the rectangle
140 * The height of the rectangle
142 public static void init(Rectangle rect
, int x
, int y
, int width
, int height
) {
146 rect
.height
= height
;
150 * Initialize a Rectangle object to another existing Rectangle's values.
153 * The Rectangle to initialize
155 * The reference Rectangle to copy
157 public static void init(Rectangle rect
, Rectangle source
) {
160 rect
.width
= source
.width
;
161 rect
.height
= source
.height
;
165 * Reduce the size of a given rectangle by the given amounts.
168 * The rectangle to modify
170 * The reduction in width
172 * The reduction in height
174 public static void deflate(Rectangle rect
, int x
, int y
) {
178 rect
.height
-= y
+ y
;
182 * Increase the size of a given rectangle by the given amounts.
185 * The rectangle to modify
187 * The augmentation in width
189 * The augmentation in height
191 public static void inflate(Rectangle rect
, int x
, int y
) {
195 rect
.height
+= y
+ y
;
198 static void dispose(Color col
) {
205 * Get the resulting color from a mix of two existing ones for a given
209 * The display device (which might affect the color conversion)
215 * The gamma level for color 1
217 * The gamma level for color 2
218 * @return The resulting color
220 public static Color
mixColors(Device display
, Color c1
, Color c2
, int w1
,
222 return new Color(display
, (w1
* c1
.getRed() + w2
* c2
.getRed())
223 / (w1
+ w2
), (w1
* c1
.getGreen() + w2
* c2
.getGreen())
224 / (w1
+ w2
), (w1
* c1
.getBlue() + w2
* c2
.getBlue())
229 * Get the system color with the given ID.
233 * @return The resulting color
235 public static Color
getSysColor(int id
) {
236 Color col
= Display
.getCurrent().getSystemColor(id
);
237 return new Color(col
.getDevice(), col
.getRGB());
241 * Get the resulting color from a mix of two existing ones for the current
249 * The gamma level for color 1
251 * The gamma level for color 2
252 * @return The resulting color
254 public static Color
mixColors(Color col1
, Color col2
, int w1
, int w2
) {
255 return mixColors(Display
.getCurrent(), col1
, col2
, w1
, w2
);
259 * Draw text in a rectangle.
266 * The rectangle object which is being drawn
268 * If true the background will be transparent
269 * @return The width of the written text
271 public static int drawText(GC gc
, String text
, Rectangle rect
, boolean transp
) {
272 Point size
= gc
.stringExtent(text
);
273 gc
.drawText(text
, rect
.x
, rect
.y
, transp
);
278 * Draw text at a given location.
285 * The X coordinate of the starting point
287 * the Y coordinate of the starting point
289 * If true the background will be transparent
290 * @return The width of the written text
292 public static int drawText(GC gc
, String text
, int x
, int y
, boolean transp
) {
293 Point size
= gc
.stringExtent(text
);
294 gc
.drawText(text
, x
, y
, transp
);
299 * Draw text in a rectangle, trimming the text to prevent exceeding the specified width.
304 * The string to be drawn
306 * The x coordinate of the top left corner of the rectangular area where the text is to be drawn
308 * The y coordinate of the top left corner of the rectangular area where the text is to be drawn
310 * The width of the area to be drawn
312 * If <code>true</code> the text will be centered in the available width if space permits
313 * @param isTransparent
314 * If <code>true</code> the background will be transparent, otherwise it will be opaque
315 * @return The number of characters written
316 * @deprecated Use {@link #drawText(GC, String, int, int, int, int, boolean, boolean)} instead.
319 public static int drawText(GC gc
, String text
, int x
, int y
, int width
, boolean isCentered
, boolean isTransparent
) {
324 int len
= text
.length();
326 boolean isReallyCentered
= isCentered
;
330 textWidth
= gc
.stringExtent(text
.substring(0, len
)).x
;
331 if (textWidth
<= width
) {
334 isReallyCentered
= false;
338 if (isReallyCentered
) {
339 realX
+= (width
- textWidth
) / 2;
341 gc
.drawText(text
.substring(0, len
), realX
, y
, isTransparent
);
347 * Draw text in a rectangle, trimming the text to prevent exceeding the specified width.
352 * The string to be drawn
354 * The x coordinate of the top left corner of the rectangular area where the text is to be drawn
356 * The y coordinate of the top left corner of the rectangular area where the text is to be drawn
358 * The width of the area to be drawn
360 * The height of the area to be drawn
362 * If <code>true</code> the text will be centered in the available area if space permits
363 * @param isTransparent
364 * If <code>true</code> the background will be transparent, otherwise it will be opaque
365 * @return The number of characters written
368 public static int drawText(GC gc
, String text
, int x
, int y
, int width
, int height
, boolean isCentered
, boolean isTransparent
) {
369 if (width
< 1 || text
.isEmpty()) {
373 String stringToDisplay
;
376 boolean isCenteredWidth
= isCentered
;
380 /* First check if the whole string fits */
381 Point textExtent
= gc
.textExtent(text
);
382 if (textExtent
.x
<= width
) {
384 stringToDisplay
= text
;
387 * The full string doesn't fit, try to find the longest one with
388 * "..." at the end that does fit.
390 * Iterate on the string length sizes, starting from 1 going up,
391 * until we find a string that does not fit. Once we do, we keep the
392 * one just before that did fit.
394 isCenteredWidth
= false;
397 while (len
<= text
.length()) {
398 textExtent
= gc
.textExtent(text
.substring(0, len
) + ELLIPSIS
);
399 if (textExtent
.x
> width
) {
401 * Here is the first length that does not fit, the one from
402 * the previous iteration is the one we will use.
407 /* This string would fit, try the next one */
411 stringToDisplay
= text
.substring(0, len
) + ELLIPSIS
;
415 /* Nothing fits, we end up drawing nothing */
419 if (isCenteredWidth
) {
420 realX
+= (width
- textExtent
.x
) / 2;
423 realY
+= (height
- textExtent
.y
) / 2 - 1;
425 gc
.drawText(stringToDisplay
, realX
, realY
, isTransparent
);
431 * Formats time in format: MM:SS:NNN
434 * @param format 0: MMMM:ss:nnnnnnnnn, 1: HH:MM:ss MMM.mmmm.nnn
435 * @param resolution the resolution
436 * @return the formatted time
438 public static String
formatTime(long time
, TimeFormat format
, Resolution resolution
) {
441 return formatTimeAbs(time
, resolution
);
443 return NumberFormat
.getInstance().format(time
);
445 return NumberFormat
.getInstance().format(time
) + Messages
.Utils_ClockCyclesUnit
;
450 StringBuffer str
= new StringBuffer();
458 long sec
= t
/ SEC_IN_NS
;
460 String ns
= formatNs(t
, resolution
);
461 if (!ns
.equals("")) { //$NON-NLS-1$
466 return str
.toString();
470 * From input time in nanoseconds, convert to Date format YYYY-MM-dd
473 * The source time, in ns
474 * @return the formatted date
476 public static String
formatDate(long absTime
) {
477 String sdate
= DATE_FORMAT
.format(new Date(absTime
/ MILLISEC_IN_NS
));
482 * Formats time in ns to Calendar format: HH:MM:SS MMM.mmm.nnn
485 * The source time, in ns
487 * The resolution to use
488 * @return the formatted time
490 public static String
formatTimeAbs(long time
, Resolution res
) {
491 StringBuffer str
= new StringBuffer();
493 // format time from nanoseconds to calendar time HH:MM:SS
494 String stime
= TIME_FORMAT
.format(new Date(time
/ MILLISEC_IN_NS
));
497 // append the Milliseconds, MicroSeconds and NanoSeconds as specified in
499 str
.append(formatNs(time
, res
));
500 return str
.toString();
507 * The time delta, in ns
509 * The time format to use
511 * The resolution to use
512 * @return the formatted time delta
514 public static String
formatDelta(long delta
, TimeFormat format
, Resolution resolution
) {
515 if (format
== TimeFormat
.CALENDAR
) {
516 return formatDeltaAbs(delta
, resolution
);
518 return formatTime(delta
, format
, resolution
);
522 * Formats time delta in ns to Calendar format, only formatting the years,
523 * days, hours or minutes if necessary.
526 * The time delta, in ns
528 * The resolution to use
529 * @return the formatted time delta
531 public static String
formatDeltaAbs(long delta
, Resolution resolution
) {
532 StringBuffer str
= new StringBuffer();
536 long ns
= Math
.abs(delta
);
537 long seconds
= TimeUnit
.NANOSECONDS
.toSeconds(ns
);
538 long minutes
= TimeUnit
.NANOSECONDS
.toMinutes(ns
);
539 long hours
= TimeUnit
.NANOSECONDS
.toHours(ns
);
540 long days
= TimeUnit
.NANOSECONDS
.toDays(ns
);
543 str
.append("d "); //$NON-NLS-1$
546 str
.append(hours
% HOURS_PER_DAY
);
547 str
.append("h "); //$NON-NLS-1$
550 str
.append(minutes
% MIN_PER_HOUR
);
551 str
.append("m "); //$NON-NLS-1$
553 str
.append(seconds
% SEC_PER_MIN
);
555 // append the ms, us and ns as specified in the resolution
556 str
.append(formatNs(delta
, resolution
));
557 str
.append("s"); //$NON-NLS-1$
558 return str
.toString();
562 * Obtains the remainder fraction on unit Seconds of the entered value in
563 * nanoseconds. e.g. input: 1241207054171080214 ns The number of fraction
564 * seconds can be obtained by removing the last 9 digits: 1241207054 the
565 * fractional portion of seconds, expressed in ns is: 171080214
568 * The source time in ns
570 * The Resolution to use
571 * @return the formatted nanosec
573 public static String
formatNs(long srcTime
, Resolution res
) {
574 StringBuffer str
= new StringBuffer();
575 long ns
= Math
.abs(srcTime
% SEC_IN_NS
);
576 String nanos
= Long
.toString(ns
);
577 str
.append("000000000".substring(nanos
.length())); //$NON-NLS-1$
580 if (res
== Resolution
.MILLISEC
) {
581 return str
.substring(0, 3);
582 } else if (res
== Resolution
.MICROSEC
) {
583 return str
.substring(0, 6);
584 } else if (res
== Resolution
.NANOSEC
) {
585 return str
.substring(0, 9);
587 return ""; //$NON-NLS-1$
591 * FIXME Currently does nothing.
598 * The minimal accepted value
600 * The maximal accepted value
601 * @return The value that was read
603 public static int loadIntOption(String opt
, int def
, int min
, int max
) {
608 * FIXME currently does nothing
615 public static void saveIntOption(String opt
, int val
) {
618 static ITimeEvent
getFirstEvent(ITimeGraphEntry entry
) {
619 if (null == entry
|| ! entry
.hasTimeEvents()) {
622 Iterator
<?
extends ITimeEvent
> iterator
= entry
.getTimeEventsIterator();
623 if (iterator
!= null && iterator
.hasNext()) {
624 return iterator
.next();
630 * Gets the {@link ITimeEvent} at the given time from the given
631 * {@link ITimeGraphEntry}.
634 * a {@link ITimeGraphEntry}
638 * this parameter means: <list> <li>-1: Previous Event</li> <li>
639 * 0: Current Event</li> <li>
640 * 1: Next Event</li> <li>2: Previous Event when located in a non
642 * @return a {@link ITimeEvent}, or <code>null</code>.
644 public static ITimeEvent
findEvent(ITimeGraphEntry entry
, long time
, int n
) {
645 if (null == entry
|| ! entry
.hasTimeEvents()) {
648 Iterator
<@NonNull ?
extends ITimeEvent
> iterator
= entry
.getTimeEventsIterator();
649 if (iterator
== null) {
652 ITimeEvent nextEvent
= null;
653 ITimeEvent currEvent
= null;
654 ITimeEvent prevEvent
= null;
656 while (iterator
.hasNext()) {
657 nextEvent
= iterator
.next();
658 long nextStartTime
= nextEvent
.getTime();
660 if (nextStartTime
> time
) {
664 if (currEvent
== null || currEvent
.getTime() != nextStartTime
||
665 (nextStartTime
!= time
&& currEvent
.getDuration() != nextEvent
.getDuration())) {
666 prevEvent
= currEvent
;
667 currEvent
= nextEvent
;
671 if (n
== -1) { //previous
672 if (currEvent
!= null && currEvent
.getTime() + currEvent
.getDuration() >= time
) {
676 } else if (n
== 0) { //current
677 if (currEvent
!= null && currEvent
.getTime() + currEvent
.getDuration() >= time
) {
681 } else if (n
== 1) { //next
682 if (nextEvent
!= null && nextEvent
.getTime() > time
) {
686 } else if (n
== 2) { //current or previous when in empty space
694 * Pretty-print a method signature.
697 * The original signature
698 * @return The pretty signature
700 public static String
fixMethodSignature(String origSig
) {
701 String sig
= origSig
;
702 int pos
= sig
.indexOf('(');
704 String ret
= sig
.substring(0, pos
);
705 sig
= sig
.substring(pos
);
706 sig
= sig
+ " " + ret
; //$NON-NLS-1$
712 * Restore an original method signature from a pretty-printed one.
715 * The pretty-printed signature
716 * @return The original method signature
718 public static String
restoreMethodSignature(String ppSig
) {
719 String ret
= ""; //$NON-NLS-1$
722 int pos
= sig
.indexOf('(');
724 ret
= sig
.substring(0, pos
);
725 sig
= sig
.substring(pos
+ 1);
727 pos
= sig
.indexOf(')');
729 sig
= sig
.substring(0, pos
);
731 String args
[] = sig
.split(","); //$NON-NLS-1$
732 StringBuffer result
= new StringBuffer("("); //$NON-NLS-1$
733 for (int i
= 0; i
< args
.length
; i
++) {
734 String arg
= args
[i
].trim();
735 if (arg
.length() == 0 && args
.length
== 1) {
738 result
.append(getTypeSignature(arg
));
740 result
.append(")").append(getTypeSignature(ret
)); //$NON-NLS-1$
741 return result
.toString();
745 * Get the mangled type information from an array of types.
748 * The types to convert. See method implementation for what it
750 * @return The mangled string of types
752 public static String
getTypeSignature(String typeStr
) {
754 String type
= typeStr
;
755 for (int j
= 0; j
< type
.length(); j
++) {
756 if (type
.charAt(j
) == '[') {
760 int pos
= type
.indexOf('[');
762 type
= type
.substring(0, pos
);
764 StringBuffer sig
= new StringBuffer(""); //$NON-NLS-1$
765 for (int j
= 0; j
< dim
; j
++)
767 sig
.append("["); //$NON-NLS-1$
769 if (type
.equals("boolean")) { //$NON-NLS-1$
771 } else if (type
.equals("byte")) { //$NON-NLS-1$
773 } else if (type
.equals("char")) { //$NON-NLS-1$
775 } else if (type
.equals("short")) { //$NON-NLS-1$
777 } else if (type
.equals("int")) { //$NON-NLS-1$
779 } else if (type
.equals("long")) { //$NON-NLS-1$
781 } else if (type
.equals("float")) { //$NON-NLS-1$
783 } else if (type
.equals("double")) { //$NON-NLS-1$
785 } else if (type
.equals("void")) { //$NON-NLS-1$
789 sig
.append('L').append(type
.replace('.', '/')).append(';');
791 return sig
.toString();
795 * Compare two doubles together.
801 * @return 1 if they are different, and 0 if they are *exactly* the same.
802 * Because of the way doubles are stored, it's possible for the
803 * same number obtained in two different ways to actually look
806 public static int compare(double d1
, double d2
) {
817 * Compare two character strings alphabetically. This is simply a wrapper
818 * around String.compareToIgnoreCase but that will handle cases where
819 * strings can be null
825 * @return A number below, equal, or greater than zero if the first string
826 * is smaller, equal, or bigger (alphabetically) than the second
829 public static int compare(String s1
, String s2
) {
830 if (s1
!= null && s2
!= null) {
831 return s1
.compareToIgnoreCase(s2
);
843 * Calculates the square of the distance between two points.
846 * x-coordinate of point 1
848 * y-coordinate of point 1
850 * x-coordinate of point 2
852 * y-coordinate of point 2
854 * @return the square of the distance in pixels^2
856 public static double distance2(int x1
, int y1
, int x2
, int y2
) {
859 int d2
= dx
* dx
+ dy
* dy
;
864 * Calculates the distance between a point and a line segment. If the point
865 * is in the perpendicular region between the segment points, return the
866 * distance from the point to its projection on the segment. Otherwise
867 * return the distance from the point to its closest segment point.
870 * x-coordinate of the point
872 * y-coordinate of the point
874 * x-coordinate of segment point 1
876 * y-coordinate of segment point 1
878 * x-coordinate of segment point 2
880 * y-coordinate of segment point 2
882 * @return the distance in pixels
884 public static double distance(int px
, int py
, int x1
, int y1
, int x2
, int y2
) {
885 double length2
= distance2(x1
, y1
, x2
, y2
);
887 return Math
.sqrt(distance2(px
, py
, x1
, y1
));
889 // 'r' is the ratio of the position, between segment point 1 and segment
890 // point 2, of the projection of the point on the segment
891 double r
= ((px
- x1
) * (x2
- x1
) + (py
- y1
) * (y2
- y1
)) / length2
;
893 // the projection is before segment point 1, return distance from
894 // the point to segment point 1
895 return Math
.sqrt(distance2(px
, py
, x1
, y1
));
898 // the projection is after segment point 2, return distance from
899 // the point to segment point 2
900 return Math
.sqrt(distance2(px
, py
, x2
, y2
));
902 // the projection is between the segment points, return distance from
903 // the point to its projection on the segment
904 int x
= (int) (x1
+ r
* (x2
- x1
));
905 int y
= (int) (y1
+ r
* (y2
- y1
));
906 return Math
.sqrt(distance2(px
, py
, x
, y
));