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; }
16 /** adds a task to the back of the queue */
17 public static void add(Task t) { singleton.runnable.append(t); }
19 public static void init() { if (singleton == null) (singleton = Platform.getScheduler()).run(); }
21 private static Task currentTask = null;
22 public static Task current() { return currentTask; }
24 /** synchronizd so that we can safely call it from an event-delivery thread, in-context */
25 private static volatile boolean rendering = false;
26 private static volatile boolean again = false;
27 public static void renderAll() {
28 if (rendering) { again = true; return; }
29 synchronized(Scheduler.class) {
34 for(int i=0; i<Surface.allSurfaces.size(); i++) {
35 Surface s = ((Surface)Surface.allSurfaces.elementAt(i));
36 do { s.render(); } while(s.abort);
47 // API which must be supported by subclasses /////////////////////////////////////
50 * SCHEDULER INVARIANT: all scheduler implementations MUST invoke
51 * Surface.renderAll() after performing a Task if no tasks remain
52 * in the queue. A scheduler may choose to invoke
53 * Surface.renderAll() more often than that if it so chooses.
55 public void run() { defaultRun(); }
56 protected Scheduler() { }
59 // Default Implementation //////////////////////////////////////////////////////
61 protected static Queue runnable = new Queue(50);
62 public void defaultRun() {
64 currentTask = (Task)runnable.remove(true);
67 for(int i=0; i<Surface.allSurfaces.size(); i++) {
68 Surface s = (Surface)Surface.allSurfaces.elementAt(i);
69 if (currentTask instanceof JS) {
70 s._mousex = Integer.MAX_VALUE;
71 s._mousey = Integer.MAX_VALUE;
77 currentTask.perform();
81 Log.info(Scheduler.class, "a JavaScript thread spawned with xwt.thread() threw an exception:");
82 Log.info(Scheduler.class, "JS Exception: " + e.getObject() + "\n" + e.backtrace());
83 Log.info(Scheduler.class,e);
84 } catch (Exception e) {
85 Log.info(Scheduler.class, "a Task threw an exception which was caught by the scheduler:");
86 Log.info(Scheduler.class, e);
88 // if an Error is thrown it will cause the engine to quit
89 } } catch (Throwable t) {