You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ListItemLayoutManager.java 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.layoutmgr.list;
  19. import java.util.ArrayList;
  20. import java.util.Collections;
  21. import java.util.LinkedList;
  22. import java.util.List;
  23. import java.util.ListIterator;
  24. import java.util.Stack;
  25. import org.apache.commons.logging.Log;
  26. import org.apache.commons.logging.LogFactory;
  27. import org.apache.fop.area.Area;
  28. import org.apache.fop.area.Block;
  29. import org.apache.fop.fo.flow.ListItem;
  30. import org.apache.fop.fo.flow.ListItemBody;
  31. import org.apache.fop.fo.flow.ListItemLabel;
  32. import org.apache.fop.fo.properties.CommonBorderPaddingBackground;
  33. import org.apache.fop.fo.properties.KeepProperty;
  34. import org.apache.fop.layoutmgr.BlockLayoutManager;
  35. import org.apache.fop.layoutmgr.BreakElement;
  36. import org.apache.fop.layoutmgr.BreakOpportunity;
  37. import org.apache.fop.layoutmgr.BreakOpportunityHelper;
  38. import org.apache.fop.layoutmgr.ElementListObserver;
  39. import org.apache.fop.layoutmgr.ElementListUtils;
  40. import org.apache.fop.layoutmgr.FloatContentLayoutManager;
  41. import org.apache.fop.layoutmgr.FootenoteUtil;
  42. import org.apache.fop.layoutmgr.Keep;
  43. import org.apache.fop.layoutmgr.KnuthBlockBox;
  44. import org.apache.fop.layoutmgr.KnuthElement;
  45. import org.apache.fop.layoutmgr.KnuthPenalty;
  46. import org.apache.fop.layoutmgr.KnuthPossPosIter;
  47. import org.apache.fop.layoutmgr.LayoutContext;
  48. import org.apache.fop.layoutmgr.LayoutManager;
  49. import org.apache.fop.layoutmgr.LeafPosition;
  50. import org.apache.fop.layoutmgr.ListElement;
  51. import org.apache.fop.layoutmgr.NonLeafPosition;
  52. import org.apache.fop.layoutmgr.PageProvider;
  53. import org.apache.fop.layoutmgr.Position;
  54. import org.apache.fop.layoutmgr.PositionIterator;
  55. import org.apache.fop.layoutmgr.SpaceResolver;
  56. import org.apache.fop.layoutmgr.SpacedBorderedPaddedBlockLayoutManager;
  57. import org.apache.fop.layoutmgr.TraitSetter;
  58. import org.apache.fop.traits.SpaceVal;
  59. import org.apache.fop.util.BreakUtil;
  60. /**
  61. * LayoutManager for a list-item FO.
  62. * The list item contains a list item label and a list item body.
  63. */
  64. public class ListItemLayoutManager extends SpacedBorderedPaddedBlockLayoutManager
  65. implements BreakOpportunity {
  66. /** logging instance */
  67. private static Log log = LogFactory.getLog(ListItemLayoutManager.class);
  68. private ListItemContentLayoutManager label;
  69. private ListItemContentLayoutManager body;
  70. private Block curBlockArea;
  71. private List<ListElement> labelList;
  72. private List<ListElement> bodyList;
  73. private Keep keepWithNextPendingOnLabel;
  74. private Keep keepWithNextPendingOnBody;
  75. public class ListItemPosition extends Position {
  76. private int labelFirstIndex;
  77. private int labelLastIndex;
  78. private int bodyFirstIndex;
  79. private int bodyLastIndex;
  80. private Position originalLabelPosition;
  81. private Position originalBodyPosition;
  82. public ListItemPosition(LayoutManager lm, int labelFirst, int labelLast,
  83. int bodyFirst, int bodyLast) {
  84. super(lm);
  85. labelFirstIndex = labelFirst;
  86. labelLastIndex = labelLast;
  87. bodyFirstIndex = bodyFirst;
  88. bodyLastIndex = bodyLast;
  89. }
  90. public int getLabelFirstIndex() {
  91. return labelFirstIndex;
  92. }
  93. public int getLabelLastIndex() {
  94. return labelLastIndex;
  95. }
  96. public int getBodyFirstIndex() {
  97. return bodyFirstIndex;
  98. }
  99. public int getBodyLastIndex() {
  100. return bodyLastIndex;
  101. }
  102. /** {@inheritDoc} */
  103. public boolean generatesAreas() {
  104. return true;
  105. }
  106. /** {@inheritDoc} */
  107. public String toString() {
  108. StringBuffer sb = new StringBuffer("ListItemPosition:");
  109. sb.append(getIndex()).append("(");
  110. sb.append("label:").append(labelFirstIndex).append("-").append(labelLastIndex);
  111. sb.append(" body:").append(bodyFirstIndex).append("-").append(bodyLastIndex);
  112. sb.append(")");
  113. return sb.toString();
  114. }
  115. public Position getOriginalLabelPosition() {
  116. return originalLabelPosition;
  117. }
  118. public void setOriginalLabelPosition(Position originalLabelPosition) {
  119. this.originalLabelPosition = originalLabelPosition;
  120. }
  121. public Position getOriginalBodyPosition() {
  122. return originalBodyPosition;
  123. }
  124. public void setOriginalBodyPosition(Position originalBodyPosition) {
  125. this.originalBodyPosition = originalBodyPosition;
  126. }
  127. }
  128. /**
  129. * Create a new list item layout manager.
  130. * @param node list-item to create the layout manager for
  131. */
  132. public ListItemLayoutManager(ListItem node) {
  133. super(node);
  134. setLabel(node.getLabel());
  135. setBody(node.getBody());
  136. }
  137. @Override
  138. protected CommonBorderPaddingBackground getCommonBorderPaddingBackground() {
  139. return getListItemFO().getCommonBorderPaddingBackground();
  140. }
  141. /**
  142. * Convenience method.
  143. * @return the ListBlock node
  144. */
  145. protected ListItem getListItemFO() {
  146. return (ListItem)fobj;
  147. }
  148. /**
  149. * Create a LM for the fo:list-item-label object
  150. * @param node the fo:list-item-label FO
  151. */
  152. public void setLabel(ListItemLabel node) {
  153. label = new ListItemContentLayoutManager(node);
  154. label.setParent(this);
  155. }
  156. /**
  157. * Create a LM for the fo:list-item-body object
  158. * @param node the fo:list-item-body FO
  159. */
  160. public void setBody(ListItemBody node) {
  161. body = new ListItemContentLayoutManager(node);
  162. body.setParent(this);
  163. }
  164. /** {@inheritDoc} */
  165. @Override
  166. public void initialize() {
  167. foSpaceBefore = new SpaceVal(
  168. getListItemFO().getCommonMarginBlock().spaceBefore, this).getSpace();
  169. foSpaceAfter = new SpaceVal(
  170. getListItemFO().getCommonMarginBlock().spaceAfter, this).getSpace();
  171. startIndent = getListItemFO().getCommonMarginBlock().startIndent.getValue(this);
  172. endIndent = getListItemFO().getCommonMarginBlock().endIndent.getValue(this);
  173. }
  174. private void resetSpaces() {
  175. this.discardBorderBefore = false;
  176. this.discardBorderAfter = false;
  177. this.discardPaddingBefore = false;
  178. this.discardPaddingAfter = false;
  179. this.effSpaceBefore = null;
  180. this.effSpaceAfter = null;
  181. }
  182. /** {@inheritDoc} */
  183. public List getNextKnuthElements(LayoutContext context, int alignment, Stack lmStack,
  184. Position restartPosition, LayoutManager restartAtLM) {
  185. referenceIPD = context.getRefIPD();
  186. LayoutContext childLC;
  187. List<ListElement> returnList = new LinkedList<ListElement>();
  188. if (!breakBeforeServed(context, returnList)) {
  189. return returnList;
  190. }
  191. addFirstVisibleMarks(returnList, context, alignment);
  192. // label
  193. childLC = makeChildLayoutContext(context);
  194. childLC.setFlags(LayoutContext.SUPPRESS_BREAK_BEFORE);
  195. label.initialize();
  196. boolean labelDone = false;
  197. Stack labelLMStack = null;
  198. Position labelRestartPosition = null;
  199. LayoutManager labelRestartLM = null;
  200. if (restartPosition != null && restartPosition instanceof ListItemPosition) {
  201. ListItemPosition lip = (ListItemPosition) restartPosition;
  202. if (lip.labelLastIndex <= lip.labelFirstIndex) {
  203. labelDone = true;
  204. } else {
  205. labelRestartPosition = lip.getOriginalLabelPosition();
  206. labelRestartLM = labelRestartPosition.getLM();
  207. LayoutManager lm = labelRestartLM;
  208. labelLMStack = new Stack();
  209. while (lm != this) {
  210. labelLMStack.push(lm);
  211. lm = lm.getParent();
  212. if (lm instanceof ListItemContentLayoutManager) {
  213. lm = lm.getParent();
  214. }
  215. }
  216. }
  217. }
  218. labelList = !labelDone ? label.getNextKnuthElements(childLC, alignment, labelLMStack,
  219. labelRestartPosition, labelRestartLM) : (List) new LinkedList<KnuthElement>();
  220. //Space resolution as if the contents were placed in a new reference area
  221. //(see 6.8.3, XSL 1.0, section on Constraints, last paragraph)
  222. SpaceResolver.resolveElementList(labelList);
  223. ElementListObserver.observe(labelList, "list-item-label", label.getPartFO().getId());
  224. context.updateKeepWithPreviousPending(childLC.getKeepWithPreviousPending());
  225. this.keepWithNextPendingOnLabel = childLC.getKeepWithNextPending();
  226. // body
  227. childLC = makeChildLayoutContext(context);
  228. childLC.setFlags(LayoutContext.SUPPRESS_BREAK_BEFORE);
  229. body.initialize();
  230. boolean bodyDone = false;
  231. Stack bodyLMStack = null;
  232. Position bodyRestartPosition = null;
  233. LayoutManager bodyRestartLM = null;
  234. if (restartPosition != null && restartPosition instanceof ListItemPosition) {
  235. ListItemPosition lip = (ListItemPosition) restartPosition;
  236. if (lip.bodyLastIndex <= lip.bodyFirstIndex) {
  237. bodyDone = true;
  238. } else {
  239. bodyRestartPosition = lip.getOriginalBodyPosition();
  240. bodyRestartLM = bodyRestartPosition.getLM();
  241. LayoutManager lm = bodyRestartLM;
  242. bodyLMStack = new Stack();
  243. while (lm != this) {
  244. bodyLMStack.push(lm);
  245. lm = lm.getParent();
  246. if (lm instanceof ListItemContentLayoutManager) {
  247. lm = lm.getParent();
  248. }
  249. }
  250. }
  251. }
  252. bodyList = !bodyDone ? body.getNextKnuthElements(childLC, alignment, bodyLMStack,
  253. bodyRestartPosition, bodyRestartLM) : (List) new LinkedList<KnuthElement>();
  254. //Space resolution as if the contents were placed in a new reference area
  255. //(see 6.8.3, XSL 1.0, section on Constraints, last paragraph)
  256. SpaceResolver.resolveElementList(bodyList);
  257. ElementListObserver.observe(bodyList, "list-item-body", body.getPartFO().getId());
  258. context.updateKeepWithPreviousPending(childLC.getKeepWithPreviousPending());
  259. this.keepWithNextPendingOnBody = childLC.getKeepWithNextPending();
  260. List<ListElement> returnedList = new LinkedList<ListElement>();
  261. if (!labelList.isEmpty() && labelList.get(0) instanceof KnuthBlockBox) {
  262. KnuthBlockBox kbb = (KnuthBlockBox) labelList.get(0);
  263. if (kbb.getWidth() == 0 && kbb.hasFloatAnchors()) {
  264. List<FloatContentLayoutManager> floats = kbb.getFloatContentLMs();
  265. returnedList.add(new KnuthBlockBox(0, Collections.emptyList(), null, false, floats));
  266. Keep keep = getKeepTogether();
  267. returnedList.add(new BreakElement(new LeafPosition(this, 0), keep.getPenalty(), keep
  268. .getContext(), context));
  269. labelList.remove(0);
  270. labelList.remove(0);
  271. }
  272. }
  273. if (!bodyList.isEmpty() && bodyList.get(0) instanceof KnuthBlockBox) {
  274. KnuthBlockBox kbb = (KnuthBlockBox) bodyList.get(0);
  275. if (kbb.getWidth() == 0 && kbb.hasFloatAnchors()) {
  276. List<FloatContentLayoutManager> floats = kbb.getFloatContentLMs();
  277. returnedList.add(new KnuthBlockBox(0, Collections.emptyList(), null, false, floats));
  278. Keep keep = getKeepTogether();
  279. returnedList.add(new BreakElement(new LeafPosition(this, 0), keep.getPenalty(), keep
  280. .getContext(), context));
  281. bodyList.remove(0);
  282. bodyList.remove(0);
  283. }
  284. }
  285. // create a combined list
  286. returnedList.addAll(getCombinedKnuthElementsForListItem(labelList, bodyList, context));
  287. // "wrap" the Position inside each element
  288. wrapPositionElements(returnedList, returnList, true);
  289. addLastVisibleMarks(returnList, context, alignment);
  290. addKnuthElementsForBreakAfter(returnList, context);
  291. context.updateKeepWithNextPending(this.keepWithNextPendingOnLabel);
  292. context.updateKeepWithNextPending(this.keepWithNextPendingOnBody);
  293. context.updateKeepWithNextPending(getKeepWithNext());
  294. context.updateKeepWithPreviousPending(getKeepWithPrevious());
  295. setFinished(true);
  296. resetSpaces();
  297. return returnList;
  298. }
  299. /**
  300. * Overridden to unconditionally add elements for space-before.
  301. * {@inheritDoc}
  302. */
  303. @Override
  304. protected void addFirstVisibleMarks(List<ListElement> elements,
  305. LayoutContext context, int alignment) {
  306. addKnuthElementsForSpaceBefore(elements, alignment);
  307. addKnuthElementsForBorderPaddingBefore(elements, !firstVisibleMarkServed);
  308. firstVisibleMarkServed = true;
  309. //Spaces, border and padding to be repeated at each break
  310. addPendingMarks(context);
  311. }
  312. private List getCombinedKnuthElementsForListItem(List<ListElement> labelElements,
  313. List<ListElement> bodyElements, LayoutContext context) {
  314. // Copy elements to array lists to improve element access performance
  315. List[] elementLists = {new ArrayList<ListElement>(labelElements),
  316. new ArrayList<ListElement>(bodyElements)};
  317. int[] fullHeights = {ElementListUtils.calcContentLength(elementLists[0]),
  318. ElementListUtils.calcContentLength(elementLists[1])};
  319. int[] partialHeights = {0, 0};
  320. int[] start = {-1, -1};
  321. int[] end = {-1, -1};
  322. int totalHeight = Math.max(fullHeights[0], fullHeights[1]);
  323. int step;
  324. int addedBoxHeight = 0;
  325. Keep keepWithNextActive = Keep.KEEP_AUTO;
  326. LinkedList<ListElement> returnList = new LinkedList<ListElement>();
  327. while ((step = getNextStep(elementLists, start, end, partialHeights)) > 0) {
  328. if (end[0] + 1 == elementLists[0].size()) {
  329. keepWithNextActive = keepWithNextActive.compare(keepWithNextPendingOnLabel);
  330. }
  331. if (end[1] + 1 == elementLists[1].size()) {
  332. keepWithNextActive = keepWithNextActive.compare(keepWithNextPendingOnBody);
  333. }
  334. // compute penalty height and box height
  335. int penaltyHeight = step
  336. + getMaxRemainingHeight(fullHeights, partialHeights)
  337. - totalHeight;
  338. //Additional penalty height from penalties in the source lists
  339. int additionalPenaltyHeight = 0;
  340. int stepPenalty = 0;
  341. int breakClass = EN_AUTO;
  342. KnuthElement endEl = elementLists[0].size() > 0 ? (KnuthElement) elementLists[0].get(end[0])
  343. : null;
  344. Position originalLabelPosition =
  345. (endEl != null && endEl.getPosition() != null) ? endEl.getPosition().getPosition() : null;
  346. if (endEl instanceof KnuthPenalty) {
  347. additionalPenaltyHeight = endEl.getWidth();
  348. stepPenalty = endEl.getPenalty() == -KnuthElement.INFINITE ? -KnuthElement.INFINITE : Math
  349. .max(stepPenalty, endEl.getPenalty());
  350. breakClass = BreakUtil.compareBreakClasses(breakClass,
  351. ((KnuthPenalty) endEl).getBreakClass());
  352. }
  353. endEl = elementLists[1].size() > 0 ? (KnuthElement) elementLists[1].get(end[1]) : null;
  354. Position originalBodyPosition =
  355. (endEl != null && endEl.getPosition() != null) ? endEl.getPosition().getPosition() : null;
  356. if (endEl instanceof KnuthPenalty) {
  357. additionalPenaltyHeight = Math.max(
  358. additionalPenaltyHeight, endEl.getWidth());
  359. stepPenalty = endEl.getPenalty() == -KnuthElement.INFINITE ? -KnuthElement.INFINITE : Math
  360. .max(stepPenalty, endEl.getPenalty());
  361. breakClass = BreakUtil.compareBreakClasses(breakClass,
  362. ((KnuthPenalty) endEl).getBreakClass());
  363. }
  364. int boxHeight = step - addedBoxHeight - penaltyHeight;
  365. penaltyHeight += additionalPenaltyHeight; //Add AFTER calculating boxHeight!
  366. // collect footnote information
  367. // TODO this should really not be done like this. ListItemLM should remain as
  368. // footnote-agnostic as possible
  369. LinkedList<LayoutManager> footnoteList = new LinkedList<LayoutManager>();
  370. for (int i = 0; i < elementLists.length; i++) {
  371. footnoteList.addAll(FootenoteUtil.getFootnotes(elementLists[i], start[i], end[i]));
  372. }
  373. LinkedList<FloatContentLayoutManager> floats = new LinkedList<FloatContentLayoutManager>();
  374. for (int i = 0; i < elementLists.length; i++) {
  375. floats.addAll(FloatContentLayoutManager.checkForFloats(elementLists[i], start[i], end[i]));
  376. }
  377. // add the new elements
  378. addedBoxHeight += boxHeight;
  379. ListItemPosition stepPosition = new ListItemPosition(this, start[0], end[0], start[1], end[1]);
  380. stepPosition.setOriginalLabelPosition(originalLabelPosition);
  381. stepPosition.setOriginalBodyPosition(originalBodyPosition);
  382. if (floats.isEmpty()) {
  383. returnList.add(new KnuthBlockBox(boxHeight, footnoteList, stepPosition, false));
  384. } else {
  385. // add a line with height zero and no content and attach float to it
  386. returnList.add(new KnuthBlockBox(0, Collections.emptyList(), stepPosition, false, floats));
  387. // add a break element to signal that we should restart LB at this break
  388. Keep keep = getKeepTogether();
  389. returnList.add(new BreakElement(stepPosition, keep.getPenalty(), keep.getContext(), context));
  390. // add the original line where the float was but without the float now
  391. returnList.add(new KnuthBlockBox(boxHeight, footnoteList, stepPosition, false));
  392. }
  393. if (originalBodyPosition != null && getKeepWithPrevious().isAuto()
  394. && shouldWeAvoidBreak(returnList, originalBodyPosition.getLM())) {
  395. stepPenalty++;
  396. }
  397. if (addedBoxHeight < totalHeight) {
  398. Keep keep = keepWithNextActive.compare(getKeepTogether());
  399. int p = stepPenalty;
  400. if (p > -KnuthElement.INFINITE) {
  401. p = Math.max(p, keep.getPenalty());
  402. breakClass = keep.getContext();
  403. }
  404. returnList.add(new BreakElement(stepPosition, penaltyHeight, p, breakClass, context));
  405. }
  406. }
  407. return returnList;
  408. }
  409. private boolean shouldWeAvoidBreak(List returnList, LayoutManager lm) {
  410. if (isChangingIPD(lm)) {
  411. if (lm instanceof BlockLayoutManager) {
  412. return true;
  413. }
  414. if (lm instanceof ListBlockLayoutManager) {
  415. int penaltyShootout = 0;
  416. for (Object o : returnList) {
  417. if (o instanceof BreakElement) {
  418. if (((BreakElement) o).getPenaltyValue() > 0) {
  419. penaltyShootout++;
  420. } else {
  421. penaltyShootout--;
  422. }
  423. }
  424. }
  425. return penaltyShootout > 0;
  426. }
  427. }
  428. return false;
  429. }
  430. private boolean isChangingIPD(LayoutManager lm) {
  431. PageProvider pageProvider = lm.getPSLM().getPageProvider();
  432. int currentIPD = pageProvider.getCurrentIPD();
  433. if (currentIPD == -1) {
  434. return false;
  435. }
  436. int nextIPD = pageProvider.getNextIPD();
  437. return nextIPD != currentIPD;
  438. }
  439. private int getNextStep(List[] elementLists, int[] start, int[] end, int[] partialHeights) {
  440. // backup of partial heights
  441. int[] backupHeights = {partialHeights[0], partialHeights[1]};
  442. // set starting points
  443. start[0] = end[0] + 1;
  444. start[1] = end[1] + 1;
  445. // get next possible sequence for label and body
  446. int seqCount = 0;
  447. for (int i = 0; i < start.length; i++) {
  448. while (end[i] + 1 < elementLists[i].size()) {
  449. end[i]++;
  450. KnuthElement el = (KnuthElement)elementLists[i].get(end[i]);
  451. if (el.isPenalty()) {
  452. if (el.getPenalty() < KnuthElement.INFINITE) {
  453. //First legal break point
  454. break;
  455. }
  456. } else if (el.isGlue()) {
  457. if (end[i] > 0) {
  458. KnuthElement prev = (KnuthElement)elementLists[i].get(end[i] - 1);
  459. if (prev.isBox()) {
  460. //Second legal break point
  461. break;
  462. }
  463. }
  464. partialHeights[i] += el.getWidth();
  465. } else {
  466. partialHeights[i] += el.getWidth();
  467. }
  468. }
  469. if (end[i] < start[i]) {
  470. partialHeights[i] = backupHeights[i];
  471. } else {
  472. seqCount++;
  473. }
  474. }
  475. if (seqCount == 0) {
  476. return 0;
  477. }
  478. // determine next step
  479. int step;
  480. if (backupHeights[0] == 0 && backupHeights[1] == 0) {
  481. // this is the first step: choose the maximum increase, so that
  482. // the smallest area in the first page will contain at least
  483. // a label area and a body area
  484. step = Math.max((end[0] >= start[0] ? partialHeights[0] : Integer.MIN_VALUE),
  485. (end[1] >= start[1] ? partialHeights[1] : Integer.MIN_VALUE));
  486. } else {
  487. // this is not the first step: choose the minimum increase
  488. step = Math.min((end[0] >= start[0] ? partialHeights[0] : Integer.MAX_VALUE),
  489. (end[1] >= start[1] ? partialHeights[1] : Integer.MAX_VALUE));
  490. }
  491. // reset bigger-than-step sequences
  492. for (int i = 0; i < partialHeights.length; i++) {
  493. if (partialHeights[i] > step) {
  494. partialHeights[i] = backupHeights[i];
  495. end[i] = start[i] - 1;
  496. }
  497. }
  498. return step;
  499. }
  500. private int getMaxRemainingHeight(int[] fullHeights, int[] partialHeights) {
  501. return Math.max(fullHeights[0] - partialHeights[0],
  502. fullHeights[1] - partialHeights[1]);
  503. }
  504. /** {@inheritDoc} */
  505. @Override
  506. public List getChangedKnuthElements(List oldList, int alignment) {
  507. // label
  508. labelList = label.getChangedKnuthElements(labelList, alignment);
  509. // body
  510. // "unwrap" the Positions stored in the elements
  511. ListIterator oldListIterator = oldList.listIterator();
  512. KnuthElement oldElement;
  513. while (oldListIterator.hasNext()) {
  514. oldElement = (KnuthElement)oldListIterator.next();
  515. Position innerPosition = oldElement.getPosition().getPosition();
  516. if (innerPosition != null) {
  517. // oldElement was created by a descendant of this BlockLM
  518. oldElement.setPosition(innerPosition);
  519. } else {
  520. // thisElement was created by this BlockLM
  521. // modify its position in order to recognize it was not created
  522. // by a child
  523. oldElement.setPosition(new Position(this));
  524. }
  525. }
  526. List returnedList = body.getChangedKnuthElements(oldList, alignment);
  527. // "wrap" the Position inside each element
  528. List tempList = returnedList;
  529. KnuthElement tempElement;
  530. returnedList = new LinkedList();
  531. for (Object aTempList : tempList) {
  532. tempElement = (KnuthElement) aTempList;
  533. tempElement.setPosition(new NonLeafPosition(this, tempElement.getPosition()));
  534. returnedList.add(tempElement);
  535. }
  536. return returnedList;
  537. }
  538. @Override
  539. public boolean hasLineAreaDescendant() {
  540. return label.hasLineAreaDescendant() || body.hasLineAreaDescendant();
  541. }
  542. @Override
  543. public int getBaselineOffset() {
  544. if (label.hasLineAreaDescendant()) {
  545. return label.getBaselineOffset();
  546. } else if (body.hasLineAreaDescendant()) {
  547. return body.getBaselineOffset();
  548. } else {
  549. throw newNoLineAreaDescendantException();
  550. }
  551. }
  552. /**
  553. * Add the areas for the break points.
  554. *
  555. * @param parentIter the position iterator
  556. * @param layoutContext the layout context for adding areas
  557. */
  558. @Override
  559. public void addAreas(PositionIterator parentIter,
  560. LayoutContext layoutContext) {
  561. getParentArea(null);
  562. addId();
  563. LayoutContext lc = LayoutContext.offspringOf(layoutContext);
  564. Position firstPos = null;
  565. Position lastPos = null;
  566. // "unwrap" the NonLeafPositions stored in parentIter
  567. LinkedList<Position> positionList = new LinkedList<Position>();
  568. Position pos;
  569. while (parentIter.hasNext()) {
  570. pos = parentIter.next();
  571. if (pos.getIndex() >= 0) {
  572. if (firstPos == null) {
  573. firstPos = pos;
  574. }
  575. lastPos = pos;
  576. }
  577. if (pos instanceof NonLeafPosition && pos.getPosition() != null) {
  578. // pos contains a ListItemPosition created by this ListBlockLM
  579. positionList.add(pos.getPosition());
  580. }
  581. }
  582. if (positionList.isEmpty()) {
  583. reset();
  584. return;
  585. }
  586. registerMarkers(true, isFirst(firstPos), isLast(lastPos));
  587. // use the first and the last ListItemPosition to determine the
  588. // corresponding indexes in the original labelList and bodyList
  589. int labelFirstIndex = ((ListItemPosition) positionList.getFirst()).getLabelFirstIndex();
  590. int labelLastIndex = ((ListItemPosition) positionList.getLast()).getLabelLastIndex();
  591. int bodyFirstIndex = ((ListItemPosition) positionList.getFirst()).getBodyFirstIndex();
  592. int bodyLastIndex = ((ListItemPosition) positionList.getLast()).getBodyLastIndex();
  593. //Determine previous break if any (in item label list)
  594. int previousBreak = ElementListUtils.determinePreviousBreak(labelList, labelFirstIndex);
  595. SpaceResolver.performConditionalsNotification(labelList,
  596. labelFirstIndex, labelLastIndex, previousBreak);
  597. //Determine previous break if any (in item body list)
  598. previousBreak = ElementListUtils.determinePreviousBreak(bodyList, bodyFirstIndex);
  599. SpaceResolver.performConditionalsNotification(bodyList,
  600. bodyFirstIndex, bodyLastIndex, previousBreak);
  601. // add label areas
  602. if (labelFirstIndex <= labelLastIndex) {
  603. KnuthPossPosIter labelIter = new KnuthPossPosIter(labelList,
  604. labelFirstIndex, labelLastIndex + 1);
  605. lc.setFlags(LayoutContext.FIRST_AREA, layoutContext.isFirstArea());
  606. lc.setFlags(LayoutContext.LAST_AREA, layoutContext.isLastArea());
  607. // set the space adjustment ratio
  608. lc.setSpaceAdjust(layoutContext.getSpaceAdjust());
  609. // TO DO: use the right stack limit for the label
  610. lc.setStackLimitBP(layoutContext.getStackLimitBP());
  611. label.addAreas(labelIter, lc);
  612. }
  613. // add body areas
  614. if (bodyFirstIndex <= bodyLastIndex) {
  615. KnuthPossPosIter bodyIter = new KnuthPossPosIter(bodyList,
  616. bodyFirstIndex, bodyLastIndex + 1);
  617. lc.setFlags(LayoutContext.FIRST_AREA, layoutContext.isFirstArea());
  618. lc.setFlags(LayoutContext.LAST_AREA, layoutContext.isLastArea());
  619. // set the space adjustment ratio
  620. lc.setSpaceAdjust(layoutContext.getSpaceAdjust());
  621. // TO DO: use the right stack limit for the body
  622. lc.setStackLimitBP(layoutContext.getStackLimitBP());
  623. body.addAreas(bodyIter, lc);
  624. }
  625. // after adding body areas, set the maximum area bpd
  626. int childCount = curBlockArea.getChildAreas().size();
  627. assert childCount >= 1 && childCount <= 2;
  628. int itemBPD = ((Block)curBlockArea.getChildAreas().get(0)).getAllocBPD();
  629. if (childCount == 2) {
  630. itemBPD = Math.max(itemBPD, ((Block)curBlockArea.getChildAreas().get(1)).getAllocBPD());
  631. }
  632. curBlockArea.setBPD(itemBPD);
  633. registerMarkers(false, isFirst(firstPos), isLast(lastPos));
  634. // We are done with this area add the background
  635. TraitSetter.addBackground(curBlockArea,
  636. getListItemFO().getCommonBorderPaddingBackground(),
  637. this);
  638. TraitSetter.addSpaceBeforeAfter(curBlockArea, layoutContext.getSpaceAdjust(),
  639. effSpaceBefore, effSpaceAfter);
  640. flush();
  641. curBlockArea = null;
  642. resetSpaces();
  643. checkEndOfLayout(lastPos);
  644. }
  645. /**
  646. * Return an Area which can contain the passed childArea. The childArea
  647. * may not yet have any content, but it has essential traits set.
  648. * In general, if the LayoutManager already has an Area it simply returns
  649. * it. Otherwise, it makes a new Area of the appropriate class.
  650. * It gets a parent area for its area by calling its parent LM.
  651. * Finally, based on the dimensions of the parent area, it initializes
  652. * its own area. This includes setting the content IPD and the maximum
  653. * BPD.
  654. *
  655. * @param childArea the child area
  656. * @return the parent are for the child
  657. */
  658. @Override
  659. public Area getParentArea(Area childArea) {
  660. if (curBlockArea == null) {
  661. curBlockArea = new Block();
  662. curBlockArea.setChangeBarList(getChangeBarList());
  663. // Set up dimensions
  664. /*Area parentArea =*/ parentLayoutManager.getParentArea(curBlockArea);
  665. // set traits
  666. ListItem fo = getListItemFO();
  667. TraitSetter.setProducerID(curBlockArea, fo.getId());
  668. TraitSetter.addBorders(curBlockArea, fo.getCommonBorderPaddingBackground(),
  669. discardBorderBefore, discardBorderAfter, false, false, this);
  670. TraitSetter.addPadding(curBlockArea, fo.getCommonBorderPaddingBackground(),
  671. discardPaddingBefore, discardPaddingAfter, false, false, this);
  672. TraitSetter.addMargins(curBlockArea, fo.getCommonBorderPaddingBackground(),
  673. fo.getCommonMarginBlock(), this);
  674. TraitSetter.addBreaks(curBlockArea, fo.getBreakBefore(), fo.getBreakAfter());
  675. int contentIPD = referenceIPD - getIPIndents();
  676. curBlockArea.setIPD(contentIPD);
  677. curBlockArea.setBidiLevel(fo.getBidiLevel());
  678. setCurrentArea(curBlockArea);
  679. }
  680. return curBlockArea;
  681. }
  682. /**
  683. * Add the child.
  684. * Rows return the areas returned by the child elements.
  685. * This simply adds the area to the parent layout manager.
  686. *
  687. * @param childArea the child area
  688. */
  689. @Override
  690. public void addChildArea(Area childArea) {
  691. if (curBlockArea != null) {
  692. curBlockArea.addBlock((Block) childArea);
  693. }
  694. }
  695. /** {@inheritDoc} */
  696. @Override
  697. public KeepProperty getKeepTogetherProperty() {
  698. return getListItemFO().getKeepTogether();
  699. }
  700. /** {@inheritDoc} */
  701. @Override
  702. public KeepProperty getKeepWithPreviousProperty() {
  703. return getListItemFO().getKeepWithPrevious();
  704. }
  705. /** {@inheritDoc} */
  706. @Override
  707. public KeepProperty getKeepWithNextProperty() {
  708. return getListItemFO().getKeepWithNext();
  709. }
  710. /** {@inheritDoc} */
  711. @Override
  712. public void reset() {
  713. super.reset();
  714. label.reset();
  715. body.reset();
  716. }
  717. @Override
  718. public int getBreakBefore() {
  719. int breakBefore = BreakOpportunityHelper.getBreakBefore(this);
  720. breakBefore = BreakUtil.compareBreakClasses(breakBefore, label.getBreakBefore());
  721. breakBefore = BreakUtil.compareBreakClasses(breakBefore, body.getBreakBefore());
  722. return breakBefore;
  723. }
  724. /** {@inheritDoc} */
  725. public boolean isRestartable() {
  726. return true;
  727. }
  728. }