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

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

Added Spell Checker
Added word count stats
Fixed some mail stuff

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