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

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