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

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

Changed the way justification works so that...
Width field has a positive value if explicitly set and under the hood stores a negative value if it has not been set explicitly.

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