source: trunk/src/org/expeditee/actions/Misc.java@ 294

Last change on this file since 294 was 294, checked in by ra33, 16 years ago
File size: 24.6 KB
Line 
1package org.expeditee.actions;
2
3import java.awt.Color;
4import java.awt.Image;
5import java.awt.image.BufferedImage;
6import java.awt.image.VolatileImage;
7import java.io.File;
8import java.io.FileNotFoundException;
9import java.io.IOException;
10import java.lang.reflect.Method;
11import java.util.ArrayList;
12import java.util.Collection;
13import java.util.LinkedList;
14import java.util.List;
15
16import javax.imageio.ImageIO;
17
18import org.expeditee.gui.DisplayIO;
19import org.expeditee.gui.Frame;
20import org.expeditee.gui.FrameGraphics;
21import org.expeditee.gui.FrameIO;
22import org.expeditee.gui.FrameMouseActions;
23import org.expeditee.gui.MessageBay;
24import org.expeditee.gui.Reminders;
25import org.expeditee.gui.TimeKeeper;
26import org.expeditee.importer.FrameDNDTransferHandler;
27import org.expeditee.items.Item;
28import org.expeditee.items.ItemUtils;
29import org.expeditee.items.Line;
30import org.expeditee.items.Text;
31import org.expeditee.math.ExpediteeJEP;
32import org.expeditee.simple.SString;
33import org.expeditee.stats.CometStats;
34import org.expeditee.stats.SessionStats;
35import org.expeditee.stats.StatsLogger;
36import org.expeditee.stats.TreeStats;
37import org.nfunk.jep.Node;
38import org.nfunk.jep.ParseException;
39
40/**
41 * A list of miscellaneous Actions and Actions specific to Expeditee
42 *
43 */
44public class Misc {
45 /**
46 * Causes the system to beep
47 */
48 public static void beep() {
49 java.awt.Toolkit.getDefaultToolkit().beep();
50 }
51
52 /**
53 * Forces a repaint of the current Frame
54 */
55 public static void display() {
56 FrameGraphics.refresh(false);
57 }
58
59 /**
60 * Restores the current frame to the last saved version currently on the
61 * hard disk
62 */
63 public static void restore() {
64 FrameIO.Reload();
65 // MessageBay.displayMessage("Restoration complete.");
66 }
67
68 /**
69 * Toggles AudienceMode on or off
70 */
71 public static void toggleAudienceMode() {
72 FrameGraphics.ToggleAudienceMode();
73 }
74
75 /**
76 * Toggles TwinFrames mode on or off
77 */
78 public static void toggleTwinFramesMode() {
79 DisplayIO.ToggleTwinFrames();
80 }
81
82 /**
83 * If the given Item is a Text Item, then the text of the Item is
84 * interpreted as actions, if not this method does nothing.
85 *
86 * @param current
87 * The Item to read the Actions from
88 */
89 public static void runItem(Item current) throws Exception {
90 if (current instanceof Text) {
91 List<String> actions = ((Text) current).getTextList();
92 for (String action : actions) {
93 if (!action.equalsIgnoreCase("runitem")) {
94 Actions.PerformAction(DisplayIO.getCurrentFrame(), current,
95 action);
96 }
97 }
98 } else {
99 MessageBay.errorMessage("Item must be a text item.");
100 }
101 }
102
103 /**
104 * Prompts the user to confirm deletion of the current Frame, and deletes if
105 * the user chooses. After deletion this action calls back(), to ensure the
106 * deleted frame is not still being shown
107 *
108 */
109 public static void DeleteFrame(Frame toDelete) {
110 String deletedFrame = toDelete.getName();
111 String deletedFrameNameLowercase = deletedFrame.toLowerCase();
112 String errorMessage = "Error deleting " + deletedFrame;
113 try {
114 String deletedFrameName = FrameIO.DeleteFrame(toDelete);
115 if (deletedFrameName != null) {
116 DisplayIO.Back();
117 // Remove any links on the previous frame to the one being
118 // deleted
119 Frame current = DisplayIO.getCurrentFrame();
120 for (Item i : current.getItems())
121 if (i.getLink() != null
122 && i.getAbsoluteLink().toLowerCase().equals(
123 deletedFrameNameLowercase)) {
124 i.setLink(null);
125 }
126 MessageBay.displayMessage(deletedFrame + " renamed "
127 + deletedFrameName);
128 // FrameGraphics.Repaint();
129 return;
130 }
131 } catch (IOException ioe) {
132 if (ioe.getMessage() != null)
133 errorMessage += ". " + ioe.getMessage();
134 } catch (SecurityException se) {
135 if (se.getMessage() != null)
136 errorMessage += ". " + se.getMessage();
137 } catch (Exception e) {
138 e.printStackTrace();
139 }
140 MessageBay.errorMessage(errorMessage);
141 }
142
143 /**
144 * Loads the Frame linked to by the given Item. The first Item on the Frame
145 * that is not the title or name is then placed on the cursor. If the given
146 * Item has no link, or no item is found then this is a no-op.
147 *
148 * @param current
149 * The Item that links to the Frame that the Item will be loaded
150 * from.
151 */
152 public static Item GetItemFromChildFrame(Item current) {
153 return getFromChildFrame(current, false);
154 }
155
156 public static void GetItemsFromChildFrame(Item current) {
157 getItemsFromChildFrame(current, false);
158 }
159
160 /**
161 * Loads the Frame linked to by the given Item. The first Text Item on the
162 * Frame that is not the title or name is then placed on the cursor. If the
163 * given Item has no link, or no item is found then this is a no-op.
164 *
165 * @param current
166 * The Item that links to the Frame that the Item will be loaded
167 * from.
168 */
169 public static Item GetTextFromChildFrame(Item current) {
170 return getFromChildFrame(current, true);
171 }
172
173 private static Item getFromChildFrame(Item current, boolean textOnly) {
174 Item item = getFirstBodyItemOnChildFrame(current, textOnly);
175 // if no item was found
176 if (item != null) {
177 // copy the item and switch
178 item = item.copy();
179 item.setPosition(DisplayIO.getMouseX(), FrameMouseActions.getY());
180 }
181 return item;
182 }
183
184 private static void getItemsFromChildFrame(Item current, boolean textOnly) {
185 Collection<Item> items = getItemsOnChildFrame(current, textOnly);
186 // if no item was found
187 if (items == null || items.size() == 0) {
188 return;
189 }
190
191 // copy the item and switch
192 Collection<Item> copies = ItemUtils.CopyItems(items);
193 Item first = items.iterator().next();
194 float deltaX = DisplayIO.getMouseX() - first.getX();
195 float deltaY = FrameMouseActions.getY() - first.getY();
196 for (Item i : copies) {
197 if (i.isVisible())
198 i.setXY(i.getX() + deltaX, i.getY() + deltaY);
199 i.setParent(null);
200 }
201 FrameMouseActions.pickup(copies);
202 FrameGraphics.Repaint();
203 }
204
205 /**
206 * Sets the given Item to have the Given Color. Color can be null (for
207 * default)
208 *
209 * @param toChange
210 * The Item to set the Color.
211 * @param toUse
212 * The Color to give the Item.
213 */
214 public static void SetItemBackgroundColor(Item toChange, Color toUse) {
215 if (toChange == null)
216 return;
217
218 toChange.setBackgroundColor(toUse);
219 FrameGraphics.Repaint();
220 }
221
222 /**
223 * Sets the given Item to have the Given Color. Color can be null (for
224 * default)
225 *
226 * @param toChange
227 * The Item to set the Color.
228 * @param toUse
229 * The Color to give the Item.
230 */
231 public static void SetItemColor(Item toChange, Color toUse) {
232 if (toChange == null)
233 return;
234
235 toChange.setColor(toUse);
236 FrameGraphics.Repaint();
237 }
238
239 /**
240 * Creates a new Text Object containing general statistics for the current
241 * session. The newly created Text Object is then attached to the cursor via
242 * FrameMouseActions.pickup(Item)
243 */
244 public static void GetSessionStats() {
245 attachStatsToCursor(SessionStats.getCurrentStats());
246 }
247
248 /**
249 * Creates a new Text Object containing statistics for the current tree.
250 */
251 public static String GetCometStats(Frame frame) {
252 TimeKeeper timer = new TimeKeeper();
253 MessageBay.displayMessage("Computing comet stats...");
254 CometStats cometStats = new CometStats(frame);
255 String result = cometStats.toString();
256 MessageBay.overwriteMessage("Comet stats time: "
257 + timer.getElapsedStringSeconds());
258 return result;
259 }
260
261 public static String GetTreeStats(Frame frame) {
262 TimeKeeper timer = new TimeKeeper();
263 MessageBay.displayMessage("Computing tree stats...");
264
265 TreeStats treeStats = new TreeStats(frame);
266 String result = treeStats.toString();
267 MessageBay.overwriteMessage("Tree stats time: "
268 + timer.getElapsedStringSeconds());
269 return result;
270
271 }
272
273 /**
274 * Creates a text item and attaches it to the cursor.
275 *
276 * @param itemText
277 * the text to attach to the cursor
278 */
279 public static void attachStatsToCursor(String itemText) {
280 SessionStats.CreatedText();
281 Frame current = DisplayIO.getCurrentFrame();
282 Item text = current.getStatsTextItem(itemText);
283 FrameMouseActions.pickup(text);
284 FrameGraphics.Repaint();
285 }
286
287 public static void attachTextToCursor(String itemText) {
288 SessionStats.CreatedText();
289 Frame current = DisplayIO.getCurrentFrame();
290 Item text = current.getTextItem(itemText);
291 FrameMouseActions.pickup(text);
292 FrameGraphics.Repaint();
293 }
294
295 /**
296 * Creates a new Text Object containing statistics for moving, deleting and
297 * creating items in the current session. The newly created Text Object is
298 * then attached to the cursor via FrameMouseActions.pickup(Item)
299 */
300 public static String getItemStats() {
301 return SessionStats.getItemStats();
302 }
303
304 /**
305 * Creates a new Text Object containing statistics for the time between
306 * events triggered by the user through mouse clicks and key presses. The
307 * newly created Text Object is then attached to the cursor via
308 * FrameMouseActions.pickup(Item)
309 */
310 public static String getEventStats() {
311 return SessionStats.getEventStats();
312 }
313
314 /**
315 * Creates a new Text Object containing the contents of the current frames
316 * file.
317 */
318 public static String getFrameFile(Frame frame) {
319 return FrameIO.ForceSaveFrame(frame);
320 }
321
322 /**
323 * Creates a new Text Object containing the available fonts.
324 */
325 public static String getFontNames() {
326 Collection<String> availableFonts = Actions.getFonts().values();
327 StringBuilder fontsList = new StringBuilder();
328 for (String s : availableFonts) {
329 fontsList.append(s).append(Text.LINE_SEPARATOR);
330 }
331 fontsList.deleteCharAt(fontsList.length() - 1);
332
333 return fontsList.toString();
334 }
335
336 public static String getUnicodeCharacters(int start, int finish) {
337 if (start < 0 && finish < 0) {
338 throw new RuntimeException("Parameters must be non negative");
339 }
340 // Swap the start and finish if they are inthe wrong order
341 if (start > finish) {
342 start += finish;
343 finish = start - finish;
344 start = start - finish;
345 }
346 StringBuilder charList = new StringBuilder();
347 int count = 0;
348 charList.append(String.format("Unicode block 0x%x - 0x%x", start,
349 finish));
350 System.out.println();
351 // charList.append("Unicode block: ").append(String.format(format,
352 // args))
353 for (char i = (char) start; i < (char) finish; i++) {
354 if (Character.isDefined(i)) {
355 if (count++ % 64 == 0)
356 charList.append(Text.LINE_SEPARATOR);
357 charList.append(Character.valueOf(i));
358 }
359 }
360 return charList.toString();
361 }
362
363 /**
364 * Gets a single block of Unicode characters.
365 *
366 * @param start
367 * the start of the block
368 */
369 public static String getUnicodeCharacters(int start) {
370 return getUnicodeCharacters(start, start + 256);
371 }
372
373 public static String getMathSymbols() {
374 return getUnicodeCharacters('\u2200', '\u2300');
375 }
376
377 /**
378 * Resets the statistics back to zero.
379 */
380 public static void repaint() {
381 StatsLogger.WriteStatsFile();
382 SessionStats.resetStats();
383 }
384
385 /**
386 * Loads a frame with the given name and saves it as a JPEG image.
387 *
388 * @param framename
389 * The name of the Frame to save
390 */
391 public static void jpegFrame(String framename) {
392 ImageFrame(framename, "JPEG");
393 }
394
395 /**
396 * Saves the current frame as a JPEG image. This is the same as calling
397 * JpegFrame(currentFrame.getName())
398 */
399 public static void jpegFrame() {
400 ImageFrame(DisplayIO.getCurrentFrame().getName(), "JPEG");
401 }
402
403 public static void jpgFrame() {
404 jpegFrame();
405 }
406
407 /**
408 * Loads a frame with the given name and saves it as a PNG image.
409 *
410 * @param framename
411 * The name of the Frame to save
412 */
413 public static void PNGFrame(String framename) {
414 ImageFrame(framename, "PNG");
415 }
416
417 /**
418 * Saves the current frame as a PNG image. This is the same as calling
419 * PNGFrame(currentFrame.getName())
420 */
421 public static void PNGFrame() {
422 ImageFrame(DisplayIO.getCurrentFrame().getName(), "PNG");
423 }
424
425 public static String SaveImage(BufferedImage screen, String format,
426 String directory, String fileName) {
427 // Check if we need to append the suffix
428 if (fileName.indexOf('.') < 0)
429 fileName += "." + format.toLowerCase();
430
431 try {
432 // set up the file for output
433 String fullFileName = directory + fileName;
434 File out = new File(fullFileName);
435 if (!out.getParentFile().exists())
436 out.mkdirs();
437
438 // If the image is successfully written out return the fileName
439 if (ImageIO.write(screen, format, out))
440 return fileName;
441
442 } catch (Exception e) {
443 e.printStackTrace();
444 }
445 return null;
446 }
447
448 public static String ImageFrame(Frame frame, String format, String directory) {
449 assert (frame != null);
450
451 Image oldBuffer = frame.getBuffer();
452 frame.setBuffer(null);
453 // Jpeg only works properly with volitile frames
454 // Png transparency only works with bufferedImage form
455 Image frameBuffer = FrameGraphics.getBuffer(frame, false, format
456 .equalsIgnoreCase("jpeg"));
457 // Make sure overlay stuff doesnt disapear on the frame visible on the
458 // screen
459 frame.setBuffer(oldBuffer);
460 BufferedImage screen = null;
461
462 if (frameBuffer instanceof VolatileImage) {
463 // If its the current frame it will be a volitive image
464 screen = ((VolatileImage) frameBuffer).getSnapshot();
465 } else {
466 assert (frameBuffer instanceof BufferedImage);
467 screen = (BufferedImage) frameBuffer;
468 }
469 return SaveImage(screen, format, directory, frame.getExportFileName());
470 }
471
472 /**
473 * Saves the Frame with the given Framename as an image of the given format.
474 *
475 * @param framename
476 * The name of the Frame to save as an image
477 * @param format
478 * The Image format to use (i.e. "PNG", "BMP", etc)
479 */
480 public static void ImageFrame(String framename, String format) {
481 Frame loaded = FrameIO.LoadFrame(framename);
482
483 // if the frame was loaded successfully
484 if (loaded != null) {
485 String path = FrameIO.IMAGES_PATH;
486 String frameName = ImageFrame(loaded, format, path);
487 if (frameName != null)
488 MessageBay.displayMessage("Frame successfully saved to " + path
489 + frameName);
490 else
491 MessageBay.errorMessage("Could not find image writer for "
492 + format + " format");
493 // if the frame was not loaded successfully, alert the user
494 } else {
495 MessageBay.displayMessage("Frame '" + framename
496 + "' could not be found.");
497 }
498 }
499
500 /**
501 * Displays a message in the message box area.
502 *
503 * @param message
504 * the message to display
505 */
506 public static void MessageLn(String message) {
507 MessageBay.displayMessage(message);
508 }
509
510 public static void MessageLn2(String message, String message2) {
511 MessageBay.displayMessage(message + " " + message2);
512 }
513
514 public static void CopyFile(String existingFile, String newFileName) {
515 try {
516 // TODO is there a built in method which will do this faster?
517
518 MessageBay.displayMessage("Copying file " + existingFile + " to "
519 + newFileName + "...");
520 FrameIO.copyFile(existingFile, newFileName);
521 MessageBay.displayMessage("File copied successfully");
522 } catch (FileNotFoundException e) {
523 MessageBay.displayMessage("Error opening file: " + existingFile);
524 } catch (Exception e) {
525 MessageBay.displayMessage("File could not be copied");
526 }
527 }
528
529 /**
530 * Runs two methods alternatively a specified number of times and reports on
531 * the time spent running each method.
532 *
533 * @param fullMethodNameA
534 * @param fullMethodNameB
535 * @param repsPerTest
536 * the number of time each method is run per test
537 * @param tests
538 * the number of tests to conduct
539 *
540 */
541 public static void CompareMethods(String fullMethodNameA,
542 String fullMethodNameB, int repsPerTest, int tests) {
543 try {
544 String classNameA = getClassName(fullMethodNameA);
545 String classNameB = getClassName(fullMethodNameB);
546 String methodNameA = getMethodName(fullMethodNameA);
547 String methodNameB = getMethodName(fullMethodNameB);
548
549 Class<?> classA = Class.forName(classNameA);
550 Class<?> classB = Class.forName(classNameB);
551 Method methodA = classA.getDeclaredMethod(methodNameA,
552 new Class[] {});
553 Method methodB = classB.getDeclaredMethod(methodNameB,
554 new Class[] {});
555 TimeKeeper timeKeeper = new TimeKeeper();
556 long timeA = 0;
557 long timeB = 0;
558 // Run the tests
559 for (int i = 0; i < tests; i++) {
560 // Test methodA
561 timeKeeper.restart();
562 for (int j = 0; j < repsPerTest; j++) {
563 methodA.invoke((Object) null, new Object[] {});
564 }
565 timeA += timeKeeper.getElapsedMillis();
566 timeKeeper.restart();
567 // Test methodB
568 for (int j = 0; j < repsPerTest; j++) {
569 methodB.invoke((Object) null, new Object[] {});
570 }
571 timeB += timeKeeper.getElapsedMillis();
572 }
573
574 float aveTimeA = timeA * 1000F / repsPerTest / tests;
575 float aveTimeB = timeB * 1000F / repsPerTest / tests;
576 // Display Results
577 MessageBay.displayMessage("Average Execution Time");
578 MessageBay.displayMessage(methodNameA + ": "
579 + TimeKeeper.Formatter.format(aveTimeA) + "us");
580 MessageBay.displayMessage(methodNameB + ": "
581 + TimeKeeper.Formatter.format(aveTimeB) + "us");
582 } catch (Exception e) {
583 MessageBay.errorMessage(e.getClass().getSimpleName() + ": "
584 + e.getMessage());
585 }
586 }
587
588 public static String getClassName(String fullMethodName) {
589 assert (fullMethodName != null);
590 assert (fullMethodName.length() > 0);
591 int lastPeriod = fullMethodName.lastIndexOf('.');
592 if (lastPeriod > 0 && lastPeriod < fullMethodName.length() - 1)
593 return fullMethodName.substring(0, lastPeriod);
594 throw new RuntimeException("Invalid method name: " + fullMethodName);
595 }
596
597 public static String getMethodName(String methodName) {
598 assert (methodName != null);
599 assert (methodName.length() > 0);
600 int lastPeriod = methodName.lastIndexOf('.');
601 if (lastPeriod > 0 && lastPeriod < methodName.length() - 1)
602 return methodName.substring(1 + lastPeriod);
603 throw new RuntimeException("Invalid method name: " + methodName);
604 }
605
606 /**
607 * Loads the Frame linked to by the given Item. The first Item on the Frame
608 * that is not the title or name is then placed on the current frame. The
609 * item that was clicked on is placed on the frame it was linked to and the
610 * link is switched to the item from the child frame. If the given Item has
611 * no link, or no item is found then this is a no-op.
612 *
613 * @param current
614 * The Item that links to the Frame that the Item will be loaded
615 * from.
616 */
617 public static void SwapItemWithItemOnChildFrame(Item current) {
618 Item item = getFirstBodyItemOnChildFrame(current, false);
619 // if no item was found
620 if (item == null) {
621 return;
622 }
623
624 // swap the items parents
625 Frame parentFrame = current.getParent();
626 Frame childFrame = item.getParent();
627 current.setParent(childFrame);
628 item.setParent(parentFrame);
629
630 // swap the items on the frames
631 parentFrame.removeItem(current);
632 childFrame.removeItem(item);
633 parentFrame.addItem(item);
634 childFrame.addItem(current);
635
636 // swap the items links
637 item.setActions(current.getAction());
638 item.setLink(childFrame.getName());
639 current.setLink(parentFrame.getName());
640 // current.setLink(null);
641 current.setActions(null);
642
643 FrameGraphics.Repaint();
644 }
645
646 private static Item getFirstBodyItemOnChildFrame(Item current,
647 boolean textOnly) {
648 // the item must link to a frame
649 if (current.getLink() == null) {
650 MessageBay
651 .displayMessage("Cannot get item from child - this item has no link");
652 return null;
653 }
654
655 Frame child = FrameIO.LoadFrame(current.getAbsoluteLink());
656
657 // if the frame could not be loaded
658 if (child == null) {
659 MessageBay.errorMessage("Could not load child frame.");
660 return null;
661 }
662
663 // find the first non-title and non-name item
664 List<Item> body = new ArrayList<Item>();
665 if (textOnly)
666 body.addAll(child.getBodyTextItems(false));
667 else
668 body.addAll(child.getItems());
669 Item item = null;
670
671 for (Item i : body)
672 if (i != child.getTitleItem() && !i.isAnnotation()) {
673 item = i;
674 break;
675 }
676
677 // if no item was found
678 if (item == null) {
679 MessageBay.displayMessage("No item found to copy");
680 return null;
681 }
682
683 return item;
684 }
685
686 private static Collection<Item> getItemsOnChildFrame(Item current,
687 boolean textOnly) {
688 // the item must link to a frame
689 if (current.getLink() == null) {
690 MessageBay
691 .displayMessage("Cannot get item from child - this item has no link");
692 return null;
693 }
694 Frame child = FrameIO.LoadFrame(current.getAbsoluteLink());
695
696 // if the frame could not be loaded
697 if (child == null) {
698 MessageBay.errorMessage("Could not load child frame.");
699 return null;
700 }
701
702 // find the first non-title and non-name item
703 Collection<Item> body = new ArrayList<Item>();
704 if (textOnly)
705 body.addAll(child.getBodyTextItems(false));
706 else
707 body.addAll(child.getItems());
708
709 return body;
710 }
711
712 public static void calculate(Frame frame, Item toCalculate) {
713 if (toCalculate instanceof Text) {
714 Text text = (Text) toCalculate;
715 ExpediteeJEP myParser = new ExpediteeJEP();
716 myParser.addVariables(frame);
717 String linkedFrame = toCalculate.getAbsoluteLink();
718 if (linkedFrame != null) {
719 myParser.addVariables(FrameIO.LoadFrame(linkedFrame));
720 }
721 myParser.resetObserver();
722
723 // Do the calculation
724 String formulaFullCase = text.getText().replace('\n', ' ');
725 String formula = formulaFullCase.toLowerCase();
726
727 try {
728 Node node = myParser.parse(formula);
729 Object result = myParser.evaluate(node);
730 text.setText(result.toString());
731 text.setFormula(formulaFullCase);
732 if (text.isFloating()) {
733 text.setPosition(FrameMouseActions.MouseX,
734 FrameMouseActions.MouseY);
735 FrameMouseActions.resetOffset();
736 } else {
737 text.getParentOrCurrentFrame().change();
738 }
739 } catch (ParseException e) {
740 MessageBay.errorMessage("Parse error "
741 + e.getMessage().replace("\n", ""));
742 } catch (Exception e) {
743 MessageBay.errorMessage("evaluation error "
744 + e.getMessage().replace("\n", ""));
745 e.printStackTrace();
746 }
747 }
748 }
749
750 /**
751 * Attach an item to the cursor.
752 *
753 * @param item
754 */
755 public static void attachToCursor(Item item) {
756 item.setParent(null);
757 FrameMouseActions.pickup(item);
758 FrameGraphics.Repaint();
759 }
760
761 public static void attachToCursor(Collection<Item> items) {
762 for (Item i : items) {
763 i.setParent(null);
764 }
765 FrameMouseActions.pickup(items);
766 FrameGraphics.Repaint();
767 }
768
769 public static void importFiles(Item item) {
770 List<File> files = new LinkedList<File>();
771 for (String s : item.getText().split("\\s+")) {
772 File file = new File(s.trim());
773 if (file.exists()) {
774 files.add(file);
775 }
776 }
777 try {
778 FrameDNDTransferHandler.getInstance().importFileList(files,
779 FrameMouseActions.getPosition());
780 } catch (Exception e) {
781 }
782 }
783
784 public static void importFile(Item item) {
785 File file = new File(item.getText().trim());
786 if (file.exists()) {
787 try {
788 FrameDNDTransferHandler.getInstance().importFile(file,
789 FrameMouseActions.getPosition());
790 } catch (Exception e) {
791 e.printStackTrace();
792 }
793 }
794 }
795
796 public static Item createPolygon(Item item, int sides) {
797 if (item instanceof Text) {
798 try {
799 SString s = new SString(item.getText());
800 sides = s.integerValue().intValue();
801 } catch (NumberFormatException e) {
802 }
803 }
804
805 if (sides < 3) {
806 MessageBay.errorMessage("Shapes must have at least 3 sides");
807 }
808 double angle = -(180 - ((sides - 2) * 180.0F) / sides);
809 double curAngle = 0;
810 double size = 50F;
811 if (item.isLineEnd() && item.getLines().size() > 0) {
812 item = item.getLines().get(0);
813 }
814 // Use line length to determine the size of the shape
815 if (item instanceof Line) {
816 size = ((Line) item).getLength();
817 }
818
819 float curX = FrameMouseActions.MouseX;
820 float curY = FrameMouseActions.MouseY;
821
822 Collection<Item> newItems = new LinkedList<Item>();
823 Item[] d = new Item[sides];
824 // create dots
825 Frame current = DisplayIO.getCurrentFrame();
826 for (int i = 0; i < d.length; i++) {
827 d[i] = current.createDot();
828 newItems.add(d[i]);
829 d[i].setPosition(curX, curY);
830 curX += (float) (Math.cos((curAngle) * Math.PI / 180.0) * size);
831 curY += (float) (Math.sin((curAngle) * Math.PI / 180.0) * size);
832
833 curAngle += angle;
834 }
835 // create lines
836 for (int i = 1; i < d.length; i++) {
837 newItems.add(new Line(d[i - 1], d[i], current.getNextItemID()));
838 }
839 newItems.add(new Line(d[d.length - 1], d[0], current.getNextItemID()));
840
841 current.addAllItems(newItems);
842 if (item instanceof Text) {
843 for (Item i : item.getAllConnected()) {
844 if (i instanceof Line) {
845 item = i;
846 break;
847 }
848 }
849 }
850
851 Color newColor = item.getColor();
852 if (newColor != null) {
853 d[0].setColor(item.getColor());
854 if (item instanceof Text && item.getBackgroundColor() != null) {
855 d[0].setFillColor(item.getBackgroundColor());
856 }else{
857 d[0].setFillColor(item.getFillColor());
858 }
859 }
860 float newThickness = item.getThickness();
861 if (newThickness > 0) {
862 d[0].setThickness(newThickness);
863 }
864
865 ItemUtils.EnclosedCheck(newItems);
866 FrameGraphics.refresh(false);
867
868 return d[0];
869 }
870
871 public static void StopReminder() {
872 Reminders.stop();
873 }
874}
Note: See TracBrowser for help on using the repository browser.