1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
8 /** Implements cooperative multitasking */
9 public class Scheduler {
11 // Public API Exposed to org.xwt /////////////////////////////////////////////////
13 private static Scheduler singleton;
14 public static interface Task { public abstract void perform() throws Exception; }
15 public static void add(Task t) { singleton.runnable.append(t); }
16 public static void init() { if (singleton == null) (singleton = Platform.getScheduler()).run(); }
18 private static Task current = null;
20 private static volatile boolean rendering = false;
21 private static volatile boolean again = false;
23 /** synchronizd so that we can safely call it from an event-delivery thread, in-context */
24 public static void renderAll() {
25 if (rendering) { again = true; return; }
26 synchronized(Scheduler.class) {
30 // FEATURE: this could be cleaner
32 for(int i=0; i<Surface.allSurfaces.size(); i++) {
33 Surface s = ((Surface)Surface.allSurfaces.elementAt(i));
34 do { s.render(); } while(s.abort);
45 // API which must be supported by subclasses /////////////////////////////////////
48 * SCHEDULER INVARIANT: all scheduler implementations MUST invoke
49 * Surface.renderAll() after performing a Task if no tasks remain
50 * in the queue. A scheduler may choose to invoke
51 * Surface.renderAll() more often than that if it so chooses.
53 public void run() { defaultRun(); }
54 protected Scheduler() { }
57 // Default Implementation //////////////////////////////////////////////////////
59 protected static Queue runnable = new Queue(50);
60 public void defaultRun() {
62 current = (Task)runnable.remove(true);
66 for(int i=0; i<Surface.allSurfaces.size(); i++) {
67 Surface s = (Surface)Surface.allSurfaces.elementAt(i);
68 if (current instanceof JS) {
69 s._mousex = Integer.MAX_VALUE;
70 s._mousey = Integer.MAX_VALUE;
80 Log.info(Scheduler.class, "a JavaScript thread spawned with xwt.thread() threw an exception:");
81 Log.info(Scheduler.class, "JS Exception: " + e.getObject() + "\n" + e.backtrace());
82 Log.info(Scheduler.class,e);
83 } catch (Exception e) {
84 Log.info(Scheduler.class, "a Task threw an exception which was caught by the scheduler:");
85 Log.info(Scheduler.class, e);
87 // if an Error is thrown it will cause the engine to quit