1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
4 import java.io.IOException;
7 import org.ibex.util.*;
8 import org.ibex.graphics.*;
9 import org.ibex.plat.*;
11 /** Implements cooperative multitasking */
12 public class Scheduler {
14 // Public API Exposed to org.ibex /////////////////////////////////////////////////
16 private static Scheduler singleton;
17 private static String taskDesc(Task t) { return t instanceof JS ? JS.debugToString((JS)t) : t.toString(); }
18 public static void add(Task t) { Log.debug(Scheduler.class, "scheduling " + taskDesc(t)); Scheduler.runnable.append(t); }
19 public static void init() { if (singleton == null) (singleton = Platform.getScheduler()).run(); }
21 private static Task current = null;
23 private static volatile boolean rendering = false;
24 private static volatile boolean again = false;
26 /** synchronizd so that we can safely call it from an event-delivery thread, in-context */
27 public static void renderAll() {
28 if (rendering) { again = true; return; }
29 synchronized(Scheduler.class) {
33 // FEATURE: this could be cleaner
35 for(int i=0; i<Surface.allSurfaces.size(); i++) {
36 Surface s = ((Surface)Surface.allSurfaces.elementAt(i));
37 do { s.render(); } while(s.abort);
48 // API which must be supported by subclasses /////////////////////////////////////
51 * SCHEDULER INVARIANT: all scheduler implementations MUST invoke
52 * Surface.renderAll() after performing a Task if no tasks remain
53 * in the queue. A scheduler may choose to invoke
54 * Surface.renderAll() more often than that if it so chooses.
56 public void run() { defaultRun(); }
57 public Scheduler() { }
60 // Default Implementation //////////////////////////////////////////////////////
62 protected static Queue runnable = new Queue(50);
63 public void defaultRun() {
65 current = (Task)runnable.remove(true);
69 for(int i=0; i<Surface.allSurfaces.size(); i++) {
70 Surface s = (Surface)Surface.allSurfaces.elementAt(i);
71 if (current instanceof JS) {
72 s._mousex = Integer.MAX_VALUE;
73 s._mousey = Integer.MAX_VALUE;
79 Log.debug(Scheduler.class, "performing " + taskDesc(current));
84 Log.info(Scheduler.class, "a JavaScript thread spawned with ibex.thread() threw an exception:");
85 Log.info(Scheduler.class,e);
86 } catch (Exception e) {
87 Log.info(Scheduler.class, "a Task threw an exception which was caught by the scheduler:");
88 Log.info(Scheduler.class, e);
89 } catch (Throwable t) {
92 // if an Error is thrown it will cause the engine to quit