2003/12/21 08:50:38
[org.ibex.core.git] / src / org / xwt / Scheduler.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.util.*;
5 import org.xwt.js.*;
6 import org.xwt.util.*;
7
8 /** Implements cooperative multitasking */
9 public class Scheduler {
10
11     // FIXME: prepending events messes with keysate -- make a "no re-ordering" invariant?
12
13     // Public API Exposed to org.xwt /////////////////////////////////////////////////
14
15     private static Scheduler singleton;
16     public static interface Task { public abstract void perform() throws Exception; }
17
18     /** adds a task to the back of the queue */
19     public static void add(Task t) { singleton.runnable.append(t); }
20
21     /** adds a task to the front of the queue (guaranteed to run next) */
22     public static void addAtFront(Task t) { singleton.runnable.prepend(t); }
23
24     public static void init() { if (singleton == null) (singleton = Platform.getScheduler()).run(); }
25
26     // API which must be supported by subclasses /////////////////////////////////////
27
28     /**
29      *  SCHEDULER INVARIANT: all scheduler implementations MUST invoke
30      *  Surface.renderAll() after performing a Task if no tasks remain
31      *  in the queue.  A scheduler may choose to invoke
32      *  Surface.renderAll() more often than that if it so chooses.
33      */
34     public void run() { defaultRun(); }
35     protected Scheduler() { }
36
37
38     // Default Implementation //////////////////////////////////////////////////////
39
40     protected static Queue runnable = new Queue(50);
41     public void defaultRun() {
42         while(true) {
43             Task t = (Task)runnable.remove(true);
44             try {
45                 t.perform();
46                 // FEATURE: be smarter about this
47                 //if (t != Surface.renderAll) add(Surface.renderAll);
48                 Surface.renderAll.perform();
49             } catch (JSExn e) {
50                 Log.log(Scheduler.class, "a JavaScript thread spawned with xwt.thread() threw an exception:");
51                 Log.log(Scheduler.class, e.toString());
52             } catch (Exception e) {
53                 Log.log(Scheduler.class, "a Task threw an exception which was caught by the scheduler:");
54                 Log.log(Scheduler.class, e);
55             }
56             // if an Error is thrown it will cause the engine to quit
57         }
58     }
59 }