KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > swing > text > ZoneView


1 /*
2  * @(#)ZoneView.java 1.17 03/12/19
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7 package javax.swing.text;
8
9 import java.util.Vector JavaDoc;
10 import java.awt.*;
11 import javax.swing.event.*;
12
13 /**
14  * ZoneView is a View implementation that creates zones for which
15  * the child views are not created or stored until they are needed
16  * for display or model/view translations. This enables a substantial
17  * reduction in memory consumption for situations where the model
18  * being represented is very large, by building view objects only for
19  * the region being actively viewed/edited. The size of the children
20  * can be estimated in some way, or calculated asynchronously with
21  * only the result being saved.
22  * <p>
23  * ZoneView extends BoxView to provide a box that implements
24  * zones for it's children. The zones are special View implementations
25  * (the children of an instance of this class) that represent only a
26  * portion of the model that an instance of ZoneView is responsible
27  * for. The zones don't create child views until an attempt is made
28  * to display them. A box shaped view is well suited to this because:
29  * <ul>
30  * <li>
31  * Boxes are a heavily used view, and having a box that
32  * provides this behavior gives substantial opportunity
33  * to plug the behavior into a view hierarchy from the
34  * view factory.
35  * <li>
36  * Boxes are tiled in one direction, so it is easy to
37  * divide them into zones in a reliable way.
38  * <li>
39  * Boxes typically have a simple relationship to the model (i.e. they
40  * create child views that directly represent the child elements).
41  * <li>
42  * Boxes are easier to estimate the size of than some other shapes.
43  * </ul>
44  * <p>
45  * The default behavior is controled by two properties, maxZoneSize
46  * and maxZonesLoaded. Setting maxZoneSize to Integer.MAX_VALUE would
47  * have the effect of causing only one zone to be created. This would
48  * effectively turn the view into an implementation of the decorator
49  * pattern. Setting maxZonesLoaded to a value of Integer.MAX_VALUE would
50  * cause zones to never be unloaded. For simplicity, zones are created on
51  * boundaries represented by the child elements of the element the view is
52  * responsible for. The zones can be any View implementation, but the
53  * default implementation is based upon AsyncBoxView which supports fairly
54  * large zones efficiently.
55  *
56  * @author Timothy Prinzing
57  * @version 1.17 12/19/03
58  * @see View
59  * @since 1.3
60  */

61 public class ZoneView extends BoxView JavaDoc {
62
63     int maxZoneSize = 8 * 1024;
64     int maxZonesLoaded = 3;
65     Vector JavaDoc loadedZones;
66
67     /**
68      * Constructs a ZoneView.
69      *
70      * @param elem the element this view is responsible for
71      * @param axis either View.X_AXIS or View.Y_AXIS
72      */

73     public ZoneView(Element JavaDoc elem, int axis) {
74     super(elem, axis);
75     loadedZones = new Vector JavaDoc();
76     }
77
78     /**
79      * Get the current maximum zone size.
80      */

81     public int getMaximumZoneSize() {
82     return maxZoneSize;
83     }
84
85     /**
86      * Set the desired maximum zone size. A
87      * zone may get larger than this size if
88      * a single child view is larger than this
89      * size since zones are formed on child view
90      * boundaries.
91      *
92      * @param size the number of characters the zone
93      * may represent before attempting to break
94      * the zone into a smaller size.
95      */

96     public void setMaximumZoneSize(int size) {
97     maxZoneSize = size;
98     }
99
100     /**
101      * Get the current setting of the number of zones
102      * allowed to be loaded at the same time.
103      */

104     public int getMaxZonesLoaded() {
105     return maxZonesLoaded;
106     }
107
108     /**
109      * Sets the current setting of the number of zones
110      * allowed to be loaded at the same time. This will throw an
111      * <code>IllegalArgumentException</code> if <code>mzl</code> is less
112      * than 1.
113      *
114      * @param mzl the desired maximum number of zones
115      * to be actively loaded, must be greater than 0
116      * @exception IllegalArgumentException if <code>mzl</code> is < 1
117      */

118     public void setMaxZonesLoaded(int mzl) {
119         if (mzl < 1) {
120             throw new IllegalArgumentException JavaDoc("ZoneView.setMaxZonesLoaded must be greater than 0.");
121         }
122     maxZonesLoaded = mzl;
123     unloadOldZones();
124     }
125
126     /**
127      * Called by a zone when it gets loaded. This happens when
128      * an attempt is made to display or perform a model/view
129      * translation on a zone that was in an unloaded state.
130      * This is imlemented to check if the maximum number of
131      * zones was reached and to unload the oldest zone if so.
132      *
133      * @param zone the child view that was just loaded.
134      */

135     protected void zoneWasLoaded(View JavaDoc zone) {
136     //System.out.println("loading: " + zone.getStartOffset() + "," + zone.getEndOffset());
137
loadedZones.addElement(zone);
138     unloadOldZones();
139     }
140
141     void unloadOldZones() {
142     while (loadedZones.size() > getMaxZonesLoaded()) {
143         View JavaDoc zone = (View JavaDoc) loadedZones.elementAt(0);
144         loadedZones.removeElementAt(0);
145         unloadZone(zone);
146     }
147     }
148
149     /**
150      * Unload a zone (Convert the zone to its memory saving state).
151      * The zones are expected to represent a subset of the
152      * child elements of the element this view is responsible for.
153      * Therefore, the default implementation is to simple remove
154      * all the children.
155      *
156      * @param zone the child view desired to be set to an
157      * unloaded state.
158      */

159     protected void unloadZone(View JavaDoc zone) {
160     //System.out.println("unloading: " + zone.getStartOffset() + "," + zone.getEndOffset());
161
zone.removeAll();
162     }
163
164     /**
165      * Determine if a zone is in the loaded state.
166      * The zones are expected to represent a subset of the
167      * child elements of the element this view is responsible for.
168      * Therefore, the default implementation is to return
169      * true if the view has children.
170      */

171     protected boolean isZoneLoaded(View JavaDoc zone) {
172     return (zone.getViewCount() > 0);
173     }
174
175     /**
176      * Create a view to represent a zone for the given
177      * range within the model (which should be within
178      * the range of this objects responsibility). This
179      * is called by the zone management logic to create
180      * new zones. Subclasses can provide a different
181      * implementation for a zone by changing this method.
182      *
183      * @param p0 the start of the desired zone. This should
184      * be >= getStartOffset() and < getEndOffset(). This
185      * value should also be < p1.
186      * @param p1 the end of the desired zone. This should
187      * be > getStartOffset() and <= getEndOffset(). This
188      * value should also be > p0.
189      */

190     protected View JavaDoc createZone(int p0, int p1) {
191     Document JavaDoc doc = getDocument();
192     View JavaDoc zone = null;
193     try {
194         zone = new Zone(getElement(),
195                 doc.createPosition(p0),
196                 doc.createPosition(p1));
197     } catch (BadLocationException JavaDoc ble) {
198         // this should puke in some way.
199
throw new StateInvariantError JavaDoc(ble.getMessage());
200     }
201     return zone;
202     }
203
204     /**
205      * Loads all of the children to initialize the view.
206      * This is called by the <code>setParent</code> method.
207      * This is reimplemented to not load any children directly
208      * (as they are created by the zones). This method creates
209      * the initial set of zones. Zones don't actually get
210      * populated however until an attempt is made to display
211      * them or to do model/view coordinate translation.
212      *
213      * @param f the view factory
214      */

215     protected void loadChildren(ViewFactory JavaDoc f) {
216     // build the first zone.
217
Document JavaDoc doc = getDocument();
218     int offs0 = getStartOffset();
219     int offs1 = getEndOffset();
220     append(createZone(offs0, offs1));
221     handleInsert(offs0, offs1 - offs0);
222     }
223
224     /**
225      * Returns the child view index representing the given position in
226      * the model.
227      *
228      * @param pos the position >= 0
229      * @return index of the view representing the given position, or
230      * -1 if no view represents that position
231      */

232     protected int getViewIndexAtPosition(int pos) {
233     // PENDING(prinz) this could be done as a binary
234
// search, and probably should be.
235
int n = getViewCount();
236     if (pos == getEndOffset()) {
237         return n - 1;
238     }
239     for(int i = 0; i < n; i++) {
240         View JavaDoc v = getView(i);
241         if(pos >= v.getStartOffset() &&
242            pos < v.getEndOffset()) {
243         return i;
244         }
245     }
246     return -1;
247     }
248
249     void handleInsert(int pos, int length) {
250     int index = getViewIndex(pos, Position.Bias.Forward);
251     View JavaDoc v = getView(index);
252     int offs0 = v.getStartOffset();
253     int offs1 = v.getEndOffset();
254     if ((offs1 - offs0) > maxZoneSize) {
255         splitZone(index, offs0, offs1);
256     }
257     }
258
259     void handleRemove(int pos, int length) {
260     // IMPLEMENT
261
}
262
263     /**
264      * Break up the zone at the given index into pieces
265      * of an acceptable size.
266      */

267     void splitZone(int index, int offs0, int offs1) {
268     // divide the old zone into a new set of bins
269
Element JavaDoc elem = getElement();
270     Document JavaDoc doc = elem.getDocument();
271     Vector JavaDoc zones = new Vector JavaDoc();
272     int offs = offs0;
273     do {
274         offs0 = offs;
275         offs = Math.min(getDesiredZoneEnd(offs0), offs1);
276         zones.addElement(createZone(offs0, offs));
277     } while (offs < offs1);
278     View JavaDoc oldZone = getView(index);
279     View JavaDoc[] newZones = new View JavaDoc[zones.size()];
280     zones.copyInto(newZones);
281     replace(index, 1, newZones);
282     }
283
284     /**
285      * Returns the zone position to use for the
286      * end of a zone that starts at the given
287      * position. By default this returns something
288      * close to half the max zone size.
289      */

290     int getDesiredZoneEnd(int pos) {
291     Element JavaDoc elem = getElement();
292     int index = elem.getElementIndex(pos + (maxZoneSize / 2));
293     Element JavaDoc child = elem.getElement(index);
294     int offs0 = child.getStartOffset();
295     int offs1 = child.getEndOffset();
296     if ((offs1 - pos) > maxZoneSize) {
297         if (offs0 > pos) {
298         return offs0;
299         }
300     }
301     return offs1;
302     }
303
304     // ---- View methods ----------------------------------------------------
305

306     /**
307      * The superclass behavior will try to update the child views
308      * which is not desired in this case, since the children are
309      * zones and not directly effected by the changes to the
310      * associated element. This is reimplemented to do nothing
311      * and return false.
312      */

313     protected boolean updateChildren(DocumentEvent.ElementChange ec,
314                      DocumentEvent e, ViewFactory JavaDoc f) {
315     return false;
316     }
317
318     /**
319      * Gives notification that something was inserted into the document
320      * in a location that this view is responsible for. This is largely
321      * delegated to the superclass, but is reimplemented to update the
322      * relevant zone (i.e. determine if a zone needs to be split into a
323      * set of 2 or more zones).
324      *
325      * @param changes the change information from the associated document
326      * @param a the current allocation of the view
327      * @param f the factory to use to rebuild if the view has children
328      * @see View#insertUpdate
329      */

330     public void insertUpdate(DocumentEvent changes, Shape a, ViewFactory JavaDoc f) {
331     handleInsert(changes.getOffset(), changes.getLength());
332     super.insertUpdate(changes, a, f);
333     }
334
335     /**
336      * Gives notification that something was removed from the document
337      * in a location that this view is responsible for. This is largely
338      * delegated to the superclass, but is reimplemented to update the
339      * relevant zones (i.e. determine if zones need to be removed or
340      * joined with another zone).
341      *
342      * @param changes the change information from the associated document
343      * @param a the current allocation of the view
344      * @param f the factory to use to rebuild if the view has children
345      * @see View#removeUpdate
346      */

347     public void removeUpdate(DocumentEvent changes, Shape a, ViewFactory JavaDoc f) {
348     handleRemove(changes.getOffset(), changes.getLength());
349     super.removeUpdate(changes, a, f);
350     }
351
352     /**
353      * Internally created view that has the purpose of holding
354      * the views that represent the children of the ZoneView
355      * that have been arranged in a zone.
356      */

357     class Zone extends AsyncBoxView JavaDoc {
358
359     private Position JavaDoc start;
360     private Position JavaDoc end;
361
362         public Zone(Element JavaDoc elem, Position JavaDoc start, Position JavaDoc end) {
363             super(elem, ZoneView.this.getAxis());
364         this.start = start;
365         this.end = end;
366         }
367
368     /**
369      * Creates the child views and populates the
370      * zone with them. This is done by translating
371      * the positions to child element index locations
372      * and building views to those elements. If the
373      * zone is already loaded, this does nothing.
374      */

375     public void load() {
376         if (! isLoaded()) {
377         setEstimatedMajorSpan(true);
378         Element JavaDoc e = getElement();
379         ViewFactory JavaDoc f = getViewFactory();
380         int index0 = e.getElementIndex(getStartOffset());
381         int index1 = e.getElementIndex(getEndOffset());
382         View JavaDoc[] added = new View JavaDoc[index1 - index0 + 1];
383         for (int i = index0; i <= index1; i++) {
384             added[i - index0] = f.create(e.getElement(i));
385         }
386         replace(0, 0, added);
387
388         zoneWasLoaded(this);
389         }
390     }
391
392     /**
393      * Removes the child views and returns to a
394      * state of unloaded.
395      */

396     public void unload() {
397         setEstimatedMajorSpan(true);
398         removeAll();
399     }
400
401     /**
402      * Determines if the zone is in the loaded state
403      * or not.
404      */

405     public boolean isLoaded() {
406         return (getViewCount() != 0);
407     }
408
409         /**
410          * This method is reimplemented to not build the children
411      * since the children are created when the zone is loaded
412      * rather then when it is placed in the view hierarchy.
413      * The major span is estimated at this point by building
414      * the first child (but not storing it), and calling
415      * setEstimatedMajorSpan(true) followed by setSpan for
416      * the major axis with the estimated span.
417          */

418         protected void loadChildren(ViewFactory JavaDoc f) {
419         // mark the major span as estimated
420
setEstimatedMajorSpan(true);
421
422         // estimate the span
423
Element JavaDoc elem = getElement();
424         int index0 = elem.getElementIndex(getStartOffset());
425         int index1 = elem.getElementIndex(getEndOffset());
426         int nChildren = index1 - index0;
427
428         // replace this with something real
429
//setSpan(getMajorAxis(), nChildren * 10);
430

431         View JavaDoc first = f.create(elem.getElement(index0));
432         first.setParent(this);
433         float w = first.getPreferredSpan(X_AXIS);
434         float h = first.getPreferredSpan(Y_AXIS);
435         if (getMajorAxis() == X_AXIS) {
436         w *= nChildren;
437         } else {
438         h += nChildren;
439         }
440
441         setSize(w, h);
442         }
443
444     /**
445      * Publish the changes in preferences upward to the parent
446      * view.
447      * <p>
448      * This is reimplemented to stop the superclass behavior
449      * if the zone has not yet been loaded. If the zone is
450      * unloaded for example, the last seen major span is the
451      * best estimate and a calculated span for no children
452      * is undesirable.
453      */

454         protected void flushRequirementChanges() {
455         if (isLoaded()) {
456         super.flushRequirementChanges();
457         }
458     }
459
460     /**
461      * Returns the child view index representing the given position in
462      * the model. Since the zone contains a cluster of the overall
463      * set of child elements, we can determine the index fairly
464      * quickly from the model by subtracting the index of the
465      * start offset from the index of the position given.
466      *
467      * @param pos the position >= 0
468      * @return index of the view representing the given position, or
469      * -1 if no view represents that position
470      * @since 1.3
471      */

472         public int getViewIndex(int pos, Position.Bias JavaDoc b) {
473         boolean isBackward = (b == Position.Bias.Backward);
474         pos = (isBackward) ? Math.max(0, pos - 1) : pos;
475         Element JavaDoc elem = getElement();
476         int index1 = elem.getElementIndex(pos);
477         int index0 = elem.getElementIndex(getStartOffset());
478         return index1 - index0;
479     }
480
481     protected boolean updateChildren(DocumentEvent.ElementChange ec,
482                      DocumentEvent e, ViewFactory JavaDoc f) {
483         // the structure of this element changed.
484
Element JavaDoc[] removedElems = ec.getChildrenRemoved();
485         Element JavaDoc[] addedElems = ec.getChildrenAdded();
486         Element JavaDoc elem = getElement();
487         int index0 = elem.getElementIndex(getStartOffset());
488         int index1 = elem.getElementIndex(getEndOffset()-1);
489         int index = ec.getIndex();
490         if ((index >= index0) && (index <= index1)) {
491         // The change is in this zone
492
int replaceIndex = index - index0;
493         int nadd = Math.min(index1 - index0 + 1, addedElems.length);
494         int nremove = Math.min(index1 - index0 + 1, removedElems.length);
495         View JavaDoc[] added = new View JavaDoc[nadd];
496         for (int i = 0; i < nadd; i++) {
497             added[i] = f.create(addedElems[i]);
498         }
499         replace(replaceIndex, nremove, added);
500         }
501         return true;
502     }
503
504     // --- View methods ----------------------------------
505

506     /**
507      * Fetches the attributes to use when rendering. This view
508      * isn't directly responsible for an element so it returns
509      * the outer classes attributes.
510      */

511         public AttributeSet JavaDoc getAttributes() {
512         return ZoneView.this.getAttributes();
513     }
514
515     /**
516      * Renders using the given rendering surface and area on that
517      * surface. This is implemented to load the zone if its not
518      * already loaded, and then perform the superclass behavior.
519      *
520      * @param g the rendering surface to use
521      * @param a the allocated region to render into
522      * @see View#paint
523      */

524         public void paint(Graphics g, Shape a) {
525         load();
526         super.paint(g, a);
527     }
528
529     /**
530      * Provides a mapping from the view coordinate space to the logical
531      * coordinate space of the model. This is implemented to first
532      * make sure the zone is loaded before providing the superclass
533      * behavior.
534      *
535      * @param x x coordinate of the view location to convert >= 0
536      * @param y y coordinate of the view location to convert >= 0
537      * @param a the allocated region to render into
538      * @return the location within the model that best represents the
539      * given point in the view >= 0
540      * @see View#viewToModel
541      */

542         public int viewToModel(float x, float y, Shape a, Position.Bias JavaDoc[] bias) {
543         load();
544         return super.viewToModel(x, y, a, bias);
545     }
546
547         /**
548          * Provides a mapping from the document model coordinate space
549          * to the coordinate space of the view mapped to it. This is
550          * implemented to provide the superclass behavior after first
551      * making sure the zone is loaded (The zone must be loaded to
552      * make this calculation).
553          *
554          * @param pos the position to convert
555          * @param a the allocated region to render into
556          * @return the bounding box of the given position
557          * @exception BadLocationException if the given position does not represent a
558          * valid location in the associated document
559          * @see View#modelToView
560          */

561         public Shape modelToView(int pos, Shape a, Position.Bias JavaDoc b) throws BadLocationException JavaDoc {
562         load();
563         return super.modelToView(pos, a, b);
564         }
565
566         /**
567          * Start of the zones range.
568      *
569          * @see View#getStartOffset
570          */

571         public int getStartOffset() {
572         return start.getOffset();
573         }
574
575     /**
576      * End of the zones range.
577      */

578         public int getEndOffset() {
579         return end.getOffset();
580         }
581
582     /**
583      * Gives notification that something was inserted into
584      * the document in a location that this view is responsible for.
585      * If the zone has been loaded, the superclass behavior is
586      * invoked, otherwise this does nothing.
587      *
588      * @param e the change information from the associated document
589      * @param a the current allocation of the view
590      * @param f the factory to use to rebuild if the view has children
591      * @see View#insertUpdate
592      */

593         public void insertUpdate(DocumentEvent e, Shape a, ViewFactory JavaDoc f) {
594         if (isLoaded()) {
595         super.insertUpdate(e, a, f);
596         }
597     }
598
599     /**
600      * Gives notification that something was removed from the document
601      * in a location that this view is responsible for.
602      * If the zone has been loaded, the superclass behavior is
603      * invoked, otherwise this does nothing.
604      *
605      * @param e the change information from the associated document
606      * @param a the current allocation of the view
607      * @param f the factory to use to rebuild if the view has children
608      * @see View#removeUpdate
609      */

610         public void removeUpdate(DocumentEvent e, Shape a, ViewFactory JavaDoc f) {
611         if (isLoaded()) {
612         super.removeUpdate(e, a, f);
613         }
614     }
615
616     /**
617      * Gives notification from the document that attributes were changed
618      * in a location that this view is responsible for.
619      * If the zone has been loaded, the superclass behavior is
620      * invoked, otherwise this does nothing.
621      *
622      * @param e the change information from the associated document
623      * @param a the current allocation of the view
624      * @param f the factory to use to rebuild if the view has children
625      * @see View#removeUpdate
626      */

627         public void changedUpdate(DocumentEvent e, Shape a, ViewFactory JavaDoc f) {
628         if (isLoaded()) {
629         super.changedUpdate(e, a, f);
630         }
631     }
632
633     }
634 }
635
Popular Tags