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