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
.swt
.graphics
.Color
;
26 import org
.eclipse
.swt
.graphics
.Device
;
27 import org
.eclipse
.swt
.graphics
.GC
;
28 import org
.eclipse
.swt
.graphics
.Point
;
29 import org
.eclipse
.swt
.graphics
.Rectangle
;
30 import org
.eclipse
.swt
.widgets
.Display
;
31 import org
.eclipse
.tracecompass
.internal
.tmf
.ui
.Messages
;
32 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimePreferences
;
33 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.model
.ITimeEvent
;
34 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.model
.ITimeGraphEntry
;
37 * 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)
60 * Timestamp displayed as a simple number
66 * Timestamp displayed as cycles
73 * Timestamp resolution
75 public static enum Resolution
{
89 private static final SimpleDateFormat TIME_FORMAT
= new SimpleDateFormat("HH:mm:ss"); //$NON-NLS-1$
90 private static final SimpleDateFormat DATE_FORMAT
= new SimpleDateFormat("yyyy-MM-dd"); //$NON-NLS-1$
91 private static final long HOURS_PER_DAY
= 24;
92 private static final long MIN_PER_HOUR
= 60;
93 private static final long SEC_PER_MIN
= 60;
94 private static final long SEC_IN_NS
= 1000000000;
95 private static final long MILLISEC_IN_NS
= 1000000;
98 * Update the time and date formats to use the current time zone
102 public static void updateTimeZone() {
103 TimeZone timeZone
= TmfTimePreferences
.getInstance().getTimeZone();
104 TIME_FORMAT
.setTimeZone(timeZone
);
105 DATE_FORMAT
.setTimeZone(timeZone
);
108 static Rectangle
clone(Rectangle source
) {
109 return new Rectangle(source
.x
, source
.y
, source
.width
, source
.height
);
113 * Initialize a Rectangle object to default values (all equal to 0)
116 * The Rectangle to initialize
118 public static void init(Rectangle rect
) {
126 * Initialize a Rectangle object with all the given values
129 * The Rectangle object to initialize
135 * The width of the rectangle
137 * The height of the rectangle
139 public static void init(Rectangle rect
, int x
, int y
, int width
, int height
) {
143 rect
.height
= height
;
147 * Initialize a Rectangle object to another existing Rectangle's values.
150 * The Rectangle to initialize
152 * The reference Rectangle to copy
154 public static void init(Rectangle rect
, Rectangle source
) {
157 rect
.width
= source
.width
;
158 rect
.height
= source
.height
;
162 * Reduce the size of a given rectangle by the given amounts.
165 * The rectangle to modify
167 * The reduction in width
169 * The reduction in height
171 public static void deflate(Rectangle rect
, int x
, int y
) {
175 rect
.height
-= y
+ y
;
179 * Increase the size of a given rectangle by the given amounts.
182 * The rectangle to modify
184 * The augmentation in width
186 * The augmentation in height
188 public static void inflate(Rectangle rect
, int x
, int y
) {
192 rect
.height
+= y
+ y
;
195 static void dispose(Color col
) {
202 * Get the resulting color from a mix of two existing ones for a given
206 * The display device (which might affect the color conversion)
212 * The gamma level for color 1
214 * The gamma level for color 2
215 * @return The resulting color
217 public static Color
mixColors(Device display
, Color c1
, Color c2
, int w1
,
219 return new Color(display
, (w1
* c1
.getRed() + w2
* c2
.getRed())
220 / (w1
+ w2
), (w1
* c1
.getGreen() + w2
* c2
.getGreen())
221 / (w1
+ w2
), (w1
* c1
.getBlue() + w2
* c2
.getBlue())
226 * Get the system color with the given ID.
230 * @return The resulting color
232 public static Color
getSysColor(int id
) {
233 Color col
= Display
.getCurrent().getSystemColor(id
);
234 return new Color(col
.getDevice(), col
.getRGB());
238 * Get the resulting color from a mix of two existing ones for the current
246 * The gamma level for color 1
248 * The gamma level for color 2
249 * @return The resulting color
251 public static Color
mixColors(Color col1
, Color col2
, int w1
, int w2
) {
252 return mixColors(Display
.getCurrent(), col1
, col2
, w1
, w2
);
256 * Draw text in a rectangle.
263 * The rectangle object which is being drawn
265 * If true the background will be transparent
266 * @return The width of the written text
268 public static int drawText(GC gc
, String text
, Rectangle rect
, boolean transp
) {
269 Point size
= gc
.stringExtent(text
);
270 gc
.drawText(text
, rect
.x
, rect
.y
, transp
);
275 * Draw text at a given location.
282 * The X coordinate of the starting point
284 * the Y coordinate of the starting point
286 * If true the background will be transparent
287 * @return The width of the written text
289 public static int drawText(GC gc
, String text
, int x
, int y
, boolean transp
) {
290 Point size
= gc
.stringExtent(text
);
291 gc
.drawText(text
, x
, y
, transp
);
296 * Draw text in a rectangle, trimming the text to prevent exceeding the specified width.
301 * The string to be drawn
303 * The x coordinate of the top left corner of the rectangular area where the text is to be drawn
305 * The y coordinate of the top left corner of the rectangular area where the text is to be drawn
307 * The width of the area to be drawn
309 * If <code>true</code> the text will be centered in the available width if space permits
310 * @param isTransparent
311 * If <code>true</code> the background will be transparent, otherwise it will be opaque
312 * @return The number of characters written
316 public static int drawText(GC gc
, String text
, int x
, int y
, int width
, boolean isCentered
, boolean isTransparent
) {
321 int len
= text
.length();
323 boolean isReallyCentered
= isCentered
;
327 textWidth
= gc
.stringExtent(text
.substring(0, len
)).x
;
328 if (textWidth
<= width
) {
331 isReallyCentered
= false;
335 if (isReallyCentered
) {
336 realX
+= (width
- textWidth
) / 2;
338 gc
.drawText(text
.substring(0, len
), realX
, y
, isTransparent
);
344 * Formats time in format: MM:SS:NNN
347 * @param format 0: MMMM:ss:nnnnnnnnn, 1: HH:MM:ss MMM.mmmm.nnn
348 * @param resolution the resolution
349 * @return the formatted time
351 public static String
formatTime(long time
, TimeFormat format
, Resolution resolution
) {
354 return formatTimeAbs(time
, resolution
);
356 return NumberFormat
.getInstance().format(time
);
358 return NumberFormat
.getInstance().format(time
) + Messages
.Utils_ClockCyclesUnit
;
363 StringBuffer str
= new StringBuffer();
371 long sec
= t
/ SEC_IN_NS
;
373 String ns
= formatNs(t
, resolution
);
374 if (!ns
.equals("")) { //$NON-NLS-1$
379 return str
.toString();
383 * From input time in nanoseconds, convert to Date format YYYY-MM-dd
386 * The source time, in ns
387 * @return the formatted date
389 public static String
formatDate(long absTime
) {
390 String sdate
= DATE_FORMAT
.format(new Date(absTime
/ MILLISEC_IN_NS
));
395 * Formats time in ns to Calendar format: HH:MM:SS MMM.mmm.nnn
398 * The source time, in ns
400 * The resolution to use
401 * @return the formatted time
403 public static String
formatTimeAbs(long time
, Resolution res
) {
404 StringBuffer str
= new StringBuffer();
406 // format time from nanoseconds to calendar time HH:MM:SS
407 String stime
= TIME_FORMAT
.format(new Date(time
/ MILLISEC_IN_NS
));
410 // append the Milliseconds, MicroSeconds and NanoSeconds as specified in
412 str
.append(formatNs(time
, res
));
413 return str
.toString();
420 * The time delta, in ns
422 * The time format to use
424 * The resolution to use
426 * @return the formatted time delta
428 public static String
formatDelta(long delta
, TimeFormat format
, Resolution resolution
) {
429 if (format
== TimeFormat
.CALENDAR
) {
430 return formatDeltaAbs(delta
, resolution
);
432 return formatTime(delta
, format
, resolution
);
436 * Formats time delta in ns to Calendar format, only formatting the years,
437 * days, hours or minutes if necessary.
440 * The time delta, in ns
442 * The resolution to use
443 * @return the formatted time delta
446 public static String
formatDeltaAbs(long delta
, Resolution resolution
) {
447 StringBuffer str
= new StringBuffer();
451 long ns
= Math
.abs(delta
);
452 long seconds
= TimeUnit
.NANOSECONDS
.toSeconds(ns
);
453 long minutes
= TimeUnit
.NANOSECONDS
.toMinutes(ns
);
454 long hours
= TimeUnit
.NANOSECONDS
.toHours(ns
);
455 long days
= TimeUnit
.NANOSECONDS
.toDays(ns
);
458 str
.append("d "); //$NON-NLS-1$
461 str
.append(hours
% HOURS_PER_DAY
);
462 str
.append("h "); //$NON-NLS-1$
465 str
.append(minutes
% MIN_PER_HOUR
);
466 str
.append("m "); //$NON-NLS-1$
468 str
.append(seconds
% SEC_PER_MIN
);
470 // append the ms, us and ns as specified in the resolution
471 str
.append(formatNs(delta
, resolution
));
472 str
.append("s"); //$NON-NLS-1$
473 return str
.toString();
477 * Obtains the remainder fraction on unit Seconds of the entered value in
478 * nanoseconds. e.g. input: 1241207054171080214 ns The number of fraction
479 * seconds can be obtained by removing the last 9 digits: 1241207054 the
480 * fractional portion of seconds, expressed in ns is: 171080214
483 * The source time in ns
485 * The Resolution to use
486 * @return the formatted nanosec
488 public static String
formatNs(long srcTime
, Resolution res
) {
489 StringBuffer str
= new StringBuffer();
490 long ns
= Math
.abs(srcTime
% SEC_IN_NS
);
491 String nanos
= Long
.toString(ns
);
492 str
.append("000000000".substring(nanos
.length())); //$NON-NLS-1$
495 if (res
== Resolution
.MILLISEC
) {
496 return str
.substring(0, 3);
497 } else if (res
== Resolution
.MICROSEC
) {
498 return str
.substring(0, 6);
499 } else if (res
== Resolution
.NANOSEC
) {
500 return str
.substring(0, 9);
502 return ""; //$NON-NLS-1$
506 * FIXME Currently does nothing.
513 * The minimal accepted value
515 * The maximal accepted value
516 * @return The value that was read
518 public static int loadIntOption(String opt
, int def
, int min
, int max
) {
523 * FIXME currently does nothing
530 public static void saveIntOption(String opt
, int val
) {
533 static ITimeEvent
getFirstEvent(ITimeGraphEntry entry
) {
534 if (null == entry
|| ! entry
.hasTimeEvents()) {
537 Iterator
<ITimeEvent
> iterator
= entry
.getTimeEventsIterator();
538 if (iterator
!= null && iterator
.hasNext()) {
539 return iterator
.next();
545 * Gets the {@link ITimeEvent} at the given time from the given
546 * {@link ITimeGraphEntry}.
549 * a {@link ITimeGraphEntry}
553 * this parameter means: <list> <li>-1: Previous Event</li> <li>
554 * 0: Current Event</li> <li>
555 * 1: Next Event</li> <li>2: Previous Event when located in a non
557 * @return a {@link ITimeEvent}, or <code>null</code>.
560 public static ITimeEvent
findEvent(ITimeGraphEntry entry
, long time
, int n
) {
561 if (null == entry
|| ! entry
.hasTimeEvents()) {
564 Iterator
<ITimeEvent
> iterator
= entry
.getTimeEventsIterator();
565 if (iterator
== null) {
568 ITimeEvent nextEvent
= null;
569 ITimeEvent currEvent
= null;
570 ITimeEvent prevEvent
= null;
572 while (iterator
.hasNext()) {
573 nextEvent
= iterator
.next();
574 long nextStartTime
= nextEvent
.getTime();
576 if (nextStartTime
> time
) {
580 if (currEvent
== null || currEvent
.getTime() != nextStartTime
||
581 (nextStartTime
!= time
&& currEvent
.getDuration() != nextEvent
.getDuration())) {
582 prevEvent
= currEvent
;
583 currEvent
= nextEvent
;
587 if (n
== -1) { //previous
588 if (currEvent
!= null && currEvent
.getTime() + currEvent
.getDuration() >= time
) {
592 } else if (n
== 0) { //current
593 if (currEvent
!= null && currEvent
.getTime() + currEvent
.getDuration() >= time
) {
597 } else if (n
== 1) { //next
598 if (nextEvent
!= null && nextEvent
.getTime() > time
) {
602 } else if (n
== 2) { //current or previous when in empty space
610 * Pretty-print a method signature.
613 * The original signature
614 * @return The pretty signature
616 public static String
fixMethodSignature(String origSig
) {
617 String sig
= origSig
;
618 int pos
= sig
.indexOf('(');
620 String ret
= sig
.substring(0, pos
);
621 sig
= sig
.substring(pos
);
622 sig
= sig
+ " " + ret
; //$NON-NLS-1$
628 * Restore an original method signature from a pretty-printed one.
631 * The pretty-printed signature
632 * @return The original method signature
634 public static String
restoreMethodSignature(String ppSig
) {
635 String ret
= ""; //$NON-NLS-1$
638 int pos
= sig
.indexOf('(');
640 ret
= sig
.substring(0, pos
);
641 sig
= sig
.substring(pos
+ 1);
643 pos
= sig
.indexOf(')');
645 sig
= sig
.substring(0, pos
);
647 String args
[] = sig
.split(","); //$NON-NLS-1$
648 StringBuffer result
= new StringBuffer("("); //$NON-NLS-1$
649 for (int i
= 0; i
< args
.length
; i
++) {
650 String arg
= args
[i
].trim();
651 if (arg
.length() == 0 && args
.length
== 1) {
654 result
.append(getTypeSignature(arg
));
656 result
.append(")").append(getTypeSignature(ret
)); //$NON-NLS-1$
657 return result
.toString();
661 * Get the mangled type information from an array of types.
664 * The types to convert. See method implementation for what it
666 * @return The mangled string of types
668 public static String
getTypeSignature(String typeStr
) {
670 String type
= typeStr
;
671 for (int j
= 0; j
< type
.length(); j
++) {
672 if (type
.charAt(j
) == '[') {
676 int pos
= type
.indexOf('[');
678 type
= type
.substring(0, pos
);
680 StringBuffer sig
= new StringBuffer(""); //$NON-NLS-1$
681 for (int j
= 0; j
< dim
; j
++)
683 sig
.append("["); //$NON-NLS-1$
685 if (type
.equals("boolean")) { //$NON-NLS-1$
687 } else if (type
.equals("byte")) { //$NON-NLS-1$
689 } else if (type
.equals("char")) { //$NON-NLS-1$
691 } else if (type
.equals("short")) { //$NON-NLS-1$
693 } else if (type
.equals("int")) { //$NON-NLS-1$
695 } else if (type
.equals("long")) { //$NON-NLS-1$
697 } else if (type
.equals("float")) { //$NON-NLS-1$
699 } else if (type
.equals("double")) { //$NON-NLS-1$
701 } else if (type
.equals("void")) { //$NON-NLS-1$
705 sig
.append('L').append(type
.replace('.', '/')).append(';');
707 return sig
.toString();
711 * Compare two doubles together.
717 * @return 1 if they are different, and 0 if they are *exactly* the same.
718 * Because of the way doubles are stored, it's possible for the
719 * same number obtained in two different ways to actually look
722 public static int compare(double d1
, double d2
) {
733 * Compare two character strings alphabetically. This is simply a wrapper
734 * around String.compareToIgnoreCase but that will handle cases where
735 * strings can be null
741 * @return A number below, equal, or greater than zero if the first string
742 * is smaller, equal, or bigger (alphabetically) than the second
745 public static int compare(String s1
, String s2
) {
746 if (s1
!= null && s2
!= null) {
747 return s1
.compareToIgnoreCase(s2
);
759 * Calculates the square of the distance between two points.
762 * x-coordinate of point 1
764 * y-coordinate of point 1
766 * x-coordinate of point 2
768 * y-coordinate of point 2
770 * @return the square of the distance in pixels^2
773 public static double distance2(int x1
, int y1
, int x2
, int y2
) {
776 int d2
= dx
* dx
+ dy
* dy
;
781 * Calculates the distance between a point and a line segment. If the point
782 * is in the perpendicular region between the segment points, return the
783 * distance from the point to its projection on the segment. Otherwise
784 * return the distance from the point to its closest segment point.
787 * x-coordinate of the point
789 * y-coordinate of the point
791 * x-coordinate of segment point 1
793 * y-coordinate of segment point 1
795 * x-coordinate of segment point 2
797 * y-coordinate of segment point 2
799 * @return the distance in pixels
802 public static double distance(int px
, int py
, int x1
, int y1
, int x2
, int y2
) {
803 double length2
= distance2(x1
, y1
, x2
, y2
);
805 return Math
.sqrt(distance2(px
, py
, x1
, y1
));
807 // 'r' is the ratio of the position, between segment point 1 and segment
808 // point 2, of the projection of the point on the segment
809 double r
= ((px
- x1
) * (x2
- x1
) + (py
- y1
) * (y2
- y1
)) / length2
;
811 // the projection is before segment point 1, return distance from
812 // the point to segment point 1
813 return Math
.sqrt(distance2(px
, py
, x1
, y1
));
816 // the projection is after segment point 2, return distance from
817 // the point to segment point 2
818 return Math
.sqrt(distance2(px
, py
, x2
, y2
));
820 // the projection is between the segment points, return distance from
821 // the point to its projection on the segment
822 int x
= (int) (x1
+ r
* (x2
- x1
));
823 int y
= (int) (y1
+ r
* (y2
- y1
));
824 return Math
.sqrt(distance2(px
, py
, x
, y
));