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
39 * @author Alvaro Sanchez-Leon
40 * @author Patrick Tasse
47 /** Time format for dates and timestamp */
48 public enum TimeFormat
{
49 /** Relative to the start of the trace */
53 * Absolute timestamp (ie, relative to the Unix epoch)
58 * Timestamp displayed as a simple number
63 * Timestamp displayed as cycles
69 * Timestamp resolution
71 public static enum Resolution
{
85 private static final SimpleDateFormat TIME_FORMAT
= new SimpleDateFormat("HH:mm:ss"); //$NON-NLS-1$
86 private static final SimpleDateFormat DATE_FORMAT
= new SimpleDateFormat("yyyy-MM-dd"); //$NON-NLS-1$
87 private static final long HOURS_PER_DAY
= 24;
88 private static final long MIN_PER_HOUR
= 60;
89 private static final long SEC_PER_MIN
= 60;
90 private static final long SEC_IN_NS
= 1000000000;
91 private static final long MILLISEC_IN_NS
= 1000000;
94 * Update the time and date formats to use the current time zone
96 public static void updateTimeZone() {
97 TimeZone timeZone
= TmfTimePreferences
.getTimeZone();
98 TIME_FORMAT
.setTimeZone(timeZone
);
99 DATE_FORMAT
.setTimeZone(timeZone
);
102 static Rectangle
clone(Rectangle source
) {
103 return new Rectangle(source
.x
, source
.y
, source
.width
, source
.height
);
107 * Initialize a Rectangle object to default values (all equal to 0)
110 * The Rectangle to initialize
112 public static void init(Rectangle rect
) {
120 * Initialize a Rectangle object with all the given values
123 * The Rectangle object to initialize
129 * The width of the rectangle
131 * The height of the rectangle
133 public static void init(Rectangle rect
, int x
, int y
, int width
, int height
) {
137 rect
.height
= height
;
141 * Initialize a Rectangle object to another existing Rectangle's values.
144 * The Rectangle to initialize
146 * The reference Rectangle to copy
148 public static void init(Rectangle rect
, Rectangle source
) {
151 rect
.width
= source
.width
;
152 rect
.height
= source
.height
;
156 * Reduce the size of a given rectangle by the given amounts.
159 * The rectangle to modify
161 * The reduction in width
163 * The reduction in height
165 public static void deflate(Rectangle rect
, int x
, int y
) {
169 rect
.height
-= y
+ y
;
173 * Increase the size of a given rectangle by the given amounts.
176 * The rectangle to modify
178 * The augmentation in width
180 * The augmentation in height
182 public static void inflate(Rectangle rect
, int x
, int y
) {
186 rect
.height
+= y
+ y
;
189 static void dispose(Color col
) {
196 * Get the resulting color from a mix of two existing ones for a given
200 * The display device (which might affect the color conversion)
206 * The gamma level for color 1
208 * The gamma level for color 2
209 * @return The resulting color
211 public static Color
mixColors(Device display
, Color c1
, Color c2
, int w1
,
213 return new Color(display
, (w1
* c1
.getRed() + w2
* c2
.getRed())
214 / (w1
+ w2
), (w1
* c1
.getGreen() + w2
* c2
.getGreen())
215 / (w1
+ w2
), (w1
* c1
.getBlue() + w2
* c2
.getBlue())
220 * Get the system color with the given ID.
224 * @return The resulting color
226 public static Color
getSysColor(int id
) {
227 Color col
= Display
.getCurrent().getSystemColor(id
);
228 return new Color(col
.getDevice(), col
.getRGB());
232 * Get the resulting color from a mix of two existing ones for the current
240 * The gamma level for color 1
242 * The gamma level for color 2
243 * @return The resulting color
245 public static Color
mixColors(Color col1
, Color col2
, int w1
, int w2
) {
246 return mixColors(Display
.getCurrent(), col1
, col2
, w1
, w2
);
250 * Draw text in a rectangle.
257 * The rectangle object which is being drawn
259 * If true the background will be transparent
260 * @return The width of the written text
262 public static int drawText(GC gc
, String text
, Rectangle rect
, boolean transp
) {
263 Point size
= gc
.stringExtent(text
);
264 gc
.drawText(text
, rect
.x
, rect
.y
, transp
);
269 * Draw text at a given location.
276 * The X coordinate of the starting point
278 * the Y coordinate of the starting point
280 * If true the background will be transparent
281 * @return The width of the written text
283 public static int drawText(GC gc
, String text
, int x
, int y
, boolean transp
) {
284 Point size
= gc
.stringExtent(text
);
285 gc
.drawText(text
, x
, y
, transp
);
290 * Draw text in a rectangle, trimming the text to prevent exceeding the specified width.
295 * The string to be drawn
297 * The x coordinate of the top left corner of the rectangular area where the text is to be drawn
299 * The y coordinate of the top left corner of the rectangular area where the text is to be drawn
301 * The width of the area to be drawn
303 * If <code>true</code> the text will be centered in the available width if space permits
304 * @param isTransparent
305 * If <code>true</code> the background will be transparent, otherwise it will be opaque
306 * @return The number of characters written
308 public static int drawText(GC gc
, String text
, int x
, int y
, int width
, boolean isCentered
, boolean isTransparent
) {
313 int len
= text
.length();
315 boolean isReallyCentered
= isCentered
;
319 textWidth
= gc
.stringExtent(text
.substring(0, len
)).x
;
320 if (textWidth
<= width
) {
323 isReallyCentered
= false;
327 if (isReallyCentered
) {
328 realX
+= (width
- textWidth
) / 2;
330 gc
.drawText(text
.substring(0, len
), realX
, y
, isTransparent
);
336 * Formats time in format: MM:SS:NNN
339 * @param format 0: MMMM:ss:nnnnnnnnn, 1: HH:MM:ss MMM.mmmm.nnn
340 * @param resolution the resolution
341 * @return the formatted time
343 public static String
formatTime(long time
, TimeFormat format
, Resolution resolution
) {
346 return formatTimeAbs(time
, resolution
);
348 return NumberFormat
.getInstance().format(time
);
350 return NumberFormat
.getInstance().format(time
) + Messages
.Utils_ClockCyclesUnit
;
355 StringBuffer str
= new StringBuffer();
363 long sec
= t
/ SEC_IN_NS
;
365 String ns
= formatNs(t
, resolution
);
366 if (!ns
.equals("")) { //$NON-NLS-1$
371 return str
.toString();
375 * From input time in nanoseconds, convert to Date format YYYY-MM-dd
378 * The source time, in ns
379 * @return the formatted date
381 public static String
formatDate(long absTime
) {
382 String sdate
= DATE_FORMAT
.format(new Date(absTime
/ MILLISEC_IN_NS
));
387 * Formats time in ns to Calendar format: HH:MM:SS MMM.mmm.nnn
390 * The source time, in ns
392 * The resolution to use
393 * @return the formatted time
395 public static String
formatTimeAbs(long time
, Resolution res
) {
396 StringBuffer str
= new StringBuffer();
398 // format time from nanoseconds to calendar time HH:MM:SS
399 String stime
= TIME_FORMAT
.format(new Date(time
/ MILLISEC_IN_NS
));
402 // append the Milliseconds, MicroSeconds and NanoSeconds as specified in
404 str
.append(formatNs(time
, res
));
405 return str
.toString();
412 * The time delta, in ns
414 * The time format to use
416 * The resolution to use
417 * @return the formatted time delta
419 public static String
formatDelta(long delta
, TimeFormat format
, Resolution resolution
) {
420 if (format
== TimeFormat
.CALENDAR
) {
421 return formatDeltaAbs(delta
, resolution
);
423 return formatTime(delta
, format
, resolution
);
427 * Formats time delta in ns to Calendar format, only formatting the years,
428 * days, hours or minutes if necessary.
431 * The time delta, in ns
433 * The resolution to use
434 * @return the formatted time delta
436 public static String
formatDeltaAbs(long delta
, Resolution resolution
) {
437 StringBuffer str
= new StringBuffer();
441 long ns
= Math
.abs(delta
);
442 long seconds
= TimeUnit
.NANOSECONDS
.toSeconds(ns
);
443 long minutes
= TimeUnit
.NANOSECONDS
.toMinutes(ns
);
444 long hours
= TimeUnit
.NANOSECONDS
.toHours(ns
);
445 long days
= TimeUnit
.NANOSECONDS
.toDays(ns
);
448 str
.append("d "); //$NON-NLS-1$
451 str
.append(hours
% HOURS_PER_DAY
);
452 str
.append("h "); //$NON-NLS-1$
455 str
.append(minutes
% MIN_PER_HOUR
);
456 str
.append("m "); //$NON-NLS-1$
458 str
.append(seconds
% SEC_PER_MIN
);
460 // append the ms, us and ns as specified in the resolution
461 str
.append(formatNs(delta
, resolution
));
462 str
.append("s"); //$NON-NLS-1$
463 return str
.toString();
467 * Obtains the remainder fraction on unit Seconds of the entered value in
468 * nanoseconds. e.g. input: 1241207054171080214 ns The number of fraction
469 * seconds can be obtained by removing the last 9 digits: 1241207054 the
470 * fractional portion of seconds, expressed in ns is: 171080214
473 * The source time in ns
475 * The Resolution to use
476 * @return the formatted nanosec
478 public static String
formatNs(long srcTime
, Resolution res
) {
479 StringBuffer str
= new StringBuffer();
480 long ns
= Math
.abs(srcTime
% SEC_IN_NS
);
481 String nanos
= Long
.toString(ns
);
482 str
.append("000000000".substring(nanos
.length())); //$NON-NLS-1$
485 if (res
== Resolution
.MILLISEC
) {
486 return str
.substring(0, 3);
487 } else if (res
== Resolution
.MICROSEC
) {
488 return str
.substring(0, 6);
489 } else if (res
== Resolution
.NANOSEC
) {
490 return str
.substring(0, 9);
492 return ""; //$NON-NLS-1$
496 * FIXME Currently does nothing.
503 * The minimal accepted value
505 * The maximal accepted value
506 * @return The value that was read
508 public static int loadIntOption(String opt
, int def
, int min
, int max
) {
513 * FIXME currently does nothing
520 public static void saveIntOption(String opt
, int val
) {
523 static ITimeEvent
getFirstEvent(ITimeGraphEntry entry
) {
524 if (null == entry
|| ! entry
.hasTimeEvents()) {
527 Iterator
<ITimeEvent
> iterator
= entry
.getTimeEventsIterator();
528 if (iterator
!= null && iterator
.hasNext()) {
529 return iterator
.next();
535 * Gets the {@link ITimeEvent} at the given time from the given
536 * {@link ITimeGraphEntry}.
539 * a {@link ITimeGraphEntry}
543 * this parameter means: <list> <li>-1: Previous Event</li> <li>
544 * 0: Current Event</li> <li>
545 * 1: Next Event</li> <li>2: Previous Event when located in a non
547 * @return a {@link ITimeEvent}, or <code>null</code>.
549 public static ITimeEvent
findEvent(ITimeGraphEntry entry
, long time
, int n
) {
550 if (null == entry
|| ! entry
.hasTimeEvents()) {
553 Iterator
<ITimeEvent
> iterator
= entry
.getTimeEventsIterator();
554 if (iterator
== null) {
557 ITimeEvent nextEvent
= null;
558 ITimeEvent currEvent
= null;
559 ITimeEvent prevEvent
= null;
561 while (iterator
.hasNext()) {
562 nextEvent
= iterator
.next();
563 long nextStartTime
= nextEvent
.getTime();
565 if (nextStartTime
> time
) {
569 if (currEvent
== null || currEvent
.getTime() != nextStartTime
||
570 (nextStartTime
!= time
&& currEvent
.getDuration() != nextEvent
.getDuration())) {
571 prevEvent
= currEvent
;
572 currEvent
= nextEvent
;
576 if (n
== -1) { //previous
577 if (currEvent
!= null && currEvent
.getTime() + currEvent
.getDuration() >= time
) {
581 } else if (n
== 0) { //current
582 if (currEvent
!= null && currEvent
.getTime() + currEvent
.getDuration() >= time
) {
586 } else if (n
== 1) { //next
587 if (nextEvent
!= null && nextEvent
.getTime() > time
) {
591 } else if (n
== 2) { //current or previous when in empty space
599 * Pretty-print a method signature.
602 * The original signature
603 * @return The pretty signature
605 public static String
fixMethodSignature(String origSig
) {
606 String sig
= origSig
;
607 int pos
= sig
.indexOf('(');
609 String ret
= sig
.substring(0, pos
);
610 sig
= sig
.substring(pos
);
611 sig
= sig
+ " " + ret
; //$NON-NLS-1$
617 * Restore an original method signature from a pretty-printed one.
620 * The pretty-printed signature
621 * @return The original method signature
623 public static String
restoreMethodSignature(String ppSig
) {
624 String ret
= ""; //$NON-NLS-1$
627 int pos
= sig
.indexOf('(');
629 ret
= sig
.substring(0, pos
);
630 sig
= sig
.substring(pos
+ 1);
632 pos
= sig
.indexOf(')');
634 sig
= sig
.substring(0, pos
);
636 String args
[] = sig
.split(","); //$NON-NLS-1$
637 StringBuffer result
= new StringBuffer("("); //$NON-NLS-1$
638 for (int i
= 0; i
< args
.length
; i
++) {
639 String arg
= args
[i
].trim();
640 if (arg
.length() == 0 && args
.length
== 1) {
643 result
.append(getTypeSignature(arg
));
645 result
.append(")").append(getTypeSignature(ret
)); //$NON-NLS-1$
646 return result
.toString();
650 * Get the mangled type information from an array of types.
653 * The types to convert. See method implementation for what it
655 * @return The mangled string of types
657 public static String
getTypeSignature(String typeStr
) {
659 String type
= typeStr
;
660 for (int j
= 0; j
< type
.length(); j
++) {
661 if (type
.charAt(j
) == '[') {
665 int pos
= type
.indexOf('[');
667 type
= type
.substring(0, pos
);
669 StringBuffer sig
= new StringBuffer(""); //$NON-NLS-1$
670 for (int j
= 0; j
< dim
; j
++)
672 sig
.append("["); //$NON-NLS-1$
674 if (type
.equals("boolean")) { //$NON-NLS-1$
676 } else if (type
.equals("byte")) { //$NON-NLS-1$
678 } else if (type
.equals("char")) { //$NON-NLS-1$
680 } else if (type
.equals("short")) { //$NON-NLS-1$
682 } else if (type
.equals("int")) { //$NON-NLS-1$
684 } else if (type
.equals("long")) { //$NON-NLS-1$
686 } else if (type
.equals("float")) { //$NON-NLS-1$
688 } else if (type
.equals("double")) { //$NON-NLS-1$
690 } else if (type
.equals("void")) { //$NON-NLS-1$
694 sig
.append('L').append(type
.replace('.', '/')).append(';');
696 return sig
.toString();
700 * Compare two doubles together.
706 * @return 1 if they are different, and 0 if they are *exactly* the same.
707 * Because of the way doubles are stored, it's possible for the
708 * same number obtained in two different ways to actually look
711 public static int compare(double d1
, double d2
) {
722 * Compare two character strings alphabetically. This is simply a wrapper
723 * around String.compareToIgnoreCase but that will handle cases where
724 * strings can be null
730 * @return A number below, equal, or greater than zero if the first string
731 * is smaller, equal, or bigger (alphabetically) than the second
734 public static int compare(String s1
, String s2
) {
735 if (s1
!= null && s2
!= null) {
736 return s1
.compareToIgnoreCase(s2
);
748 * Calculates the square of the distance between two points.
751 * x-coordinate of point 1
753 * y-coordinate of point 1
755 * x-coordinate of point 2
757 * y-coordinate of point 2
759 * @return the square of the distance in pixels^2
761 public static double distance2(int x1
, int y1
, int x2
, int y2
) {
764 int d2
= dx
* dx
+ dy
* dy
;
769 * Calculates the distance between a point and a line segment. If the point
770 * is in the perpendicular region between the segment points, return the
771 * distance from the point to its projection on the segment. Otherwise
772 * return the distance from the point to its closest segment point.
775 * x-coordinate of the point
777 * y-coordinate of the point
779 * x-coordinate of segment point 1
781 * y-coordinate of segment point 1
783 * x-coordinate of segment point 2
785 * y-coordinate of segment point 2
787 * @return the distance in pixels
789 public static double distance(int px
, int py
, int x1
, int y1
, int x2
, int y2
) {
790 double length2
= distance2(x1
, y1
, x2
, y2
);
792 return Math
.sqrt(distance2(px
, py
, x1
, y1
));
794 // 'r' is the ratio of the position, between segment point 1 and segment
795 // point 2, of the projection of the point on the segment
796 double r
= ((px
- x1
) * (x2
- x1
) + (py
- y1
) * (y2
- y1
)) / length2
;
798 // the projection is before segment point 1, return distance from
799 // the point to segment point 1
800 return Math
.sqrt(distance2(px
, py
, x1
, y1
));
803 // the projection is after segment point 2, return distance from
804 // the point to segment point 2
805 return Math
.sqrt(distance2(px
, py
, x2
, y2
));
807 // the projection is between the segment points, return distance from
808 // the point to its projection on the segment
809 int x
= (int) (x1
+ r
* (x2
- x1
));
810 int y
= (int) (y1
+ r
* (y2
- y1
));
811 return Math
.sqrt(distance2(px
, py
, x
, y
));