2003/08/14 05:16:08
[org.ibex.core.git] / src / org / xwt / Surface.java
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import org.bouncycastle.util.encoders.Base64;
5 import org.xwt.util.*;
6 import java.io.*;
7 import java.util.*;
8
9 /** 
10  *  A Surface, as described in the XWT Reference.
11  *
12  *  Platform subclasses should include an inner class subclass of
13  *  Surface to return from the Platform._createSurface() method
14  *
15  *  Note that the members in the section 'state variables' are either
16  *  in real-time (the actual size/position/state), or in
17  *  MessageQueue-time (the size/position/state at the time that the
18  *  now-executing message was enqueued). This distinction is important.
19  */
20 public abstract class Surface {
21
22     // Static Data ////////////////////////////////////////////////////////////////////////////////
23
24     /** true iff a user-created surface was created */
25     static boolean refreshableSurfaceWasCreated = false;
26
27     /** a reference to the most recently enqueued Move message; used to throttle the message rate */
28     private static Message lastMoveMessage = null;
29
30     /** all instances of Surface which need to be refreshed by the MessageQueue */
31     public static Vec allSurfaces = new Vec();
32
33     /** true iff the alt button is pressed down, in real time */
34     public static boolean alt = false;
35     
36     /** true iff the control button is pressed down, in real time */
37     public static boolean control = false;
38
39     /** true iff the shift button is pressed down, in real time */
40     public static boolean shift = false;
41
42     /** true iff button 1 is depressed, in MessageQueue-time */
43     public static boolean button1 = false;
44
45     /** true iff button 2 is depressed, in MessageQueue-time */
46     public static boolean button2 = false;
47
48     /** true iff button 3 is depressed, in MessageQueue-time */
49     public static boolean button3 = false;
50
51     /** true iff all surfaces created from now on should be scarred */
52     public static boolean scarAllSurfacesFromNowOn = false;
53
54     /** false if the surface has never been rendered; used to determine if the surface should be repositioned to be centered on the screen */
55     public boolean centerSurfaceOnRender = true;
56
57     /** the x position of the mouse, relative to this Surface, in MessageQueue-time */
58     public int mousex;
59
60     /** the y position of the mouse, relative to this Surface, in MessageQueue-time */
61     public int mousey;
62
63     /** True iff this surface is minimized, in real time */
64     public boolean minimized = false;
65
66     /** True iff this surface is maximized, in real time */
67     public boolean maximized = false;
68
69     /** The name of the cursor on this surface -- this value fluctuates during rendering, so it may not be accurate;
70      *  syncCursor() is called once the value is stable, to prevent the "flickering cursor" phenomenon
71      */
72     public String cursor = "default";
73
74     /** The Box at the root of this surface */
75     public Box root;
76
77     /** The number of SizeChange/PosChange traps triggered since the last successful render -- used to detect infinite loops */
78     public int sizePosChangesSinceLastRender = 0;
79
80
81     // Used For Simulating Clicks and DoubleClicks /////////////////////////////////////////////////
82
83     /** the x-position of the mouse the last time a Press message was enqueued */
84     int last_press_x = Integer.MAX_VALUE;
85
86     /** the y-position of the mouse the last time a Press message was enqueued */
87     int last_press_y = Integer.MAX_VALUE;
88
89     /** the last button to recieve a Click message; used for simulating DoubleClick's */
90     static int lastClickButton = 0;
91
92     /** the last time a Click message was processed; used for simulating DoubleClick's */
93     static long lastClickTime = 0;
94     
95     
96     // Methods to be overridden by subclasses ///////////////////////////////////////////////////////
97
98     /** when this method is invoked, the surface should push itself to the back of the stacking order */
99     public abstract void toBack();
100
101     /** when this method is invoked, the surface should pull itself to the front of the stacking order */
102     public abstract void toFront();
103
104     /** sets the <i>actual</i> cursor for this surface to the cursor referenced by <tt>cursor</tt> */
105     public abstract void syncCursor();
106
107     /** If <tt>b == true</tt>, make the window invisible; otherwise, make it non-invisible. */
108     public abstract void setInvisible(boolean b);
109
110     /** If <tt>b == true</tt>, maximize the surface; otherwise, un-maximize it. */
111     protected abstract void _setMaximized(boolean b);
112
113     /** If <tt>b == true</tt>, minimize the surface; otherwise, un-minimize it. */
114     protected abstract void _setMinimized(boolean b);
115
116     /** Sets the surface's width and height. */
117     protected abstract void setSize(int width, int height);
118
119     /** Sets the surface's x and y position. */
120     public abstract void setLocation(int x, int y);
121
122     /** Sets the surface's title bar text, if applicable */
123     public abstract void setTitleBarText(String s);
124
125     /** Sets the surface's title bar text, if applicable */
126     public abstract void setIcon(Picture i);
127
128     /** copies a region from the doublebuffer to this surface */
129     public abstract void blit(DoubleBuffer source, int sx, int sy, int dx, int dy, int dx2, int dy2);
130
131     /** Destroy the surface */
132     public abstract void _dispose();
133
134     /** Notifies the surface that limits have been imposed on the surface's size */
135     public void setLimits(int min_width, int min_height, int max_width, int max_height) { }
136
137
138     // Helper methods for subclasses ////////////////////////////////////////////////////////////
139
140     protected final void Press(final int button) {
141         last_press_x = mousex;
142         last_press_y = mousey;
143
144         if (button == 1) button1 = true;
145         else if (button == 2) button2 = true;
146         else if (button == 3) button3 = true;
147
148         if (button == 1) new SimpleMessage("Press1", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
149         else if (button == 2) new SimpleMessage("Press2", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
150         else if (button == 3) {
151             final Box who = Box.whoIs(root, mousex, mousey);
152             MessageQueue.add(new Message() { public void perform() {
153                 Platform.clipboardReadEnabled = true;
154                 root.put("Press3", Boolean.TRUE);
155                 Platform.clipboardReadEnabled = false;
156             }});
157         }
158     }
159
160     protected final void Release(int button) {
161         if (button == 1) button1 = false;
162         else if (button == 2) button2 = false;
163         else if (button == 3) button3 = false;
164
165         if (button == 1) new SimpleMessage("Release1", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
166         else if (button == 2) new SimpleMessage("Release2", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
167         else if (button == 3) new SimpleMessage("Release3", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
168
169         if (Platform.needsAutoClick() && Math.abs(last_press_x - mousex) < 5 && Math.abs(last_press_y - mousey) < 5) Click(button);
170         last_press_x = Integer.MAX_VALUE;
171         last_press_y = Integer.MAX_VALUE;
172     }
173
174     protected final void Click(int button) {
175         if (button == 1) new SimpleMessage("Click1", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
176         else if (button == 2) new SimpleMessage("Click2", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
177         else if (button == 3) new SimpleMessage("Click3", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
178         if (Platform.needsAutoDoubleClick()) {
179             long now = System.currentTimeMillis();
180             if (lastClickButton == button && now - lastClickTime < 350) DoubleClick(button);
181             lastClickButton = button;
182             lastClickTime = now;
183         }
184     }
185
186     protected final void DoubleClick(int button) {
187         if (button == 1) new SimpleMessage("DoubleClick1", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
188         else if (button == 2) new SimpleMessage("DoubleClick2", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
189         else if (button == 3) new SimpleMessage("DoubleClick3", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
190     }
191
192     /** sends a KeyPressed message; subclasses should not add the C- or A- prefixes, nor should they capitalize alphabet characters */
193     protected final void KeyPressed(String key) {
194         if (key == null) return;
195
196         if (key.toLowerCase().endsWith("shift")) shift = true;
197         else if (shift) key = key.toUpperCase();
198
199         if (key.toLowerCase().equals("alt")) alt = true;
200         else if (alt) key = "A-" + key;
201
202         if (key.toLowerCase().endsWith("control")) control = true;
203         else if (control) key = "C-" + key;
204
205         final String fkey = key;
206         MessageQueue.add(new KMessage(key));
207     }
208
209     // This is implemented as a private static class instead of an anonymous class to work around a GCJ bug
210     private class KMessage implements Message {
211         String key = null;
212         public KMessage(String k) { key = k; }
213         public void perform() {
214             if (key.equals("C-v") || key.equals("A-v")) Platform.clipboardReadEnabled = true;
215             outer: for(int i=0; i<keywatchers.size(); i++) {
216                 Box b = (Box)keywatchers.elementAt(i);
217                 for(Box cur = b; cur != null; cur = cur.getParent())
218                     if (cur.invisible) continue outer;
219                 b.put("KeyPressed", key);
220             }
221             Platform.clipboardReadEnabled = false;
222         }
223     }
224
225     /** sends a KeyReleased message; subclasses should not add the C- or A- prefixes, nor should they capitalize alphabet characters */
226     protected final void KeyReleased(final String key) {
227         if (key == null) return;
228         if (key.toLowerCase().equals("alt")) alt = false;
229         else if (key.toLowerCase().equals("control")) control = false;
230         else if (key.toLowerCase().equals("shift")) shift = false;
231         MessageQueue.add(new Message() { public void perform() {
232             outer: for(int i=0; i<keywatchers.size(); i++) {
233                 Box b = (Box)keywatchers.elementAt(i);
234                 for(Box cur = b; cur != null; cur = cur.getParent())
235                     if (cur.invisible) continue outer;
236                 b.put("KeyReleased", key);
237             }
238         }});
239     }
240
241     /**
242      *  Notify XWT that the mouse has moved. If the mouse leaves the
243      *  surface, but the host windowing system does not provide its new
244      *  position (for example, a Java MouseListener.mouseExited()
245      *  message), the subclass should use (-1,-1).
246      */
247     protected final void Move(final int newmousex, final int newmousey) {
248         MessageQueue.add(lastMoveMessage = new Message() { public void perform() {
249             synchronized(Surface.this) {
250
251                 // if move messages are arriving faster than we can process them, we just start ignoring them
252                 if (lastMoveMessage != this) return;
253
254                 int oldmousex = mousex;
255                 int oldmousey = mousey;
256                 mousex = newmousex;
257                 mousey = newmousey;
258
259                 String oldcursor = cursor;
260                 cursor = "default";
261
262                 // Root gets motion events outside itself (if trapped, of course)
263                 if (!root.inside(oldmousex, oldmousey) && !root.inside(mousex, mousey) && (button1 || button2 || button3))
264                     root.put("Move", Boolean.TRUE);
265
266                 root.Move(oldmousex, oldmousey, mousex, mousey);
267                 if (!cursor.equals(oldcursor)) syncCursor();
268             }
269         }});
270     }
271
272     protected final void SizeChange(final int width, final int height) {
273         MessageQueue.add(new Message() { public void perform() {
274             if (width == root.width && height == root.height) return;
275             root.width = width;
276             root.height = height;
277             root.needs_reflow = true;
278         }});
279         abort = true;
280     }
281
282     protected final void PosChange(final int x, final int y) {
283         MessageQueue.add(new Message() { public void perform() {
284             root.put("x", new Integer(x));
285             root.put("y", new Integer(y));
286         }});
287     }
288
289     protected final void Close() { new SimpleMessage("Close", Boolean.TRUE, root); }
290     protected final void Minimized(boolean b) { minimized = b; new SimpleMessage("Minimized", b ? Boolean.TRUE : Boolean.FALSE, root); }
291     protected final void Maximized(boolean b) { maximized = b; new SimpleMessage("Maximized", b ? Boolean.TRUE : Boolean.FALSE, root); }
292     protected final void Focused(boolean b) { new SimpleMessage("Focused", b ? Boolean.TRUE : Boolean.FALSE, root); }
293     public static void Refresh() { MessageQueue.refresh(); }
294
295     // the following value is split into two int's to work around GCJ bug java/6393
296
297     /** This is how subclasses signal a 'shallow dirty', indicating that although the backbuffer is valid, the screen is not */
298     public final void Dirty(int x, int y, int w, int h) {
299         screenDirtyRegions.dirty(x, y, w, h);
300         Refresh();
301     }
302
303
304     // Private Instance Data /////////////////////////////////////////////////////////////////////////////////////////////
305
306     /** The automatic double buffer for the root box */
307     DoubleBuffer backbuffer = null;
308
309     /** Dirty regions on the backbuffer which need to be rebuilt using Box.render() */
310     private DirtyList backbufferDirtyRegions = new DirtyList();
311
312     /** Dirty regions on the screen which need to be rebuilt using Surface.blit() */
313     private DirtyList screenDirtyRegions = new DirtyList();
314
315     /** A list of all the Boxes on this Surface that should be notified of keyboard events */
316     Vec keywatchers = new Vec();
317
318     /** When set to true, render() should abort as soon as possible and restart the rendering process */
319     static volatile boolean abort = false;
320
321     /** a solid red 10x10 double buffer */
322     private DoubleBuffer showRenderBuf = null;
323
324     /** a striped 100x100 double buffer */
325     private DoubleBuffer showRenderBuf2 = null;
326
327     /** true iff this window should be scarred */
328     private boolean scarred = true;
329
330
331     // Other Methods ///////////////////////////////////////////////////////////////////////////////
332
333     /** If <tt>b == true</tt>, maximize the surface; otherwise, un-maximize it. */
334     public final void setMaximized(boolean b) {
335         if (b == maximized) return;
336         _setMaximized(b);
337         maximized = b;
338     }
339
340     /** If <tt>b == true</tt>, minimize the surface; otherwise, un-minimize it. */
341     public final void setMinimized(boolean b) {
342         if (b == minimized) return;
343         _setMinimized(b);
344         minimized = b;
345     }
346
347     /** wrapper for setSize() which makes sure to dirty the place where the scar used to be */
348     void setSize() {
349         if (scarred) {
350             root.width = Math.max(root.width, scarPicture.getWidth());
351             root.height = Math.max(root.height, scarPicture.getHeight());
352             dirty(hscar,
353                   root.height - vscar - scarPicture.getHeight(),
354                   scarPicture.getWidth(),
355                   scarPicture.getHeight());
356         }
357         setSize(root.width, root.height);
358     }
359
360     /** Indicates that the Surface is no longer needed */
361     public final void dispose(boolean quitIfAllSurfacesGone) {
362         if (root == null) return;
363         if (Log.on) Log.log(this, "disposing " + this);
364         allSurfaces.removeElement(this);
365         _dispose();
366
367         // quit when all windows are closed
368         if (allSurfaces.size() == 0 && quitIfAllSurfacesGone && Main.doneInitializing) {
369             if (Log.on) {
370                 if (refreshableSurfaceWasCreated) Log.log(this, "exiting because last remaining surface was disposed");
371                 else Log.log(this, "exiting because no surface was ever created");
372             }
373             Platform.exit();
374         }
375     }
376
377     /** Indicates that the backbuffer region x,y,w,h is no longer correct and must be regenerated */
378     public void dirty(int x, int y, int w, int h) {
379         backbufferDirtyRegions.dirty(x, y, w, h);
380         Refresh();
381     }
382
383     public Surface(Box root) {
384         this.scarred = scarAllSurfacesFromNowOn;
385         scarAllSurfacesFromNowOn = true;
386         this.root = root;
387         if (root.surface != null && root.surface.root == root) {
388             root.surface.dispose(false);
389         } else {
390             root.remove();
391         }
392         root.surface = this;
393
394         // make sure the root is properly sized
395         do {
396             abort = false;
397             root.reflow();
398         } while(abort);
399
400         // this is a bit dangerous since we're passing ourselves to another method before subclasses' ctors have run...        
401         backbuffer = Platform.createDoubleBuffer(Platform.getScreenWidth(), Platform.getScreenHeight(), this);
402
403         root.dirty();
404         Refresh();
405     }
406
407     /** runs the prerender() and render() pipelines in the root Box to regenerate the backbuffer, then blits it to the screen */
408     public synchronized void render() {
409
410         // make sure the root is properly sized
411         do {
412             abort = false;
413             root.reflow();
414             // update mouseinside and trigger Enter/Leave as a result of box size/position changes
415             String oldcursor = cursor;
416             cursor = "default";
417             root.Move(mousex, mousey, mousex, mousey);
418             if (!cursor.equals(oldcursor)) syncCursor();
419         } while(abort);
420
421         if (centerSurfaceOnRender) {
422             centerSurfaceOnRender = false;
423             int x = (Platform.getScreenWidth() - root.width) / 2;
424             int y = (Platform.getScreenHeight() - root.height) / 2;
425             setLocation(x, y);
426             root.x = x;
427             root.y = y;
428         }
429
430         sizePosChangesSinceLastRender = 0;
431         int[][] dirt = backbufferDirtyRegions.flush();
432         for(int i = 0; dirt != null && i < dirt.length; i++) {
433             if (dirt[i] == null) continue;
434             int x = dirt[i][0];
435             int y = dirt[i][1];
436             int w = dirt[i][2];
437             int h = dirt[i][3];
438             if (x < 0) x = 0;
439             if (y < 0) y = 0;
440             if (x+w > root.width) w = root.width - x;
441             if (y+h > root.height) h = root.height - y;
442             if (w <= 0 || h <= 0) continue;
443
444             root.render(0, 0, x, y, w, h, backbuffer);
445             
446             // if any area under the scar was repainted, rescar that area
447             if (scarred && x < hscar + scarPicture.getWidth() &&
448                 y + h > root.height - scarPicture.getHeight() - vscar) {
449                 int _x1 = Math.max(x, hscar);
450                 int _x2 = Math.min(x + w, hscar + scarPicture.getWidth());
451                 int _y1 = Math.max(y, root.height - scarPicture.getHeight() - vscar);
452                 int _y2 = Math.min(y + h, root.height - vscar);
453                 
454                 backbuffer.drawPicture(scarPicture, _x1, _y1, _x2, _y2,
455                                        _x1 - (hscar),
456                                        _y1 - (root.height - scarPicture.getHeight() - vscar),
457                                        _x2 - (hscar),
458                                        _y2 - (root.height - scarPicture.getHeight() - vscar)
459                                        );
460             }
461
462             if (abort) {
463
464                 // x,y,w,h is only partially reconstructed, so we must be careful not to re-blit it
465                 blitDirtyScreenRegions(x, y, w, h);
466                 screenDirtyRegions.dirty(x, y, w, h);
467
468                 // put back all the dirty regions we haven't yet processed (including the current one)
469                 for(int j=i; j<dirt.length; j++)
470                     if (dirt[j] != null)
471                         backbufferDirtyRegions.dirty(dirt[j][0], dirt[j][1], dirt[j][2], dirt[j][3]);
472
473                 // tail-recurse
474                 render();
475                 return;
476             }
477
478             // now that we've reconstructed this region in the backbuffer, queue it to be reblitted
479             screenDirtyRegions.dirty(x, y, w, h);
480         }
481
482         // blit out all the areas we've just reconstructed
483         blitDirtyScreenRegions();
484     }
485
486     /** blits from the backbuffer to the screen for all regions of the screen which have become dirty */
487     public synchronized void blitDirtyScreenRegions() { blitDirtyScreenRegions(-1, -1, 0, 0); }
488
489     /** same as blitDirtyScreenRegions(), except that it will skip any regions within a,b,c,d */
490     private synchronized void blitDirtyScreenRegions(int a, int b, int c, int d) {
491
492         int[][] dirt = screenDirtyRegions.flush();
493         if (Main.showRenders && dirt != null && dirt.length > 0 && a == -1)
494             blit(backbuffer, 0, 0, 0, 0, root.width, root.height);
495
496         for(int i = 0; dirt != null && i < dirt.length; i++) {
497             if (dirt[i] == null) continue;
498             int x = dirt[i][0];
499             int y = dirt[i][1];
500             int w = dirt[i][2];
501             int h = dirt[i][3];
502             if (x < 0) x = 0;
503             if (y < 0) y = 0;
504             if (x+w > root.width) w = root.width - x;
505             if (y+h > root.height) h = root.height - y;
506             if (w <= 0 || h <= 0) continue;
507
508             // if any part of this region falls within the "bad region", just skip it
509             boolean hhit = (x >= a && x <= a + c) || (x+w >= a && x+w <= a + c);
510             boolean vhit = (y >= b && y <= b + d) || (y+h >= b && y+h <= b + d);
511             if (hhit && vhit) {
512                 screenDirtyRegions.dirty(x, y, w, h);
513                 continue;
514             }
515
516             blit(backbuffer, x, y, x, y, w + x, h + y);
517             
518             if (Main.showRenders) {
519                 if (showRenderBuf == null) {
520                     showRenderBuf = Platform.createDoubleBuffer(10, 10, this);
521                     showRenderBuf.fillRect(0, 0, 10, 10, 0x00FF0000);
522                     showRenderBuf2 = Platform.createDoubleBuffer(100, 100, this);
523                     for(int y1 = 0; y1<100; y1++)
524                         for(int x1 = 0; x1<100; x1++)
525                             if ((x1 + y1) % 5 == 0)
526                                 showRenderBuf2.fillRect(x1, y1, x1 + 1, y1 + 1, 0x00FF0000);
527                 }
528                 for(int x1 = x; x1<x + w; x1 += 100)
529                     for(int y1 = y; y1< y + h; y1 += 100) {
530                         blit(showRenderBuf2, 0, 0, x1, y1, Math.min(x1 + 100, x + w), Math.min(y1 + 100, y + h));
531                     }
532                 for(int j=x; j<x + w; j += 10) {
533                     blit(showRenderBuf, 0, 0, j, y, Math.min(j+ 10, x + w), y + 1);
534                     blit(showRenderBuf, 0, 0, j, y + h, Math.min(j + 10, x + w), y + h + 1);
535                 }
536                 for(int j=y; j<y + h; j += 10) {
537                     blit(showRenderBuf, 0, 0, x, j, x + 1, Math.min(j + 10, y + h));
538                     blit(showRenderBuf, 0, 0, x + w, j, x + w + 1, Math.min(j + 10, y + h));
539                 }
540             }
541
542         }
543     }
544
545     // FEATURE: reinstate recycler
546     public class SimpleMessage implements Message {
547         
548         private Box boxContainingMouse;
549         private Object value;
550         public String name;
551         
552         SimpleMessage(String name, Object value, Box boxContainingMouse) {
553             this.boxContainingMouse = boxContainingMouse;
554             this.name = name;
555             this.value = value;
556             MessageQueue.add(this);
557         }
558         
559         public void perform() { boxContainingMouse.put(name, value); }
560         public String toString() { return "SimpleMessage [name=" + name + ", value=" + value + "]"; }
561         
562     }
563
564     // Scar-Related Stuff ////////////////////////////////////////////////////////////////////
565
566     /** The scar's horizontal offset */
567     int hscar = 0;
568
569     /** The scar's vertical offset */
570     int vscar = 0;
571
572     /** the scar image drawn on the bottom right hand corner */
573     static Picture scarPicture = null;
574
575 }