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