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

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