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

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