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