1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
4 import java.io.IOException;
7 import org.ibex.util.*;
9 /** Implements cooperative multitasking */
10 public class Scheduler {
12 // Public API Exposed to org.ibex /////////////////////////////////////////////////
14 private static Scheduler singleton;
15 public static interface Task { public abstract void perform() throws IOException, JSExn; }
16 public static void add(Task t) { Scheduler.runnable.append(t); }
17 public static void init() { if (singleton == null) (singleton = Platform.getScheduler()).run(); }
19 private static Task current = null;
21 private static volatile boolean rendering = false;
22 private static volatile boolean again = false;
24 /** synchronizd so that we can safely call it from an event-delivery thread, in-context */
25 public static void renderAll() {
26 if (rendering) { again = true; return; }
27 synchronized(Scheduler.class) {
31 // FEATURE: this could be cleaner
33 for(int i=0; i<Surface.allSurfaces.size(); i++) {
34 Surface s = ((Surface)Surface.allSurfaces.elementAt(i));
35 do { s.render(); } while(s.abort);
46 // API which must be supported by subclasses /////////////////////////////////////
49 * SCHEDULER INVARIANT: all scheduler implementations MUST invoke
50 * Surface.renderAll() after performing a Task if no tasks remain
51 * in the queue. A scheduler may choose to invoke
52 * Surface.renderAll() more often than that if it so chooses.
54 public void run() { defaultRun(); }
55 protected Scheduler() { }
58 // Default Implementation //////////////////////////////////////////////////////
60 protected static Queue runnable = new Queue(50);
61 public void defaultRun() {
63 current = (Task)runnable.remove(true);
67 for(int i=0; i<Surface.allSurfaces.size(); i++) {
68 Surface s = (Surface)Surface.allSurfaces.elementAt(i);
69 if (current instanceof JS) {
70 s._mousex = Integer.MAX_VALUE;
71 s._mousey = Integer.MAX_VALUE;
81 Log.info(Scheduler.class, "a JavaScript thread spawned with ibex.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);
87 } catch (Throwable t) {
90 // if an Error is thrown it will cause the engine to quit