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
{
86 private static final SimpleDateFormat TIME_FORMAT
= new SimpleDateFormat("HH:mm:ss"); //$NON-NLS-1$
87 private static final SimpleDateFormat DATE_FORMAT
= new SimpleDateFormat("yyyy-MM-dd"); //$NON-NLS-1$
88 private static final long HOURS_PER_DAY
= 24;
89 private static final long MIN_PER_HOUR
= 60;
90 private static final long SEC_PER_MIN
= 60;
91 private static final long SEC_IN_NS
= 1000000000;
92 private static final long MILLISEC_IN_NS
= 1000000;
95 * Update the time and date formats to use the current time zone
97 public static void updateTimeZone() {
98 TimeZone timeZone
= TmfTimePreferences
.getTimeZone();
99 TIME_FORMAT
.setTimeZone(timeZone
);
100 DATE_FORMAT
.setTimeZone(timeZone
);
103 static Rectangle
clone(Rectangle source
) {
104 return new Rectangle(source
.x
, source
.y
, source
.width
, source
.height
);
108 * Initialize a Rectangle object to default values (all equal to 0)
111 * The Rectangle to initialize
113 public static void init(Rectangle rect
) {
121 * Initialize a Rectangle object with all the given values
124 * The Rectangle object to initialize
130 * The width of the rectangle
132 * The height of the rectangle
134 public static void init(Rectangle rect
, int x
, int y
, int width
, int height
) {
138 rect
.height
= height
;
142 * Initialize a Rectangle object to another existing Rectangle's values.
145 * The Rectangle to initialize
147 * The reference Rectangle to copy
149 public static void init(Rectangle rect
, Rectangle source
) {
152 rect
.width
= source
.width
;
153 rect
.height
= source
.height
;
157 * Reduce the size of a given rectangle by the given amounts.
160 * The rectangle to modify
162 * The reduction in width
164 * The reduction in height
166 public static void deflate(Rectangle rect
, int x
, int y
) {
170 rect
.height
-= y
+ y
;
174 * Increase the size of a given rectangle by the given amounts.
177 * The rectangle to modify
179 * The augmentation in width
181 * The augmentation in height
183 public static void inflate(Rectangle rect
, int x
, int y
) {
187 rect
.height
+= y
+ y
;
190 static void dispose(Color col
) {
197 * Get the resulting color from a mix of two existing ones for a given
201 * The display device (which might affect the color conversion)
207 * The gamma level for color 1
209 * The gamma level for color 2
210 * @return The resulting color
212 public static Color
mixColors(Device display
, Color c1
, Color c2
, int w1
,
214 return new Color(display
, (w1
* c1
.getRed() + w2
* c2
.getRed())
215 / (w1
+ w2
), (w1
* c1
.getGreen() + w2
* c2
.getGreen())
216 / (w1
+ w2
), (w1
* c1
.getBlue() + w2
* c2
.getBlue())
221 * Get the system color with the given ID.
225 * @return The resulting color
227 public static Color
getSysColor(int id
) {
228 Color col
= Display
.getCurrent().getSystemColor(id
);
229 return new Color(col
.getDevice(), col
.getRGB());
233 * Get the resulting color from a mix of two existing ones for the current
241 * The gamma level for color 1
243 * The gamma level for color 2
244 * @return The resulting color
246 public static Color
mixColors(Color col1
, Color col2
, int w1
, int w2
) {
247 return mixColors(Display
.getCurrent(), col1
, col2
, w1
, w2
);
251 * Draw text in a rectangle.
258 * The rectangle object which is being drawn
260 * If true the background will be transparent
261 * @return The width of the written text
263 public static int drawText(GC gc
, String text
, Rectangle rect
, boolean transp
) {
264 Point size
= gc
.stringExtent(text
);
265 gc
.drawText(text
, rect
.x
, rect
.y
, transp
);
270 * Draw text at a given location.
277 * The X coordinate of the starting point
279 * the Y coordinate of the starting point
281 * If true the background will be transparent
282 * @return The width of the written text
284 public static int drawText(GC gc
, String text
, int x
, int y
, boolean transp
) {
285 Point size
= gc
.stringExtent(text
);
286 gc
.drawText(text
, x
, y
, transp
);
291 * Draw text in a rectangle, trimming the text to prevent exceeding the specified width.
296 * The string to be drawn
298 * The x coordinate of the top left corner of the rectangular area where the text is to be drawn
300 * The y coordinate of the top left corner of the rectangular area where the text is to be drawn
302 * The width of the area to be drawn
304 * If <code>true</code> the text will be centered in the available width if space permits
305 * @param isTransparent
306 * If <code>true</code> the background will be transparent, otherwise it will be opaque
307 * @return The number of characters written
309 public static int drawText(GC gc
, String text
, int x
, int y
, int width
, boolean isCentered
, boolean isTransparent
) {
314 int len
= text
.length();
316 boolean isReallyCentered
= isCentered
;
320 textWidth
= gc
.stringExtent(text
.substring(0, len
)).x
;
321 if (textWidth
<= width
) {
324 isReallyCentered
= false;
328 if (isReallyCentered
) {
329 realX
+= (width
- textWidth
) / 2;
331 gc
.drawText(text
.substring(0, len
), realX
, y
, isTransparent
);
337 * Draw text in a rectangle, trimming the text to prevent exceeding the specified width.
342 * The string to be drawn
344 * The x coordinate of the top left corner of the rectangular area where the text is to be drawn
346 * The y coordinate of the top left corner of the rectangular area where the text is to be drawn
348 * The width of the area to be drawn
350 * The height of the area to be drawn
352 * If <code>true</code> the text will be centered in the available area if space permits
353 * @param isTransparent
354 * If <code>true</code> the background will be transparent, otherwise it will be opaque
355 * @return The number of characters written
358 public static int drawText(GC gc
, String text
, int x
, int y
, int width
, int height
, boolean isCentered
, boolean isTransparent
) {
363 int len
= text
.length();
365 boolean isCenteredWidth
= isCentered
;
369 Point textExtent
= null;
371 textExtent
= gc
.textExtent(text
.substring(0, len
));
372 textWidth
= textExtent
.x
;
373 if (textWidth
<= width
) {
376 isCenteredWidth
= false;
378 textExtent
= gc
.textExtent(text
.substring(0, len
));
381 if (isCenteredWidth
) {
382 realX
+= (width
- textWidth
) / 2;
384 if (isCentered
&& textExtent
!= null) {
385 realY
+= (height
- textExtent
.y
) / 2 - 1;
387 gc
.drawText(text
.substring(0, len
), realX
, realY
, isTransparent
);
393 * Formats time in format: MM:SS:NNN
396 * @param format 0: MMMM:ss:nnnnnnnnn, 1: HH:MM:ss MMM.mmmm.nnn
397 * @param resolution the resolution
398 * @return the formatted time
400 public static String
formatTime(long time
, TimeFormat format
, Resolution resolution
) {
403 return formatTimeAbs(time
, resolution
);
405 return NumberFormat
.getInstance().format(time
);
407 return NumberFormat
.getInstance().format(time
) + Messages
.Utils_ClockCyclesUnit
;
412 StringBuffer str
= new StringBuffer();
420 long sec
= t
/ SEC_IN_NS
;
422 String ns
= formatNs(t
, resolution
);
423 if (!ns
.equals("")) { //$NON-NLS-1$
428 return str
.toString();
432 * From input time in nanoseconds, convert to Date format YYYY-MM-dd
435 * The source time, in ns
436 * @return the formatted date
438 public static String
formatDate(long absTime
) {
439 String sdate
= DATE_FORMAT
.format(new Date(absTime
/ MILLISEC_IN_NS
));
444 * Formats time in ns to Calendar format: HH:MM:SS MMM.mmm.nnn
447 * The source time, in ns
449 * The resolution to use
450 * @return the formatted time
452 public static String
formatTimeAbs(long time
, Resolution res
) {
453 StringBuffer str
= new StringBuffer();
455 // format time from nanoseconds to calendar time HH:MM:SS
456 String stime
= TIME_FORMAT
.format(new Date(time
/ MILLISEC_IN_NS
));
459 // append the Milliseconds, MicroSeconds and NanoSeconds as specified in
461 str
.append(formatNs(time
, res
));
462 return str
.toString();
469 * The time delta, in ns
471 * The time format to use
473 * The resolution to use
474 * @return the formatted time delta
476 public static String
formatDelta(long delta
, TimeFormat format
, Resolution resolution
) {
477 if (format
== TimeFormat
.CALENDAR
) {
478 return formatDeltaAbs(delta
, resolution
);
480 return formatTime(delta
, format
, resolution
);
484 * Formats time delta in ns to Calendar format, only formatting the years,
485 * days, hours or minutes if necessary.
488 * The time delta, in ns
490 * The resolution to use
491 * @return the formatted time delta
493 public static String
formatDeltaAbs(long delta
, Resolution resolution
) {
494 StringBuffer str
= new StringBuffer();
498 long ns
= Math
.abs(delta
);
499 long seconds
= TimeUnit
.NANOSECONDS
.toSeconds(ns
);
500 long minutes
= TimeUnit
.NANOSECONDS
.toMinutes(ns
);
501 long hours
= TimeUnit
.NANOSECONDS
.toHours(ns
);
502 long days
= TimeUnit
.NANOSECONDS
.toDays(ns
);
505 str
.append("d "); //$NON-NLS-1$
508 str
.append(hours
% HOURS_PER_DAY
);
509 str
.append("h "); //$NON-NLS-1$
512 str
.append(minutes
% MIN_PER_HOUR
);
513 str
.append("m "); //$NON-NLS-1$
515 str
.append(seconds
% SEC_PER_MIN
);
517 // append the ms, us and ns as specified in the resolution
518 str
.append(formatNs(delta
, resolution
));
519 str
.append("s"); //$NON-NLS-1$
520 return str
.toString();
524 * Obtains the remainder fraction on unit Seconds of the entered value in
525 * nanoseconds. e.g. input: 1241207054171080214 ns The number of fraction
526 * seconds can be obtained by removing the last 9 digits: 1241207054 the
527 * fractional portion of seconds, expressed in ns is: 171080214
530 * The source time in ns
532 * The Resolution to use
533 * @return the formatted nanosec
535 public static String
formatNs(long srcTime
, Resolution res
) {
536 StringBuffer str
= new StringBuffer();
537 long ns
= Math
.abs(srcTime
% SEC_IN_NS
);
538 String nanos
= Long
.toString(ns
);
539 str
.append("000000000".substring(nanos
.length())); //$NON-NLS-1$
542 if (res
== Resolution
.MILLISEC
) {
543 return str
.substring(0, 3);
544 } else if (res
== Resolution
.MICROSEC
) {
545 return str
.substring(0, 6);
546 } else if (res
== Resolution
.NANOSEC
) {
547 return str
.substring(0, 9);
549 return ""; //$NON-NLS-1$
553 * FIXME Currently does nothing.
560 * The minimal accepted value
562 * The maximal accepted value
563 * @return The value that was read
565 public static int loadIntOption(String opt
, int def
, int min
, int max
) {
570 * FIXME currently does nothing
577 public static void saveIntOption(String opt
, int val
) {
580 static ITimeEvent
getFirstEvent(ITimeGraphEntry entry
) {
581 if (null == entry
|| ! entry
.hasTimeEvents()) {
584 Iterator
<?
extends ITimeEvent
> iterator
= entry
.getTimeEventsIterator();
585 if (iterator
!= null && iterator
.hasNext()) {
586 return iterator
.next();
592 * Gets the {@link ITimeEvent} at the given time from the given
593 * {@link ITimeGraphEntry}.
596 * a {@link ITimeGraphEntry}
600 * this parameter means: <list> <li>-1: Previous Event</li> <li>
601 * 0: Current Event</li> <li>
602 * 1: Next Event</li> <li>2: Previous Event when located in a non
604 * @return a {@link ITimeEvent}, or <code>null</code>.
606 public static ITimeEvent
findEvent(ITimeGraphEntry entry
, long time
, int n
) {
607 if (null == entry
|| ! entry
.hasTimeEvents()) {
610 Iterator
<@NonNull ?
extends ITimeEvent
> iterator
= entry
.getTimeEventsIterator();
611 if (iterator
== null) {
614 ITimeEvent nextEvent
= null;
615 ITimeEvent currEvent
= null;
616 ITimeEvent prevEvent
= null;
618 while (iterator
.hasNext()) {
619 nextEvent
= iterator
.next();
620 long nextStartTime
= nextEvent
.getTime();
622 if (nextStartTime
> time
) {
626 if (currEvent
== null || currEvent
.getTime() != nextStartTime
||
627 (nextStartTime
!= time
&& currEvent
.getDuration() != nextEvent
.getDuration())) {
628 prevEvent
= currEvent
;
629 currEvent
= nextEvent
;
633 if (n
== -1) { //previous
634 if (currEvent
!= null && currEvent
.getTime() + currEvent
.getDuration() >= time
) {
638 } else if (n
== 0) { //current
639 if (currEvent
!= null && currEvent
.getTime() + currEvent
.getDuration() >= time
) {
643 } else if (n
== 1) { //next
644 if (nextEvent
!= null && nextEvent
.getTime() > time
) {
648 } else if (n
== 2) { //current or previous when in empty space
656 * Pretty-print a method signature.
659 * The original signature
660 * @return The pretty signature
662 public static String
fixMethodSignature(String origSig
) {
663 String sig
= origSig
;
664 int pos
= sig
.indexOf('(');
666 String ret
= sig
.substring(0, pos
);
667 sig
= sig
.substring(pos
);
668 sig
= sig
+ " " + ret
; //$NON-NLS-1$
674 * Restore an original method signature from a pretty-printed one.
677 * The pretty-printed signature
678 * @return The original method signature
680 public static String
restoreMethodSignature(String ppSig
) {
681 String ret
= ""; //$NON-NLS-1$
684 int pos
= sig
.indexOf('(');
686 ret
= sig
.substring(0, pos
);
687 sig
= sig
.substring(pos
+ 1);
689 pos
= sig
.indexOf(')');
691 sig
= sig
.substring(0, pos
);
693 String args
[] = sig
.split(","); //$NON-NLS-1$
694 StringBuffer result
= new StringBuffer("("); //$NON-NLS-1$
695 for (int i
= 0; i
< args
.length
; i
++) {
696 String arg
= args
[i
].trim();
697 if (arg
.length() == 0 && args
.length
== 1) {
700 result
.append(getTypeSignature(arg
));
702 result
.append(")").append(getTypeSignature(ret
)); //$NON-NLS-1$
703 return result
.toString();
707 * Get the mangled type information from an array of types.
710 * The types to convert. See method implementation for what it
712 * @return The mangled string of types
714 public static String
getTypeSignature(String typeStr
) {
716 String type
= typeStr
;
717 for (int j
= 0; j
< type
.length(); j
++) {
718 if (type
.charAt(j
) == '[') {
722 int pos
= type
.indexOf('[');
724 type
= type
.substring(0, pos
);
726 StringBuffer sig
= new StringBuffer(""); //$NON-NLS-1$
727 for (int j
= 0; j
< dim
; j
++)
729 sig
.append("["); //$NON-NLS-1$
731 if (type
.equals("boolean")) { //$NON-NLS-1$
733 } else if (type
.equals("byte")) { //$NON-NLS-1$
735 } else if (type
.equals("char")) { //$NON-NLS-1$
737 } else if (type
.equals("short")) { //$NON-NLS-1$
739 } else if (type
.equals("int")) { //$NON-NLS-1$
741 } else if (type
.equals("long")) { //$NON-NLS-1$
743 } else if (type
.equals("float")) { //$NON-NLS-1$
745 } else if (type
.equals("double")) { //$NON-NLS-1$
747 } else if (type
.equals("void")) { //$NON-NLS-1$
751 sig
.append('L').append(type
.replace('.', '/')).append(';');
753 return sig
.toString();
757 * Compare two doubles together.
763 * @return 1 if they are different, and 0 if they are *exactly* the same.
764 * Because of the way doubles are stored, it's possible for the
765 * same number obtained in two different ways to actually look
768 public static int compare(double d1
, double d2
) {
779 * Compare two character strings alphabetically. This is simply a wrapper
780 * around String.compareToIgnoreCase but that will handle cases where
781 * strings can be null
787 * @return A number below, equal, or greater than zero if the first string
788 * is smaller, equal, or bigger (alphabetically) than the second
791 public static int compare(String s1
, String s2
) {
792 if (s1
!= null && s2
!= null) {
793 return s1
.compareToIgnoreCase(s2
);
805 * Calculates the square of the distance between two points.
808 * x-coordinate of point 1
810 * y-coordinate of point 1
812 * x-coordinate of point 2
814 * y-coordinate of point 2
816 * @return the square of the distance in pixels^2
818 public static double distance2(int x1
, int y1
, int x2
, int y2
) {
821 int d2
= dx
* dx
+ dy
* dy
;
826 * Calculates the distance between a point and a line segment. If the point
827 * is in the perpendicular region between the segment points, return the
828 * distance from the point to its projection on the segment. Otherwise
829 * return the distance from the point to its closest segment point.
832 * x-coordinate of the point
834 * y-coordinate of the point
836 * x-coordinate of segment point 1
838 * y-coordinate of segment point 1
840 * x-coordinate of segment point 2
842 * y-coordinate of segment point 2
844 * @return the distance in pixels
846 public static double distance(int px
, int py
, int x1
, int y1
, int x2
, int y2
) {
847 double length2
= distance2(x1
, y1
, x2
, y2
);
849 return Math
.sqrt(distance2(px
, py
, x1
, y1
));
851 // 'r' is the ratio of the position, between segment point 1 and segment
852 // point 2, of the projection of the point on the segment
853 double r
= ((px
- x1
) * (x2
- x1
) + (py
- y1
) * (y2
- y1
)) / length2
;
855 // the projection is before segment point 1, return distance from
856 // the point to segment point 1
857 return Math
.sqrt(distance2(px
, py
, x1
, y1
));
860 // the projection is after segment point 2, return distance from
861 // the point to segment point 2
862 return Math
.sqrt(distance2(px
, py
, x2
, y2
));
864 // the projection is between the segment points, return distance from
865 // the point to its projection on the segment
866 int x
= (int) (x1
+ r
* (x2
- x1
));
867 int y
= (int) (y1
+ r
* (y2
- y1
));
868 return Math
.sqrt(distance2(px
, py
, x
, y
));