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 currentTask = null;
27 public static Task current() { return currentTask; }
29 /** synchronizd so that we can safely call it from an event-delivery thread, in-context */
30 private static volatile boolean rendering = false;
31 private static volatile boolean again = false;
32 public static void renderAll() {
33 if (rendering) { again = true; return; }
34 synchronized(Scheduler.class) {
39 for(int i=0; i<Surface.allSurfaces.size(); i++) {
40 Surface s = ((Surface)Surface.allSurfaces.elementAt(i));
41 do { s.render(); } while(s.abort);
52 // API which must be supported by subclasses /////////////////////////////////////
55 * SCHEDULER INVARIANT: all scheduler implementations MUST invoke
56 * Surface.renderAll() after performing a Task if no tasks remain
57 * in the queue. A scheduler may choose to invoke
58 * Surface.renderAll() more often than that if it so chooses.
60 public void run() { defaultRun(); }
61 protected Scheduler() { }
64 // Default Implementation //////////////////////////////////////////////////////
66 protected static Queue runnable = new Queue(50);
67 public void defaultRun() {
69 currentTask = (Task)runnable.remove(true);
72 for(int i=0; i<Surface.allSurfaces.size(); i++) {
73 Surface s = (Surface)Surface.allSurfaces.elementAt(i);
74 if (currentTask instanceof JSFunction) {
75 s._mousex = Integer.MAX_VALUE;
76 s._mousey = Integer.MAX_VALUE;
82 currentTask.perform();
86 Log.info(Scheduler.class, "a JavaScript thread spawned with xwt.thread() threw an exception:");
87 Log.info(Scheduler.class, "JS Exception: " + e.getObject() + "\n" + e.backtrace());
88 Log.info(Scheduler.class,e);
89 } catch (Exception e) {
90 Log.info(Scheduler.class, "a Task threw an exception which was caught by the scheduler:");
91 Log.info(Scheduler.class, e);
93 // if an Error is thrown it will cause the engine to quit