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

Last change on this file since 944 was 924, checked in by jts21, 10 years ago

Fix for titles on new frames getting set to the minimum font-size when the template's title is centred

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