OSDN Git Service

2005-04-19 Roman Kennke <roman@kennke.org>
[pf3gnuchains/gcc-fork.git] / libjava / javax / swing / RepaintManager.java
1 /* RepaintManager.java --
2    Copyright (C) 2002, 2004  Free Software Foundation, Inc.
3
4 This file is part of GNU Classpath.
5
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING.  If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA.
20
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library.  Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
25
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module.  An independent module is a module which is not derived from
33 or based on this library.  If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so.  If you do not wish to do so, delete this
36 exception statement from your version. */
37
38
39 package javax.swing;
40
41 import java.awt.Component;
42 import java.awt.Dimension;
43 import java.awt.Image;
44 import java.awt.Rectangle;
45 import java.util.Enumeration;
46 import java.util.HashMap;
47 import java.util.Hashtable;
48 import java.util.Iterator;
49 import java.util.Map;
50 import java.util.Vector;
51
52 /**
53  * <p>The repaint manager holds a set of dirty regions, invalid components,
54  * and a double buffer surface.  The dirty regions and invalid components
55  * are used to coalesce multiple revalidate() and repaint() calls in the
56  * component tree into larger groups to be refreshed "all at once"; the
57  * double buffer surface is used by root components to paint
58  * themselves.</p>
59  *
60  * <p>In general, painting is very confusing in swing. see <a
61  * href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">this
62  * document</a> for more details.</p>
63  *
64  * @author Graydon Hoare (graydon@redhat.com)
65  */
66 public class RepaintManager
67 {
68
69   /**
70    * <p>A helper class which is placed into the system event queue at
71    * various times in order to facilitate repainting and layout. There is
72    * typically only one of these objects active at any time. When the
73    * {@link RepaintManager} is told to queue a repaint, it checks to see if
74    * a {@link RepaintWorker} is "live" in the system event queue, and if
75    * not it inserts one using {@link SwingUtilities.invokeLater}.</p>
76    *
77    * <p>When the {@link RepaintWorker} comes to the head of the system
78    * event queue, its {@link RepaintWorker#run} method is executed by the
79    * swing paint thread, which revalidates all invalid components and
80    * repaints any damage in the swing scene.</p>
81    */
82
83   protected class RepaintWorker
84     implements Runnable
85   {
86     boolean live;
87     public RepaintWorker()
88     {
89       live = false;
90     }
91     public synchronized void setLive(boolean b) 
92     {
93       live = b;
94     }
95     public synchronized boolean isLive()
96     {
97       return live;
98     }
99     public void run()
100     {
101       RepaintManager rm = RepaintManager.globalManager;
102       setLive(false);
103       rm.validateInvalidComponents();
104       rm.paintDirtyRegions();
105     }
106   }
107
108   
109   /** 
110    * A table storing the dirty regions of components.  The keys of this
111    * table are components, the values are rectangles. Each component maps
112    * to exactly one rectangle.  When more regions are marked as dirty on a
113    * component, they are union'ed with the existing rectangle.
114    *
115    * @see #addDirtyRegion
116    * @see #getDirtyRegion
117    * @see #isCompletelyDirty
118    * @see #markCompletelyClean
119    * @see #markCompletelyDirty
120    */
121   Hashtable dirtyComponents;
122
123   /**
124    * A single, shared instance of the helper class. Any methods which mark
125    * components as invalid or dirty eventually activate this instance. It
126    * is added to the event queue if it is not already active, otherwise
127    * reused.
128    *
129    * @see #addDirtyRegion
130    * @see #addInvalidComponent
131    */
132   RepaintWorker repaintWorker;
133
134   /** 
135    * The set of components which need revalidation, in the "layout" sense.
136    * There is no additional information about "what kind of layout" they
137    * need (as there is with dirty regions), so it is just a vector rather
138    * than a table.
139    *
140    * @see #addInvalidComponent
141    * @see #removeInvalidComponent
142    * @see #validateInvalidComponents
143    */
144   Vector invalidComponents;
145
146   /** 
147    * Whether or not double buffering is enabled on this repaint
148    * manager. This is merely a hint to clients; the RepaintManager will
149    * always return an offscreen buffer when one is requested.
150    * 
151    * @see #getDoubleBufferingEnabled
152    * @see #setDoubleBufferingEnabled
153    */
154   boolean doubleBufferingEnabled;
155
156   /** 
157    * The current offscreen buffer. This is reused for all requests for
158    * offscreen drawing buffers. It grows as necessary, up to {@link
159    * #doubleBufferMaximumSize}, but there is only one shared instance.
160    *
161    * @see #getOffscreenBuffer
162    * @see #doubleBufferMaximumSize
163    */
164   Image doubleBuffer;
165
166   /**
167    * The maximum width and height to allocate as a double buffer. Requests
168    * beyond this size are ignored.
169    *
170    * @see #paintDirtyRegions
171    * @see #getDoubleBufferMaximumSize
172    * @see #setDoubleBufferMaximumSize
173    */
174   Dimension doubleBufferMaximumSize;
175
176
177   /**
178    * The global, shared RepaintManager instance. This is reused for all
179    * components in all windows.
180    *
181    * @see #currentManager
182    * @see #setCurrentManager
183    */
184   private static RepaintManager globalManager;
185
186   /**
187    * Create a new RepaintManager object.
188    */
189   public RepaintManager()
190   {
191     dirtyComponents = new Hashtable();
192     invalidComponents = new Vector();
193     repaintWorker = new RepaintWorker();
194     doubleBufferMaximumSize = new Dimension(2000,2000);
195     doubleBufferingEnabled = true;
196   }
197
198   /**
199    * Get the value of the shared {@link #globalManager} instance, possibly
200    * returning a special manager associated with the specified
201    * component. The default implementaiton ignores the component parameter.
202    *
203    * @param component A component to look up the manager of
204    *
205    * @return The current repaint manager
206    *
207    * @see #setCurrentManager
208    */
209   public static RepaintManager currentManager(Component component)
210   {
211     if (globalManager == null)
212       globalManager = new RepaintManager();
213     return globalManager;
214   }
215
216   /**
217    * Get the value of the shared {@link #globalManager} instance, possibly
218    * returning a special manager associated with the specified
219    * component. The default implementaiton ignores the component parameter.
220    *
221    * @param component A component to look up the manager of
222    *
223    * @return The current repaint manager
224    *
225    * @see #setCurrentManager
226    */
227   public static RepaintManager currentManager(JComponent component)
228   {
229     return currentManager((Component)component);
230   }
231
232   /**
233    * Set the value of the shared {@link #globalManager} instance.
234    *
235    * @param manager The new value of the shared instance
236    *
237    * @see #currentManager
238    */
239   public static void setCurrentManager(RepaintManager manager)
240   {
241     globalManager = manager;
242   }
243
244   /**
245    * Add a component to the {@link #invalidComponents} vector. If the
246    * {@link #repaintWorker} class is not active, insert it in the system
247    * event queue.
248    *
249    * @param component The component to add
250    *
251    * @see #removeInvalidComponent
252    */
253   public synchronized void addInvalidComponent(JComponent component)
254   {
255     Component ancestor = component.getParent();
256
257     while (ancestor != null
258            && (! (ancestor instanceof JComponent)
259                || ! ((JComponent) ancestor).isValidateRoot() ))
260       ancestor = ancestor.getParent();
261
262     if (ancestor != null
263         && ancestor instanceof JComponent
264         && ((JComponent) ancestor).isValidateRoot())
265       component = (JComponent) ancestor;
266
267     if (invalidComponents.contains(component))
268       return;
269
270     invalidComponents.add(component);
271     
272     if (! repaintWorker.isLive())
273       {
274         repaintWorker.setLive(true);
275         SwingUtilities.invokeLater(repaintWorker);
276       }
277   }
278
279   /**
280    * Remove a component from the {@link #invalidComponents} vector.
281    *
282    * @param component The component to remove
283    *
284    * @see #addInvalidComponent
285    */
286   public synchronized void removeInvalidComponent(JComponent component)
287   {
288     invalidComponents.removeElement(component);
289   }
290
291   /**
292    * Add a region to the set of dirty regions for a specified component.
293    * This involves union'ing the new region with any existing dirty region
294    * associated with the component. If the {@link #repaintWorker} class
295    * is not active, insert it in the system event queue.
296    *
297    * @param component The component to add a dirty region for
298    * @param x The left x coordinate of the new dirty region
299    * @param y The top y coordinate of the new dirty region
300    * @param w The width of the new dirty region
301    * @param h The height of the new dirty region
302    *
303    * @see #addDirtyRegion
304    * @see #getDirtyRegion
305    * @see #isCompletelyDirty
306    * @see #markCompletelyClean
307    * @see #markCompletelyDirty
308    */
309   public synchronized void addDirtyRegion(JComponent component, int x, int y,
310                                           int w, int h)
311   {
312     if (w == 0 || h == 0)
313       return;
314
315     Rectangle r = new Rectangle(x, y, w, h);
316     if (dirtyComponents.containsKey(component))
317       r = r.union((Rectangle)dirtyComponents.get(component));
318     dirtyComponents.put(component, r);
319     if (! repaintWorker.isLive())
320       {
321         repaintWorker.setLive(true);
322         SwingUtilities.invokeLater(repaintWorker);
323       }
324   }
325   
326   /**
327    * Get the dirty region associated with a component, or <code>null</code>
328    * if the component has no dirty region.
329    *
330    * @param component The component to get the dirty region of
331    *
332    * @return The dirty region of the component
333    *
334    * @see #dirtyComponents
335    * @see #addDirtyRegion
336    * @see #isCompletelyDirty
337    * @see #markCompletelyClean
338    * @see #markCompletelyDirty
339    */
340   public Rectangle getDirtyRegion(JComponent component)
341   {
342     return (Rectangle) dirtyComponents.get(component);
343   }
344   
345   /**
346    * Mark a component as dirty over its entire bounds.
347    *
348    * @param component The component to mark as dirty
349    *
350    * @see #dirtyComponents
351    * @see #addDirtyRegion
352    * @see #getDirtyRegion
353    * @see #isCompletelyDirty
354    * @see #markCompletelyClean
355    */
356   public void markCompletelyDirty(JComponent component)
357   {
358     Rectangle r = component.getBounds();
359     addDirtyRegion(component, r.x, r.y, r.width, r.height);
360   }
361
362   /**
363    * Remove all dirty regions for a specified component
364    *
365    * @param component The component to mark as clean
366    *
367    * @see #dirtyComponents
368    * @see #addDirtyRegion
369    * @see #getDirtyRegion
370    * @see #isCompletelyDirty
371    * @see #markCompletelyDirty
372    */
373   public void markCompletelyClean(JComponent component)
374   {
375     dirtyComponents.remove(component);
376   }
377
378   /**
379    * Return <code>true</code> if the specified component is completely
380    * contained within its dirty region, otherwise <code>false</code>
381    *
382    * @param component The component to check for complete dirtyness
383    *
384    * @return Whether the component is completely dirty
385    *
386    * @see #dirtyComponents
387    * @see #addDirtyRegion
388    * @see #getDirtyRegion
389    * @see #isCompletelyDirty
390    * @see #markCompletelyClean
391    */
392   public boolean isCompletelyDirty(JComponent component)
393   {
394     Rectangle dirty = (Rectangle) dirtyComponents.get(component);
395     if (dirty == null)
396       return false;
397     Rectangle r = component.getBounds();
398     if (r == null)
399       return true;
400     return dirty.contains(r);
401   }
402
403   /**
404    * Validate all components which have been marked invalid in the {@link
405    * #invalidComponents} vector.
406    */
407   public void validateInvalidComponents()
408   {
409     for (Enumeration e = invalidComponents.elements(); e.hasMoreElements(); )
410       {
411         JComponent comp = (JComponent) e.nextElement();
412         if (! (comp.isVisible() && comp.isShowing()))
413           continue;
414         comp.validate();
415       }
416     invalidComponents.clear();
417   }
418
419   /**
420    * Repaint all regions of all components which have been marked dirty in
421    * the {@link #dirtyComponents} table.
422    */
423   public void paintDirtyRegions()
424   {
425     // step 1: pull out roots and calculate spanning damage
426
427     HashMap roots = new HashMap();
428     for (Enumeration e = dirtyComponents.keys(); e.hasMoreElements(); )
429       {
430         JComponent comp = (JComponent) e.nextElement();
431         if (! (comp.isVisible() && comp.isShowing()))
432           continue;
433         Rectangle damaged = getDirtyRegion(comp);
434         if (damaged.width == 0 || damaged.height == 0)
435           continue;
436         JRootPane root = comp.getRootPane();
437         // If the component has no root, no repainting will occur.
438         if (root == null)
439           continue;
440         Rectangle rootDamage = SwingUtilities.convertRectangle(comp, damaged, root);
441         if (! roots.containsKey(root))
442           {
443             roots.put(root, rootDamage);
444           }
445         else
446           {
447             roots.put(root, ((Rectangle)roots.get(root)).union(rootDamage));
448           }
449       }
450     dirtyComponents.clear();
451
452     // step 2: paint those roots
453     Iterator i = roots.entrySet().iterator();
454     while(i.hasNext())
455       {
456         Map.Entry ent = (Map.Entry) i.next();
457         JRootPane root = (JRootPane) ent.getKey();
458         Rectangle rect = (Rectangle) ent.getValue();
459         root.paintImmediately(rect);                    
460       }
461   }
462
463   /**
464    * Get an offscreen buffer for painting a component's image. This image
465    * may be smaller than the proposed dimensions, depending on the value of
466    * the {@link #doubleBufferMaximumSize} property.
467    *
468    * @param component The component to return an offscreen buffer for
469    * @param proposedWidth The proposed width of the offscreen buffer
470    * @param proposedHeight The proposed height of the offscreen buffer
471    *
472    * @return A shared offscreen buffer for painting
473    *
474    * @see #doubleBuffer
475    */
476   public Image getOffscreenBuffer(Component component, int proposedWidth,
477                                   int proposedHeight)
478   {
479     if (doubleBuffer == null 
480         || (((doubleBuffer.getWidth(null) < proposedWidth) 
481              || (doubleBuffer.getHeight(null) < proposedHeight))
482             && (proposedWidth < doubleBufferMaximumSize.width)
483             && (proposedHeight < doubleBufferMaximumSize.height)))
484       {
485         doubleBuffer = component.createImage(proposedWidth, proposedHeight);
486       }
487     return doubleBuffer;
488   }
489
490   /**
491    * Get the value of the {@link #doubleBufferMaximumSize} property.
492    *
493    * @return The current value of the property
494    *
495    * @see #setDoubleBufferMaximumSize
496    */
497   public Dimension getDoubleBufferMaximumSize()
498   {
499     return doubleBufferMaximumSize;
500   }
501
502   /**
503    * Set the value of the {@link #doubleBufferMaximumSize} property.
504    *
505    * @param size The new value of the property
506    *
507    * @see #getDoubleBufferMaximumSize
508    */
509   public void setDoubleBufferMaximumSize(Dimension size)
510   {
511     doubleBufferMaximumSize = size;
512   }
513
514   /**
515    * Set the value of the {@link #doubleBufferingEnabled} property.
516    *
517    * @param buffer The new value of the property
518    *
519    * @see #getDoubleBufferingEnabled
520    */
521   public void setDoubleBufferingEnabled(boolean buffer)
522   {
523     doubleBufferingEnabled = buffer;
524   }
525
526   /**
527    * Get the value of the {@link #doubleBufferingEnabled} property.
528    *
529    * @return The current value of the property
530    *
531    * @see #setDoubleBufferingEnabled
532    */
533   public boolean isDoubleBufferingEnabled()
534   {
535     return doubleBufferingEnabled;
536   }
537   
538   public String toString()
539   {
540     return "RepaintManager";
541   }
542 }