source: trunk/src/org/expeditee/io/Conversion.java@ 421

Last change on this file since 421 was 421, checked in by ra33, 16 years ago

Can now move lines while the mouse button is depressed

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