1. /*
  2. * @(#)AsyncBoxView.java 1.14 03/01/23
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package javax.swing.text;
  8. import java.util.*;
  9. import java.awt.*;
  10. import javax.swing.SwingUtilities;
  11. import javax.swing.event.DocumentEvent;
  12. /**
  13. * A box that does layout asynchronously. This
  14. * is useful to keep the GUI event thread moving by
  15. * not doing any layout on it. The layout is done
  16. * on a granularity of operations on the child views.
  17. * After each child view is accessed for some part
  18. * of layout (a potentially time consuming operation)
  19. * the remaining tasks can be abandoned or a new higher
  20. * priority task (i.e. to service a synchronous request
  21. * or a visible area) can be taken on.
  22. * <p>
  23. * While the child view is being accessed
  24. * a read lock is aquired on the associated document
  25. * so that the model is stable while being accessed.
  26. *
  27. * @author Timothy Prinzing
  28. * @version 1.14 01/23/03
  29. * @since 1.3
  30. */
  31. public class AsyncBoxView extends View {
  32. /**
  33. * Construct a box view that does asynchronous layout.
  34. *
  35. * @param elem the element of the model to represent
  36. * @param axis the axis to tile along. This can be
  37. * either X_AXIS or Y_AXIS.
  38. */
  39. public AsyncBoxView(Element elem, int axis) {
  40. super(elem);
  41. stats = new ArrayList();
  42. this.axis = axis;
  43. locator = new ChildLocator();
  44. flushTask = new FlushTask();
  45. minorSpan = Short.MAX_VALUE;
  46. estimatedMajorSpan = false;
  47. }
  48. /**
  49. * Fetch the major axis (the axis the children
  50. * are tiled along). This will have a value of
  51. * either X_AXIS or Y_AXIS.
  52. */
  53. public int getMajorAxis() {
  54. return axis;
  55. }
  56. /**
  57. * Fetch the minor axis (the axis orthoginal
  58. * to the tiled axis). This will have a value of
  59. * either X_AXIS or Y_AXIS.
  60. */
  61. public int getMinorAxis() {
  62. return (axis == X_AXIS) ? Y_AXIS : X_AXIS;
  63. }
  64. /**
  65. * Get the top part of the margin around the view.
  66. */
  67. public float getTopInset() {
  68. return topInset;
  69. }
  70. /**
  71. * Set the top part of the margin around the view.
  72. *
  73. * @param i the value of the inset
  74. */
  75. public void setTopInset(float i) {
  76. topInset = i;
  77. }
  78. /**
  79. * Get the bottom part of the margin around the view.
  80. */
  81. public float getBottomInset() {
  82. return bottomInset;
  83. }
  84. /**
  85. * Set the bottom part of the margin around the view.
  86. *
  87. * @param i the value of the inset
  88. */
  89. public void setBottomInset(float i) {
  90. bottomInset = i;
  91. }
  92. /**
  93. * Get the left part of the margin around the view.
  94. */
  95. public float getLeftInset() {
  96. return leftInset;
  97. }
  98. /**
  99. * Set the left part of the margin around the view.
  100. *
  101. * @param i the value of the inset
  102. */
  103. public void setLeftInset(float i) {
  104. leftInset = i;
  105. }
  106. /**
  107. * Get the right part of the margin around the view.
  108. */
  109. public float getRightInset() {
  110. return rightInset;
  111. }
  112. /**
  113. * Set the right part of the margin around the view.
  114. *
  115. * @param i the value of the inset
  116. */
  117. public void setRightInset(float i) {
  118. rightInset = i;
  119. }
  120. /**
  121. * Fetch the span along an axis that is taken up by the insets.
  122. *
  123. * @param axis the axis to determine the total insets along,
  124. * either X_AXIS or Y_AXIS.
  125. * @since 1.4
  126. */
  127. protected float getInsetSpan(int axis) {
  128. float margin = (axis == X_AXIS) ?
  129. getLeftInset() + getRightInset() : getTopInset() + getBottomInset();
  130. return margin;
  131. }
  132. /**
  133. * Set the estimatedMajorSpan property that determines if the
  134. * major span should be treated as being estimated. If this
  135. * property is true, the value of setSize along the major axis
  136. * will change the requirements along the major axis and incremental
  137. * changes will be ignored until all of the children have been updated
  138. * (which will cause the property to automatically be set to false).
  139. * If the property is false the value of the majorSpan will be
  140. * considered to be accurate and incremental changes will be
  141. * added into the total as they are calculated.
  142. *
  143. * @since 1.4
  144. */
  145. protected void setEstimatedMajorSpan(boolean isEstimated) {
  146. estimatedMajorSpan = isEstimated;
  147. }
  148. /**
  149. * Is the major span currently estimated?
  150. *
  151. * @since 1.4
  152. */
  153. protected boolean getEstimatedMajorSpan() {
  154. return estimatedMajorSpan;
  155. }
  156. /**
  157. * Fetch the object representing the layout state of
  158. * of the child at the given index.
  159. *
  160. * @param index the child index. This should be a
  161. * value >= 0 and < getViewCount().
  162. */
  163. protected ChildState getChildState(int index) {
  164. synchronized(stats) {
  165. if ((index >= 0) && (index < stats.size())) {
  166. return (ChildState) stats.get(index);
  167. }
  168. return null;
  169. }
  170. }
  171. /**
  172. * Fetch the queue to use for layout.
  173. */
  174. protected LayoutQueue getLayoutQueue() {
  175. return LayoutQueue.getDefaultQueue();
  176. }
  177. /**
  178. * New ChildState records are created through
  179. * this method to allow subclasses the extend
  180. * the ChildState records to do/hold more
  181. */
  182. protected ChildState createChildState(View v) {
  183. return new ChildState(v);
  184. }
  185. /**
  186. * Requirements changed along the major axis.
  187. * This is called by the thread doing layout for
  188. * the given ChildState object when it has completed
  189. * fetching the child views new preferences.
  190. * Typically this would be the layout thread, but
  191. * might be the event thread if it is trying to update
  192. * something immediately (such as to perform a
  193. * model/view translation).
  194. * <p>
  195. * This is implemented to mark the major axis as having
  196. * changed so that a future check to see if the requirements
  197. * need to be published to the parent view will consider
  198. * the major axis. If the span along the major axis is
  199. * not estimated, it is updated by the given delta to reflect
  200. * the incremental change. The delta is ignored if the
  201. * major span is estimated.
  202. */
  203. protected synchronized void majorRequirementChange(ChildState cs, float delta) {
  204. if (estimatedMajorSpan == false) {
  205. majorSpan += delta;
  206. }
  207. majorChanged = true;
  208. }
  209. /**
  210. * Requirements changed along the minor axis.
  211. * This is called by the thread doing layout for
  212. * the given ChildState object when it has completed
  213. * fetching the child views new preferences.
  214. * Typically this would be the layout thread, but
  215. * might be the GUI thread if it is trying to update
  216. * something immediately (such as to perform a
  217. * model/view translation).
  218. */
  219. protected synchronized void minorRequirementChange(ChildState cs) {
  220. minorChanged = true;
  221. }
  222. /**
  223. * Publish the changes in preferences upward to the parent
  224. * view. This is normally called by the layout thread.
  225. */
  226. protected void flushRequirementChanges() {
  227. AbstractDocument doc = (AbstractDocument) getDocument();
  228. try {
  229. doc.readLock();
  230. View parent = null;
  231. boolean horizontal = false;
  232. boolean vertical = false;
  233. synchronized(this) {
  234. // perform tasks that iterate over the children while
  235. // preventing the collection from changing.
  236. synchronized(stats) {
  237. int n = getViewCount();
  238. if ((n > 0) && (minorChanged || estimatedMajorSpan)) {
  239. LayoutQueue q = getLayoutQueue();
  240. ChildState min = getChildState(0);
  241. ChildState pref = getChildState(0);
  242. float span = 0f;
  243. for (int i = 1; i < n; i++) {
  244. ChildState cs = getChildState(i);
  245. if (minorChanged) {
  246. if (cs.min > min.min) {
  247. min = cs;
  248. }
  249. if (cs.pref > pref.pref) {
  250. pref = cs;
  251. }
  252. }
  253. if (estimatedMajorSpan) {
  254. span += cs.getMajorSpan();
  255. }
  256. }
  257. if (minorChanged) {
  258. minRequest = min;
  259. prefRequest = pref;
  260. }
  261. if (estimatedMajorSpan) {
  262. majorSpan = span;
  263. estimatedMajorSpan = false;
  264. majorChanged = true;
  265. }
  266. }
  267. }
  268. // message preferenceChanged
  269. if (majorChanged || minorChanged) {
  270. parent = getParent();
  271. if (parent != null) {
  272. if (axis == X_AXIS) {
  273. horizontal = majorChanged;
  274. vertical = minorChanged;
  275. } else {
  276. vertical = majorChanged;
  277. horizontal = minorChanged;
  278. }
  279. }
  280. majorChanged = false;
  281. minorChanged = false;
  282. }
  283. }
  284. // propagate a preferenceChanged, using the
  285. // layout thread.
  286. if (parent != null) {
  287. parent.preferenceChanged(this, horizontal, vertical);
  288. // probably want to change this to be more exact.
  289. Component c = getContainer();
  290. if (c != null) {
  291. c.repaint();
  292. }
  293. }
  294. } finally {
  295. doc.readUnlock();
  296. }
  297. }
  298. /**
  299. * Calls the superclass to update the child views, and
  300. * updates the status records for the children. This
  301. * is expected to be called while a write lock is held
  302. * on the model so that interaction with the layout
  303. * thread will not happen (i.e. the layout thread
  304. * acquires a read lock before doing anything).
  305. *
  306. * @param offset the starting offset into the child views >= 0
  307. * @param length the number of existing views to replace >= 0
  308. * @param views the child views to insert
  309. */
  310. public void replace(int offset, int length, View[] views) {
  311. synchronized(stats) {
  312. // remove the replaced state records
  313. for (int i = 0; i < length; i++) {
  314. ChildState cs = (ChildState)stats.remove(offset);
  315. float csSpan = cs.getMajorSpan();
  316. cs.getChildView().setParent(null);
  317. if (csSpan != 0) {
  318. majorRequirementChange(cs, -csSpan);
  319. }
  320. }
  321. // insert the state records for the new children
  322. LayoutQueue q = getLayoutQueue();
  323. if (views != null) {
  324. for (int i = 0; i < views.length; i++) {
  325. ChildState s = createChildState(views[i]);
  326. stats.add(offset + i, s);
  327. q.addTask(s);
  328. }
  329. }
  330. // notify that the size changed
  331. q.addTask(flushTask);
  332. }
  333. }
  334. /**
  335. * Loads all of the children to initialize the view.
  336. * This is called by the <a href="#setParent">setParent</a>
  337. * method. Subclasses can reimplement this to initialize
  338. * their child views in a different manner. The default
  339. * implementation creates a child view for each
  340. * child element.
  341. * <p>
  342. * Normally a write-lock is held on the Document while
  343. * the children are being changed, which keeps the rendering
  344. * and layout threads safe. The exception to this is when
  345. * the view is initialized to represent an existing element
  346. * (via this method), so it is synchronized to exclude
  347. * preferenceChanged while we are initializing.
  348. *
  349. * @param f the view factory
  350. * @see #setParent
  351. */
  352. protected void loadChildren(ViewFactory f) {
  353. Element e = getElement();
  354. int n = e.getElementCount();
  355. if (n > 0) {
  356. View[] added = new View[n];
  357. for (int i = 0; i < n; i++) {
  358. added[i] = f.create(e.getElement(i));
  359. }
  360. replace(0, 0, added);
  361. }
  362. }
  363. /**
  364. * Fetches the child view index representing the given position in
  365. * the model. This is implemented to fetch the view in the case
  366. * where there is a child view for each child element.
  367. *
  368. * @param pos the position >= 0
  369. * @return index of the view representing the given position, or
  370. * -1 if no view represents that position
  371. */
  372. protected synchronized int getViewIndexAtPosition(int pos, Position.Bias b) {
  373. boolean isBackward = (b == Position.Bias.Backward);
  374. pos = (isBackward) ? Math.max(0, pos - 1) : pos;
  375. Element elem = getElement();
  376. return elem.getElementIndex(pos);
  377. }
  378. /**
  379. * Update the layout in response to receiving notification of
  380. * change from the model. This is implemented to note the
  381. * change on the ChildLocator so that offsets of the children
  382. * will be correctly computed.
  383. *
  384. * @param ec changes to the element this view is responsible
  385. * for (may be null if there were no changes).
  386. * @param e the change information from the associated document
  387. * @param a the current allocation of the view
  388. * @see #insertUpdate
  389. * @see #removeUpdate
  390. * @see #changedUpdate
  391. */
  392. protected void updateLayout(DocumentEvent.ElementChange ec,
  393. DocumentEvent e, Shape a) {
  394. if (ec != null) {
  395. // the newly inserted children don't have a valid
  396. // offset so the child locator needs to be messaged
  397. // that the child prior to the new children has
  398. // changed size.
  399. int index = Math.max(ec.getIndex() - 1, 0);
  400. ChildState cs = getChildState(index);
  401. locator.childChanged(cs);
  402. }
  403. }
  404. // --- View methods ------------------------------------
  405. /**
  406. * Sets the parent of the view.
  407. * This is reimplemented to provide the superclass
  408. * behavior as well as calling the <code>loadChildren</code>
  409. * method if this view does not already have children.
  410. * The children should not be loaded in the
  411. * constructor because the act of setting the parent
  412. * may cause them to try to search up the hierarchy
  413. * (to get the hosting Container for example).
  414. * If this view has children (the view is being moved
  415. * from one place in the view hierarchy to another),
  416. * the <code>loadChildren</code> method will not be called.
  417. *
  418. * @param parent the parent of the view, null if none
  419. */
  420. public void setParent(View parent) {
  421. super.setParent(parent);
  422. if ((parent != null) && (getViewCount() == 0)) {
  423. ViewFactory f = getViewFactory();
  424. loadChildren(f);
  425. }
  426. }
  427. /**
  428. * Child views can call this on the parent to indicate that
  429. * the preference has changed and should be reconsidered
  430. * for layout. This is reimplemented to queue new work
  431. * on the layout thread. This method gets messaged from
  432. * multiple threads via the children.
  433. *
  434. * @param child the child view
  435. * @param width true if the width preference has changed
  436. * @param height true if the height preference has changed
  437. * @see javax.swing.JComponent#revalidate
  438. */
  439. public synchronized void preferenceChanged(View child, boolean width, boolean height) {
  440. if (child == null) {
  441. getParent().preferenceChanged(this, width, height);
  442. } else {
  443. if (changing != null) {
  444. View cv = changing.getChildView();
  445. if (cv == child) {
  446. // size was being changed on the child, no need to
  447. // queue work for it.
  448. changing.preferenceChanged(width, height);
  449. return;
  450. }
  451. }
  452. int index = getViewIndex(child.getStartOffset(),
  453. Position.Bias.Forward);
  454. ChildState cs = getChildState(index);
  455. cs.preferenceChanged(width, height);
  456. LayoutQueue q = getLayoutQueue();
  457. q.addTask(cs);
  458. q.addTask(flushTask);
  459. }
  460. }
  461. /**
  462. * Sets the size of the view. This should cause
  463. * layout of the view if the view caches any layout
  464. * information.
  465. * <p>
  466. * Since the major axis is updated asynchronously and should be
  467. * the sum of the tiled children the call is ignored for the major
  468. * axis. Since the minor axis is flexible, work is queued to resize
  469. * the children if the minor span changes.
  470. *
  471. * @param width the width >= 0
  472. * @param height the height >= 0
  473. */
  474. public void setSize(float width, float height) {
  475. setSpanOnAxis(X_AXIS, width);
  476. setSpanOnAxis(Y_AXIS, height);
  477. }
  478. /**
  479. * Retrieves the size of the view along an axis.
  480. *
  481. * @param axis may be either <code>View.X_AXIS</code> or
  482. * <code>View.Y_AXIS</code>
  483. * @return the current span of the view along the given axis, >= 0
  484. */
  485. float getSpanOnAxis(int axis) {
  486. if (axis == getMajorAxis()) {
  487. return majorSpan;
  488. }
  489. return minorSpan;
  490. }
  491. /**
  492. * Sets the size of the view along an axis. Since the major
  493. * axis is updated asynchronously and should be the sum of the
  494. * tiled children the call is ignored for the major axis. Since
  495. * the minor axis is flexible, work is queued to resize the
  496. * children if the minor span changes.
  497. *
  498. * @param axis may be either <code>View.X_AXIS</code> or
  499. * <code>View.Y_AXIS</code>
  500. * @param span the span to layout to >= 0
  501. */
  502. void setSpanOnAxis(int axis, float span) {
  503. float margin = getInsetSpan(axis);
  504. if (axis == getMinorAxis()) {
  505. float targetSpan = span - margin;
  506. if (targetSpan != minorSpan) {
  507. minorSpan = targetSpan;
  508. // mark all of the ChildState instances as needing to
  509. // resize the child, and queue up work to fix them.
  510. int n = getViewCount();
  511. if (n != 0) {
  512. LayoutQueue q = getLayoutQueue();
  513. for (int i = 0; i < n; i++) {
  514. ChildState cs = getChildState(i);
  515. cs.childSizeValid = false;
  516. q.addTask(cs);
  517. }
  518. q.addTask(flushTask);
  519. }
  520. }
  521. } else {
  522. // along the major axis the value is ignored
  523. // unless the estimatedMajorSpan property is
  524. // true.
  525. if (estimatedMajorSpan) {
  526. majorSpan = span - margin;
  527. }
  528. }
  529. }
  530. /**
  531. * Render the view using the given allocation and
  532. * rendering surface.
  533. * <p>
  534. * This is implemented to determine whether or not the
  535. * desired region to be rendered (i.e. the unclipped
  536. * area) is up to date or not. If up-to-date the children
  537. * are rendered. If not up-to-date, a task to build
  538. * the desired area is placed on the layout queue as
  539. * a high priority task. This keeps by event thread
  540. * moving by rendering if ready, and postponing until
  541. * a later time if not ready (since paint requests
  542. * can be rescheduled).
  543. *
  544. * @param g the rendering surface to use
  545. * @param alloc the allocated region to render into
  546. * @see View#paint
  547. */
  548. public void paint(Graphics g, Shape alloc) {
  549. synchronized (locator) {
  550. locator.setAllocation(alloc);
  551. locator.paintChildren(g);
  552. }
  553. }
  554. /**
  555. * Determines the preferred span for this view along an
  556. * axis.
  557. *
  558. * @param axis may be either View.X_AXIS or View.Y_AXIS
  559. * @return the span the view would like to be rendered into >= 0.
  560. * Typically the view is told to render into the span
  561. * that is returned, although there is no guarantee.
  562. * The parent may choose to resize or break the view.
  563. * @exception IllegalArgumentException for an invalid axis type
  564. */
  565. public float getPreferredSpan(int axis) {
  566. float margin = getInsetSpan(axis);
  567. if (axis == this.axis) {
  568. return majorSpan + margin;
  569. }
  570. if (prefRequest != null) {
  571. View child = prefRequest.getChildView();
  572. return child.getPreferredSpan(axis) + margin;
  573. }
  574. // nothing is known about the children yet
  575. return margin + 30;
  576. }
  577. /**
  578. * Determines the minimum span for this view along an
  579. * axis.
  580. *
  581. * @param axis may be either View.X_AXIS or View.Y_AXIS
  582. * @return the span the view would like to be rendered into >= 0.
  583. * Typically the view is told to render into the span
  584. * that is returned, although there is no guarantee.
  585. * The parent may choose to resize or break the view.
  586. * @exception IllegalArgumentException for an invalid axis type
  587. */
  588. public float getMinimumSpan(int axis) {
  589. if (axis == this.axis) {
  590. return getPreferredSpan(axis);
  591. }
  592. if (minRequest != null) {
  593. View child = minRequest.getChildView();
  594. return child.getMinimumSpan(axis);
  595. }
  596. // nothing is known about the children yet
  597. if (axis == X_AXIS) {
  598. return getLeftInset() + getRightInset() + 5;
  599. } else {
  600. return getTopInset() + getBottomInset() + 5;
  601. }
  602. }
  603. /**
  604. * Determines the maximum span for this view along an
  605. * axis.
  606. *
  607. * @param axis may be either View.X_AXIS or View.Y_AXIS
  608. * @return the span the view would like to be rendered into >= 0.
  609. * Typically the view is told to render into the span
  610. * that is returned, although there is no guarantee.
  611. * The parent may choose to resize or break the view.
  612. * @exception IllegalArgumentException for an invalid axis type
  613. */
  614. public float getMaximumSpan(int axis) {
  615. if (axis == this.axis) {
  616. return getPreferredSpan(axis);
  617. }
  618. return Short.MAX_VALUE;
  619. }
  620. /**
  621. * Returns the number of views in this view. Since
  622. * the default is to not be a composite view this
  623. * returns 0.
  624. *
  625. * @return the number of views >= 0
  626. * @see View#getViewCount
  627. */
  628. public int getViewCount() {
  629. synchronized(stats) {
  630. return stats.size();
  631. }
  632. }
  633. /**
  634. * Gets the nth child view. Since there are no
  635. * children by default, this returns null.
  636. *
  637. * @param n the number of the view to get, >= 0 && < getViewCount()
  638. * @return the view
  639. */
  640. public View getView(int n) {
  641. ChildState cs = getChildState(n);
  642. if (cs != null) {
  643. return cs.getChildView();
  644. }
  645. return null;
  646. }
  647. /**
  648. * Fetches the allocation for the given child view.
  649. * This enables finding out where various views
  650. * are located, without assuming the views store
  651. * their location. This returns null since the
  652. * default is to not have any child views.
  653. *
  654. * @param index the index of the child, >= 0 && < getViewCount()
  655. * @param a the allocation to this view.
  656. * @return the allocation to the child
  657. */
  658. public Shape getChildAllocation(int index, Shape a) {
  659. Shape ca = locator.getChildAllocation(index, a);
  660. return ca;
  661. }
  662. /**
  663. * Returns the child view index representing the given position in
  664. * the model. By default a view has no children so this is implemented
  665. * to return -1 to indicate there is no valid child index for any
  666. * position.
  667. *
  668. * @param pos the position >= 0
  669. * @return index of the view representing the given position, or
  670. * -1 if no view represents that position
  671. * @since 1.3
  672. */
  673. public int getViewIndex(int pos, Position.Bias b) {
  674. return getViewIndexAtPosition(pos, b);
  675. }
  676. /**
  677. * Provides a mapping from the document model coordinate space
  678. * to the coordinate space of the view mapped to it.
  679. *
  680. * @param pos the position to convert >= 0
  681. * @param a the allocated region to render into
  682. * @param b the bias toward the previous character or the
  683. * next character represented by the offset, in case the
  684. * position is a boundary of two views.
  685. * @return the bounding box of the given position is returned
  686. * @exception BadLocationException if the given position does
  687. * not represent a valid location in the associated document
  688. * @exception IllegalArgumentException for an invalid bias argument
  689. * @see View#viewToModel
  690. */
  691. public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException {
  692. int index = getViewIndex(pos, b);
  693. Shape ca = locator.getChildAllocation(index, a);
  694. // forward to the child view, and make sure we don't
  695. // interact with the layout thread by synchronizing
  696. // on the child state.
  697. ChildState cs = getChildState(index);
  698. synchronized (cs) {
  699. View cv = cs.getChildView();
  700. Shape v = cv.modelToView(pos, ca, b);
  701. return v;
  702. }
  703. }
  704. /**
  705. * Provides a mapping from the view coordinate space to the logical
  706. * coordinate space of the model. The biasReturn argument will be
  707. * filled in to indicate that the point given is closer to the next
  708. * character in the model or the previous character in the model.
  709. * <p>
  710. * This is expected to be called by the GUI thread, holding a
  711. * read-lock on the associated model. It is implemented to
  712. * locate the child view and determine it's allocation with a
  713. * lock on the ChildLocator object, and to call viewToModel
  714. * on the child view with a lock on the ChildState object
  715. * to avoid interaction with the layout thread.
  716. *
  717. * @param x the X coordinate >= 0
  718. * @param y the Y coordinate >= 0
  719. * @param a the allocated region to render into
  720. * @return the location within the model that best represents the
  721. * given point in the view >= 0. The biasReturn argument will be
  722. * filled in to indicate that the point given is closer to the next
  723. * character in the model or the previous character in the model.
  724. */
  725. public int viewToModel(float x, float y, Shape a, Position.Bias[] biasReturn) {
  726. int pos; // return position
  727. int index; // child index to forward to
  728. Shape ca; // child allocation
  729. // locate the child view and it's allocation so that
  730. // we can forward to it. Make sure the layout thread
  731. // doesn't change anything by trying to flush changes
  732. // to the parent while the GUI thread is trying to
  733. // find the child and it's allocation.
  734. synchronized (locator) {
  735. index = locator.getViewIndexAtPoint(x, y, a);
  736. ca = locator.getChildAllocation(index, a);
  737. }
  738. // forward to the child view, and make sure we don't
  739. // interact with the layout thread by synchronizing
  740. // on the child state.
  741. ChildState cs = getChildState(index);
  742. synchronized (cs) {
  743. View v = cs.getChildView();
  744. pos = v.viewToModel(x, y, ca, biasReturn);
  745. }
  746. return pos;
  747. }
  748. /**
  749. * Provides a way to determine the next visually represented model
  750. * location that one might place a caret. Some views may not be visible,
  751. * they might not be in the same order found in the model, or they just
  752. * might not allow access to some of the locations in the model.
  753. *
  754. * @param pos the position to convert >= 0
  755. * @param a the allocated region to render into
  756. * @param direction the direction from the current position that can
  757. * be thought of as the arrow keys typically found on a keyboard;
  758. * this may be one of the following:
  759. * <ul>
  760. * <code>SwingConstants.WEST</code>
  761. * <code>SwingConstants.EAST</code>
  762. * <code>SwingConstants.NORTH</code>
  763. * <code>SwingConstants.SOUTH</code>
  764. * </ul>
  765. * @param biasRet an array contain the bias that was checked
  766. * @return the location within the model that best represents the next
  767. * location visual position
  768. * @exception BadLocationException
  769. * @exception IllegalArgumentException if <code>direction</code> is invalid
  770. */
  771. public int getNextVisualPositionFrom(int pos, Position.Bias b, Shape a,
  772. int direction,
  773. Position.Bias[] biasRet)
  774. throws BadLocationException {
  775. return Utilities.getNextVisualPositionFrom(
  776. this, pos, b, a, direction, biasRet);
  777. }
  778. // --- variables -----------------------------------------
  779. /**
  780. * The major axis against which the children are
  781. * tiled.
  782. */
  783. int axis;
  784. /**
  785. * The children and their layout statistics.
  786. */
  787. java.util.List stats;
  788. /**
  789. * Current span along the major axis. This
  790. * is also the value returned by getMinimumSize,
  791. * getPreferredSize, and getMaximumSize along
  792. * the major axis.
  793. */
  794. float majorSpan;
  795. /**
  796. * Is the span along the major axis estimated?
  797. */
  798. boolean estimatedMajorSpan;
  799. /**
  800. * Current span along the minor axis. This
  801. * is what layout was done against (i.e. things
  802. * are flexible in this direction).
  803. */
  804. float minorSpan;
  805. /**
  806. * Object that manages the offsets of the
  807. * children. All locking for management of
  808. * child locations is on this object.
  809. */
  810. protected ChildLocator locator;
  811. float topInset;
  812. float bottomInset;
  813. float leftInset;
  814. float rightInset;
  815. ChildState minRequest;
  816. ChildState prefRequest;
  817. boolean majorChanged;
  818. boolean minorChanged;
  819. Runnable flushTask;
  820. /**
  821. * Child that is actively changing size. This often
  822. * causes a preferenceChanged, so this is a cache to
  823. * possibly speed up the marking the state. It also
  824. * helps flag an opportunity to avoid adding to flush
  825. * task to the layout queue.
  826. */
  827. ChildState changing;
  828. /**
  829. * A class to manage the effective position of the
  830. * child views in a localized area while changes are
  831. * being made around the localized area. The AsyncBoxView
  832. * may be continuously changing, but the visible area
  833. * needs to remain fairly stable until the layout thread
  834. * decides to publish an update to the parent.
  835. */
  836. public class ChildLocator {
  837. /**
  838. * construct a child locator.
  839. */
  840. public ChildLocator() {
  841. lastAlloc = new Rectangle();
  842. childAlloc = new Rectangle();
  843. }
  844. /**
  845. * Notification that a child changed. This can effect
  846. * whether or not new offset calculations are needed.
  847. * This is called by a ChildState object that has
  848. * changed it's major span. This can therefore be
  849. * called by multiple threads.
  850. */
  851. public synchronized void childChanged(ChildState cs) {
  852. if (lastValidOffset == null) {
  853. lastValidOffset = cs;
  854. } else if (cs.getChildView().getStartOffset() <
  855. lastValidOffset.getChildView().getStartOffset()) {
  856. lastValidOffset = cs;
  857. }
  858. }
  859. /**
  860. * Paint the children that intersect the clip area.
  861. */
  862. public synchronized void paintChildren(Graphics g) {
  863. Rectangle clip = g.getClipBounds();
  864. float targetOffset = (axis == X_AXIS) ?
  865. clip.x - lastAlloc.x : clip.y - lastAlloc.y;
  866. int index = getViewIndexAtVisualOffset(targetOffset);
  867. int n = getViewCount();
  868. float offs = getChildState(index).getMajorOffset();
  869. for (int i = index; i < n; i++) {
  870. ChildState cs = getChildState(i);
  871. cs.setMajorOffset(offs);
  872. Shape ca = getChildAllocation(i);
  873. if (intersectsClip(ca, clip)) {
  874. synchronized (cs) {
  875. View v = cs.getChildView();
  876. v.paint(g, ca);
  877. }
  878. } else {
  879. // done painting intersection
  880. break;
  881. }
  882. offs += cs.getMajorSpan();
  883. }
  884. }
  885. /**
  886. * Fetch the allocation to use for a child view.
  887. * This will update the offsets for all children
  888. * not yet updated before the given index.
  889. */
  890. public synchronized Shape getChildAllocation(int index, Shape a) {
  891. if (a == null) {
  892. return null;
  893. }
  894. setAllocation(a);
  895. ChildState cs = getChildState(index);
  896. if (lastValidOffset == null) {
  897. lastValidOffset = getChildState(0);
  898. }
  899. if (cs.getChildView().getStartOffset() >
  900. lastValidOffset.getChildView().getStartOffset()) {
  901. // offsets need to be updated
  902. updateChildOffsetsToIndex(index);
  903. }
  904. Shape ca = getChildAllocation(index);
  905. return ca;
  906. }
  907. /**
  908. * Fetches the child view index at the given point.
  909. * This is called by the various View methods that
  910. * need to calculate which child to forward a message
  911. * to. This should be called by a block synchronized
  912. * on this object, and would typically be followed
  913. * with one or more calls to getChildAllocation that
  914. * should also be in the synchronized block.
  915. *
  916. * @param x the X coordinate >= 0
  917. * @param y the Y coordinate >= 0
  918. * @param a the allocation to the View
  919. * @return the nearest child index
  920. */
  921. public int getViewIndexAtPoint(float x, float y, Shape a) {
  922. setAllocation(a);
  923. float targetOffset = (axis == X_AXIS) ? x - lastAlloc.x : y - lastAlloc.y;
  924. int index = getViewIndexAtVisualOffset(targetOffset);
  925. return index;
  926. }
  927. /**
  928. * Fetch the allocation to use for a child view.
  929. * <em>This does not update the offsets in the ChildState
  930. * records.</em>
  931. */
  932. protected Shape getChildAllocation(int index) {
  933. ChildState cs = getChildState(index);
  934. if (! cs.isLayoutValid()) {
  935. cs.run();
  936. }
  937. if (axis == X_AXIS) {
  938. childAlloc.x = lastAlloc.x + (int) cs.getMajorOffset();
  939. childAlloc.y = lastAlloc.y + (int) cs.getMinorOffset();
  940. childAlloc.width = (int) cs.getMajorSpan();
  941. childAlloc.height = (int) cs.getMinorSpan();
  942. } else {
  943. childAlloc.y = lastAlloc.y + (int) cs.getMajorOffset();
  944. childAlloc.x = lastAlloc.x + (int) cs.getMinorOffset();
  945. childAlloc.height = (int) cs.getMajorSpan();
  946. childAlloc.width = (int) cs.getMinorSpan();
  947. }
  948. childAlloc.x += (int)getLeftInset();
  949. childAlloc.y += (int)getRightInset();
  950. return childAlloc;
  951. }
  952. /**
  953. * Copy the currently allocated shape into the Rectangle
  954. * used to store the current allocation. This would be
  955. * a floating point rectangle in a Java2D-specific implmentation.
  956. */
  957. protected void setAllocation(Shape a) {
  958. if (a instanceof Rectangle) {
  959. lastAlloc.setBounds((Rectangle) a);
  960. } else {
  961. lastAlloc.setBounds(a.getBounds());
  962. }
  963. setSize(lastAlloc.width, lastAlloc.height);
  964. }
  965. /**
  966. * Locate the view responsible for an offset into the box
  967. * along the major axis. Make sure that offsets are set
  968. * on the ChildState objects up to the given target span
  969. * past the desired offset.
  970. *
  971. * @return index of the view representing the given visual
  972. * location (targetOffset), or -1 if no view represents
  973. * that location
  974. */
  975. protected int getViewIndexAtVisualOffset(float targetOffset) {
  976. int n = getViewCount();
  977. if (n > 0) {
  978. boolean lastValid = (lastValidOffset != null);
  979. if (lastValidOffset == null) {
  980. lastValidOffset = getChildState(0);
  981. }
  982. if (targetOffset > majorSpan) {
  983. // should only get here on the first time display.
  984. if (!lastValid) {
  985. return 0;
  986. }
  987. int pos = lastValidOffset.getChildView().getStartOffset();
  988. int index = getViewIndex(pos, Position.Bias.Forward);
  989. return index;
  990. } else if (targetOffset > lastValidOffset.getMajorOffset()) {
  991. // roll offset calculations forward
  992. return updateChildOffsets(targetOffset);
  993. } else {
  994. // no changes prior to the needed offset
  995. // this should be a binary search
  996. float offs = 0f;
  997. for (int i = 0; i < n; i++) {
  998. ChildState cs = getChildState(i);
  999. float nextOffs = offs + cs.getMajorSpan();
  1000. if (targetOffset < nextOffs) {
  1001. return i;
  1002. }
  1003. offs = nextOffs;
  1004. }
  1005. }
  1006. }
  1007. return n - 1;
  1008. }
  1009. /**
  1010. * Move the location of the last offset calculation forward
  1011. * to the desired offset.
  1012. */
  1013. int updateChildOffsets(float targetOffset) {
  1014. int n = getViewCount();
  1015. int targetIndex = n - 1;;
  1016. int pos = lastValidOffset.getChildView().getStartOffset();
  1017. int startIndex = getViewIndex(pos, Position.Bias.Forward);
  1018. float start = lastValidOffset.getMajorOffset();
  1019. float lastOffset = start;
  1020. for (int i = startIndex; i < n; i++) {
  1021. ChildState cs = getChildState(i);
  1022. cs.setMajorOffset(lastOffset);
  1023. lastOffset += cs.getMajorSpan();
  1024. if (targetOffset < lastOffset) {
  1025. targetIndex = i;
  1026. lastValidOffset = cs;
  1027. break;
  1028. }
  1029. }
  1030. return targetIndex;
  1031. }
  1032. /**
  1033. * Move the location of the last offset calculation forward
  1034. * to the desired index.
  1035. */
  1036. void updateChildOffsetsToIndex(int index) {
  1037. int pos = lastValidOffset.getChildView().getStartOffset();
  1038. int startIndex = getViewIndex(pos, Position.Bias.Forward);
  1039. float lastOffset = lastValidOffset.getMajorOffset();
  1040. for (int i = startIndex; i <= index; i++) {
  1041. ChildState cs = getChildState(i);
  1042. cs.setMajorOffset(lastOffset);
  1043. lastOffset += cs.getMajorSpan();
  1044. }
  1045. }
  1046. boolean intersectsClip(Shape childAlloc, Rectangle clip) {
  1047. Rectangle cs = (childAlloc instanceof Rectangle) ?
  1048. (Rectangle) childAlloc : childAlloc.getBounds();
  1049. if (cs.intersects(clip)) {
  1050. // Make sure that lastAlloc also contains childAlloc,
  1051. // this will be false if haven't yet flushed changes.
  1052. return lastAlloc.intersects(cs);
  1053. }
  1054. return false;
  1055. }
  1056. /**
  1057. * The location of the last offset calculation
  1058. * that is valid.
  1059. */
  1060. protected ChildState lastValidOffset;
  1061. /**
  1062. * The last seen allocation (for repainting when changes
  1063. * are flushed upward).
  1064. */
  1065. protected Rectangle lastAlloc;
  1066. /**
  1067. * A shape to use for the child allocation to avoid
  1068. * creating a lot of garbage.
  1069. */
  1070. protected Rectangle childAlloc;
  1071. }
  1072. /**
  1073. * A record representing the layout state of a
  1074. * child view. It is runnable as a task on another
  1075. * thread. All access to the child view that is
  1076. * based upon a read-lock on the model should synchronize
  1077. * on this object (i.e. The layout thread and the GUI
  1078. * thread can both have a read lock on the model at the
  1079. * same time and are not protected from each other).
  1080. * Access to a child view hierarchy is serialized via
  1081. * synchronization on the ChildState instance.
  1082. */
  1083. public class ChildState implements Runnable {
  1084. /**
  1085. * Construct a child status. This needs to start
  1086. * out as fairly large so we don't falsely begin with
  1087. * the idea that all of the children are visible.
  1088. */
  1089. public ChildState(View v) {
  1090. child = v;
  1091. minorValid = false;
  1092. majorValid = false;
  1093. childSizeValid = false;
  1094. child.setParent(AsyncBoxView.this);
  1095. }
  1096. /**
  1097. * Fetch the child view this record represents
  1098. */
  1099. public View getChildView() {
  1100. return child;
  1101. }
  1102. /**
  1103. * Update the child state. This should be
  1104. * called by the thread that desires to spend
  1105. * time updating the child state (intended to
  1106. * be the layout thread).
  1107. * <p>
  1108. * This aquires a read lock on the associated
  1109. * document for the duration of the update to
  1110. * ensure the model is not changed while it is
  1111. * operating. The first thing to do would be
  1112. * to see if any work actually needs to be done.
  1113. * The following could have conceivably happened
  1114. * while the state was waiting to be updated:
  1115. * <ol>
  1116. * <li>The child may have been removed from the
  1117. * view hierarchy.
  1118. * <li>The child may have been updated by a
  1119. * higher priority operation (i.e. the child
  1120. * may have become visible).
  1121. * </ol>
  1122. */
  1123. public void run () {
  1124. AbstractDocument doc = (AbstractDocument) getDocument();
  1125. try {
  1126. doc.readLock();
  1127. if (minorValid && majorValid && childSizeValid) {
  1128. // nothing to do
  1129. return;
  1130. }
  1131. if (child.getParent() == AsyncBoxView.this) {
  1132. // this may overwrite anothers threads cached
  1133. // value for actively changing... but that just
  1134. // means it won't use the cache if there is an
  1135. // overwrite.
  1136. synchronized(AsyncBoxView.this) {
  1137. changing = this;
  1138. }
  1139. updateChild();
  1140. synchronized(AsyncBoxView.this) {
  1141. changing = null;
  1142. }
  1143. // setting the child size on the minor axis
  1144. // may have caused it to change it's preference
  1145. // along the major axis.
  1146. updateChild();
  1147. }
  1148. } finally {
  1149. doc.readUnlock();
  1150. }
  1151. }
  1152. void updateChild() {
  1153. boolean minorUpdated = false;
  1154. synchronized(this) {
  1155. if (! minorValid) {
  1156. int minorAxis = getMinorAxis();
  1157. min = child.getMinimumSpan(minorAxis);
  1158. pref = child.getPreferredSpan(minorAxis);
  1159. max = child.getMaximumSpan(minorAxis);
  1160. minorValid = true;
  1161. minorUpdated = true;
  1162. }
  1163. }
  1164. if (minorUpdated) {
  1165. minorRequirementChange(this);
  1166. }
  1167. boolean majorUpdated = false;
  1168. float delta = 0.0f;
  1169. synchronized(this) {
  1170. if (! majorValid) {
  1171. float old = span;
  1172. span = child.getPreferredSpan(axis);
  1173. delta = span - old;
  1174. majorValid = true;
  1175. majorUpdated = true;
  1176. }
  1177. }
  1178. if (majorUpdated) {
  1179. majorRequirementChange(this, delta);
  1180. locator.childChanged(this);
  1181. }
  1182. synchronized(this) {
  1183. if (! childSizeValid) {
  1184. float w;
  1185. float h;
  1186. if (axis == X_AXIS) {
  1187. w = span;
  1188. h = getMinorSpan();
  1189. } else {
  1190. w = getMinorSpan();
  1191. h = span;
  1192. }
  1193. childSizeValid = true;
  1194. child.setSize(w, h);
  1195. }
  1196. }
  1197. }
  1198. /**
  1199. * What is the span along the minor axis.
  1200. */
  1201. public float getMinorSpan() {
  1202. if (max < minorSpan) {
  1203. return max;
  1204. }
  1205. // make it the target width, or as small as it can get.
  1206. return Math.max(min, minorSpan);
  1207. }
  1208. /**
  1209. * What is the offset along the minor axis
  1210. */
  1211. public float getMinorOffset() {
  1212. if (max < minorSpan) {
  1213. // can't make the child this wide, align it
  1214. float align = child.getAlignment(getMinorAxis());
  1215. return ((minorSpan - max) * align);
  1216. }
  1217. return 0f;
  1218. }
  1219. /**
  1220. * What is the span along the major axis.
  1221. */
  1222. public float getMajorSpan() {
  1223. return span;
  1224. }
  1225. /**
  1226. * Get the offset along the major axis
  1227. */
  1228. public float getMajorOffset() {
  1229. return offset;
  1230. }
  1231. /**
  1232. * This method should only be called by the ChildLocator,
  1233. * it is simply a convenient place to hold the cached
  1234. * location.
  1235. */
  1236. public void setMajorOffset(float offs) {
  1237. offset = offs;
  1238. }
  1239. /**
  1240. * Mark preferences changed for this child.
  1241. *
  1242. * @param width true if the width preference has changed
  1243. * @param height true if the height preference has changed
  1244. * @see javax.swing.JComponent#revalidate
  1245. */
  1246. public void preferenceChanged(boolean width, boolean height) {
  1247. if (axis == X_AXIS) {
  1248. if (width) {
  1249. majorValid = false;
  1250. }
  1251. if (height) {
  1252. minorValid = false;
  1253. }
  1254. } else {
  1255. if (width) {
  1256. minorValid = false;
  1257. }
  1258. if (height) {
  1259. majorValid = false;
  1260. }
  1261. }
  1262. childSizeValid = false;
  1263. }
  1264. /**
  1265. * Has the child view been laid out.
  1266. */
  1267. public boolean isLayoutValid() {
  1268. return (minorValid && majorValid && childSizeValid);
  1269. }
  1270. // minor axis
  1271. private float min;
  1272. private float pref;
  1273. private float max;
  1274. private float align;
  1275. private boolean minorValid;
  1276. // major axis
  1277. private float span;
  1278. private float offset;
  1279. private boolean majorValid;
  1280. private View child;
  1281. private boolean childSizeValid;
  1282. }
  1283. /**
  1284. * Task to flush requirement changes upward
  1285. */
  1286. class FlushTask implements Runnable {
  1287. public void run() {
  1288. flushRequirementChanges();
  1289. }
  1290. }
  1291. }