blob: eb073aed8d9add609da04e3d930b7f7d28206c13 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
/*****************************************************************************
* Copyright (c) 2013 CEA LIST.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*
* CEA LIST - Initial API and implementation
*
*****************************************************************************/
package org.eclipse.papyrus.infra.gmfdiag.common.utils;
import java.text.ParseException;
import org.eclipse.gef.rulers.RulerProvider;
import org.eclipse.swt.widgets.Display;
import com.ibm.icu.text.NumberFormat;
/**
*
* This class allows to convert easily units (Centimeters, Pixels and Inches)
*
*/
public class UnitsConverterUtils {
private UnitsConverterUtils() {
// to avoid instanciation
}
/**
*
* @param fromUnits
* the initial unity
* @param toUnits
* the new unity
* @param valueStr
* the value to convert
* @return
* the new String
*/
public static final String convertUnits(final int fromUnits, final int toUnits, final String valueStr) {
// String valueStr = gridSpacing.getStringValue();
if (fromUnits == toUnits) {
return valueStr;
}
// Double value = Double.valueOf( valueStr );
NumberFormat numberFormatter = NumberFormat.getInstance();
Double value = new Double(0.125);
try {
value = forceDouble(numberFormatter.parse(valueStr));
} catch (ParseException e) {
// Use the default
}
double pixelValue = 0;
Display display = Display.getDefault();
switch (fromUnits) {
case RulerProvider.UNIT_INCHES:
pixelValue = value.doubleValue() * display.getDPI().x;
break;
case RulerProvider.UNIT_CENTIMETERS:
pixelValue = value.doubleValue() * display.getDPI().x / UnitsConstants.INCH2CM;
break;
case RulerProvider.UNIT_PIXELS:
pixelValue = value.intValue();
break;
default:
break;
}
double returnValue = 0;
switch (toUnits) {
case RulerProvider.UNIT_INCHES:
returnValue = pixelValue / display.getDPI().x;
break;
case RulerProvider.UNIT_CENTIMETERS:
returnValue = pixelValue * UnitsConstants.INCH2CM / display.getDPI().x;
break;
case RulerProvider.UNIT_PIXELS:
returnValue = pixelValue;
break;
default:
break;
}
return numberFormatter.format(returnValue);
}
/**
*
* @param number
* a number
* @return
* a double
*/
private static final Double forceDouble(final Number number) {
if (!(number instanceof Double)) {
return new Double(number.doubleValue());
}
return (Double) number;
}
}
|