source: trunk/src/org/expeditee/gui/Browser.java@ 1244

Last change on this file since 1244 was 1244, checked in by davidb, 5 years ago

After change to have resources-public and resources-private, some changes needed to support running Expeditee for a single user; other main change is to allow FrameDirs to specify relative directory paths, to help with when Expeditee is run on the cloud -- similar work still needs to occurr for ImageDir and AudioDir; some other minor changes also made.

File size: 17.3 KB
Line 
1/**
2 * Browser.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.IOException;
23import java.net.Authenticator;
24import java.nio.file.Path;
25import java.security.KeyStoreException;
26import java.security.NoSuchAlgorithmException;
27import java.security.cert.CertificateException;
28import java.sql.SQLException;
29import java.util.ArrayList;
30import java.util.Collection;
31
32import org.expeditee.actions.Actions;
33import org.expeditee.actions.Simple;
34import org.expeditee.agents.mail.MailSession;
35import org.expeditee.core.BlockingRunnable;
36import org.expeditee.core.Colour;
37import org.expeditee.core.Dimension;
38import org.expeditee.core.Point;
39import org.expeditee.gio.EcosystemManager;
40import org.expeditee.gio.EcosystemManager.Ecosystem;
41import org.expeditee.gio.GraphicsManager;
42import org.expeditee.gio.InputManager;
43import org.expeditee.gio.InputManager.WindowEventListener;
44import org.expeditee.gio.InputManager.WindowEventType;
45import org.expeditee.gio.gesture.StandardGestureActions;
46import org.expeditee.io.ProxyAuth;
47import org.expeditee.items.Item;
48import org.expeditee.items.ItemUtils;
49import org.expeditee.items.Text;
50import org.expeditee.items.widgets.WidgetCacheManager;
51import org.expeditee.network.FrameShare;
52import org.expeditee.settings.Settings;
53import org.expeditee.settings.UserSettings;
54import org.expeditee.stats.Logger;
55import org.expeditee.stats.StatsLogger;
56import org.expeditee.taskmanagement.EntitySaveManager;
57import org.expeditee.taskmanagement.SaveStateChangedEvent;
58import org.expeditee.taskmanagement.SaveStateChangedEventListener;
59
60/**
61 * The Main GUI class, comprises what people will see on the screen.<br>
62 * Note: Each Object (Item) is responsible for drawing itself on the screen.<br>
63 * Note2: The Frame is registered as a MouseListener and KeyListener, and
64 * processes any Events.
65 *
66 * TODO List:
67 *
68 * Back to standard:
69 * - JavaFX Text-hitting (requires JFX1.9)
70 * - Overlays and Vectors review
71 * - Pop-ups (unused in base Expeditee, only in Apollo)
72 * - Apollo input (test)
73 * - The rest of Apollo
74 * - Make sure clipping/invalidation takes twin-frames into account
75 * - Reinstate Simple input commands
76 * - Test LinkedTrack.paintInFreeSpace()
77 * - Test EmulatedTextItem.onMouseReleased(MouseEvent) (removed emulatedSource mouse button check)
78 * - Constrained placement of items
79 *
80 * Extra:
81 * - Self-describing input
82 * - Thread safety (most stuff on GIO event thread but Agents can start new threads)
83 * - Touch input
84 * - Better reflection??? (currently changes to the code break reflection as it relies on names)
85 * - JavaFX lag (always rendering to images doesn't gel well with JavaFX)
86 * - Swing widgets in JFX
87 * - JavaFX Widgets (exception on drawing?)
88 * - Reduce reliance on into-image rendering to improve JavaFX performance (utilise enforced-clip)
89 * - Block Swing ecosystem setup until window is available, or...
90 * - Reconfigure window-resized code so things are properly resized (PREFERRED).
91 * - Swing alpha-compositing of colours (currently alpha is ignored e.g. drop-shadow in transition).
92 * - Overly-thick extrusion lines (seems to depend on number of connected lines...)
93 * - Make FreeItems control pickup etc.
94 * - Remove MouseEventRouter
95 * - Highlighting (should be controlled by the items themselves)
96 * - Make Widgets into fully-fledged items (maybe???)
97 * - Merge Widget and HeavyDutyWidget
98 * - Redefine TextLayouts (relative/absolute layouts)
99 * - Settings exceptions (Password widget in JFX) (currently fixed with hack)
100 * - MessageBay (what did I mean by this specifically?)
101 * - Order-dependency of start-up code
102 * - MessageBay not refreshing at start-up
103 * - Invalidation hierarchy (item => frame => display controller area => window)
104 * - Add gesture data type checking
105 * - Paintable interface
106 * - EcosystemSpecific interface (utilise to enable/disable features based on ecosystem)
107 * - Remove/modify Mutable class (in Apollo.util, change to InOutReference)
108 * - Convert BlockingRunnable to interface
109 * - Modify Metronome to utilise Timeouts
110 * - Need AWT in FastAlphaEffect???
111 *
112 * General:
113 * - Tidy FrameGraphics
114 * - Comment
115 * - UserSettings.DEFAULT_PROFILE_NAME not actually a user setting
116 *
117 * Done:
118 * - Timers
119 * - Timer input animations
120 * - Finish DisplayController/FrameGraphics separation
121 * - Anchor constraints (create class)
122 * - Make MessageBay take lead from DisplayController
123 * - Make message bay display again (to do with above)
124 * - Tooltips (layout broken in Swing as window size not correct when tooltips laid out)
125 * - Frame transitions
126 * - Frame transitions in twin-frames mode drawing over each other
127 * - JFX DnD manager
128 * - Reinstate Simple
129 * - Reinstate exclude source
130 * - Reinstate commented code
131 * - Twin-frames division 0 at startup
132 * - Twin frames off-by-one frame size (draws a line of erroneous pixels)
133 * - MessageBay delays showing messages on start-up
134 * - JFX Antialiasing done on theScene??? Doesn't apply for our situation
135 * - Incorporate Clip class into code
136 * - Enforced clip
137 *
138 * @author cts16
139 * @author jdm18
140 */
141public class Browser implements SaveStateChangedEventListener {
142
143 public static final Ecosystem ECOSYSTEM_TYPE = Ecosystem.Swing;
144
145 public static Browser _theBrowser = null;
146
147 public static ProxyAuth proxyAuth = new ProxyAuth();
148
149 public static boolean _hasExited = false;
150
151 public static String USER_NOBODY = "nobody";
152
153 /** A flag which is set once the application is exiting. */
154 protected boolean _isExiting = false;
155
156 protected static boolean _initComplete = false;
157
158 private static String _startFrame = null;
159
160
161 /**
162 * Constructs a new Browser object, then launches it
163 *
164 * @param args
165 */
166 public static void main(String[] args)
167 {
168 if (Boolean.getBoolean("auth")) {
169 String starting_user_name = System.getProperty("user.name");
170 System.setProperty("startinguser.name", starting_user_name);
171 System.setProperty("user.name", USER_NOBODY);
172 }
173
174 // Parse the starting frame command-line argument
175 if(args.length > 0) {
176 setStartFrame(args[0]);
177 if(!Character.isDigit(getStartFrame().charAt(getStartFrame().length() - 1))) {
178 setStartFrame(getStartFrame() + "1");
179 }
180 } else {
181 setStartFrame("home1");
182 }
183
184 // Window icon must be set before initialisation
185 GraphicsManager.setWindowIcon(DisplayController.ICON_IMAGE);
186
187 // Setup the GIO ecosystem so it is ready when we need it
188 EcosystemManager.createEcosystem(ECOSYSTEM_TYPE);
189
190 try {
191 EcosystemManager.getMiscManager().runOnGIOThread(new BlockingRunnable() {
192 @Override
193 public void execute() {
194 init();
195 }
196 });
197 } catch (Throwable e) {
198 e.printStackTrace(System.err);
199 System.exit(1);
200 }
201
202 DisplayController.requestRefresh(false, () -> { MessageBay.showDelayedMessages(false); return true; });
203 }
204
205 public static void init() {
206 if (Boolean.getBoolean("auth")) {
207 try {
208 org.expeditee.auth.Authenticator.getInstance();
209 _initComplete = true;
210 return;
211 } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | ClassNotFoundException | SQLException e) {
212 e.printStackTrace();
213 }
214 }
215 _theBrowser = new Browser();
216
217 EcosystemManager.getGraphicsManager().requestFocus();
218
219 Authenticator.setDefault(proxyAuth);
220
221 _initComplete = true;
222 }
223
224 /**
225 * @return
226 *
227 * True if the application is about to exit. False if not. Note that this is
228 * only set once the window is in its closed state (not closing) or if the
229 * application has explicitly being requested to exit.
230 *
231 * @see Browser#exit()
232 *
233 */
234 public boolean isExiting() {
235 return _isExiting;
236 }
237
238 public static boolean isInitComplete() {
239 return _initComplete;
240 }
241
242 protected Browser() {
243 // center the frame on the screen
244 GraphicsManager g = EcosystemManager.getGraphicsManager();
245 Dimension screen = g.getScreenSize();
246 double xpos = (screen.width - UserSettings.InitialWidth.get()) / 2.0;
247 double ypos = (screen.height - UserSettings.InitialHeight.get()) / 2.0;
248 g.setWindowLocation(new Point((int) xpos, (int) ypos));
249
250 DisplayController.Init();
251
252 DisplayController.addDisplayObserver(WidgetCacheManager.getInstance());
253 if (ECOSYSTEM_TYPE == Ecosystem.Swing) {
254 DisplayController.addDisplayObserver(PopupManager.getInstance());
255 }
256
257 setInputManagerWindowRoutines();
258
259 // Reset windows to user specified size
260 Dimension initialWindowSize = new Dimension(UserSettings.InitialWidth.get(), UserSettings.InitialHeight.get());
261 g.setWindowSize(initialWindowSize);
262
263 // Load documentation and start pages
264 FrameUtils.extractResources(false);
265
266 // Load fonts before loading any frames so the items on the frames will be able
267 // to access their fonts
268 Text.InitFonts();
269
270 Settings.Init();
271 Frame userProfile = loadProfiles();
272
273 if (!Boolean.getBoolean("auth")) {
274 String userName = UserSettings.ProfileName.get();
275 FrameIO.setupPersonalResources(userName);
276 }
277 // Listen for save status to display during and after runtime
278 EntitySaveManager.getInstance().addSaveStateChangedEventListener(this);
279
280 try {
281 MessageBay.warningMessages(Actions.Init());
282
283 // Go to the start frame if specified, otherwise go to the profile frame
284 Frame start = null;
285 if (getStartFrame() == null) {
286 setStartFrame(UserSettings.StartFrame.get());
287 if (getStartFrame() != null && !Character.isDigit(getStartFrame().charAt(getStartFrame().length() - 1))) {
288 setStartFrame(getStartFrame() + "1");
289 }
290 }
291
292 if ((start = FrameIO.LoadFrame(getStartFrame())) != null) {
293 // Make sure HomeFrame gets set
294 UserSettings.HomeFrame.set(start.getName());
295
296 // Go to the start frame
297 DisplayController.setCurrentFrame(start, true);
298 } else {
299 // If an invalid start frame was specified, show a warning
300 if (getStartFrame() != null) {
301 MessageBay.warningMessage("Unknown frame: " + getStartFrame());
302 }
303
304 // Go to the profile frame
305 FrameUtils.loadFirstFrame(userProfile);
306 }
307
308 DisplayController.updateTitle();
309
310 // Don't refresh for the profile frame otherwise error messages are shown twice
311 if (!DisplayController.getCurrentFrame().equals(userProfile)) {
312 StandardGestureActions.Refresh();
313 // If it's the profile frame just reparse it in order to display
314 // images/circles/widgets correctly
315 } else {
316 FrameUtils.Parse(userProfile);
317 }
318 } catch (Exception e) {
319 e.printStackTrace();
320 Logger.Log(e);
321 }
322 }
323
324 @Override
325 public void saveCompleted(SaveStateChangedEvent event)
326 {
327 MessageBay.displayMessage("Save finished!", Colour.BLUE);
328 }
329
330 @Override
331 public void saveStarted(SaveStateChangedEvent event)
332 {
333 String name = event.getEntity().getSaveName();
334 if (name == null) {
335 name = "data";
336 }
337 MessageBay.displayMessage("Saving " + name + "...", Colour.BLUE);
338 }
339
340 /**
341 * Closes the browser and ends the application. Performs saving operations -
342 * halting until saves have completed. Feedback is given to the user while
343 * the application is exiting. Must call on the swing thread.
344 */
345 public void exit() {
346
347 // Set exiting flag
348 _isExiting = true;
349
350 MessageBay.displayMessage("System exiting...");
351
352 /**
353 * TODO: Prompt the user etc.
354 */
355
356 // TODO: Should we should a popup with a progress bar for user feedback?
357 // this would be nice and easy to do.
358 // Exit on a dedicated thread so that feedback can be obtained
359 new Exiter().start(); // this will exit the application
360 }
361
362 /**
363 * The system must exit on a different thread other than the swing thread so
364 * that the save threads can fire save-feedback to the swing thread and thus
365 * provide user feedback on asynchronous save operations.
366 *
367 * @author Brook Novak
368 *
369 */
370 private class Exiter extends Thread {
371
372 @Override
373 public void run() {
374
375 // The final save point for saveable entities
376 EntitySaveManager.getInstance().saveAll();
377 try {
378 EntitySaveManager.getInstance().waitUntilAllSavingFinished();
379 } catch (InterruptedException e) {
380 e.printStackTrace();
381 }
382
383 // Stop any agents or simple programs
384 Simple.stop();
385 Actions.stopAgent();
386 // Wait for them to stop
387 try {
388 // Only stop if need to...
389 // Brook: What purpose does this serve?
390 MessageBay.displayMessage("Stopping Simple programs...");
391 while (Simple.isProgramRunning()) {
392 Thread.sleep(100);
393 }
394
395 MessageBay.displayMessage("Stopping Agents...");
396 /* TODO: Only stop if need to... */
397 while (Actions.isAgentRunning()) {
398 Thread.sleep(100); // Brook: What purpose does this serve?
399 }
400 } catch (Exception e) {
401
402 }
403
404 MessageBay.displayMessage("Saving current frame...");
405 FrameIO.SaveFrame(DisplayController.getCurrentFrame());
406
407 MessageBay.displayMessage("Saving stats...");
408 StatsLogger.WriteStatsFile();
409
410 if (MailSession.getInstance() != null) {
411 if (MailSession.getInstance().finalise()) {
412 // TODO display this message before the finalising
413 // is done but only if the mail needs closing
414 MessageBay.displayMessage("Closed ExpMail...");
415 }
416 }
417
418 if (FrameShare.getInstance() != null) {
419 MessageBay.displayMessage("Stopping FrameServer...");
420 FrameShare.getInstance().finalise();
421 }
422
423 MessageBay.displayMessage("System exited");
424
425 // Finally remove the messages frameset
426 FrameIO.moveFrameset("messages", FrameIO.MESSAGES_PATH);
427
428 /*
429 * Create a new messages folder so that it doesn't throw
430 * Exceptions when two Expeditee's open at once and the
431 * second tries to save its messages
432 */
433 File file = new File(FrameIO.MESSAGES_PATH + "messages");
434 file.mkdirs();
435
436 Browser._hasExited = true;
437
438 System.exit(0);
439 }
440 }
441
442 /**
443 * Used to set up the the browser for use in testing.
444 *
445 * @return
446 */
447 public static Browser initializeForTesting()
448 {
449 if (Browser._theBrowser == null) {
450 FrameShare.disableNetworking = true;
451 MailSession._autoConnect = false;
452
453 Browser.main(new String[]{});
454 try {
455 while (!isInitComplete()) {
456 Thread.sleep(10);
457 }
458 } catch (Exception e) {
459 }
460 }
461 return _theBrowser;
462 }
463
464 private static void setInputManagerWindowRoutines() {
465 InputManager manager = EcosystemManager.getInputManager();
466
467 // Refresh the layout when the window resizes
468 manager.addWindowEventListener(new WindowEventListener() {
469 @Override
470 public void onWindowEvent(WindowEventType type)
471 {
472 if (type != WindowEventType.WINDOW_RESIZED) {
473 return;
474 }
475 DisplayController.refreshWindowSize();
476 FrameIO.RefreshCacheImages();
477 for (Frame frame : DisplayController.getFrames()) {
478 if (frame != null) {
479 ItemUtils.Justify(frame);
480 frame.refreshSize();
481 }
482 }
483 DisplayController.requestRefresh(false);
484 }
485 });
486
487 manager.addWindowEventListener(new WindowEventListener() {
488 @Override
489 public void onWindowEvent(WindowEventType type)
490 {
491 if (type != WindowEventType.MOUSE_EXITED_WINDOW) {
492 return;
493 }
494 StandardGestureActions.mouseExitedWindow();
495 }
496 });
497
498 manager.addWindowEventListener(new WindowEventListener() {
499 @Override
500 public void onWindowEvent(WindowEventType type)
501 {
502 if (type != WindowEventType.MOUSE_ENTERED_WINDOW) {
503 return;
504 }
505 StandardGestureActions.mouseEnteredWindow();
506 }
507 });
508
509 manager.addWindowEventListener(new WindowEventListener() {
510 @Override
511 public void onWindowEvent(WindowEventType type)
512 {
513 if (type != WindowEventType.WINDOW_CLOSED) {
514 return;
515 }
516 if (Browser._theBrowser != null) {
517 Browser._theBrowser.exit();
518 }
519 }
520 });
521 }
522
523 /**
524 * @return The user's profile frame.
525 */
526 public static Frame loadProfiles()
527 {
528 String defaultProfileName = UserSettings.DEFAULT_PROFILE_NAME;
529 String userName = UserSettings.ProfileName.get();
530
531 Frame userProfile = loadProfile(userName);
532 Frame defaultProfile = loadProfile(defaultProfileName);
533
534 MessageBay.warningMessages(FrameUtils.ParseProfile(defaultProfile));
535
536 // Save the cursor if the defaultProfile had a custom cursor
537 Collection<Item> cursor = null;
538 if(FreeItems.hasCursor()) {
539 cursor = new ArrayList<Item>();
540 cursor.addAll(FreeItems.getCursor());
541 }
542
543 MessageBay.warningMessages(FrameUtils.ParseProfile(userProfile));
544
545 if (cursor != null && !FreeItems.hasCursor()) {
546 FreeItems.setCursor(cursor);
547 }
548
549 return userProfile;
550 }
551
552 protected static Frame loadProfile(String userName) {
553 Frame profile = FrameIO.LoadProfile(userName);
554
555 if (profile == null) {
556 try {
557 profile = FrameIO.CreateNewProfile(userName, null);
558 } catch (Exception e) {
559 // TODO tell the user that there was a problem creating the
560 // profile frame and close nicely
561 e.printStackTrace();
562 assert (false);
563 }
564 }
565 return profile;
566 }
567
568 public static String getStartFrame() {
569 return _startFrame;
570 }
571
572 public static void setStartFrame(String _startFrame) {
573 Browser._startFrame = _startFrame;
574 }
575}
Note: See TracBrowser for help on using the repository browser.