1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
5 import org.ibex.util.*;
7 /** Implements cooperative multitasking */
8 public class Scheduler {
10 // Public API Exposed to org.ibex /////////////////////////////////////////////////
12 private static Scheduler singleton;
13 public static interface Task { public abstract void perform() throws Exception; }
14 public static void add(Task t) { Scheduler.runnable.append(t); }
15 public static void init() { if (singleton == null) (singleton = Platform.getScheduler()).run(); }
17 private static Task current = null;
19 private static volatile boolean rendering = false;
20 private static volatile boolean again = false;
22 /** synchronizd so that we can safely call it from an event-delivery thread, in-context */
23 public static void renderAll() {
24 if (rendering) { again = true; return; }
25 synchronized(Scheduler.class) {
29 // FEATURE: this could be cleaner
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);
44 // API which must be supported by subclasses /////////////////////////////////////
47 * SCHEDULER INVARIANT: all scheduler implementations MUST invoke
48 * Surface.renderAll() after performing a Task if no tasks remain
49 * in the queue. A scheduler may choose to invoke
50 * Surface.renderAll() more often than that if it so chooses.
52 public void run() { defaultRun(); }
53 protected Scheduler() { }
56 // Default Implementation //////////////////////////////////////////////////////
58 protected static Queue runnable = new Queue(50);
59 public void defaultRun() {
61 current = (Task)runnable.remove(true);
65 for(int i=0; i<Surface.allSurfaces.size(); i++) {
66 Surface s = (Surface)Surface.allSurfaces.elementAt(i);
67 if (current instanceof JS) {
68 s._mousex = Integer.MAX_VALUE;
69 s._mousey = Integer.MAX_VALUE;
79 Log.info(Scheduler.class, "a JavaScript thread spawned with ibex.thread() threw an exception:");
80 Log.info(Scheduler.class, "JS Exception: " + e.getObject() + "\n" + e.backtrace());
81 Log.info(Scheduler.class,e);
82 } catch (Exception e) {
83 Log.info(Scheduler.class, "a Task threw an exception which was caught by the scheduler:");
84 Log.info(Scheduler.class, e);
86 // if an Error is thrown it will cause the engine to quit