1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
8 /** Implements cooperative multitasking */
9 public class Scheduler {
11 // FIXME: prepending events messes with keysate -- make a "no re-ordering" invariant?
13 // Public API Exposed to org.xwt /////////////////////////////////////////////////
15 private static Scheduler singleton;
16 public static interface Task { public abstract void perform() throws Exception; }
18 /** adds a task to the back of the queue */
19 public static void add(Task t) { singleton.runnable.append(t); }
21 /** adds a task to the front of the queue (guaranteed to run next) */
22 public static void addAtFront(Task t) { singleton.runnable.prepend(t); }
24 public static void init() { if (singleton == null) (singleton = Platform.getScheduler()).run(); }
26 private static Task current = null;
27 public static Task current() { return current; }
29 /** synchronizd so that we can safely call it from an event-delivery thread, in-context */
30 public static synchronized void renderAll() {
31 for(int i=0; i<Surface.allSurfaces.size(); i++) {
32 Surface s = ((Surface)Surface.allSurfaces.elementAt(i));
33 do { s.render(); } while(s.abort);
39 // API which must be supported by subclasses /////////////////////////////////////
42 * SCHEDULER INVARIANT: all scheduler implementations MUST invoke
43 * Surface.renderAll() after performing a Task if no tasks remain
44 * in the queue. A scheduler may choose to invoke
45 * Surface.renderAll() more often than that if it so chooses.
47 public void run() { defaultRun(); }
48 protected Scheduler() { }
51 // Default Implementation //////////////////////////////////////////////////////
53 protected static Queue runnable = new Queue(50);
54 public void defaultRun() {
56 current = (Task)runnable.remove(true);
59 for(int i=0; i<Surface.allSurfaces.size(); i++) {
60 Surface s = (Surface)Surface.allSurfaces.elementAt(i);
61 if (current instanceof JSFunction) {
62 s._mousex = Integer.MAX_VALUE;
63 s._mousey = Integer.MAX_VALUE;
73 Log.info(Scheduler.class, "a JavaScript thread spawned with xwt.thread() threw an exception:");
74 Log.info(Scheduler.class, e);
75 } catch (Exception e) {
76 Log.info(Scheduler.class, "a Task threw an exception which was caught by the scheduler:");
77 Log.info(Scheduler.class, e);
79 // if an Error is thrown it will cause the engine to quit