source: trunk/src/org/expeditee/gui/FrameUtils.java@ 1363

Last change on this file since 1363 was 1363, checked in by bln4, 5 years ago

It is now possible to complete the process of recovering access to a Expeditee account. Further work, in the form of frames in the authentication frameset, are to follow.
A refactoring/tidy up has also been completed.

File size: 64.1 KB
Line 
1/**
2 * FrameUtils.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.File;
22import java.io.FileInputStream;
23import java.io.FileOutputStream;
24import java.io.IOException;
25import java.io.InputStream;
26import java.lang.reflect.InvocationTargetException;
27import java.net.JarURLConnection;
28import java.net.URISyntaxException;
29import java.net.URL;
30import java.net.URLConnection;
31import java.nio.file.FileVisitResult;
32import java.nio.file.FileVisitor;
33import java.nio.file.Files;
34import java.nio.file.Path;
35import java.nio.file.Paths;
36import java.nio.file.attribute.BasicFileAttributes;
37import java.util.ArrayList;
38import java.util.Arrays;
39import java.util.Collection;
40import java.util.Collections;
41import java.util.Comparator;
42import java.util.Enumeration;
43import java.util.LinkedHashSet;
44import java.util.LinkedList;
45import java.util.List;
46import java.util.Map;
47import java.util.Scanner;
48import java.util.function.Consumer;
49import java.util.jar.JarEntry;
50import java.util.jar.JarFile;
51import java.util.stream.Collectors;
52import java.util.zip.ZipEntry;
53
54import org.expeditee.agents.ExistingFramesetException;
55import org.expeditee.agents.InvalidFramesetNameException;
56import org.expeditee.auth.AuthenticatorBrowser;
57import org.expeditee.auth.mail.gui.MailBay;
58import org.expeditee.core.Colour;
59import org.expeditee.core.Point;
60import org.expeditee.core.bounds.AxisAlignedBoxBounds;
61import org.expeditee.core.bounds.PolygonBounds;
62import org.expeditee.gio.EcosystemManager;
63import org.expeditee.gio.gesture.StandardGestureActions;
64import org.expeditee.items.Circle;
65import org.expeditee.items.Dot;
66import org.expeditee.items.FrameBitmap;
67import org.expeditee.items.FrameImage;
68import org.expeditee.items.Item;
69import org.expeditee.items.Item.HighlightMode;
70import org.expeditee.items.ItemUtils;
71import org.expeditee.items.JSItem;
72import org.expeditee.items.Line;
73import org.expeditee.items.PermissionPair;
74import org.expeditee.items.Picture;
75import org.expeditee.items.Text;
76import org.expeditee.items.UserAppliedPermission;
77import org.expeditee.items.XRayable;
78import org.expeditee.items.widgets.ButtonWidget;
79import org.expeditee.items.widgets.InteractiveWidgetInitialisationFailedException;
80import org.expeditee.items.widgets.InteractiveWidgetNotAvailableException;
81import org.expeditee.items.widgets.Widget;
82import org.expeditee.items.widgets.WidgetCorner;
83import org.expeditee.items.widgets.WidgetEdge;
84import org.expeditee.setting.Setting;
85import org.expeditee.settings.Settings;
86import org.expeditee.settings.UserSettings;
87import org.expeditee.settings.templates.TemplateSettings;
88import org.expeditee.stats.Logger;
89import org.expeditee.stats.SessionStats;
90
91public class FrameUtils {
92
93 /**
94 * The list of known start pages framesets which will have prepopulated links in
95 * the home frame.
96 */
97 public static final String[] startPages = { "exploratorysearch", "webbrowser" };
98
99 private static final int COLUMN_WIDTH = 50;
100
101 /**
102 * Provides a way to monitor the time elapsed between button-down and the
103 * finished painting.
104 */
105 public static TimeKeeper ResponseTimer = new TimeKeeper();
106
107 private static float _ResponseTimeSum = 0;
108
109 private static float _LastResponse = 0;
110
111 private static Text LastEdited = null;
112
113 public static int MINIMUM_INTERITEM_SPACING = -6;
114
115 private static Item _tdfcItem = null;
116
117 public static float getResponseTimeTotal() {
118 return _ResponseTimeSum;
119 }
120
121 public static float getLastResponseTime() {
122 return _LastResponse;
123 }
124
125 /**
126 * Checks if the given top Item is above the given bottom Item, allowing for the
127 * X coordinates to be off by a certain width...
128 *
129 * @param item1
130 * The Item to check is above the other Item
131 * @param item2
132 * The Item to check is below the top Item
133 * @return True if top is above bottom, False otherwise.
134 */
135 public static boolean inSameColumn(Item item1, Item item2) {
136 if (!(item1 instanceof Text) || !(item2 instanceof Text)) {
137 return false;
138 }
139
140 if (item1.getID() < 0 || item2.getID() < 0) {
141 return false;
142 }
143
144 int minX = item2.getX();
145 int maxX = item2.getX() + item2.getBoundsWidth();
146
147 int startX = item1.getX();
148 int endX = item1.getX() + item1.getBoundsWidth();
149
150 // Check that the two items left values are close
151 if (Math.abs(item1.getX() - item2.getX()) > COLUMN_WIDTH) {
152 return false;
153 }
154
155 // Ensure the two items
156 if ((minX >= startX && minX <= endX) || (maxX >= startX && maxX <= endX) || (startX >= minX && startX <= maxX)
157 || (endX >= minX && endX <= maxX)) {
158 return true;
159 }
160
161 return false;
162 }
163
164 public static boolean sameBulletType(String bullet1, String bullet2) {
165 if (bullet1 == null || bullet2 == null) {
166 return false;
167 }
168
169 if (bullet1.equals("") || bullet2.equals("")) {
170 return false;
171 }
172
173 if (Character.isLetter(bullet1.charAt(0)) && Character.isLetter(bullet2.charAt(0))) {
174 return true;
175 }
176
177 if (Character.isDigit(bullet1.charAt(0)) && Character.isDigit(bullet2.charAt(0))) {
178 return true;
179 }
180
181 // TODO make this more sofisticated
182
183 return false;
184 }
185
186 private static boolean needsRenumbering(String s) {
187 if (s == null || s.equals("")) {
188 return false;
189 }
190 if (!Character.isLetterOrDigit(s.charAt(0))) {
191 return false;
192 }
193
194 s = s.trim();
195 // if its all letters then we dont want to auto adjust
196 if (s.length() > 2) {
197 for (int i = 0; i < s.length() - 1; i++) {
198 if (!Character.isLetter(s.charAt(i))) {
199 return true;
200 }
201 }
202 } else {
203 return true;
204 }
205
206 return false;
207 }
208
209 /**
210 *
211 * @param toAlign
212 * @param moveAll
213 * @param adjust
214 * @return
215 */
216 public static int Align(List<Text> toAlign, boolean moveAll, int adjust, List<Item> changedItems) {
217 Collections.sort(toAlign);
218
219 /*
220 * Single items dont need alignment But if there are two items we may still want
221 * to format them... ie if they are too close together.
222 */
223 if (toAlign.size() < 1) {
224 return 0;
225 }
226
227 // get the first item
228 Text from = toAlign.get(0);
229 if (from.getParent() == null) {
230 from = toAlign.get(1);
231 }
232 int x = from.getX();
233
234 Frame curr = from.getParent();
235 Text above = curr.getTextAbove(from);
236
237 String lastBullet = "";
238
239 if (above != null && curr.isNormalTextItem(above)) {
240 lastBullet = StandardGestureActions.getAutoBullet(above.getText());
241 } else {
242 lastBullet = StandardGestureActions.getBullet(toAlign.get(0).getText());
243 }
244 if (needsRenumbering(lastBullet)) {
245 // renumber...
246 for (int i = 0; i < toAlign.size(); i++) {
247
248 Text currentText = toAlign.get(i);
249 String currentBullet = StandardGestureActions.getAutoBullet(currentText.getText());
250
251 if (sameBulletType(lastBullet, currentBullet)) {
252 String oldText = currentText.getText();
253
254 currentText.stripFirstWord();
255
256 currentText.setText(lastBullet + currentText.getText());
257 lastBullet = StandardGestureActions.getAutoBullet(currentText.getText());
258
259 // if we changed the item, add to changedItems list
260 if (changedItems != null && oldText != currentText.getText()
261 && !changedItems.contains(currentText)) {
262 Item copy = currentText.copy();
263 copy.setID(currentText.getID());
264 copy.setText(oldText);
265 changedItems.add(copy);
266 }
267 }
268 }
269 }
270
271 // work out the spacing between the first item and the one above it
272
273 int space = 10 + adjust;
274
275 // if we are dropping from the title make the space a little bigger
276 // than normal
277
278 // If there are only two items get the gap from the start item on the
279 // zero frame if there is one
280 if (above == curr.getTitleItem()) {
281 Frame zero = FrameIO.LoadFrame(curr.getFramesetName() + '0');
282 String strGap = zero.getAnnotationValue("start");
283 if (strGap != null) {
284 try {
285 int gap = Integer.parseInt(strGap);
286 space = gap;
287 } catch (NumberFormatException nfe) {
288
289 }
290 }
291 } else if (above != null) {
292 // Make the gap between all items the same as the gap between
293 // the first two
294 space = from.getBounds().getMinY() - above.getBounds().getMaxY();
295
296 if (space < MINIMUM_INTERITEM_SPACING) {
297 space = MINIMUM_INTERITEM_SPACING;
298 }
299
300 if (UserSettings.FormatSpacingMax.get() != null) {
301 double maxSpace = UserSettings.FormatSpacingMax.get() * above.getSize();
302 if (maxSpace < space) {
303 space = (int) Math.round(maxSpace);
304 }
305 }
306
307 if (UserSettings.FormatSpacingMin.get() != null) {
308 double minSpace = UserSettings.FormatSpacingMin.get() * above.getSize();
309 if (minSpace > space) {
310 space = (int) Math.round(minSpace);
311 }
312 }
313
314 // Need to do things differently for FORMAT than for DROPPING
315 if (moveAll && above != curr.getNameItem() && above != curr.getTitleItem()) {
316 x = above.getX();
317 int y = above.getBounds().getMaxY() + space + (from.getY() - from.getBounds().getMinY());
318
319 if (changedItems != null && (from.getX() != x || from.getY() != y) && !changedItems.contains(from)) {
320 Item copy = from.copy();
321 copy.setID(from.getID());
322 changedItems.add(copy);
323 }
324 from.setPosition(x, y);
325 } else {
326 x = from.getX();
327 }
328
329 space += adjust;
330 }
331 for (int i = 1; i < toAlign.size(); i++) {
332 Item current = toAlign.get(i);
333 Item top = toAlign.get(i - 1);
334
335 // The bottom of the previous item
336 int bottom = top.getBounds().getMaxY();
337
338 // the difference between the current item's Y coordinate and
339 // the top of the highlight box
340 int diff = current.getY() - current.getBounds().getMinY();
341
342 int newPos = bottom + space + diff;
343
344 if (changedItems != null && ((moveAll && current.getX() != x) || current.getY() != newPos)
345 && !changedItems.contains(current)) {
346 Item copy = current.copy();
347 copy.setID(current.getID());
348 changedItems.add(copy);
349 }
350
351 if (moveAll) {
352 current.setPosition(x, newPos);
353 } else if (newPos > current.getY()) {
354 current.setY(newPos);
355 }
356
357 }
358
359 // if (insert != null)
360 // return insert.getY();
361
362 // Michael thinks we return the y value for the next new item??
363 int y = from.getY() + from.getBoundsHeight() + space;
364 return y;
365 }
366
367 public static int Align(List<Text> toAlign, boolean moveAll, int adjust) {
368 return Align(toAlign, moveAll, adjust, null);
369 }
370
371 public static boolean LeavingFrame(Frame current) {
372 checkTDFCItemWaiting(current);
373 // active overlay frames may also require saving if they have been
374 // changed
375 for (Overlay o : current.getOverlays()) {
376 if (!SaveCheck(o.Frame)) {
377 return false;
378 }
379 }
380
381 // if the check fails there is no point continuing
382 if (!SaveCheck(current)) {
383 return false;
384 }
385
386 for (Item i : current.getItems()) {
387 i.setHighlightMode(Item.HighlightMode.None);
388 i.setHighlightColorToDefault();
389 }
390 return true;
391 }
392
393 private static boolean SaveCheck(Frame toSave) {
394 // don't bother saving frames that haven't changed
395 if (!toSave.hasChanged()) {
396 return true;
397 }
398
399 // if the frame has been changed, then save it
400 if (DisplayController.isTwinFramesOn()) {
401 Frame opposite = DisplayController.getOppositeFrame();
402
403 String side = "left";
404 if (DisplayController.getCurrentSide() == DisplayController.TwinFramesSide.RIGHT) {
405 side = "right";
406 }
407
408 // if the two frames both have changes, prompt the user for the
409 // next move
410 if (opposite.hasChanged() && opposite.equals(toSave)) {
411 if (EcosystemManager.getGraphicsManager().showDialog("Changes",
412 "Leaving this frame will discard changes made in the " + side + " Frame. Continue?")) {
413 FrameIO.SaveFrame(toSave);
414 DisplayController.Reload(DisplayController.getSideFrameIsOn(opposite));
415 return true;
416 } else {
417 return false;
418 }
419 } else if (opposite.hasOverlay(toSave)) {
420 if (toSave.hasChanged()) {
421 if (EcosystemManager.getGraphicsManager().showDialog("Changes",
422 "Leaving this frame will discard changes made in the " + side + " Frame. Continue?")) {
423 FrameIO.SaveFrame(toSave);
424 DisplayController.Reload(DisplayController.getSideFrameIsOn(opposite));
425 return true;
426 } else {
427 return false;
428 }
429 }
430 }
431
432 // save the current frame and restore the other side
433 FrameIO.SaveFrame(toSave);
434 return true;
435 }
436
437 // single-frame mode can just save and return
438 FrameIO.SaveFrame(toSave);
439 return true;
440 }
441
442 // TODO: consider reloating this method to Frame class?
443 protected static Item getAnnotation(Frame frame, String annotationStr) {
444 Item matched_item = null;
445
446 // check for an updated template...
447 for (Item i : frame.getAnnotationItems()) {
448
449 if (ItemUtils.startsWithTag(i, annotationStr)) {
450
451 matched_item = i;
452 break;
453 }
454 }
455
456 return matched_item;
457 }
458
459 protected static void doFrameTransition(Item frameTransition, Frame from, Frame to) {
460 String s = frameTransition.getText();
461 String[] s_array = s.split(":");
462 if (s_array.length > 1) {
463 String slide_mode_method = s_array[1].trim();
464
465 FrameTransition transition = new FrameTransition(from.getBuffer(), slide_mode_method);
466
467 DisplayController.setTransition(from, transition);
468
469 System.out.println("Triggered on annotation: " + s);
470 } else {
471 System.err.println("Warning: failed to detect frameTransition type");
472 // TODO: print list as a result of reflection listing
473 }
474 }
475
476 /**
477 * Displays the given Frame on the display. If the current frame has changed
478 * since the last save then it will be saved before the switch is made. The
479 * caller can also dictate whether the current frame is added to the back-stack
480 * or not.
481 *
482 * @param toDisplay
483 * The Frame to display on the screen
484 * @param addToBack
485 * True if the current Frame should be added to the back-stack, False
486 * otherwise
487 */
488 public static void DisplayFrame(Frame toDisplay, boolean addToBack, boolean incrementStats) {
489 if (toDisplay == null) {
490 return;
491 }
492
493 final PermissionPair framePermissions = toDisplay.getPermission();
494 if (framePermissions != null
495 && framePermissions.getPermission(toDisplay.getOwner()) == UserAppliedPermission.denied) {
496 MessageBay.errorMessage("Insufficient permissions to navigate to frame: " + toDisplay.getName());
497 return;
498 }
499
500 Frame current = DisplayController.getCurrentFrame();
501
502 // Dont need to do anything if the frame to display is already being
503 // displayed
504 if (current.equals(toDisplay)) {
505 return;
506 }
507
508 // move any anchored connected items
509 if (FreeItems.hasItemsAttachedToCursor()) {
510 List<Item> toAdd = new ArrayList<Item>();
511 List<Item> toCheck = new ArrayList<Item>(FreeItems.getInstance());
512
513 while (toCheck.size() > 0) {
514 Item i = toCheck.get(0);
515 Collection<Item> connected = i.getAllConnected();
516
517 // // Only move completely enclosed items
518 // if (!toCheck.containsAll(connected)) {
519 // connected.retainAll(FreeItems.getInstance());
520 // FreeItems.getInstance().removeAll(connected);
521 // toCheck.removeAll(connected);
522 // FrameMouseActions.anchor(connected);
523 // } else {
524 // toCheck.removeAll(connected);
525 // }
526
527 // Anchor overlay items where they belong
528 if (i.getParent() != null && i.getParent() != current) {
529 FreeItems.getInstance().removeAll(connected);
530 toCheck.removeAll(connected);
531 StandardGestureActions.anchor(connected);
532 } else {
533 // Add stuff that is partially enclosed
534 // remove all the connected items from our list to check
535 toCheck.removeAll(connected);
536 // Dont add the items that are free
537 connected.removeAll(FreeItems.getInstance());
538 toAdd.addAll(connected);
539 }
540 }
541
542 current.removeAllItems(toAdd);
543
544 boolean oldChange = toDisplay.hasChanged();
545 toDisplay.updateIDs(toAdd);
546 toDisplay.addAllItems(toAdd);
547 toDisplay.setChanged(oldChange);
548 }
549
550 if (addToBack && current != toDisplay) {
551 FrameIO.checkTDFC(current);
552 }
553
554 // if the saving happened properly, we can continue
555 if (!LeavingFrame(current)) {
556 MessageBay.displayMessage("Navigation cancelled");
557 return;
558 }
559
560 if (addToBack && current != toDisplay) {
561 DisplayController.addToBack(current);
562 }
563
564 Parse(toDisplay);
565
566 if (DisplayController.isAudienceMode()) {
567 // Only need to worry about frame transitions when in Audience Mode
568
569 // Test to see if frame transition specified through annotation, and perform it
570 // if one if found
571 Item frameTransition = getAnnotation(toDisplay, "@frameTransition");
572 if (frameTransition != null) {
573 doFrameTransition(frameTransition, current, toDisplay);
574 }
575 }
576
577 DisplayController.setCurrentFrame(toDisplay, incrementStats);
578 StandardGestureActions.updateCursor();
579 // FrameMouseActions.getInstance().refreshHighlights();
580 // update response timer
581 _LastResponse = ResponseTimer.getElapsedSeconds();
582 _ResponseTimeSum += _LastResponse;
583 DisplayController.updateTitle();
584 }
585
586 /**
587 * Loads and displays the Frame with the given framename, and adds the current
588 * frame to the back-stack if required.
589 *
590 * @param framename
591 * The name of the Frame to load and display
592 * @param addToBack
593 * True if the current Frame should be added to the back-stack, false
594 * otherwise
595 */
596 public static void DisplayFrame(String frameName, boolean addToBack, boolean incrementStats) {
597 Frame newFrame = getFrame(frameName);
598
599 if (newFrame != null) {
600 // display the frame
601 DisplayFrame(newFrame, addToBack, incrementStats);
602 }
603 }
604
605 /**
606 * Loads and displays the Frame with the given framename and adds the current
607 * frame to the back-stack. This is the same as calling DisplayFrame(framename,
608 * true)
609 *
610 * @param framename
611 * The name of the Frame to load and display
612 */
613 public static void DisplayFrame(String framename) {
614 DisplayFrame(framename, true, true);
615 }
616
617 public static Frame getFrame(String frameName) {
618 // if the new frame does not exist then tell the user
619 Frame f = FrameIO.LoadFrame(frameName);
620
621 if (f == null) {
622 MessageBay.errorMessage("Frame '" + frameName + "' could not be found.");
623 }
624
625 return f;
626 }
627
628 /**
629 * Creates a new Picture Item from the given Text source Item and adds it to the
630 * given Frame.
631 *
632 * @return True if the image was created successfully, false otherwise
633 */
634 private static boolean createPicture(Frame frame, Text txt) {
635 // attempt to create the picture
636 Picture pic = ItemUtils.CreatePicture(txt);
637
638 // if the picture could not be created successfully
639 if (pic == null) {
640 String imagePath = txt.getText();
641 assert (imagePath != null);
642 imagePath = new AttributeValuePair(imagePath).getValue().trim();
643 if (imagePath.length() == 0) {
644 return false;
645 // MessageBay.errorMessage("Expected image path after @i:");
646 } else {
647 MessageBay.errorMessage("Image " + imagePath + " could not be loaded");
648 }
649 return false;
650 }
651 frame.addItem(pic);
652
653 return true;
654 }
655
656 /**
657 * Creates an interactive widget and adds it to a frame. If txt has no parent
658 * the parent will be set to frame.
659 *
660 * @param frame
661 * Frame to add widget to. Must not be null.
662 *
663 * @param txt
664 * Text to create the widget from. Must not be null.
665 *
666 * @return True if created/added. False if could not create.
667 *
668 * @author Brook Novak
669 */
670 private static boolean createWidget(Frame frame, Text txt) {
671
672 if (frame == null) {
673 throw new NullPointerException("frame");
674 }
675 if (txt == null) {
676 throw new NullPointerException("txt");
677 }
678
679 // Safety
680 if (txt.getParent() == null) {
681 txt.setParent(frame);
682 }
683
684 Widget iw = null;
685
686 try {
687
688 iw = Widget.createWidget(txt);
689
690 } catch (InteractiveWidgetNotAvailableException e) {
691 e.printStackTrace();
692 MessageBay.errorMessage("Cannot create iWidget: " + e.getMessage());
693 } catch (InteractiveWidgetInitialisationFailedException e) {
694 e.printStackTrace();
695 MessageBay.errorMessage("Cannot create iWidget: " + e.getMessage());
696 } catch (IllegalArgumentException e) {
697 e.printStackTrace();
698 MessageBay.errorMessage("Cannot create iWidget: " + e.getMessage());
699 }
700
701 if (iw == null) {
702 return false;
703 }
704
705 frame.removeItem(txt);
706
707 frame.addAllItems(iw.getItems());
708
709 return true;
710 }
711
712 public static List<String> ParseProfile(Frame profile) {
713 List<String> errors = new LinkedList<String>();
714
715 if (profile == null) {
716 return errors;
717 }
718
719 /*
720 * Make sure the correct cursor shows when turning off the custom cursor and
721 * reparsing the profile frame
722 */
723 FreeItems.getCursor().clear();
724 DisplayController.setCursor(Item.HIDDEN_CURSOR);
725 DisplayController.setCursor(Item.DEFAULT_CURSOR);
726
727 // check for settings tags
728 for (Text item : profile.getBodyTextItems(true)) {
729 try {
730
731 AttributeValuePair avp = new AttributeValuePair(item.getText());
732 String attributeFullCase = avp.getAttributeOrValue();
733
734 if (attributeFullCase == null) {
735 continue;
736 }
737
738 String attribute = attributeFullCase.trim().toLowerCase().replaceAll("^@", "");
739
740 if (attribute.equals("settings")) {
741 Settings.parseSettings(item);
742 }
743
744 } catch (Exception e) {
745 if (e.getMessage() != null) {
746 errors.add(e.getMessage());
747 } else {
748 e.printStackTrace();
749 errors.add("Error parsing [" + item.getText() + "] on " + profile.getName());
750 }
751 }
752 }
753
754 return errors;
755 }
756
757 /**
758 * Sets the first frame to be displayed.
759 *
760 * @param profile
761 */
762 public static void loadFirstFrame(Frame profile) {
763 if (UserSettings.HomeFrame.get() == null) {
764 UserSettings.HomeFrame.set(profile.getName());
765 }
766
767 Frame firstFrame = FrameIO.LoadFrame(UserSettings.HomeFrame.get());
768 if (firstFrame == null) {
769 MessageBay.warningMessage("Home frame not found: " + UserSettings.HomeFrame);
770 UserSettings.HomeFrame.set(profile.getName());
771 DisplayController.setCurrentFrame(profile, true);
772 } else {
773 DisplayController.setCurrentFrame(firstFrame, true);
774 }
775
776 }
777
778 public static Colour[] getColorWheel(Frame frame) {
779 if (frame != null) {
780 List<Text> textItems = frame.getBodyTextItems(false);
781 Colour[] colorList = new Colour[textItems.size() + 1];
782 for (int i = 0; i < textItems.size(); i++) {
783 colorList[i] = textItems.get(i).getColor();
784 }
785 // Make the last item transparency or default for forecolor
786 colorList[colorList.length - 1] = null;
787
788 return colorList;
789 }
790 return new Colour[] { Colour.BLACK, Colour.WHITE, null };
791 }
792
793 public static String getLink(Item item, String alt) {
794 if (item == null || !(item instanceof Text)) {
795 return alt;
796 }
797
798 AttributeValuePair avp = new AttributeValuePair(item.getText());
799 assert (avp != null);
800
801 if (avp.hasPair() && avp.getValue().trim().length() != 0) {
802 item.setLink(avp.getValue());
803 return avp.getValue();
804 } else if (item.getLink() != null) {
805 return item.getAbsoluteLink();
806 }
807
808 return alt;
809 }
810
811 public static String getDir(String name) {
812 if (name != null) {
813 File tester = new File(name);
814 if (tester.exists() && tester.isDirectory()) {
815 if (name.endsWith(File.separator)) {
816 return name;
817 } else {
818 return name + File.separator;
819 }
820 } else {
821 throw new RuntimeException("Directory not found: " + name);
822 }
823 }
824 throw new RuntimeException("Missing value for profile attribute" + name);
825 }
826
827 public static ArrayList<String> getDirs(Item item) {
828 ArrayList<String> dirsToAdd = new ArrayList<String>();
829 String dirListFrameName = item.getAbsoluteLink();
830 if (dirListFrameName != null) {
831 Frame dirListFrame = FrameIO.LoadFrame(dirListFrameName);
832 if (dirListFrame != null) {
833 for (Text t : dirListFrame.getBodyTextItems(false)) {
834 String dirName = t.getText().trim();
835 File tester = new File(dirName);
836 if (tester.exists() && tester.isDirectory()) {
837 if (dirName.endsWith(File.separator)) {
838 dirsToAdd.add(dirName);
839 } else {
840 dirsToAdd.add(dirName + File.separator);
841 }
842 }
843 }
844 }
845 }
846
847 return dirsToAdd;
848 }
849
850 public static void Parse(Frame toParse) {
851 Parse(toParse, false);
852 }
853
854 /**
855 * Checks for any special Annotation items and updates the display as necessary.
856 * Special Items: Images, overlays, sort.
857 *
858 */
859 public static void Parse(Frame toParse, boolean firstParse) {
860 Parse(toParse, firstParse, false);
861 }
862
863 /**
864 *
865 * @param toParse
866 * @param firstParse
867 * @param ignoreAnnotations
868 * used to prevent infinate loops such as when performing TDFC with
869 * an ao tag linked to a frame with an frameImage of a frame which
870 * also has an ao tag on it.
871 */
872 public static void Parse(Frame toParse, boolean firstParse, boolean ignoreAnnotations) {
873 // TODO check why we are getting toParse == null... when profile frame
874 // is being created and change the lines below
875 if (toParse == null) {
876 return;
877 }
878
879 if (firstParse) {
880 ItemUtils.EnclosedCheck(toParse.getItems());
881 }
882
883 List<Item> items = toParse.getItems();
884
885 // if XRayMode is on, replace pictures with their underlying text
886 if (DisplayController.isXRayMode()) {
887
888 // BROOK: Must handle these a little different
889 List<Widget> widgets = toParse.getInteractiveWidgets();
890
891 for (Item i : items) {
892 if (i instanceof XRayable) {
893 toParse.removeItem(i);
894 // Show the items
895 for (Item item : ((XRayable) i).getConnected()) {
896 item.setVisible(true);
897 item.removeEnclosure(i);
898 }
899 } else if (i instanceof WidgetCorner) {
900 toParse.removeItem(i);
901 } else if (i instanceof WidgetEdge) {
902 toParse.removeItem(i);
903 } else if (i.hasFormula()) {
904 i.setText(i.getFormula());
905 } else if (i.hasOverlay()) {
906 i.setVisible(true);
907 // int x = i.getBoundsHeight();
908 }
909 }
910
911 for (Widget iw : widgets) {
912 toParse.addItem(iw.getSource());
913 }
914 }
915
916 // Text title = null;
917 // Text template = UserSettingsTemplate.copy();
918
919 List<Overlay> overlays = new ArrayList<Overlay>();
920 List<Vector> vectors = new ArrayList<Vector>();
921
922 // disable reading of cached overlays if in twinframes mode
923 if (DisplayController.isTwinFramesOn()) {
924 FrameIO.SuspendCache();
925 }
926
927 // DotType pointtype = DotType.square;
928 // boolean filledPoints = true;
929
930 UserAppliedPermission permission = toParse.getUserAppliedPermission();
931 toParse.clearAnnotations();
932
933 // check for any new overlay items
934 for (Item i : toParse.getItems()) {
935 try {
936 // reset overlay permission
937 i.setOverlayPermission(null);
938 // i.setPermission(permission);
939 if (i instanceof WidgetCorner) {
940 // TODO improve efficiency so it only updates once... using
941 // observer design pattern
942 i.update();
943 } else if (i instanceof Text) {
944 if (i.isAnnotation()) {
945 if (ItemUtils.startsWithTag(i, ItemUtils.TAG_POINTTYPE)) {
946 Text txt = (Text) i;
947 String line = txt.getFirstLine();
948 line = ItemUtils.StripTag(line, ItemUtils.GetTag(ItemUtils.TAG_POINTTYPE));
949
950 if (line != null) {
951 line = line.toLowerCase();
952 if (line.indexOf(" ") > 0) {
953 String fill = line.substring(line.indexOf(" ") + 1);
954 if (fill.startsWith("nofill")) {
955 // filledPoints = false;
956 } else {
957 // filledPoints = true;
958 }
959 }
960
961 if (line.startsWith("circle")) {
962 // pointtype = DotType.circle;
963 } else {
964 // pointtype = DotType.square;
965 }
966 }
967 } // check for new VECTOR items
968 else if (!DisplayController.isXRayMode() && ItemUtils.startsWithTag(i, ItemUtils.TAG_VECTOR)
969 && i.getLink() != null) {
970 if (!i.getAbsoluteLink().equals(toParse.getName())) {
971 addVector(vectors, UserAppliedPermission.none, permission, i);
972 }
973 } else if (!DisplayController.isXRayMode()
974 && ItemUtils.startsWithTag(i, ItemUtils.TAG_ACTIVE_VECTOR) && i.getLink() != null) {
975 if (!i.getAbsoluteLink().equals(toParse.getName())) {
976 addVector(vectors, UserAppliedPermission.followLinks, permission, i);
977 }
978 }
979 // check for new OVERLAY items
980 else if (!ignoreAnnotations && ItemUtils.startsWithTag(i, ItemUtils.TAG_OVERLAY)
981 && i.getLink() != null) {
982 if (i.getAbsoluteLink().equalsIgnoreCase(toParse.getName())) {
983 // This frame contains an active overlay which
984 // points to itself
985 MessageBay.errorMessage(toParse.getName() + " contains an @o which links to itself");
986 continue;
987 }
988
989 Frame overlayFrame = FrameIO.LoadFrame(i.getAbsoluteLink());
990 // Parse(overlay);
991 if (overlayFrame != null && Overlay.getOverlay(overlays, overlayFrame) == null) {
992 overlays.add(new Overlay(overlayFrame, UserAppliedPermission.none));
993 }
994 }
995 // check for ACTIVE_OVERLAY items
996 else if (!ignoreAnnotations && ItemUtils.startsWithTag(i, ItemUtils.TAG_ACTIVE_OVERLAY)
997 && i.getLink() != null) {
998 String link = i.getAbsoluteLink();
999 if (link.equalsIgnoreCase(toParse.getName())) {
1000 // This frame contains an active overlay which
1001 // points to itself
1002 MessageBay.errorMessage(toParse.getName() + " contains an @ao which links to itself");
1003 continue;
1004 }
1005 Frame overlayFrame = null;
1006
1007 Frame current = DisplayController.getCurrentFrame();
1008 if (current != null) {
1009 for (Overlay o : current.getOverlays()) {
1010 if (o.Frame.getName().equalsIgnoreCase(link)) {
1011 overlayFrame = o.Frame;
1012 }
1013 }
1014 }
1015 if (overlayFrame == null) {
1016 overlayFrame = FrameIO.LoadFrame(link);
1017 }
1018
1019 // get level if specified
1020 String level = new AttributeValuePair(i.getText()).getValue();
1021 // default permission (if none is specified)
1022 PermissionPair permissionLevel = new PermissionPair(level,
1023 UserAppliedPermission.followLinks);
1024
1025 if (overlayFrame != null) {
1026 Overlay existingOverlay = Overlay.getOverlay(overlays, overlayFrame);
1027 // If it wasn't in the list create it and add
1028 // it.
1029 if (existingOverlay == null) {
1030 Overlay newOverlay = new Overlay(overlayFrame,
1031 permissionLevel.getPermission(overlayFrame.getOwner()));
1032 i.setOverlay(newOverlay);
1033 overlays.add(newOverlay);
1034 } else {
1035 existingOverlay.Frame.setPermission(permissionLevel);
1036 }
1037 }
1038 }
1039 // check for Images and widgets
1040 else {
1041 if (!DisplayController.isXRayMode()) {
1042 if (ItemUtils.startsWithTag(i, ItemUtils.TAG_IMAGE, true)) {
1043 if (!i.hasEnclosures()) {
1044 createPicture(toParse, (Text) i);
1045 }
1046 // check for frame images
1047 } else if (ItemUtils.startsWithTag(i, ItemUtils.TAG_FRAME_IMAGE) && i.getLink() != null
1048 && !i.getAbsoluteLink().equalsIgnoreCase(toParse.getName())) {
1049 XRayable image = null;
1050 if (i.hasEnclosures()) {
1051 // i.setHidden(true);
1052 // image =
1053 // i.getEnclosures().iterator().next();
1054 // image.refresh();
1055 } else {
1056 image = new FrameImage((Text) i, null);
1057 }
1058 // TODO Add the image when creating new
1059 // FrameImage
1060 toParse.addItem(image);
1061 } else if (ItemUtils.startsWithTag(i, ItemUtils.TAG_BITMAP_IMAGE) && i.getLink() != null
1062 && !i.getAbsoluteLink().equalsIgnoreCase(toParse.getName())) {
1063 XRayable image = null;
1064 if (i.hasEnclosures()) {
1065 // image =
1066 // i.getEnclosures().iterator().next();
1067 // image.refresh();
1068 // i.setHidden(true);
1069 } else {
1070 // If a new bitmap is created for a
1071 // frame which already has a bitmap dont
1072 // recreate the bitmap
1073 image = new FrameBitmap((Text) i, null);
1074 }
1075 toParse.addItem(image);
1076 } else if (ItemUtils.startsWithTag(i, "@c")) {
1077 // Can only have a @c
1078 if (!i.hasEnclosures() && i.getLines().size() == 1) {
1079 toParse.addItem(new Circle((Text) i));
1080 }
1081 // Check for JSItem
1082 } else if (ItemUtils.startsWithTag(i, "@js")) {
1083 toParse.addItem(new JSItem((Text) i));
1084 // Check for interactive widgets
1085 } else if (ItemUtils.startsWithTag(i, ItemUtils.TAG_IWIDGET)) {
1086 createWidget(toParse, (Text) i);
1087 }
1088 }
1089 // TODO decide exactly what to do here!!
1090 toParse.addAnnotation((Text) i);
1091 }
1092 } else if (!DisplayController.isXRayMode() && i.hasFormula()) {
1093 i.calculate(i.getFormula());
1094 }
1095 }
1096 } catch (Exception e) {
1097 Logger.Log(e);
1098 e.printStackTrace();
1099 System.err.println("**** Have temporarily supressed MessageBay call, as resulted in infinite recursion");
1100 //MessageBay.warningMessage("Exception occured when loading " + i.getClass().getSimpleName() + "(ID: "
1101 // + i.getID() + ") " + e.getMessage() != null ? e.getMessage() : "");
1102 }
1103 }
1104
1105 /*
1106 * for (Item i : items) { if (i instanceof Dot) { ((Dot)
1107 * i).setPointType(pointtype); ((Dot) i).useFilledPoints(filledPoints); } }
1108 */
1109
1110 FrameIO.ResumeCache();
1111
1112 toParse.clearOverlays();
1113 toParse.clearVectors();
1114 toParse.addAllOverlays(overlays);
1115 toParse.addAllVectors(vectors);
1116
1117 }
1118
1119 /**
1120 * TODO: Comment. cts16
1121 *
1122 * @param vectors
1123 * @param permission
1124 * @param i
1125 */
1126 private static void addVector(List<Vector> vectors, UserAppliedPermission defaultPermission,
1127 UserAppliedPermission framePermission, Item i) {
1128 // TODO It is possible to get into an infinite loop if a
1129 // frame contains an @ao which leads to a frame with an
1130 // @v which points back to the frame with the @ao
1131 Frame vector = FrameIO.LoadFrame(i.getAbsoluteLink());
1132
1133 // Get the permission from off the vector frame
1134 UserAppliedPermission vectorPermission = UserAppliedPermission
1135 .getPermission(vector.getAnnotationValue("permission"), defaultPermission);
1136
1137 // If the frame permission is lower, use that
1138 vectorPermission = UserAppliedPermission.min(vectorPermission, framePermission);
1139
1140 // Highest permissable permission for vectors is copy
1141 vectorPermission = UserAppliedPermission.min(vectorPermission, UserAppliedPermission.copy);
1142 if (vector != null) {
1143 String scaleString = new AttributeValuePair(i.getText()).getValue();
1144 Float scale = 1F;
1145 try {
1146 scale = Float.parseFloat(scaleString);
1147 } catch (Exception e) {
1148 }
1149 Vector newVector = new Vector(vector, vectorPermission, scale, i);
1150 i.setOverlay(newVector);
1151 i.setVisible(false);
1152 vectors.add(newVector);
1153 }
1154 }
1155
1156 public static Item onItem(float floatX, float floatY, boolean changeLastEdited) {
1157 return onItem(DisplayController.getCurrentFrame(), floatX, floatY, changeLastEdited);
1158 }
1159
1160 /**
1161 * Searches through the list of items on this frame to find one at the given x,y
1162 * coordinates.
1163 *
1164 * @param x
1165 * The x coordinate
1166 * @param y
1167 * The y coordinate
1168 * @return The Item at the given coordinates, or NULL if none is found.
1169 */
1170 public static Item onItem(Frame toCheck, float floatX, float floatY, boolean bResetLastEdited) {
1171 // System.out.println("MouseX: " + floatX + " MouseY: " + floatY);
1172 int x = Math.round(floatX);
1173 int y = Math.round(floatY);
1174 if (toCheck == null) {
1175 return null;
1176 }
1177
1178 List<Item> possibles = new ArrayList<Item>(0);
1179
1180 // if the mouse is in the message area
1181 if (y >= DisplayController.getMessageBayPaintArea().getMinY()) {
1182 // check the individual bay items (MessageBay + MailBay)
1183 List<Item> bayItems = new LinkedList<Item>();
1184 if (DisplayController.isMailMode()) {
1185 bayItems.addAll(MailBay.getPreviewMessages());
1186 } else {
1187 bayItems.addAll(MessageBay.getMessages());
1188 }
1189 for (Item message : bayItems) {
1190 if (message != null) {
1191 if (message.contains(new Point(x, y))) {
1192 message.setOverlayPermission(UserAppliedPermission.copy);
1193 possibles.add(message);
1194 } else {
1195 // Not sure why but if the line below is removed then
1196 // several items can be highlighted at once
1197 message.setHighlightMode(Item.HighlightMode.None);
1198 message.setHighlightColorToDefault();
1199 }
1200 }
1201 }
1202
1203 // check the link to the message/mail frame
1204 Item linkItem = DisplayController.isMailMode() ? MailBay.getMailLink() : MessageBay.getMessageLink();
1205 if (linkItem != null && linkItem.contains(new Point(x, y))) {
1206 linkItem.setOverlayPermission(UserAppliedPermission.copy);
1207 possibles.add(linkItem);
1208 }
1209
1210 // this is taken into account in contains
1211 // y -= FrameGraphics.getMaxFrameSize().height;
1212 // otherwise, the mouse is on the frame
1213 } else {
1214 if (LastEdited != null) {
1215 if (LastEdited.contains(x, y) && !FreeItems.getInstance().contains(LastEdited)
1216 && LastEdited.getParent() == DisplayController.getCurrentFrame()
1217 && LastEdited.getParent().getItems().contains(LastEdited)) {
1218 LastEdited.setOverlayPermission(UserAppliedPermission.full);
1219 return LastEdited;
1220 } else if (bResetLastEdited) {
1221 setLastEdited(null);
1222 }
1223 }
1224 ArrayList<Item> checkList = new ArrayList<Item>();
1225 checkList.addAll(toCheck.getInteractableItems());
1226 checkList.add(toCheck.getNameItem());
1227
1228 for (Item i : checkList) {
1229
1230 // do not check annotation items in audience mode
1231 // TODO: Upon hover of Rubbish Bin, Undo and Restore Widgets, flickering occurs
1232 // depending on the mouse distance from a corner. Resolve this.
1233 if (i.isVisible() && !(DisplayController.isAudienceMode() && i.isAnnotation())) {
1234 if (i instanceof WidgetCorner) {
1235 WidgetCorner wc = (WidgetCorner) i;
1236 if (wc.getWidgetSource() instanceof ButtonWidget) {
1237 ButtonWidget bw = (ButtonWidget) wc.getWidgetSource();
1238
1239 if (bw.getdropInteractableStatus() == true) {
1240 Widget iw = wc.getWidgetSource();
1241
1242 if (iw.getBounds().contains(x, y)) {
1243
1244 if (!FreeItems.getInstance().contains(i)) {
1245 possibles.add(i);
1246 }
1247 }
1248 }
1249 }
1250 }
1251
1252 if (i.contains(new Point(x, y))) {
1253 if (!FreeItems.getInstance().contains(i)) {
1254 possibles.add(i);
1255 }
1256 }
1257
1258 }
1259 }
1260 }
1261
1262 // if there are no possible items, return null
1263 if (possibles.size() == 0) {
1264 return null;
1265 }
1266
1267 // if there is only one possibility, return it
1268 if (possibles.size() == 1) {
1269 return possibles.get(0);
1270 }
1271
1272 // return closest x,y pair to mouse
1273 Item closest = possibles.get(0);
1274 int distance = (int) Math.round(
1275 Math.sqrt(Math.pow(Math.abs(closest.getX() - x), 2) + Math.pow(Math.abs(closest.getY() - y), 2)));
1276
1277 for (Item i : possibles) {
1278 int d = (int) Math
1279 .round(Math.sqrt(Math.pow(Math.abs(i.getX() - x), 2) + Math.pow(Math.abs(i.getY() - y), 2)));
1280
1281 // System.out.println(d);
1282 if (d <= distance) {
1283 distance = d;
1284
1285 // dots take precedence over lines
1286 if ((!(closest instanceof Dot && i instanceof Line))
1287 && (!(closest instanceof Text && i instanceof Line))) {
1288 closest = i;
1289 }
1290
1291 }
1292
1293 }
1294
1295 return closest;
1296 }
1297
1298 /**
1299 * Checks if the mouse is currently over an item.
1300 *
1301 * @return True if the mouse is over any item, false otherwise.
1302 */
1303 public static boolean hasCurrentItem() {
1304 return getCurrentItem() != null;
1305 }
1306
1307 public synchronized static Item getCurrentItem() {
1308 return onItem(DisplayController.getCurrentFrame(), DisplayController.getMouseX(), DisplayController.getMouseY(),
1309 true);
1310 }
1311
1312 public static PolygonBounds getEnlosingPolygon() {
1313 Collection<Item> enclosure = getEnclosingLineEnds();
1314
1315 if (enclosure == null || enclosure.size() == 0) {
1316 return null;
1317 }
1318
1319 return enclosure.iterator().next().getEnclosedShape();
1320 }
1321
1322 /**
1323 *
1324 * @param currentItem
1325 * @return
1326 */
1327 public static Collection<Item> getCurrentItems() {
1328 return getCurrentItems(getCurrentItem());
1329 }
1330
1331 public static Collection<Item> getCurrentItems(Item currentItem) {
1332 Collection<Item> enclosure = getEnclosingLineEnds();
1333
1334 if (enclosure == null || enclosure.size() == 0) {
1335 return null;
1336 }
1337
1338 Item firstItem = enclosure.iterator().next();
1339
1340 Collection<Item> enclosed = getItemsEnclosedBy(DisplayController.getCurrentFrame(),
1341 firstItem.getEnclosedShape());
1342
1343 // Brook: enclosed widgets are to be fully enclosed, never partially
1344 /*
1345 * MIKE says: but doesn't this mean that widgets are treated differently from
1346 * ALL other object which only need to be partially enclosed to be picked up
1347 */
1348 List<Widget> enclosedWidgets = new LinkedList<Widget>();
1349 for (Item i : enclosed) {
1350 // Don't want to lose the highlighting from the current item
1351 if (i == currentItem || enclosure.contains(i)) {
1352 continue;
1353 }
1354 // Don't want to lose the highlighting of connected Dots
1355 // TODO: this code does nothing (perhaps the continue is meant for the outer
1356 // for loop?). cts16
1357 if (i instanceof Dot && i.getHighlightMode() == HighlightMode.Connected) {
1358 for (Line l : i.getLines()) {
1359 if (l.getOppositeEnd(i).getHighlightMode() == HighlightMode.Normal) {
1360 continue;
1361 }
1362 }
1363 }
1364
1365 if (i instanceof WidgetCorner) {
1366 if (!enclosedWidgets.contains(((WidgetCorner) i).getWidgetSource())) {
1367 enclosedWidgets.add(((WidgetCorner) i).getWidgetSource());
1368 }
1369 }
1370
1371 i.setHighlightMode(Item.HighlightMode.None);
1372 i.setHighlightColorToDefault();
1373 }
1374
1375 for (Widget iw : enclosedWidgets) {
1376 for (Item i : iw.getItems()) {
1377 if (!enclosed.contains(i)) {
1378 enclosed.add(i);
1379 }
1380 }
1381 }
1382
1383 return enclosed;
1384 }
1385
1386 /**
1387 * Gets the collection of Dot items that form the enclosure nearest to the
1388 * current mouse position.
1389 */
1390 public static Collection<Item> getEnclosingLineEnds() {
1391 return getEnclosingLineEnds(new Point(DisplayController.getMouseX(), DisplayController.getMouseY()));
1392 }
1393
1394 /**
1395 * Gets the collection of Dot items that form the enclosure nearest to the given
1396 * position.
1397 */
1398 public static Collection<Item> getEnclosingLineEnds(Point position) {
1399 // update enclosed shapes
1400 Frame current = DisplayController.getCurrentFrame();
1401 if (current == null) {
1402 return null;
1403 }
1404 List<Item> items = current.getItems();
1405
1406 // Remove all items that are connected to freeItems
1407 List<Item> freeItems = new ArrayList<Item>(FreeItems.getInstance());
1408 while (freeItems.size() > 0) {
1409 Item item = freeItems.get(0);
1410 Collection<Item> connected = item.getAllConnected();
1411 items.removeAll(connected);
1412 freeItems.removeAll(connected);
1413 }
1414
1415 List<Item> used = new ArrayList<Item>(0);
1416
1417 while (items.size() > 0) {
1418 Item i = items.get(0);
1419 items.remove(i);
1420 if (i.isEnclosed()) {
1421 PolygonBounds p = i.getEnclosedShape();
1422 if (p.contains(position)) {
1423 used.add(i);
1424 items.removeAll(i.getEnclosingDots());
1425 }
1426 }
1427 }
1428
1429 if (used.size() == 0) {
1430 return null;
1431 }
1432
1433 // if there is only one possibility, return it
1434 if (used.size() == 1) {
1435 return used.get(0).getEnclosingDots();
1436 // otherwise, determine which polygon is closest to the cursor
1437 } else {
1438 Collections.sort(used, new Comparator<Item>() {
1439 @Override
1440 public int compare(Item d1, Item d2) {
1441 PolygonBounds p1 = d1.getEnclosedShape();
1442 PolygonBounds p2 = d2.getEnclosedShape();
1443
1444 int closest = Integer.MAX_VALUE;
1445 int close2 = Integer.MAX_VALUE;
1446
1447 int mouseX = DisplayController.getMouseX();
1448 int mouseY = DisplayController.getMouseY();
1449
1450 for (int i = 0; i < p1.getPointCount(); i++) {
1451 int diff = Math.abs(p1.getPoint(i).getX() - mouseX) + Math.abs(p1.getPoint(i).getY() - mouseY);
1452 int diff2 = Integer.MAX_VALUE;
1453
1454 if (i < p2.getPointCount()) {
1455 diff2 = Math.abs(p2.getPoint(i).getX() - mouseX) + Math.abs(p2.getPoint(i).getY() - mouseY);
1456 }
1457
1458 if (diff < Math.abs(closest)) {
1459 close2 = closest;
1460 closest = diff;
1461 } else if (diff < Math.abs(close2)) {
1462 close2 = diff;
1463 }
1464
1465 if (diff2 < Math.abs(closest)) {
1466 close2 = closest;
1467 closest = -diff2;
1468 } else if (diff2 < Math.abs(close2)) {
1469 close2 = diff2;
1470 }
1471 }
1472
1473 if (closest > 0 && close2 > 0) {
1474 return -10;
1475 }
1476
1477 if (closest < 0 && close2 < 0) {
1478 return 10;
1479 }
1480
1481 if (closest > 0) {
1482 return -10;
1483 }
1484
1485 return 10;
1486 }
1487
1488 });
1489
1490 return used.get(0).getEnclosingDots();
1491 }
1492 }
1493
1494 // TODO Remove this method!!
1495 // Can just getItemsWithin be used?
1496 public static Collection<Item> getItemsEnclosedBy(Frame frame, PolygonBounds poly) {
1497 Collection<Item> contained = frame.getItemsWithin(poly);
1498
1499 Collection<Item> results = new LinkedHashSet<Item>(contained.size());
1500
1501 // check for correct permissions
1502 for (Item item : contained) {
1503 // if the item is on the frame
1504 if (item.getParent() == frame || item.getParent() == null) {
1505 // item.Permission = Permission.full;
1506 results.add(item);
1507 // otherwise, it must be on an overlay frame
1508 } else {
1509 for (Overlay overlay : frame.getOverlays()) {
1510 if (overlay.Frame == item.getParent()) {
1511 item.setOverlayPermission(overlay.permission);
1512 results.add(item);
1513 break;
1514 }
1515 }
1516 }
1517 }
1518
1519 return results;
1520 }
1521
1522 public static void CreateDefaultProfile(String profileFor, Frame profile) {
1523 CreateDefaultProfile(profileFor, profile, null, null);
1524 }
1525
1526 /**
1527 * Copies the content from the default profile to the specified profile.
1528 * @param profileFor Name of profile that is destination of copy.
1529 * @param profile Profile being setup.
1530 * @param specifiedTextSettings text settings to provide a default value for in the new profile
1531 * @param specifiedGenericSettings generic settings to provide a default value for in the new profile
1532 */
1533 public static void CreateDefaultProfile(String profileFor, Frame profile,
1534 Map<String, Setting> specifiedSettings, Map<String, Consumer<Frame>> notifyWhenGenerated) {
1535 // If this is already the default profile then nothing (other than setting
1536 // title) needs to be done.
1537 Text titleItem = profile.getTitleItem();
1538 Text title = titleItem;
1539 if (!profileFor.equals(UserSettings.DEFAULT_PROFILE_NAME)) {
1540 // If this profile is not the default profile, copy it from the default profile
1541 // instead of generating a new profile
1542 // (this allows the possibility of modifying the default profile and having any
1543 // new profiles get those modifications)
1544 Frame defaultFrame = FrameIO.LoadProfile(UserSettings.DEFAULT_PROFILE_NAME);
1545 if (defaultFrame == null) {
1546 try {
1547 // If we do not have a default to copy, create one.
1548 defaultFrame = FrameIO.CreateNewProfile(UserSettings.DEFAULT_PROFILE_NAME, null, null);
1549 } catch (InvalidFramesetNameException invalidNameEx) {
1550 MessageBay.errorMessage("Failed to create default profile named: "
1551 + UserSettings.DEFAULT_PROFILE_NAME + ". "
1552 + "Profile names must start and end with a letter and must contain only letters and numbers.");
1553 return;
1554 } catch (ExistingFramesetException existingFramesetEx) {
1555 MessageBay.errorMessage("Failed to create the desired default frameset: "
1556 + UserSettings.DEFAULT_PROFILE_NAME + ", "
1557 + "because it already exists. This should never happen as we shouldn't be asking to create it if it already exists.");
1558 return;
1559 }
1560 }
1561
1562 MessageBay.suppressMessages(true);
1563 int lastNumber = FrameIO.getLastNumber(defaultFrame.getFramesetName());
1564 for (int i = 1; i <= lastNumber; i++) {
1565 // Load in next default, if it doesn't exist continue loop.
1566 defaultFrame = FrameIO.LoadFrame(defaultFrame.getFramesetName() + i);
1567 if (defaultFrame == null) {
1568 continue;
1569 }
1570
1571 // Create the next next (currently blank) profile frame.
1572 // If there is frame gaps in the default (say if there is no 4.exp but there is
1573 // a 5.exp) then retain those gaps.
1574 // This way copied relative links work.
1575 while (profile.getNumber() < defaultFrame.getNumber()) {
1576 profile = FrameIO.CreateFrame(profile.getFramesetName(), null, null);
1577 }
1578 // Ensure we are working from a blank slate.
1579 profile.reset();
1580 profile.removeAllItems(profile.getAllItems());
1581
1582 // For each item on defaultFrame:
1583 // 1. Set all items to be relatively linked so once copied their links correctly
1584 // point to the frame on the created profile rather than the default profile.
1585 // 2. Copy item from defaultFrame to the current profile frame being
1586 // constructed.
1587 // 3. Replace settings values of copied items with those specified in
1588 // specifiedSettings (if present)
1589 for (Item item : defaultFrame.getAllItems()) {
1590 item.setRelativeLink();
1591 }
1592 profile.addAllItems(defaultFrame.getAllItems());
1593 if (i == 1 && titleItem != null) {
1594 titleItem.setText(profileFor + "'s Profile");
1595 }
1596 String category = profile.getTitle();
1597 List<String> settingsKeys = null;
1598 if (specifiedSettings != null) {
1599 settingsKeys = specifiedSettings.keySet().stream().filter(key ->
1600 key.startsWith(category)).collect(Collectors.toList());
1601 }
1602 if (settingsKeys != null) {
1603 for (String key: settingsKeys) {
1604 Setting setting = specifiedSettings.get(key);
1605 String name = setting.getName();
1606 Text representation = setting.generateRepresentation(name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase(), profile.getFramesetName());
1607 Collection<Text> canditates = profile.getTextItems();
1608 canditates.removeIf(text -> !text.getText().startsWith(representation.getText().split(" ")[0]));
1609 canditates.forEach(text -> {
1610 Point backupPos = text.getPosition();
1611 Item.DuplicateItem(representation, text);
1612 text.setText(representation.getText());
1613 text.setPosition(backupPos);
1614 });
1615 }
1616 }
1617 if (notifyWhenGenerated != null && notifyWhenGenerated.containsKey(category)) {
1618 notifyWhenGenerated.get(category).accept(profile);
1619 }
1620 FrameIO.SaveFrame(profile);
1621 }
1622 MessageBay.suppressMessages(false);
1623 } else {
1624 title.setText("Default Profile Frame");
1625 int xPos = 300;
1626 int yPos = 100;
1627 Text t;
1628
1629 // Add documentation links
1630 File helpDirectory = new File(FrameIO.HELP_PATH);
1631 if (helpDirectory != null) {
1632 File[] helpFramesets = helpDirectory.listFiles();
1633 if (helpFramesets != null) {
1634
1635 // Add the title for the help index
1636 Text help = profile.addText(xPos, yPos, "@Expeditee Help", null);
1637 help.setSize(25);
1638 help.setFontStyle("Bold");
1639 help.setFamily("SansSerif");
1640 help.setColor(TemplateSettings.ColorWheel.get()[3]);
1641
1642 xPos += 25;
1643 System.out.println("Installing frameset: ");
1644
1645 boolean first_item = true;
1646 for (File helpFrameset : helpFramesets) {
1647 String framesetName = helpFrameset.getName();
1648 if (!FrameIO.isValidFramesetName(framesetName)) {
1649 continue;
1650 }
1651
1652 if (first_item) {
1653 System.out.print(" " + framesetName);
1654 first_item = false;
1655 } else {
1656 System.out.print(", " + framesetName);
1657 }
1658 System.out.flush();
1659
1660 Frame indexFrame = FrameIO.LoadFrame(framesetName + '1');
1661 // Look through the folder for help index pages
1662 if (indexFrame != null && ItemUtils.FindTag(indexFrame.getItems(), "@HelpIndex") != null) {
1663 // yPos += spacing;
1664 yPos += 30;
1665 t = profile.addText(xPos, yPos, '@' + indexFrame.getFramesetName(), null);
1666 t.setLink(indexFrame.getName());
1667 t.setColor(Colour.GREY);
1668 }
1669 }
1670 System.out.println();
1671 }
1672 }
1673
1674 xPos = 50;
1675 yPos = 100;
1676
1677 // Populate Start Pages and Settings
1678 File framesetDirectory = new File(FrameIO.FRAME_PATH);
1679
1680 if (framesetDirectory.exists()) {
1681 File[] startpagesFramesets = framesetDirectory.listFiles();
1682
1683 if (startpagesFramesets != null) {
1684 // Add Start Page title
1685 Text templates = profile.addText(xPos, yPos, "@Start Pages", null);
1686 templates.setSize(25);
1687 templates.setFontStyle("Bold");
1688 templates.setFamily("SansSerif");
1689 templates.setColor(TemplateSettings.ColorWheel.get()[3]);
1690
1691 xPos += 25;
1692
1693 // Start Pages should be the first frame in its own frameset +
1694 // frameset name should be present in FrameUtils.startPages[].
1695 for (File startpagesFrameset : startpagesFramesets) {
1696 String framesetName = startpagesFrameset.getName();
1697
1698 // Only add link if frameset is a startpage
1699 for (int i = 0; i < startPages.length; i++) {
1700 if (framesetName.equals(startPages[i])) {
1701 Frame indexFrame = FrameIO.LoadFrame(framesetName + '1');
1702
1703 // Add start page link
1704 if (indexFrame != null) {
1705 yPos += 30;
1706 t = profile.addText(xPos, yPos, '@' + indexFrame.getFramesetName(), null);
1707 t.setLink(indexFrame.getName());
1708 t.setColor(Colour.GREY);
1709 }
1710 }
1711 }
1712 }
1713 }
1714 }
1715
1716 FrameIO.SaveFrame(profile);
1717
1718 // Populate settings frameset
1719 Settings.Init();
1720 t = profile.addText(550, 100, "@Settings", null);
1721 t.setSize((float) 25.0);
1722 t.setFamily("SansSerif");
1723 t.setFontStyle("Bold");
1724 t.setColor(Colour.GREY);
1725 Settings.generateSettingsTree(t);
1726 System.out.println("@Settings: Default settings generation complete.");
1727
1728 FrameIO.SaveFrame(profile);
1729 }
1730 }
1731
1732 private static void checkTDFCItemWaiting(Frame currentFrame) {
1733 Item tdfcItem = FrameUtils.getTdfcItem();
1734 // if there is a TDFC Item waiting
1735 if (tdfcItem != null) {
1736 boolean change = currentFrame.hasChanged();
1737 boolean saved = currentFrame.isSaved();
1738 // Save the parent of the item if it has not been saved
1739 if (!change && !saved) {
1740 tdfcItem.setLink(null);
1741 tdfcItem.getParent().setChanged(true);
1742 FrameIO.SaveFrame(tdfcItem.getParent());
1743 DisplayController.requestRefresh(true);
1744 } else {
1745 SessionStats.CreatedFrame();
1746 }
1747
1748 setTdfcItem(null);
1749 }
1750 }
1751
1752 public static void setTdfcItem(Item _tdfcItem) {
1753 FrameUtils._tdfcItem = _tdfcItem;
1754 }
1755
1756 public static Item getTdfcItem() {
1757 return FrameUtils._tdfcItem;
1758 }
1759
1760 public static void setLastEdited(Text lastEdited) {
1761 // If the lastEdited is being changed then check if its @i
1762 Frame toReparse = null;
1763 Frame toRecalculate = null;
1764 Frame toUpdateObservers = null;
1765
1766 if (LastEdited == null) {
1767 // System.out.print("N");
1768 } else if (LastEdited != null) {
1769 // System.out.print("T");
1770 Frame parent = LastEdited.getParentOrCurrentFrame();
1771
1772 if (lastEdited != LastEdited) {
1773 if (LastEdited.startsWith("@i")) {
1774 // Check if its an image that can be resized to fit a box
1775 // around it
1776 String text = LastEdited.getText();
1777 if (text.startsWith("@i:") && !Character.isDigit(text.charAt(text.length() - 1))) {
1778 Collection<Item> enclosure = FrameUtils.getEnclosingLineEnds(LastEdited.getPosition());
1779 if (enclosure != null) {
1780 for (Item i : enclosure) {
1781 if (i.isLineEnd() && i.isEnclosed()) {
1782 DisplayController.getCurrentFrame().removeAllItems(enclosure);
1783 AxisAlignedBoxBounds rect = i.getEnclosedBox();
1784 LastEdited.setText(LastEdited.getText() + " " + Math.round(rect.getWidth()));
1785 LastEdited.setPosition(rect.getTopLeft());
1786 LastEdited.setThickness(i.getThickness());
1787 LastEdited.setBorderColor(i.getColor());
1788 break;
1789 }
1790 }
1791 StandardGestureActions.deleteItems(enclosure, false);
1792 }
1793 }
1794 toReparse = parent;
1795 } else if (LastEdited.recalculateWhenChanged()) {
1796 toRecalculate = parent;
1797 }
1798
1799 if (parent.hasObservers()) {
1800 toUpdateObservers = parent;
1801 }
1802 // Update the formula if in XRay mode
1803 if (DisplayController.isXRayMode() && LastEdited.hasFormula()) {
1804 LastEdited.setFormula(LastEdited.getText());
1805 }
1806 }
1807 if (lastEdited != LastEdited && LastEdited.getText().length() == 0 && LastEdited.getMinWidth() == null) {
1808 parent.removeItem(LastEdited);
1809 }
1810 }
1811 LastEdited = lastEdited;
1812
1813 if (!DisplayController.isXRayMode()) {
1814 if (toReparse != null) {
1815 Parse(toReparse, false, false);
1816 } else {
1817 if (toRecalculate != null) {
1818 toRecalculate.recalculate();
1819 }
1820
1821 if (toUpdateObservers != null) {
1822 toUpdateObservers.notifyObservers(false);
1823 }
1824 }
1825 }
1826 }
1827
1828 /**
1829 * Extracts files/folders from assets/resources-public and assets/resources-private
1830 * to {Expeditee Home}/resources-public and {Expeditee Home}/resources-private respectively.
1831 * @param force if true, resources will be extracted even ifthey have already been extracted before.
1832 */
1833 public static void extractResources(boolean force) {
1834 if (UserSettings.PublicAndPrivateResources) {
1835 // Extract private resources
1836 Path resourcesPrivate = Paths.get(FrameIO.PARENT_FOLDER).resolve("resources-private");
1837 extractResources("org/expeditee/assets/resources-private", resourcesPrivate, force);
1838
1839 // Extract public resources
1840 Path resourcesPublic = Paths.get(FrameIO.PARENT_FOLDER).resolve("resources-public");
1841 extractResources("org/expeditee/assets/resources-public", resourcesPublic, force);
1842 } else if (AuthenticatorBrowser.isAuthenticationRequired()) {
1843 // Deal with the instance of being in the old regime but using authentication.
1844
1845 // Ensure additional framesets
1846 Path framesetsDir = Paths.get(FrameIO.FRAME_PATH);
1847 boolean extracted = extractResources("org/expeditee/assets/resources-public/framesets", framesetsDir, force);
1848
1849 // Ensure additional images
1850 Path imagesDir = Paths.get(FrameIO.IMAGES_PATH);
1851 extracted |= extractResources("org/expeditee/assets/resources-public/images", imagesDir, force);
1852
1853 // Ensure deaddrops area exists
1854 extracted |= Paths.get(FrameIO.PARENT_FOLDER).resolve("deaddrops").toFile().mkdir();
1855
1856 if (extracted) {
1857 @SuppressWarnings("resource")
1858 Scanner in = new Scanner(System.in);
1859 System.out.println("Extracting resources...In order to use authentication, you need a new default profile frameset.");
1860 System.out.println("This is a destructive process, your existing default profile frameset (if it exists) will be deleted.");
1861 System.out.print("Do you want to proceed? y/N:");
1862 System.out.flush();
1863 String answer = in.nextLine();
1864 if (!answer.toLowerCase().startsWith("y")) {
1865 System.out.println("Exiting...");
1866 System.exit(1);
1867 }
1868
1869 // Ensure the default profile is 'update to date'.
1870 //NB: this limits the potential for those running old regime with authentication the ability to customise the default profile.
1871 Path defaultProfile = Paths.get(FrameIO.PROFILE_PATH).resolve("default");
1872 try {
1873 Files.walkFileTree(defaultProfile, new FileVisitor<Path>() {
1874 @Override
1875 public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
1876 dir.toFile().delete();
1877 return FileVisitResult.CONTINUE;
1878 }
1879 @Override
1880 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
1881 return FileVisitResult.CONTINUE;
1882 }
1883 @Override
1884 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1885 file.toFile().delete();
1886 return FileVisitResult.CONTINUE;
1887 }
1888 @Override
1889 public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
1890 return FileVisitResult.CONTINUE;
1891 }
1892 });
1893 } catch (IOException e) {
1894 e.printStackTrace();
1895 }
1896 }
1897 }
1898 }
1899
1900 private static boolean extractResources(String source, Path destination, boolean force) {
1901 // If resources have already been extracted, and we are not forcing the extraction, there is nothing to do.
1902 if (!force && destination.resolve(".res").toFile().exists()) {
1903 return false;
1904 }
1905
1906 System.out.println("Extracting/Installing resources to: " + destination.getFileName());
1907
1908 // Create the destination
1909 destination.getParent().toFile().mkdirs();
1910
1911 ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
1912 URL resourceUrl = classLoader.getResource(source);
1913 if (resourceUrl.getProtocol().equals("jar")) {
1914 try {
1915 JarURLConnection ju_connection = (JarURLConnection) resourceUrl.openConnection();
1916 JarFile jf = ju_connection.getJarFile();
1917 Enumeration<JarEntry> jarEntries = jf.entries();
1918 extractFromJarFile(classLoader, jarEntries, source, destination);
1919 } catch (IOException e) {
1920 System.err.println("Error: FrameUtils::extractResources. Exception whilst extracting resources from Jar File. Message: " + e.getMessage());
1921 }
1922 } else if (resourceUrl.getProtocol().equals("bundleresource")) {
1923 try {
1924 URLConnection urlConnection = resourceUrl.openConnection();
1925 Class<?> c = urlConnection.getClass();
1926 java.lang.reflect.Method toInvoke = c.getMethod("getFileURL");
1927 URL fileURL = (URL) toInvoke.invoke(urlConnection);
1928 extractResourcesFromFolder(new File(fileURL.getPath()), source, destination);
1929 } catch (IOException e) {
1930 System.err.println("Error: FrameUtils::extractResources. Problem opening connection to bundleresource. Message: " + e.getMessage());
1931 } catch (NoSuchMethodException e) {
1932 System.err.println("Error: FrameUtils::extractResources. Unable to find method URLConnection::getFileURL. Message: " + e.getMessage());
1933 } catch (InvocationTargetException e) {
1934 System.err.println("Error: FrameUtils::extractResources. Problem invoking URLConnection::getFileURL. Message: " + e.getMessage());
1935 } catch (IllegalAccessException e) {
1936 System.err.println("Error: FrameUtils::extractResources. Problem invoking URLConnection::getFileURL. Message: " + e.getMessage());
1937 }
1938 } else {
1939 try {
1940 File folder = new File(resourceUrl.toURI().getPath());
1941 extractResourcesFromFolder(folder, source, destination);
1942 } catch (URISyntaxException e) {
1943 System.err.println("Error: FrameUtils::extractResources. Problem converting URL to URI. Message: " + e.getMessage());
1944 } catch (IOException e) {
1945 System.err.println("Error: FrameUtils::extractResources. Exception whilst extracting resources from folder. Message: " + e.getMessage());
1946 }
1947 }
1948
1949 // Create the .res file to signal completion
1950 try {
1951 destination.resolve(".res").toFile().createNewFile();
1952 } catch (IOException e) {
1953 System.err.println("Error: FrameUtils::extractResources. Unable to create the .res file to flag that resources have been extracted. Message: " + e.getMessage());
1954 }
1955
1956 return true;
1957 }
1958
1959 private static void extractFromJarFile(ClassLoader classLoader, Enumeration<JarEntry> jarEntries, String source, Path destination) throws IOException {
1960 while (jarEntries.hasMoreElements()) {
1961 ZipEntry ze = jarEntries.nextElement();
1962 if (!ze.getName().startsWith(source)) {
1963 continue;
1964 }
1965 File out = destination.resolve(ze.getName().substring(source.length())).toFile();
1966 if (ze.isDirectory()) {
1967 out.mkdirs();
1968 continue;
1969 }
1970 FileOutputStream fOut = null;
1971 InputStream fIn = null;
1972 try {
1973 fOut = new FileOutputStream(out);
1974 fIn = classLoader.getResourceAsStream(ze.getName());
1975 byte[] bBuffer = new byte[1024];
1976 int nLen;
1977 while ((nLen = fIn.read(bBuffer)) > 0) {
1978 fOut.write(bBuffer, 0, nLen);
1979 }
1980 fOut.flush();
1981 } catch (Exception e) {
1982 e.printStackTrace();
1983 } finally {
1984 if (fOut != null) {
1985 fOut.close();
1986 }
1987 if (fIn != null) {
1988 fIn.close();
1989 }
1990 }
1991 }
1992 }
1993
1994 private static void extractResourcesFromFolder(File folder, String source, Path destination) throws IOException {
1995 LinkedList<File> items = new LinkedList<File>();
1996 items.addAll(Arrays.asList(folder.listFiles()));
1997 LinkedList<File> files = new LinkedList<File>();
1998
1999 while (items.size() > 0) {
2000 File file = items.remove(0);
2001 if (file.isFile()) {
2002 if (!file.getName().contains(".svn")) {
2003 files.add(file);
2004 }
2005 } else {
2006 if (!file.getName().contains(".svn")) {
2007 items.addAll(Arrays.asList(file.listFiles()));
2008 }
2009 }
2010 }
2011 for (File file : files) {
2012 String path = file.getPath();
2013 System.out.println(path);
2014 Path relativize = folder.toPath().relativize(Paths.get(file.getPath()));
2015 File out = destination.resolve(relativize).toFile();
2016 copyFile(file, out, true);
2017 }
2018 }
2019
2020 /**
2021 * @param src
2022 * @param dst
2023 * @throws IOException
2024 */
2025 public static void copyFile(File src, File dst, boolean overWrite) throws IOException {
2026 if (!overWrite && dst.exists()) {
2027 return;
2028 }
2029
2030 dst.getParentFile().mkdirs();
2031 FileOutputStream fOut = null;
2032 FileInputStream fIn = null;
2033 try {
2034 // System.out.println(out.getPath());
2035 fOut = new FileOutputStream(dst);
2036 fIn = new FileInputStream(src);
2037 byte[] bBuffer = new byte[1024];
2038 int nLen;
2039 while ((nLen = fIn.read(bBuffer)) > 0) {
2040 fOut.write(bBuffer, 0, nLen);
2041 }
2042 fOut.flush();
2043 } catch (Exception e) {
2044 e.printStackTrace();
2045 } finally {
2046 if (fOut != null) {
2047 fOut.close();
2048 }
2049 if (fIn != null) {
2050 fIn.close();
2051 }
2052 }
2053 }
2054
2055 public static Text getLastEdited() {
2056 return LastEdited;
2057 }
2058
2059 public static Collection<Text> getCurrentTextItems() {
2060 Collection<Text> currentTextItems = new LinkedHashSet<Text>();
2061 Collection<Item> currentItems = getCurrentItems(null);
2062 if (currentItems != null) {
2063 for (Item i : getCurrentItems(null)) {
2064 if (i instanceof Text && !i.isLineEnd()) {
2065 currentTextItems.add((Text) i);
2066 }
2067 }
2068 }
2069 return currentTextItems;
2070 }
2071}
Note: See TracBrowser for help on using the repository browser.