source: trunk/src/org/expeditee/gui/FrameIO.java@ 154

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

Fixing bugs for Rob

File size: 34.3 KB
Line 
1package org.expeditee.gui;
2
3import java.io.BufferedReader;
4import java.io.BufferedWriter;
5import java.io.File;
6import java.io.FileInputStream;
7import java.io.FileOutputStream;
8import java.io.FileReader;
9import java.io.FileWriter;
10import java.io.IOException;
11import java.sql.Time;
12import java.util.HashMap;
13
14import org.expeditee.agents.ExistingFramesetException;
15import org.expeditee.io.Conversion;
16import org.expeditee.io.ExpReader;
17import org.expeditee.io.ExpWriter;
18import org.expeditee.io.FrameReader;
19import org.expeditee.io.FrameWriter;
20import org.expeditee.io.KMSReader;
21import org.expeditee.io.KMSWriter;
22import org.expeditee.io.Logger;
23import org.expeditee.items.Item;
24import org.expeditee.items.ItemUtils;
25import org.expeditee.items.Permission;
26import org.expeditee.items.Text;
27import org.expeditee.stats.SessionStats;
28
29/**
30 * This class provides static methods for all saving and loading of Frames
31 * to\from disk. This class also handles any caching of previously loaded
32 * Frames.
33 *
34 * @author jdm18
35 *
36 */
37public class FrameIO {
38
39 private static final char FRAME_NAME_LAST_CHAR = 'A';
40
41 public static void changeParentFolder(String newFolder) {
42 PARENT_FOLDER = newFolder;
43 FRAME_PATH = PARENT_FOLDER + "framesets" + File.separator;
44 TRASH_PATH = PARENT_FOLDER + "trash" + File.separator;
45 IMAGES_PATH = PARENT_FOLDER + IMAGES_FOLDER;
46 HELP_PATH = PARENT_FOLDER + "documentation" + File.separator;
47 PROFILE_PATH = PARENT_FOLDER + "profiles" + File.separator;
48 EXPORTS_DIR = PARENT_FOLDER + "exports" + File.separator;
49 STATISTICS_DIR = PARENT_FOLDER + "statistics" + File.separator;
50 LOGS_DIR = PARENT_FOLDER + "logs" + File.separator;
51 }
52
53 /**
54 * The default location for storing the framesets. Each frameset has its own
55 * subdirectory in this directory.
56 */
57 public static String IMAGES_FOLDER = "images" + File.separator;
58
59 public static String TRASH_PATH;
60
61 public static String PARENT_FOLDER;
62
63 public static String FRAME_PATH;
64
65 public static String IMAGES_PATH;
66
67 public static String HELP_PATH;
68
69 public static String PROFILE_PATH;
70
71 public static String EXPORTS_DIR;
72
73 public static String STATISTICS_DIR;
74
75 public static String LOGS_DIR;
76
77 private static final String INF_FILENAME = "frame.inf";
78
79 public static final String ILLEGAL_CHARS = ";:\\/?";
80
81 public static final int MAX_NAME_LENGTH = 64;
82
83 public static final int MAX_CACHE = 100;
84
85 private static HashMap<String, Frame> _Cache = new HashMap<String, Frame>();
86
87 // private static HashMap<String, String> _FramesetNameCache = new
88 // HashMap<String, String>();
89
90 private static boolean ENABLE_CACHE = true;
91
92 private static boolean _UseCache = true;
93
94 private static boolean _SuspendedCache = false;
95
96 // All methods are static, this should not be instantiated
97 private FrameIO() {
98 }
99
100 public static boolean isCacheOn() {
101 return _UseCache && ENABLE_CACHE;
102 }
103
104 public static void Precache(String framename) {
105 // if the cache is turned off, do nothing
106 if (!isCacheOn())
107 return;
108
109 // if the frame is already in the cache, do nothing
110 if (_Cache.containsKey(framename.toLowerCase()))
111 return;
112
113 // otherwise, load the frame and put it in the cache
114 Logger.Log(Logger.SYSTEM, Logger.LOAD, "Precaching " + framename + ".");
115
116 // do not display errors encountered to the user
117 // (they will be shown at load time)
118 MessageBay.supressMessages(true);
119 // loading automatically caches the frame is caching is turned on
120 LoadUnknownPath(framename);
121 MessageBay.supressMessages(false);
122 }
123
124 /**
125 * Checks if a string is a representation of a positive integer.
126 *
127 * @param s
128 * @return true if s is a positive integer
129 */
130 public static boolean isPositiveInteger(String s) {
131 if (s == null || s.length() == 0)
132 return false;
133
134 for (int i = 0; i < s.length(); i++) {
135 if (!Character.isDigit(s.charAt(i)))
136 return false;
137 }
138 return true;
139 }
140
141 public static Frame LoadFrame(String frameName) {
142 if (!isValidFrameName(frameName))
143 return null;
144
145 String frameNameLower = frameName.toLowerCase();
146 // first try reading from cache
147 if (isCacheOn() && _Cache.containsKey(frameNameLower)) {
148 Logger.Log(Logger.SYSTEM, Logger.LOAD, "Loading " + frameName
149 + " from cache.");
150 return _Cache.get(frameNameLower);
151 }
152
153 Logger.Log(Logger.SYSTEM, Logger.LOAD, "Loading " + frameName
154 + " from disk.");
155 return LoadUnknownPath(frameName);
156 }
157
158 private static Frame LoadUnknownPath(String framename) {
159 Frame loaded = null;
160
161 for (String path : UserSettings.FrameDirs) {
162 loaded = LoadFrame(path, framename);
163 if (loaded != null) {
164 FrameUtils.Parse(loaded, true);
165 break;
166 }
167 }
168
169 return loaded;
170 }
171
172 /**
173 * Gets a list of all the framesets available to the user
174 *
175 * @return a string containing a list of all the available framesets on
176 * separate lines
177 */
178 public static String getFramesetList() {
179 StringBuffer list = new StringBuffer();
180
181 for (String path : UserSettings.FrameDirs) {
182 File files = new File(path);
183 if (!files.exists())
184 continue;
185 for (File f : (new File(path)).listFiles()) {
186 if (f.isDirectory()) {
187 list.append(f.getName()).append('\n');
188 }
189 }
190 }
191 // remove the final new line char
192 list.deleteCharAt(list.length() - 1);
193 return list.toString();
194 }
195
196 /**
197 * Gets the full path and file name of the frame.
198 *
199 * @param path-
200 * the directory in which to look for the frameset containing the
201 * frame.
202 * @param frameName-
203 * the name of the frame for which the path is being requested.
204 * @return null if the frame can not be located.
205 */
206 public static String getFrameFullPathName(String path, String frameName) {
207 String source = path + Conversion.getFramesetName(frameName)
208 + File.separator;
209
210 File tester = new File(source);
211 if (!tester.exists())
212 return null;
213
214 // check for the new file name format
215 String fullPath = source + Conversion.getFrameNumber(frameName)
216 + ExpReader.EXTENTION;
217 tester = new File(fullPath);
218
219 if (tester.exists())
220 return fullPath;
221
222 // check for oldfile name format
223 fullPath = source + Conversion.getFramesetName(frameName) + "."
224 + Conversion.getFrameNumber(frameName);
225 tester = new File(fullPath);
226
227 if (tester.exists())
228 return fullPath;
229
230 return null;
231 }
232
233 public static boolean canAccessFrame(String frameName) {
234 for (String path : UserSettings.FrameDirs) {
235 if (getFrameFullPathName(path, frameName) != null)
236 return true;
237 }
238 return false;
239 }
240
241 private static Frame LoadFrame(String path, String frameName) {
242 String fullPath = getFrameFullPathName(path, frameName);
243 if (fullPath == null)
244 return null;
245
246 try {
247 FrameReader reader;
248
249 if (fullPath.endsWith(ExpReader.EXTENTION)) {
250 reader = new ExpReader(frameName);
251 } else {
252 reader = new KMSReader();
253 }
254 Frame frame = reader.readFrame(fullPath);
255
256 if (frame == null) {
257 MessageBay.errorMessage("Error: " + frameName
258 + " could not be successfully loaded.");
259 return null;
260 }
261
262 frame.path = path;
263
264 // do not put 0 frames or virtual frames into the cache
265 if (_Cache.size() > MAX_CACHE)
266 _Cache.clear();
267
268 if (frame.getNumber() > 0 && isCacheOn())
269 _Cache.put(frameName.toLowerCase(), frame);
270
271 return frame;
272 } catch (IOException ioe) {
273 ioe.printStackTrace();
274 Logger.Log(ioe);
275 } catch (Exception e) {
276 e.printStackTrace();
277 Logger.Log(e);
278 MessageBay.errorMessage("Error: " + frameName
279 + " could not be successfully loaded.");
280 }
281
282 return null;
283 }
284
285 public static void Reload() {
286 // disable cache
287 boolean cache = _UseCache;
288
289 _UseCache = false;
290 Frame fresh = FrameIO.LoadFrame(DisplayIO.getCurrentFrame().getName());
291 _UseCache = cache;
292 if (_Cache.containsKey(fresh.getName().toLowerCase()))
293 addToCache(fresh);
294 DisplayIO.setCurrentFrame(fresh, false);
295 }
296
297 public static Frame LoadPrevious(Frame current) {
298 checkTDFC(current);
299
300 // the current name and number
301 String name = current.getFramesetName();
302 int num = current.getNumber() - 1;
303
304 // loop until a frame that exists is found
305 for (; num >= 0; num--) {
306 Frame f = LoadFrame(name + num);
307 if (f != null)
308 return f;
309 }
310
311 // if we did not find another Frame then this one must be the last one
312 // in the frameset
313 MessageBay
314 .displayMessageOnce("This is the first frame in the frameset");
315 return null;
316 }
317
318 /**
319 * Returns the next Frame in the current Frameset (The Frame with the next
320 * highest Frame number) If the current Frame is the last one in the
321 * Frameset, or an error occurs then null is returned.
322 *
323 * @return The Frame after this one in the current frameset, or null
324 */
325 public static Frame LoadNext(Frame current) {
326 checkTDFC(current);
327
328 // the current name and number
329 int num = current.getNumber() + 1;
330 int max = num + 1;
331 String name = current.getFramesetName();
332
333 // read the maximum from the INF file
334 try {
335 max = ReadINF(current.path, current.getFramesetName());
336 } catch (IOException ioe) {
337 MessageBay.errorMessage("Error loading INF file for frameset '"
338 + name + "'");
339 return null;
340 }
341
342 // loop until a frame that exists is found
343 for (; num <= max; num++) {
344 Frame f = LoadFrame(name + num);
345 if (f != null)
346 return f;
347 }
348
349 // if we did not find another Frame then this one must be the last one
350 // in the frameset
351 MessageBay
352 .displayMessageOnce("This is the last frame in the frameset");
353 return null;
354 }
355
356 /**
357 * This method checks if the current frame has just been created with TDFC.
358 * If it has the frame is saved regardless of whether it has been edited or
359 * not and the TDFC item property is cleared. This is to ensure that the
360 * link is saved on the parent frame.
361 *
362 * @param current
363 */
364 public static void checkTDFC(Frame current) {
365 if (FrameUtils.getTdfcItem() != null) {
366 FrameUtils.setTdfcItem(null);
367 current.change();
368 }
369 }
370
371 public static Frame LoadLast(String framesetName, String path) {
372 // read the maximum from the INF file
373 int max;
374 try {
375 max = ReadINF(path, framesetName);
376 } catch (IOException ioe) {
377 MessageBay.errorMessage("Error loading INF file for frameset '"
378 + framesetName + "'");
379 return null;
380 }
381
382 // loop backwards until a frame that exists is found
383 for (int num = max; num > 0; num--) {
384 Frame f = LoadFrame(framesetName + num);
385 if (f != null)
386 return f;
387 }
388
389 // if we did not find another Frame then this one must be the last one
390 // in the frameset
391 MessageBay.displayMessage("This is the last frame in the frameset");
392 return null;
393 }
394
395 public static Frame LoadZero(String framesetName, String path) {
396 return LoadFrame(framesetName + 0);
397 }
398
399 public static Frame LoadZero() {
400 Frame current = DisplayIO.getCurrentFrame();
401 return LoadZero(current.getFramesetName(), current.path);
402 }
403
404 public static Frame LoadLast() {
405 Frame current = DisplayIO.getCurrentFrame();
406 return LoadLast(current.getFramesetName(), current.path);
407 }
408
409 public static Frame LoadNext() {
410 return LoadNext(DisplayIO.getCurrentFrame());
411 }
412
413 public static Frame LoadPrevious() {
414 return LoadPrevious(DisplayIO.getCurrentFrame());
415 }
416
417 /**
418 * Deletes the given Frame on disk and removes the cached Frame if there is
419 * one. Also adds the deleted frame into the deletedFrames frameset.
420 *
421 * @param toDelete
422 * The Frame to be deleted
423 * @return The name the deleted frame was changed to, or null if the delete failed
424 */
425 public static String DeleteFrame(Frame toDelete) throws IOException,
426 SecurityException {
427 if (toDelete == null)
428 return null;
429
430 // Dont delete the zero frame
431 if (toDelete.getNumber() == 0) {
432 throw new SecurityException("Deleting a zero frame is illegal");
433 }
434
435 SaveFrame(toDelete);
436
437 // Copy deleted frames to the DeletedFrames frameset
438 // get the last used frame in the destination frameset
439 final String DELETED_FRAMES = "DeletedFrames";
440 int lastNumber = FrameIO.getLastNumber(DELETED_FRAMES);
441 String framePath;
442 try {
443 // create the new frameset
444 Frame one = FrameIO.CreateFrameset(DELETED_FRAMES, toDelete.path);
445 framePath = one.path;
446 lastNumber = 0;
447 } catch (Exception e) {
448 Frame zero = FrameIO.LoadFrame(DELETED_FRAMES + "0");
449 framePath = zero.path;
450 }
451
452 // get the fill path to determine which file version it is
453 String source = getFrameFullPathName(toDelete.path, toDelete.getName());
454
455 String oldFrameName = toDelete.getName().toLowerCase();
456 // Now save the frame in the new location
457 toDelete.setFrameset(DELETED_FRAMES);
458 toDelete.setFrameNumber(lastNumber + 1);
459 toDelete.path = framePath;
460 ForceSaveFrame(toDelete);
461
462 if (_Cache.containsKey(oldFrameName))
463 _Cache.remove(oldFrameName);
464
465 File del = new File(source);
466
467 java.io.FileInputStream ff = new java.io.FileInputStream(del);
468 ff.close();
469
470 if( del.delete()){
471 return toDelete.getName();
472 }
473
474 return null;
475 }
476
477 /**
478 * Creates a new Frame in the given frameset and assigns it the given Title,
479 * which can be null. The newly created Frame is a copy of the frameset's .0
480 * file with the number updated based on the last recorded Frame name in the
481 * frameset's INF file.
482 *
483 * @param frameset
484 * The frameset to create the new Frame in
485 * @param frameTitle
486 * The title to assign to the newly created Frame (can be NULL).
487 * @return The newly created Frame.
488 */
489 public static Frame CreateFrame(String frameset, String frameTitle,
490 String templateFrame) throws RuntimeException {
491
492 if (!FrameIO.isValidFramesetName(frameset)) {
493 throw new RuntimeException(frameset
494 + " is not a valid frameset name");
495 }
496
497 int next = -1;
498
499 // disable caching of 0 frames
500 SuspendCache();
501 String zeroFrameName = frameset + "0";
502 Frame destFramesetZero = LoadFrame(zeroFrameName);
503 if (destFramesetZero == null) {
504 throw new RuntimeException(zeroFrameName + " could not be found");
505 }
506
507 Frame template = null;
508 if (templateFrame == null) {
509 // load in frame.0
510 template = destFramesetZero;
511 } else {
512 template = LoadFrame(templateFrame);
513 if (template == null) {
514 throw new RuntimeException("LinkTemplate " + templateFrame
515 + " could not be found");
516 }
517 }
518
519 ResumeCache();
520
521 // read the next number from the INF file
522 try {
523 next = ReadINF(destFramesetZero.path, frameset);
524 } catch (IOException ioe) {
525 ioe.printStackTrace();
526 throw new RuntimeException("INF file could not be read");
527 }
528
529 // Remove the old frame from the cashe then add the new one
530 // TODO figure out some way that we can put both in the cache
531 _Cache.remove(template.getName().toLowerCase());
532 // set the number and title of the new frame
533 template.setName(frameset, ++next);
534 template.setTitle(frameTitle);
535 // _Cache.put(template.getName().toLowerCase(), template);
536
537 Logger.Log(Logger.SYSTEM, Logger.TDFC, "Creating new frame: "
538 + template.getName() + " from TDFC");
539
540 // update INF file
541 try {
542 WriteINF(template.path, frameset, frameset + next);
543 } catch (IOException ioe) {
544 ioe.printStackTrace();
545 Logger.Log(ioe);
546 }
547
548 template.setOwner(UserSettings.Username);
549 template.resetDateCreated();
550 for (Item i : template.getItems()) {
551 if (ItemUtils.startsWithTag(i, ItemUtils.TAG_PARENT))
552 i.setLink(null);
553 }
554
555 // do auto shrinking of the title IF not in twin frames mode
556 Item titleItem = template.getTitleItem();
557
558 if (!DisplayIO.isTwinFramesOn()) {
559 // BROOK: This had recursion!! Changed to avoid...
560 if ((titleItem.getX() + 1) < template.getNameItem().getX()) {
561 while (titleItem.getBoundsWidth() + titleItem.getX() > template
562 .getNameItem().getX()) {
563 titleItem.setSize(titleItem.getSize() - 1);
564 }
565 } else {
566 System.out.println("Bad title x position: " + titleItem.getX());
567 }
568 }
569
570 return template;
571 }
572
573 public static void DisableCache() {
574 _UseCache = false;
575 }
576
577 public static void EnableCache() {
578 _UseCache = true;
579 }
580
581 public static void SuspendCache() {
582 if (_UseCache) {
583 DisableCache();
584 _SuspendedCache = true;
585 } else {
586 _SuspendedCache = false;
587 }
588 }
589
590 public static void ResumeCache() {
591 if (_SuspendedCache) {
592 EnableCache();
593 _SuspendedCache = false;
594 }
595 }
596
597 public static void RefreshCasheImages() {
598 SuspendCache();
599 for (Frame f : _Cache.values())
600 f.setBuffer(null);
601 ResumeCache();
602 }
603
604 /**
605 * Creates a new frameset using the given name. This includes creating a new
606 * subdirectory in the <code>FRAME_PATH</code> directory, Copying over the
607 * default.0 frame from the default frameset, copying the .0 Frame to make a
608 * .1 Frame, and creating the frameset's INF file.
609 *
610 * @param frameset
611 * The name of the Frameset to create
612 * @return The first Frame of the new Frameset (Frame.1)
613 */
614 public static Frame CreateFrameset(String frameset, String path)
615 throws Exception {
616 return CreateFrameset(frameset, path, false);
617 }
618
619 /**
620 * Tests if the given String is a 'proper' framename, that is, the String
621 * must begin with a character, end with a number with 0 or more letters and
622 * numbers in between.
623 *
624 * @param frameName
625 * The String to test for validity as a frame name
626 * @return True if the given framename is proper, false otherwise.
627 */
628 public static boolean isValidFrameName(String frameName) {
629
630 if (frameName == null || frameName.length() < 2)
631 return false;
632
633 int lastCharIndex = frameName.length() - 1;
634 // String must begin with a letter and end with a digit
635 if (!Character.isLetter(frameName.charAt(0))
636 || !Character.isDigit(frameName.charAt(lastCharIndex)))
637 return false;
638
639 // All the characters between first and last must be letters
640 // or digits
641 for (int i = 1; i < lastCharIndex; i++) {
642 if (!Character.isLetterOrDigit(frameName.charAt(i)))
643 return false;
644 }
645 return true;
646 }
647
648 /**
649 * Saves the given Frame to disk in the corresponding frameset directory.
650 * This is the same as calling SaveFrame(toSave, true)
651 *
652 * @param toSave
653 * The Frame to save to disk
654 */
655 public static String SaveFrame(Frame toSave) {
656 return SaveFrame(toSave, true);
657 }
658
659 public static String SaveFrame(Frame toSave, boolean inc) {
660 return SaveFrame(toSave, inc, true);
661 }
662
663 /**
664 * Saves the given Frame to disk in the corresponding frameset directory, if
665 * inc is true then the saved frames counter is incremented, otherwise it is
666 * untouched.
667 *
668 * @param toSave
669 * The Frame to save to disk
670 * @param inc
671 * True if the saved frames counter should be incremented, false
672 * otherwise.
673 * @param checkBackup
674 * True if the frame should be checked for the back up tag
675 */
676 public static String SaveFrame(Frame toSave, boolean inc,
677 boolean checkBackup) {
678
679 // TODO When loading a frame maybe append onto the event history too- with a
680 // break to indicate the end of a session
681
682 if (toSave == null ||!toSave.hasChanged() || toSave.isSaved()){
683 SessionStats.NewFrameSession();
684 return "";
685 }
686 // Get the full path only to determine which format to use for saving
687 // the frame
688 // At this stage use Exp format for saving Exp frames only.
689 // Later this will be changed so that KMS frames will be updated to the
690 // Exp format.
691 String fullPath = getFrameFullPathName(toSave.path, toSave.getName());
692
693 // Dont save if the frame is protected and it exists
694 if (checkBackup
695 && toSave.isReadOnly()) {
696 _Cache.remove(toSave.getName().toLowerCase());
697 SessionStats.NewFrameSession();
698 return "";
699 }
700
701 // Check if the frame exists
702 if (checkBackup && fullPath == null) {
703 // The first time a frame with the backup tag is saved, dont back it
704 // up
705 checkBackup = false;
706 }
707
708 FrameWriter writer = null;
709 int savedVersion;
710 try {
711 // if its a new frame or an existing Exp frame...
712 if (fullPath == null || fullPath.endsWith(ExpReader.EXTENTION)) {
713 writer = new ExpWriter();
714 savedVersion = ExpReader.getVersion(fullPath);
715 } else {
716 writer = new KMSWriter();
717 savedVersion = KMSReader.getVersion(fullPath);
718 }
719 // Check if we are trying to save an out of date version
720 if (savedVersion > toSave.getVersion()
721 && !toSave.getFramesetName().equalsIgnoreCase(
722 MessageBay.MESSAGES_FRAMESET_NAME)) {
723 // remove this frame from the cache if it is there
724 // This will make sure links to the original are set correctly
725 _Cache.remove(toSave.getName().toLowerCase());
726 int nextnum = ReadINF(toSave.path, toSave.getFramesetName()) + 1;
727 SuspendCache();
728 Frame original = LoadFrame(toSave.getName());
729 toSave.setFrameNumber(nextnum);
730 ResumeCache();
731 // Put the modified version in the cache
732 addToCache(toSave);
733 // Show the messages alerting the user
734 Text originalMessage = new Text(-1);
735 originalMessage.setColor(MessageBay.ERROR_COLOR);
736 originalMessage.setText(original.getName()
737 + " was updated by another user.");
738 originalMessage.setLink(original.getName());
739 Text yourMessage = new Text(-1);
740 yourMessage.setColor(MessageBay.ERROR_COLOR);
741 yourMessage.setText("Your version was renamed "
742 + toSave.getName());
743 yourMessage.setLink(toSave.getName());
744 MessageBay.displayMessage(originalMessage);
745 MessageBay.displayMessage(yourMessage);
746 } else if (checkBackup
747 && ItemUtils.ContainsExactTag(toSave.getItems(),
748 ItemUtils.TAG_BACKUP)) {
749 SuspendCache();
750 Frame original = LoadFrame(toSave.getName());
751 if (original == null)
752 original = toSave;
753 int orignum = original.getNumber();
754 int nextnum = ReadINF(toSave.path, toSave.getFramesetName()) + 1;
755
756 original.setFrameNumber(nextnum);
757 original.setPermission(Permission.copy);
758 original.change();
759 SaveFrame(original, false, false);
760
761 Item i = ItemUtils.FindExactTag(toSave.getItems(),
762 ItemUtils.TAG_BACKUP);
763 i.setLink(original.getName());
764 toSave.setFrameNumber(orignum);
765 ResumeCache();
766 }
767 // Update general stuff about frame
768 toSave.setLastModifyDate(Logger.EasyDateFormat("ddMMMyyyy:HHmm"));
769 toSave.setLastModifyUser(UserSettings.Username);
770 toSave.setVersion(toSave.getVersion() + 1);
771 Time darkTime = new Time(SessionStats.getFrameDarkTime().getTime()
772 + toSave.getDarkTime().getTime());
773 Time activeTime = new Time(SessionStats.getFrameActiveTime()
774 .getTime()
775 + toSave.getActiveTime().getTime());
776 toSave.setDarkTime(darkTime);
777 toSave.setActiveTime(activeTime);
778
779 //int oldMode = FrameGraphics.getMode();
780 //if (oldMode != FrameGraphics.MODE_XRAY)
781 // FrameGraphics.setMode(FrameGraphics.MODE_XRAY, true);
782 writer.writeFrame(toSave);
783 //FrameGraphics.setMode(oldMode, true);
784 toSave.setSaved();
785 if (inc) {
786 SessionStats.SavedFrame(toSave.getName());
787 }
788
789 // avoid out-of-sync frames (when in TwinFrames mode)
790 if (_Cache.containsKey(toSave.getName().toLowerCase()))
791 addToCache(toSave);
792
793 Logger.Log(Logger.SYSTEM, Logger.SAVE, "Saving " + toSave.getName()
794 + " to disk.");
795
796 // check that the INF file is not out of date
797 int last = ReadINF(toSave.path, toSave.getFramesetName());
798 if (last <= toSave.getNumber())
799 WriteINF(toSave.path, toSave.getFramesetName(), toSave
800 .getName());
801
802 // check if this was the profile frame (and thus needs
803 // re-parsing)
804 if (isProfileFrame(toSave)) {
805 Frame profile = FrameIO.LoadFrame(toSave.getFramesetName()
806 + "1");
807 assert (profile != null);
808 FrameUtils.ParseProfile(profile);
809 }
810 } catch (IOException ioe) {
811 ioe.getStackTrace();
812 Logger.Log(ioe);
813 return null;
814 }
815
816 return writer.getFileContents();
817 }
818
819 /**
820 * @param toAdd
821 */
822 public static void addToCache(Frame toAdd) {
823 _Cache.put(toAdd.getName().toLowerCase(), toAdd);
824 }
825
826 /**
827 * Checks if a frame is in the current user profile frameset.
828 *
829 * @param toCheck
830 * the frame to check
831 * @return true if the frame is in the current user profile frameset
832 */
833 public static boolean isProfileFrame(Frame toCheck) {
834 if (toCheck.getNumber() == 0)
835 return false;
836 return toCheck.getFramesetName()
837 .equalsIgnoreCase(UserSettings.Username);
838 }
839
840 public static Frame LoadProfile(String userName) {
841 return LoadFrame(userName + "1");
842 }
843
844 public static Frame CreateNewProfile(String username) throws Exception {
845 Frame profile = CreateFrameset(username, PROFILE_PATH, true);
846 FrameUtils.CreateDefaultProfile(profile);
847 return profile;
848 }
849
850 /**
851 * Reads the INF file that corresponds to the given Frame name
852 *
853 * @param framename
854 * The Frame to lookup the INF file for
855 * @throws IOException
856 * Any exceptions encountered by the BufferedReader used to read
857 * the INF.
858 */
859 private static int ReadINF(String path, String frameset) throws IOException {
860 assert (!frameset.endsWith("."));
861
862 // read INF
863 BufferedReader reader;
864 try {
865 reader = new BufferedReader(new FileReader(path
866 + frameset.toLowerCase() + File.separator + INF_FILENAME));
867 } catch (Exception e) {
868 reader = new BufferedReader(new FileReader(path
869 + frameset.toLowerCase() + File.separator
870 + frameset.toLowerCase() + ".inf"));
871 }
872 String inf = reader.readLine();
873 reader.close();
874
875 return Conversion.getFrameNumber(inf);
876 }
877
878 /**
879 * Writes the given String out to the INF file corresponding to the current
880 * frameset.
881 *
882 * @param toWrite
883 * The String to write to the file.
884 * @throws IOException
885 * Any exception encountered by the BufferedWriter.
886 */
887 private static void WriteINF(String path, String frameset, String frameName)
888 throws IOException {
889 assert (!frameset.endsWith("."));
890
891 path += frameset.toLowerCase() + File.separator + INF_FILENAME;
892
893 BufferedWriter writer = new BufferedWriter(new FileWriter(path));
894 writer.write(frameName);
895 writer.close();
896 }
897
898 public static boolean FrameIsCached(String name) {
899 return _Cache.containsKey(name);
900 }
901
902 public static String ConvertToValidFramesetName(String toValidate) {
903 assert (toValidate != null && toValidate.length() > 0);
904
905 StringBuffer result = new StringBuffer();
906
907 if (Character.isDigit(toValidate.charAt(0))) {
908 result.append(FRAME_NAME_LAST_CHAR);
909 }
910
911 boolean capital = false;
912 for (int i = 0; i < toValidate.length()
913 && result.length() < MAX_NAME_LENGTH; i++) {
914 char cur = toValidate.charAt(i);
915
916 // capitalize all characters after spaces
917 if (Character.isLetterOrDigit(cur)) {
918 if (capital) {
919 capital = false;
920 result.append(Character.toUpperCase(cur));
921 } else
922 result.append(cur);
923 } else {
924 capital = true;
925 }
926 }
927 assert (result.length() > 0);
928 int lastCharIndex = result.length() - 1;
929 if (!Character.isLetter(result.charAt(lastCharIndex))) {
930 if (lastCharIndex == MAX_NAME_LENGTH - 1)
931 result.setCharAt(lastCharIndex, FRAME_NAME_LAST_CHAR);
932 else
933 result.append(FRAME_NAME_LAST_CHAR);
934 }
935
936 assert (isValidFramesetName(result.toString()));
937 return result.toString();
938 }
939
940 public static Frame CreateNewFrame(Item linker) throws RuntimeException {
941 String title = linker.getName();
942
943 String templateLink = linker.getAbsoluteLinkTemplate();
944 String framesetLink = linker.getAbsoluteLinkFrameset();
945 String frameset = (framesetLink != null ? framesetLink : DisplayIO
946 .getCurrentFrame().getFramesetName());
947
948 Frame newFrame = FrameIO.CreateFrame(frameset, title, templateLink);
949
950 return newFrame;
951 }
952
953 /**
954 * Creates a new Frameset on disk, including a .0, .1, and .inf files. The
955 * Default.0 frame is copied to make the initial .0 and .1 Frames
956 *
957 * @param name
958 * The Frameset name to use
959 * @return The name of the first Frame in the newly created Frameset (the .1
960 * frame)
961 */
962 public static Frame CreateNewFrameset(String name) throws Exception {
963 String path = DisplayIO.getCurrentFrame().path;
964
965 // if current frameset is profile directory change it to framesets
966 if (path.equals(FrameIO.PROFILE_PATH)) {
967 path = FrameIO.FRAME_PATH;
968 }
969
970 return FrameIO.CreateFrameset(name, path);
971 }
972
973 /**
974 *
975 * @param frameset
976 * @return
977 */
978 public static int getLastNumber(String frameset) { // Rob thinks it might
979 // have been
980 // GetHighestNumExFrame
981 // TODO minimise the number of frames being read in!!
982 int num = -1;
983
984 Frame zero = LoadFrame(frameset + "0");
985
986 // the frameset does not exist (or has no 0 frame)
987 if (zero == null)
988 return -1;
989
990 try {
991 num = ReadINF(zero.path, frameset);
992 } catch (IOException e) {
993 // TODO Auto-generated catch block
994 // e.printStackTrace();
995 }
996
997 /*
998 * Michael doesnt think the code below is really needed... it will just
999 * slow things down when we are reading frames over a network***** for (;
1000 * num >= 0; num--) { System.out.println("This code is loading frames to
1001 * find the highest existing frame..."); if (LoadFrame(frameset + num) !=
1002 * null) break; }
1003 */
1004
1005 return num;
1006 }
1007
1008 /**
1009 * Checks if a given frameset is accessable.
1010 *
1011 * @param framesetName
1012 * @return
1013 */
1014 public static Boolean canAccessFrameset(String framesetName) {
1015 framesetName = framesetName.toLowerCase();
1016 for (String path : UserSettings.FrameDirs) {
1017 if ((new File(path + framesetName)).exists())
1018 return true;
1019 }
1020 return false;
1021 }
1022
1023 public static Frame CreateFrameset(String frameset, String path,
1024 boolean recreate) throws Exception {
1025 String conversion = frameset + " --> ";
1026
1027 if (!isValidFramesetName(frameset)) {
1028 throw new Exception("Invalid frameset name");
1029 }
1030
1031 if (!recreate && FrameIO.canAccessFrameset(frameset)) {
1032 throw new ExistingFramesetException(frameset);
1033 }
1034
1035 conversion += frameset;
1036 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Frameset Name: "
1037 + conversion);
1038 conversion = frameset;
1039
1040 /**
1041 * TODO: Update this to exclude any\all invalid filename characters
1042 */
1043 // ignore annotation character
1044 if (frameset.startsWith("@"))
1045 frameset = frameset.substring(1);
1046
1047 conversion += " --> " + frameset;
1048 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Name: " + conversion);
1049
1050 // create the new Frameset directory
1051 File dir = new File(path + frameset.toLowerCase() + File.separator);
1052
1053 dir.mkdirs();
1054
1055 // create the new INF file
1056 try {
1057 WriteINF(path, frameset, frameset + '1');
1058 } catch (IOException ioe) {
1059 ioe.printStackTrace();
1060 Logger.Log(ioe);
1061 }
1062
1063 SuspendCache();
1064 // copy the default .0 and .1 files
1065 Frame base = null;
1066 try {
1067 base = LoadFrame(UserSettings.DefaultFrame);
1068 } catch (Exception e) {
1069 }
1070 // The frame may not be accessed for various reasons... in all these
1071 // cases just create a new one
1072 if (base == null) {
1073 base = new Frame();
1074 }
1075
1076 ResumeCache();
1077
1078 base.resetDateCreated();
1079 base.setFrameset(frameset);
1080 base.setFrameNumber(0);
1081 base.setTitle(base.getFramesetName() + "0");
1082 base.path = path;
1083 base.change();
1084 SaveFrame(base, false);
1085
1086 base.resetDateCreated();
1087 base.setFrameNumber(1);
1088 base.setTitle(frameset);
1089 base.change();
1090 SaveFrame(base, true);
1091
1092 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Created new frameset: "
1093 + frameset);
1094
1095 return base;
1096 }
1097
1098 /**
1099 * Tests if a frameset name is valid. That is it must begin and end with a
1100 * letter and contain only letters and digits in between.
1101 *
1102 * @param frameset
1103 * the name to be tested
1104 * @return true if the frameset name is valid
1105 */
1106 public static boolean isValidFramesetName(String frameset) {
1107 if (frameset == null) {
1108 return false;
1109 }
1110
1111 int nameLength = frameset.length();
1112 if (frameset.length() <= 0 || nameLength > MAX_NAME_LENGTH) {
1113 return false;
1114 }
1115
1116 int lastCharIndex = nameLength - 1;
1117
1118 if (!Character.isLetter(frameset.charAt(0))
1119 || !Character.isLetter(frameset.charAt(lastCharIndex)))
1120 return false;
1121
1122 for (int i = 1; i < lastCharIndex; i++) {
1123 if (!Character.isLetterOrDigit(frameset.charAt(i))) {
1124 return false;
1125 }
1126 }
1127 return true;
1128 }
1129
1130 public static boolean DeleteFrameset(String framesetName) {
1131 if (!FrameIO.canAccessFrameset(framesetName))
1132 return false;
1133 // Search all the available directories for the directory
1134 for (String path : UserSettings.FrameDirs) {
1135 String source = path + framesetName.toLowerCase() + File.separator;
1136 File framesetDirectory = new File(source);
1137 // Once we have found the directory move it to the trash
1138 if (framesetDirectory.exists()) {
1139 String destPath = FrameIO.TRASH_PATH
1140 + framesetName.toLowerCase();
1141 int copyNumber = 1;
1142 File dest = new File(destPath + File.separator);
1143 // Create the trash folder if it doesnt already exist
1144 if (!dest.getParentFile().exists())
1145 dest.mkdirs();
1146 // If a frameset with the same name is already in the trash add
1147 // a number to the end
1148 while (dest.exists()) {
1149 dest = new File(destPath + ++copyNumber + File.separator);
1150 }
1151 if (!framesetDirectory.renameTo(dest)) {
1152 for (File f : framesetDirectory.listFiles()) {
1153 if (!f.delete())
1154 return false;
1155 }
1156 if (!framesetDirectory.delete())
1157 return false;
1158 }
1159 return true;
1160 }
1161 }
1162 return false;
1163 }
1164
1165 public static boolean CopyFrameset(String framesetToCopy,
1166 String copiedFrameset) throws Exception {
1167 if (!FrameIO.canAccessFrameset(framesetToCopy))
1168 return false;
1169 if (FrameIO.canAccessFrameset(copiedFrameset))
1170 return false;
1171 // search through all the directories to find the frameset we are
1172 // copying
1173 for (String path : UserSettings.FrameDirs) {
1174 String source = path + framesetToCopy.toLowerCase()
1175 + File.separator;
1176 File framesetDirectory = new File(source);
1177 if (framesetDirectory.exists()) {
1178 // copy the frameset
1179 File copyFramesetDirectory = new File(path
1180 + copiedFrameset.toLowerCase() + File.separator);
1181 if (!copyFramesetDirectory.mkdirs())
1182 return false;
1183 // copy each of the frames
1184 for (File f : framesetDirectory.listFiles()) {
1185 // Ignore hidden files
1186 if (f.getName().charAt(0) == '.')
1187 continue;
1188 String copyPath = copyFramesetDirectory.getAbsolutePath()
1189 + File.separator + f.getName();
1190 FrameIO.copyFile(f.getAbsolutePath(), copyPath);
1191 }
1192 return true;
1193 }
1194 }
1195 return false;
1196 }
1197
1198 /**
1199 * Copies a file from one location to another.
1200 *
1201 * @param existingFile
1202 * @param newFileName
1203 * @throws Exception
1204 */
1205 public static void copyFile(String existingFile, String newFileName)
1206 throws Exception {
1207 FileInputStream is = new FileInputStream(existingFile);
1208 FileOutputStream os = new FileOutputStream(newFileName, false);
1209 int data;
1210 while ((data = is.read()) != -1) {
1211 os.write(data);
1212 }
1213 os.flush();
1214 os.close();
1215 is.close();
1216 }
1217
1218 /**
1219 * Saves a frame regardless of whether or not the frame is marked as having
1220 * been changed.
1221 *
1222 * @param frame
1223 * the frame to save
1224 * @return the contents of the frame or null if it could not be saved
1225 */
1226 public static String ForceSaveFrame(Frame frame) {
1227 frame.change();
1228 return SaveFrame(frame, false);
1229 }
1230
1231 public static boolean isValidLink(String frameName) {
1232 return frameName == null || isPositiveInteger(frameName)
1233 || isValidFrameName(frameName);
1234 }
1235
1236}
Note: See TracBrowser for help on using the repository browser.