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