source: trunk/org/expeditee/io/Conversion.java@ 4

Last change on this file since 4 was 4, checked in by davidb, 16 years ago

Starting source code to Expeditee

File size: 15.7 KB
Line 
1package org.expeditee.io;
2
3import java.awt.Color;
4import java.awt.Font;
5import java.awt.Point;
6import java.lang.reflect.Field;
7import java.lang.reflect.Method;
8import java.util.LinkedList;
9import java.util.List;
10import java.util.StringTokenizer;
11
12import org.expeditee.gui.DisplayIO;
13import org.expeditee.items.Item;
14import org.expeditee.items.Text;
15
16/**
17 * This class provides various methods for converting values to\from Java
18 * objects and KMS file values.
19 *
20 * @author jdm18
21 *
22 */
23public class Conversion {
24
25 private static final double FONT_SCALE = 0.85;
26
27 // used for rounding when converting between Sandbox and KMS font sizes.
28 private static final double FONT_ROUNDING = 0.07;
29
30 // border around edges
31 public static final int X_ADJUST = 5;
32
33 public static final int Y_ADJUST = 20;
34
35 /**
36 * Returns the Color corresponding to the given KMS color code. For example:
37 * <br>
38 * green4 = 0% red, 40% green, 0% blue.
39 *
40 * @param colorCode
41 * The KMS color code to convert
42 * @return The Color object corresponding to the given code
43 */
44 public static Color getColor(String colorCode, Color current) {
45 if (colorCode == null || colorCode.equals("null")
46 || colorCode.equals("none")) {
47 return current;
48 }
49
50 Color rgb = getRGBColor(colorCode, current);
51 if (rgb != null)
52 return rgb;
53
54 // separate percentage from color (if necessary)
55 String num = "";
56 int last = colorCode.length() - 1;
57
58 char c = colorCode.charAt(last);
59
60 while (c >= '0' && c <= '9') {
61 num = c + num;
62 if (last <= 0)
63 break;
64
65 c = colorCode.charAt(--last);
66 }
67
68 float amount = 10f;
69 if (num.length() > 0)
70 amount = Float.parseFloat(num);
71
72 float color[] = { 0, 0, 0 };
73
74 if (colorCode.toLowerCase().startsWith("red"))
75 color[0] = amount / 10;
76
77 if (colorCode.toLowerCase().startsWith("green"))
78 color[1] = amount / 10;
79
80 if (colorCode.toLowerCase().startsWith("blue"))
81 color[2] = amount / 10;
82
83 return new Color(color[0], color[1], color[2]);
84 }
85
86 private static Color getRGBColor(String colorCode, Color current) {
87 int color[] = { 0, 0, 0 };
88
89 try {
90 String r = colorCode.substring(0, colorCode.indexOf(" "));
91 colorCode = colorCode.substring(r.length() + 1);
92
93 String g = colorCode.substring(0, colorCode.indexOf(" "));
94 colorCode = colorCode.substring(g.length() + 1);
95
96 String b = colorCode.substring(0);
97
98 if (current != null && (r.startsWith("+") || r.startsWith("-"))) {
99 int mult = 1;
100 if (r.startsWith("-"))
101 mult = -1;
102
103 r = r.substring(1);
104
105 color[0] = combine(r, current.getRed(), mult);
106 color[1] = combine(g, current.getGreen(), mult);
107 color[2] = combine(b, current.getBlue(), mult);
108 } else {
109 color[0] = Integer.parseInt(r);
110 color[1] = Integer.parseInt(g);
111 color[2] = Integer.parseInt(b);
112
113 for (int i = 0; i < color.length; i++)
114 color[i] = (int) Math.floor((color[i] / 100.0) * 255);
115 }
116
117 for (int i = 0; i < color.length; i++) {
118 if (color[i] > 255)
119 color[i] = 255;
120
121 if (color[i] < 0)
122 color[i] = 0;
123 }
124
125 return new Color(color[0], color[1], color[2]);
126 } catch (Exception e) {
127 return current;
128 }
129 }
130
131 private static int combine(String toParse, int current, int mult) {
132 return ((int) Math.floor((Integer.parseInt(toParse) / 100.0) * 255) * mult)
133 + current;
134 }
135
136 /**
137 * Converts the given Color object to the corresponding KMS color code
138 *
139 * @param color
140 * The Color to be turned into KMS color code.
141 * @return A String containing the KMS color code, NULL if the color is
142 * black.
143 */
144 public static String getKMSColorCode(Color color) {
145 if (color == null)
146 return null;
147
148 int r = (int) ((color.getRed() / 255.0) * 100 + 0.5);
149 int g = (int) ((color.getGreen() / 255.0) * 100 + 0.5);
150 int b = (int) ((color.getBlue() / 255.0) * 100 + 0.5);
151
152 return r + " " + g + " " + b;
153 }
154
155 /**
156 * Adjusts the given x,y coordinates. This is done to allow room for the
157 * title bar and menu bar
158 *
159 * @param x
160 * The x coordinate
161 * @param y
162 * The y coordinate
163 * @return The new values with a small margin on the left and space on the
164 * top
165 */
166 public static java.awt.Point adjust(int x, int y) {
167 return new Point(x + X_ADJUST, y + Y_ADJUST);
168 }
169
170 /**
171 * Adjusts the given Point to allow room for the title bar and menu bar.
172 *
173 * @param p
174 * The point to adjust.
175 * @return A new point with the adjusted values
176 */
177 public static Point adjust(Point p) {
178 return adjust(p.x, p.y);
179 }
180
181 /**
182 * Restores KMS coordinates after an adjust() has been performed
183 *
184 * @param point
185 * The Point to restore
186 * @return a new Point with the restored values.
187 */
188 public static java.awt.Point deAdjust(java.awt.Point point) {
189 return new Point(point.x - X_ADJUST, point.y - Y_ADJUST);
190 }
191
192 /**
193 * Converts the given Font to a corresponding KMS font code.
194 *
195 * @param font
196 * The Font to convert to a code.
197 * @return The KMS font code that corresponds to the given Font.
198 */
199 public static String getKMSFontCode(Font font) {
200 String code = "t";
201 String fontName = font.getFamily().toLowerCase();
202
203 for (int i = 0; i < Text.FONT_WHEEL.length; i++) {
204 if (Text.FONT_WHEEL[i].equals(fontName)){
205 code = "" + Text.FONT_CHARS[i];
206 break;
207 }
208 }
209
210 switch (font.getStyle()) {
211 case Font.BOLD:
212 code += "b";
213 break;
214 case Font.PLAIN:
215 code += "r";
216 break;
217 case Font.ITALIC:
218 code += "i";
219 break;
220 default:
221 code += "p";
222 break;
223 }
224
225 double dsize = font.getSize() / FONT_SCALE;
226 if ((Math.ceil(dsize)) - dsize < FONT_ROUNDING)
227 dsize = Math.ceil(dsize);
228 else
229 dsize = Math.floor(dsize);
230
231 code += (int) dsize;
232
233 return code;
234 }
235
236 /**
237 * Converts the given KMS font code to a Font object.<br>
238 * For example: <br>
239 * tr16 = times, roman, 16pt
240 *
241 * @param fontCode
242 * The font code to convert to a Font
243 * @return the Font that corresponds to the given font code.
244 */
245 public static Font getFont(String fontCode) {
246 String code = Text.FONT_WHEEL[0];
247
248 char c = fontCode.charAt(0);
249 for (int i = 0; i < Text.FONT_CHARS.length; i++) {
250 if (c == Text.FONT_CHARS[i]) {
251 code = Text.FONT_WHEEL[i] + '-';
252 break;
253 }
254 }
255
256 switch (fontCode.charAt(1)) {
257 case 'r':
258 code += "Plain";
259 break;
260 case 'b':
261 code += "Bold";
262 break;
263 case 'i':
264 code += "Italic";
265 break;
266 case 'p':
267 code += "BoldItalic";
268 break;
269 }
270
271 code += "-";
272
273 Font font = null;
274
275 try {
276 int size = Integer.parseInt(fontCode.substring(2));
277 double dsize = size * FONT_SCALE;
278 if (dsize - ((int) dsize) > FONT_ROUNDING)
279 dsize = Math.ceil(dsize);
280
281 code += (int) dsize;
282
283 font = Font.decode(code);
284 } catch (NumberFormatException nfe) {
285 font = Font.decode(fontCode);
286 }
287
288 return font;
289 }
290
291 /**
292 * Returns the number portion (Frame Number) of the given Frame name.
293 *
294 * @param framename
295 * The Frame name to extract the number from
296 * @return The Frame number
297 */
298 public static int getFrameNumber(String framename) {
299 String num = framename
300 .replaceFirst("^\\w+([^\\d]+|\\d+[.][^\\d]+)", "");
301
302 try {
303 return Integer.parseInt(num);
304 } catch (NumberFormatException nfe) {
305 return -1;
306 }
307 }
308
309 /**
310 * Returns the frameset poriton of the given Frame name (frame number
311 * removed)
312 *
313 * @param frame
314 * The full name to extract the Frameset name from
315 * @return the name of the Frameset extracted from the given Frame name.
316 */
317 public static String getFrameset(String frame) {
318 return getFrameset(frame, true);
319 }
320
321 public static String getFrameset(String frame, boolean convertToLower) {
322 String set = frame.replaceFirst("(\\d+|[.]\\d+)$", "");
323
324 // if there is no frameset given, then add the current frameset
325 if (set.length() == 0) {
326 set = DisplayIO.getCurrentFrame().getFramesetName();
327 }
328
329 if (convertToLower)
330 return set.toLowerCase();
331
332 return set;
333 }
334
335 /**
336 * Converts the given KMS justification code into a int corresponding to the
337 * constants defined in Item.
338 *
339 * @param justCode
340 * The KMS justification code to convert
341 * @return The resulting int corresponding to one of the constants defined
342 * in Item
343 */
344 public static int getJustification(String justCode) {
345 // as read from file
346 if (justCode.length() == 1) {
347 switch (justCode.charAt(0)) {
348 case 'F':
349 return Item.JUSTIFICATION_FULL;
350 case 'L':
351 return Item.JUSTIFICATION_LEFT;
352 case 'R':
353 return Item.JUSTIFICATION_RIGHT;
354 case 'C':
355 return Item.JUSTIFICATION_CENTER;
356 }
357 }
358
359 // from the user
360 justCode = justCode.trim().toLowerCase();
361 if (justCode.equals("center"))
362 return Item.JUSTIFICATION_CENTER;
363 if (justCode.equals("left"))
364 return Item.JUSTIFICATION_LEFT;
365 if (justCode.equals("right"))
366 return Item.JUSTIFICATION_RIGHT;
367 if (justCode.equals("full"))
368 return Item.JUSTIFICATION_FULL;
369
370 // default justification
371 return Item.JUSTIFICATION_NONE;
372 }
373
374 public static String getKMSJustificationCode(int justification) {
375 switch (justification) {
376 case Item.JUSTIFICATION_CENTER:
377 return "C";
378 case Item.JUSTIFICATION_FULL:
379 return "F";
380 case Item.JUSTIFICATION_LEFT:
381 return "L";
382 case Item.JUSTIFICATION_RIGHT:
383 return "R";
384 default:
385 return null;
386 }
387
388 }
389
390 public static Object Convert(Class type, String value) {
391 return Convert(type, value, null);
392 }
393
394 // Will convert from KMS color values to RGB...
395 public static Object Convert(Class type, String value, Object orig) {
396 // System.out.println("Orig: " + orig);
397
398 if (type == String.class
399 && String.CASE_INSENSITIVE_ORDER.compare(value, "") == 0)
400 return null;
401 else if (type == String.class)
402 return value;
403
404 /*
405 * if(type == int.class || type == Integer.class){ return
406 * Integer.parseInt(value); }
407 *
408 * if(type == float.class || type == Float.class){ return
409 * Float.parseFloat(value); }
410 */
411
412 if (type == Font.class) {
413 return getFont(value);
414 }
415
416 if (type.equals(Color.class)) {
417 if (value.length() == 0)
418 return null;
419
420 try {
421 // Find the field and value of colorName
422 Field field = Class.forName("java.awt.Color").getField(
423 value.toLowerCase());
424 return (Color) field.get(null);
425 } catch (Exception e) {
426 return getColor(value, (Color) orig);
427 }
428 }
429
430 if (type.equals(int.class)) {
431 if (orig instanceof Integer
432 && (value.startsWith("+") || value.startsWith("-"))) {
433 value = value.replace("+", "");
434
435 return ((Integer) orig) + Integer.parseInt(value);
436 }
437
438 if (value.equals("null"))
439 return -1;
440
441 return Integer.parseInt(value);
442 }
443
444 if (type.equals(float.class)) {
445 if (orig instanceof Float
446 && (value.startsWith("+") || value.startsWith("-"))) {
447 value = value.replace("+", "");
448
449 return ((Float) orig) + Float.parseFloat(value);
450 }
451
452 return Float.parseFloat(value);
453 }
454
455 if (type.equals(double.class)) {
456 if (orig instanceof Double
457 && (value.startsWith("+") || value.startsWith("-"))) {
458 value = value.replace("+", "");
459
460 return ((Double) orig) + Double.parseDouble(value);
461 }
462
463 return Double.parseDouble(value);
464 }
465
466 if (type.equals(int[].class)) {
467 StringTokenizer st = new StringTokenizer(value, " ");
468 int[] param = new int[st.countTokens()];
469 for (int i = 0; i < param.length; i++) {
470 try {
471 param[i] = Integer.parseInt(st.nextToken());
472 } catch (Exception e) {
473 return null;
474 }
475 }
476
477 return param;
478 }
479
480 if (type.equals(Font.class)) {
481 return Conversion.getFont(value);
482 }
483
484 if (type.equals(boolean.class)) {
485 value = value.toLowerCase().trim();
486
487 if (value.equals("t") || value.equals("true")
488 || value.equals("yes") || value.equals("y")
489 || value.equals(""))
490 return true;
491
492 if (value.equals("f") || value.equals("false")
493 || value.equals("no") || value.equals("n"))
494 return false;
495
496 return null;
497 }
498
499 // return name + ": " + value;
500 /*
501 * String[] val = new String[1]; val[0] = value;
502 */
503 return null;
504
505 }
506
507 public static Object[] Convert(Method method, String value) {
508 return Convert(method, value, null);
509 }
510
511 public static Object[] Convert(Method method, String value, Object current) {
512
513 String name = method.getName();
514 Class[] types = method.getParameterTypes();
515 if (name.equals("setPosition")) {
516 Point[] p = new Point[1];
517 p[0] = new Point();
518 p[0].x = Integer.parseInt(value.substring(0, value.indexOf(" ")));
519 p[0].y = Integer.parseInt(value.substring(value.indexOf(" ") + 1));
520 p[0] = adjust(p[0]);
521 return p;
522 }
523
524 if (name.equals("setJustification")) {
525 Integer[] just = new Integer[1];
526 just[0] = getJustification(value);
527 return just;
528 }
529
530 if (name.endsWith("Arrow")) {
531 if (value.indexOf(" ") < 0)
532 return null;
533
534 Integer a = Integer
535 .parseInt(value.substring(0, value.indexOf(" ")));
536 Double b = Double.parseDouble(value
537 .substring(value.indexOf(" ") + 1));
538
539 Object[] vals = new Object[2];
540 vals[0] = a;
541 vals[1] = b;
542 return vals;
543 }
544
545 if (types.length == 1 && types[0] == List.class) {
546 StringTokenizer st = new StringTokenizer(value, "\n");
547 List<String> list = new LinkedList<String>();
548 while (st.hasMoreTokens())
549 list.add(st.nextToken());
550
551 Object[] vals = new Object[1];
552 vals[0] = list;
553 return vals;
554 }
555
556 if (types.length == 1) {
557 Object o[] = new Object[1];
558 o[0] = Convert(types[0], value, current);
559 return o;
560 }
561 /*
562 * if(types.length == 1 && types[0] == int.class){ Convert(types[0],
563 * value);
564 *
565 * Integer[] val = new Integer[1]; val[0] = Integer.parseInt(value);
566 * return val; }
567 *
568 * if(types.length == 1 && types[0] == float.class){ Float[] val = new
569 * Float[1]; val[0] = Float.parseFloat(value); return val; }
570 *
571 * if(types.length == 1 && types[0] == Font.class){ Font f =
572 * getFont(value); if(f != null){ Font[] res = new Font[1]; res[0] = f;
573 * return res; }
574 *
575 * return null; }
576 *
577 * if(types.length == 1 && types[0] == Color.class){ Color c =
578 * getColor(value, null); if(c != null){ Color[] res = new Color[1];
579 * res[0] = c; return res; }
580 *
581 * return null; }
582 *
583 * if(types.length == 1 && types[0] == int[].class){ if(value.length() ==
584 * 0) return null;
585 *
586 * StringTokenizer st = new StringTokenizer(value, " "); int[] param =
587 * new int[st.countTokens()]; for(int i = 0; i < param.length; i++){
588 * try{ param[i] = Integer.parseInt(st.nextToken()); }catch(Exception
589 * e){ return null; } }
590 *
591 * Object[] o = new Object[1]; o[0] = param; return o; }
592 */
593
594 // return name + ": " + value;
595 String[] val = new String[1];
596 val[0] = value;
597 return val;
598 }
599
600 public static Object ConvertToKMS(Method method, Object output) {
601 if (output == null)
602 return null;
603
604 if (method == null) {
605 System.out.println("Output: " + output);
606 }
607
608 String name = method.getName();
609
610 if (output instanceof List)
611 return output;
612
613 if (name.endsWith("Justification"))
614 return getKMSJustificationCode((Integer) output);
615
616 // strings can be returned immediately
617 if (output instanceof String)
618 return (String) output;
619
620 // integers can also be returned immediately
621 if (output instanceof Integer && (Integer) output >= 0)
622 return "" + output;
623
624 // floats can also be returned immediately
625 if (output instanceof Float && (Float) output >= 0)
626 return "" + output;
627
628 // convert fonts
629 if (output instanceof Font)
630 return getKMSFontCode((Font) output);
631
632 // convert colors
633 if (output instanceof Color)
634 return getKMSColorCode((Color) output);
635
636 // covert points
637 if (output instanceof Point)
638 return (((Point) output).x - X_ADJUST) + " "
639 + (((Point) output).y - Y_ADJUST);
640
641 if (output instanceof Boolean)
642 if ((Boolean) output)
643 return null;
644 else
645 return "F";
646
647 if (output instanceof int[]) {
648 int[] out = (int[]) output;
649 String res = "";
650 for (int i : out)
651 res += i + " ";
652
653 res = res.trim();
654 if (res.length() > 0)
655 return res;
656 }
657 // default
658 return null;
659 }
660}
Note: See TracBrowser for help on using the repository browser.