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

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

Added lots of stuff

File size: 15.9 KB
Line 
1package org.expeditee.actions;
2
3import java.awt.Color;
4import java.awt.Dimension;
5import java.awt.GraphicsEnvironment;
6import java.awt.image.BufferedImage;
7import java.io.File;
8import java.io.FileNotFoundException;
9import java.io.IOException;
10import java.lang.reflect.Method;
11import java.util.ArrayList;
12import java.util.List;
13
14import javax.imageio.ImageIO;
15
16import org.expeditee.gui.DisplayIO;
17import org.expeditee.gui.Frame;
18import org.expeditee.gui.FrameGraphics;
19import org.expeditee.gui.FrameIO;
20import org.expeditee.gui.FrameMouseActions;
21import org.expeditee.gui.TimeKeeper;
22import org.expeditee.items.Item;
23import org.expeditee.items.Text;
24import org.expeditee.stats.SessionStats;
25import org.expeditee.stats.StatsLogger;
26
27/**
28 * A list of miscellaneous KMS Actions and Actions specific to Expeditee
29 *
30 */
31public class Misc {
32 private static final int FRAME_FILE_FONT_SIZE = 10;
33
34 /**
35 * Causes the system to beep
36 */
37 public static void Beep() {
38 java.awt.Toolkit.getDefaultToolkit().beep();
39 }
40
41 /**
42 * Forces a repaint of the current Frame
43 */
44 public static void Display() {
45 FrameGraphics.ForceRepaint();
46 }
47
48 /**
49 * Restores the current frame to the last saved version currently on the
50 * hard disk
51 */
52 public static void Restore() {
53 FrameIO.Reload();
54
55 FrameGraphics.DisplayMessage("Restoration complete.");
56 }
57
58 /**
59 * Toggles AudienceMode on or off
60 */
61 public static void ToggleAudienceMode() {
62 FrameGraphics.ToggleAudienceMode();
63 }
64
65 /**
66 * Toggles TwinFrames mode on or off
67 */
68 public static void ToggleTwinFramesMode() {
69 DisplayIO.ToggleTwinFrames();
70 }
71
72 /**
73 * Exits the System
74 */
75 public static void Exit() {
76 /**
77 * TODO: Prompt the user etc.
78 */
79 FrameIO.SaveFrame(DisplayIO.getCurrentFrame());
80
81 while (FrameIO.DeleteFrameset("messages"))
82 ;
83
84 StatsLogger.WriteStatsFile();
85
86 System.exit(0);
87 }
88
89 /**
90 * If the given Item is a Text Item, then the text of the Item is
91 * interpreted as actions, if not this method does nothing.
92 *
93 * @param current
94 * The Item to read the Actions from
95 */
96 public static void RunCurrentItem(Item current) {
97 if (current instanceof Text) {
98 List<String> actions = ((Text) current).getText();
99
100 for (String action : actions) {
101 Actions.PerformAction(DisplayIO.getCurrentFrame(), current,
102 action);
103 }
104 }
105
106 }
107
108 /**
109 * Prompts the user to confirm deletion of the current Frame, and deletes if
110 * the user chooses. After deletion this action calls back(), to ensure the
111 * deleted frame is not still being shown
112 *
113 */
114 public static void DeleteFrame() {
115 Frame toDelete = DisplayIO.getCurrentFrame();
116 DisplayIO.Back();
117 String deletedFrame = toDelete.getFrameName();
118 String deletedFrameNameLowercase = deletedFrame.toLowerCase();
119 try {
120 boolean del = FrameIO.DeleteFrame(toDelete);
121 if (!del) {
122 FrameGraphics.ErrorMessage("Error trying to delete "
123 + toDelete.getFrameName());
124 } else {
125 Frame current = DisplayIO.getCurrentFrame();
126 for (Item i : current.getItems())
127 if (i.getLink() != null
128 && i.getAbsoluteLink().toLowerCase().equals(
129 deletedFrameNameLowercase)) {
130 i.setLink(null);
131 }
132
133 FrameGraphics.Repaint();
134 FrameGraphics.DisplayMessage(deletedFrame + " Deleted.");
135 }
136 } catch (IOException ioe) {
137 FrameGraphics.ErrorMessage("Error trying to delete " + deletedFrame
138 + ":\n" + ioe.getMessage());
139 }
140 }
141
142 /**
143 * Loads the Frame linked to by the given Item. The first Item on the Frame
144 * that is not the title or name is then placed on the cursor. If the given
145 * Item has no link, or no item is found then this is a no-op.
146 *
147 * @param current
148 * The Item that links to the Frame that the Item will be loaded
149 * from.
150 */
151 public static void GetItemFromChildFrame(Item current) {
152 getFromChildFrame(current, false);
153 }
154
155 /**
156 * Loads the Frame linked to by the given Item. The first Text Item on the
157 * Frame that is not the title or name is then placed on the cursor. If the
158 * given Item has no link, or no item is found then this is a no-op.
159 *
160 * @param current
161 * The Item that links to the Frame that the Item will be loaded
162 * from.
163 */
164 public static void GetTextFromChildFrame(Item current) {
165 getFromChildFrame(current, true);
166 }
167
168 private static void getFromChildFrame(Item current, boolean textOnly) {
169 Item item = getFirstBodyItemOnChildFrame(current, textOnly);
170 // if no item was found
171 if (item == null) {
172 return;
173 }
174
175 // copy the item and switch
176 item = item.copy();
177 item.setPosition(DisplayIO.getMouseX(), DisplayIO.getMouseY());
178 item.setParent(null);
179
180 FrameMouseActions.pickup(item);
181 FrameGraphics.Repaint();
182 }
183
184 /**
185 * Sets the given Item to have the Given Color. Color can be null (for
186 * default)
187 *
188 * @param toChange
189 * The Item to set the Color.
190 * @param toUse
191 * The Color to give the Item.
192 */
193 public static void SetCurrentItemBackgroundColor(Item toChange, Color toUse) {
194 if (toChange == null)
195 return;
196
197 toChange.setBackgroundColor(toUse);
198 FrameGraphics.Repaint();
199 }
200
201 /**
202 * Sets the given Item to have the Given Color. Color can be null (for
203 * default)
204 *
205 * @param toChange
206 * The Item to set the Color.
207 * @param toUse
208 * The Color to give the Item.
209 */
210 public static void SetCurrentItemColor(Item toChange, Color toUse) {
211 if (toChange == null)
212 return;
213
214 toChange.setColor(toUse);
215 FrameGraphics.Repaint();
216 }
217
218 /**
219 * Creates a new Text Object containing general statistics for the current
220 * session. The newly created Text Object is then attached to the cursor via
221 * FrameMouseActions.pickup(Item)
222 */
223 public static void GetSessionStats() {
224 CreateTextItem(SessionStats.getCurrentStats());
225 }
226
227 public static void CreateTextItem(String itemText) {
228 SessionStats.CreatedText();
229 Frame current = DisplayIO.getCurrentFrame();
230 Text text = current.getStatsTextItem(itemText);
231 FrameMouseActions.pickup(text);
232 FrameGraphics.Repaint();
233 }
234
235 /**
236 * Creates a new Text Object containing statistics for moving, deleting and
237 * creating items in the current session. The newly created Text Object is
238 * then attached to the cursor via FrameMouseActions.pickup(Item)
239 */
240 public static void GetItemStats() {
241 CreateTextItem(SessionStats.getItemStats());
242 }
243
244 /**
245 * Creates a new Text Object containing statistics for the time between
246 * events triggered by the user through mouse clicks and key presses. The
247 * newly created Text Object is then attached to the cursor via
248 * FrameMouseActions.pickup(Item)
249 */
250 public static void GetEventStats() {
251 CreateTextItem(SessionStats.getEventStats());
252 }
253
254 /**
255 * Creates a new Text Object containing the contents of the current frames
256 * file.
257 */
258 public static void GetCurrentFrameFile() {
259
260 String fileContents = FrameIO.SaveFrame(DisplayIO.getCurrentFrame());
261
262 Text text = DisplayIO.getCurrentFrame().createNewText();
263 // We dont want the stats to wrap at all
264 text.setMaxSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
265
266 text.setText(fileContents);
267
268 text.setPosition(DisplayIO.getMouseX(), DisplayIO.getMouseY());
269 text.setSize(FRAME_FILE_FONT_SIZE);
270
271 FrameMouseActions.pickup(text);
272
273 FrameGraphics.Repaint();
274 }
275
276 /**
277 * Creates a new Text Object containing the available fonts.
278 */
279 public static void GetAvailableFontFamilyNames() {
280
281 String[] availableFonts = GraphicsEnvironment
282 .getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
283 StringBuilder fontsList = new StringBuilder();
284 for (String s : availableFonts) {
285 fontsList.append(s).append('\n');
286 }
287
288 Text text = DisplayIO.getCurrentFrame().createNewText();
289 // We dont want the stats to wrap at all
290 text.setMaxSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
291 text.setText(fontsList.toString());
292
293 text.setPosition(DisplayIO.getMouseX(), DisplayIO.getMouseY());
294 text.setSize(FRAME_FILE_FONT_SIZE);
295
296 FrameMouseActions.pickup(text);
297
298 FrameGraphics.Repaint();
299 }
300
301 /**
302 * Resets the statistics back to zero.
303 */
304 public static void ResetStats() {
305 StatsLogger.WriteStatsFile();
306 SessionStats.resetStats();
307 }
308
309 /**
310 * Loads a frame with the given name and saves it as a JPEG image.
311 *
312 * @param framename
313 * The name of the Frame to save
314 */
315 public static void JpegFrame(String framename) {
316 ImageFrame(framename, "JPG");
317 }
318
319 /**
320 * Saves the current frame as a JPEG image. This is the same as calling
321 * JpegFrame(currentFrame.getFrameName())
322 */
323 public static void JpegFrame() {
324 ImageFrame(DisplayIO.getCurrentFrame().getFrameName(), "JPG");
325 }
326
327 /**
328 * Loads a frame with the given name and saves it as a PNG image.
329 *
330 * @param framename
331 * The name of the Frame to save
332 */
333 public static void PNGFrame(String framename) {
334 ImageFrame(framename, "PNG");
335 }
336
337 /**
338 * Saves the current frame as a PNG image. This is the same as calling
339 * PNGFrame(currentFrame.getFrameName())
340 */
341 public static void PNGFrame() {
342 ImageFrame(DisplayIO.getCurrentFrame().getFrameName(), "PNG");
343 }
344
345 /**
346 * Saves the Frame with the given Framename as an image of the given format.
347 *
348 * @param framename
349 * The name of the Frame to save as an image
350 * @param format
351 * The Image format to use (i.e. "PNG", "BMP", etc)
352 */
353 public static void ImageFrame(String framename, String format) {
354 Frame loaded = FrameIO.LoadFrame(framename);
355 String fileName = loaded.getExportFileName();
356
357 // if the frame was loaded successfully
358 if (loaded != null) {
359 // check if the buffer needs to be redrawn
360 // if (loaded.getBuffer() == null)
361 FrameGraphics.UpdateBuffer(loaded, false);
362
363 BufferedImage screen = loaded.getBuffer().getSnapshot();
364
365 try {
366 // set up the file for output
367 File out = new File(FrameIO.EXPORTS_DIR + fileName + "."
368 + format.toLowerCase());
369 if (!out.getParentFile().exists())
370 out.mkdirs();
371
372 ImageIO.write(screen, format, out);
373 FrameGraphics.DisplayMessage("Frame successfully saved to "
374 + FrameIO.EXPORTS_DIR + out.getName());
375 } catch (IOException e) {
376 FrameGraphics.ErrorMessage(e.getMessage());
377 }
378 // if the frame was not loaded successfully, alert the user
379 } else
380 FrameGraphics.DisplayMessage("Frame '" + framename
381 + "' could not be found.");
382 }
383
384 /**
385 * Displays a message in the message box area.
386 *
387 * @param message
388 * the message to display
389 */
390 public static void MessageLn(String message) {
391 FrameGraphics.DisplayMessage(message);
392 }
393
394 public static void MessageLn2(String message, String message2) {
395 FrameGraphics.DisplayMessage(message + " " + message2);
396 }
397
398 public static void CopyFile(String existingFile, String newFileName) {
399 try {
400 // TODO is there a built in method which will do this faster?
401
402 FrameGraphics.DisplayMessage("Copying file " + existingFile
403 + " to " + newFileName + "...");
404 FrameIO.copyFile(existingFile, newFileName);
405 FrameGraphics.DisplayMessage("File copied successfully");
406 } catch (FileNotFoundException e) {
407 FrameGraphics.DisplayMessage("Error opening file: " + existingFile);
408 } catch (Exception e) {
409 FrameGraphics.DisplayMessage("File could not be copied");
410 }
411 }
412
413 /**
414 * Runs two methods alternatively a specified number of times and reports on
415 * the time spent running each method.
416 *
417 * @param fullMethodNameA
418 * @param fullMethodNameB
419 * @param repsPerTest
420 * the number of time each method is run per test
421 * @param tests
422 * the number of tests to conduct
423 *
424 */
425 public static void CompareMethods(String fullMethodNameA,
426 String fullMethodNameB, int repsPerTest, int tests) {
427 try {
428 String classNameA = getClassName(fullMethodNameA);
429 String classNameB = getClassName(fullMethodNameB);
430 String methodNameA = getMethodName(fullMethodNameA);
431 String methodNameB = getMethodName(fullMethodNameB);
432
433 Class classA = Class.forName(classNameA);
434 Class classB = Class.forName(classNameB);
435 Method methodA = classA.getDeclaredMethod(methodNameA,
436 new Class[] {});
437 Method methodB = classB.getDeclaredMethod(methodNameB,
438 new Class[] {});
439 TimeKeeper timeKeeper = new TimeKeeper();
440 long timeA = 0;
441 long timeB = 0;
442 // Run the tests
443 for (int i = 0; i < tests; i++) {
444 // Test methodA
445 timeKeeper.restart();
446 for (int j = 0; j < repsPerTest; j++) {
447 methodA.invoke((Object) null, new Object[]{});
448 }
449 timeA += timeKeeper.getElapsedMillis();
450 timeKeeper.restart();
451 // Test methodB
452 for (int j = 0; j < repsPerTest; j++) {
453 methodB.invoke((Object) null, new Object[]{});
454 }
455 timeB += timeKeeper.getElapsedMillis();
456 }
457
458 float aveTimeA = timeA * 1000F / repsPerTest / tests;
459 float aveTimeB = timeB * 1000F / repsPerTest / tests;
460 // Display Results
461 FrameGraphics.DisplayMessage("Average Execution Time");
462 FrameGraphics.DisplayMessage(methodNameA + ": "
463 + TimeKeeper.Formatter.format(aveTimeA) + "us");
464 FrameGraphics.DisplayMessage(methodNameB + ": "
465 + TimeKeeper.Formatter.format(aveTimeB) + "us");
466 } catch (Exception e) {
467 FrameGraphics.ErrorMessage(e.getClass().getSimpleName() + ": "
468 + e.getMessage());
469 }
470 }
471
472 public static String getClassName(String fullMethodName) {
473 assert (fullMethodName != null);
474 assert (fullMethodName.length() > 0);
475 int lastPeriod = fullMethodName.lastIndexOf('.');
476 if (lastPeriod > 0 && lastPeriod < fullMethodName.length() - 1)
477 return fullMethodName.substring(0, lastPeriod);
478 throw new RuntimeException("Invalid method name: " + fullMethodName);
479 }
480
481 public static String getMethodName(String methodName) {
482 assert (methodName != null);
483 assert (methodName.length() > 0);
484 int lastPeriod = methodName.lastIndexOf('.');
485 if (lastPeriod > 0 && lastPeriod < methodName.length() - 1)
486 return methodName.substring(1 + lastPeriod);
487 throw new RuntimeException("Invalid method name: " + methodName);
488 }
489
490 /**
491 * Loads the Frame linked to by the given Item. The first Item on the Frame
492 * that is not the title or name is then placed on the current frame. The
493 * item that was clicked on is placed on the frame it was linked to and the
494 * link is switched to the item from the child frame. If the given Item has
495 * no link, or no item is found then this is a no-op.
496 *
497 * @param current
498 * The Item that links to the Frame that the Item will be loaded
499 * from.
500 */
501 public static void SwapItemWithItemOnChildFrame(Item current) {
502 Item item = getFirstBodyItemOnChildFrame(current, false);
503 // if no item was found
504 if (item == null) {
505 return;
506 }
507
508 // swap the items parents
509 Frame parentFrame = current.getParent();
510 Frame childFrame = item.getParent();
511 current.setParent(childFrame);
512 item.setParent(parentFrame);
513
514 // swap the items on the frames
515 parentFrame.removeItem(current);
516 childFrame.removeItem(item);
517 parentFrame.addItem(item);
518 childFrame.addItem(current);
519
520 // swap the items links
521 item.setAction(current.getAction());
522 item.setLink(childFrame.getFrameName());
523 current.setLink(parentFrame.getFrameName());
524 // current.setLink(null);
525 current.setAction(null);
526
527 FrameGraphics.Repaint();
528 }
529
530 private static Item getFirstBodyItemOnChildFrame(Item current,
531 boolean textOnly) {
532 // the item must link to a frame
533 if (current.getLink() == null) {
534 FrameGraphics
535 .DisplayMessage("Cannot get item from child - this item has no link");
536 return null;
537 }
538
539 Frame child = FrameIO.LoadFrame(current.getAbsoluteLink());
540
541 // if the frame could not be loaded
542 if (child == null) {
543 FrameGraphics.ErrorMessage("Could not load child frame.");
544 return null;
545 }
546
547 // find the first non-title and non-name item
548 List<Item> body = new ArrayList<Item>();
549 if (textOnly)
550 body.addAll(child.getBodyTextItems(false));
551 else
552 body.addAll(child.getItems());
553 Item item = null;
554
555 for (Item i : body)
556 if (i != child.getTitle() && !i.isAnnotation()) {
557 item = i;
558 break;
559 }
560
561 // if no item was found
562 if (item == null) {
563 FrameGraphics.DisplayMessage("No item found to copy");
564 return null;
565 }
566
567 return item;
568 }
569}
Note: See TracBrowser for help on using the repository browser.