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.

TableStepper.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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.table;
  19. import java.util.Iterator;
  20. import java.util.LinkedList;
  21. import java.util.List;
  22. import org.apache.commons.logging.Log;
  23. import org.apache.commons.logging.LogFactory;
  24. import org.apache.fop.fo.Constants;
  25. import org.apache.fop.fo.flow.table.EffRow;
  26. import org.apache.fop.fo.flow.table.GridUnit;
  27. import org.apache.fop.fo.flow.table.PrimaryGridUnit;
  28. import org.apache.fop.layoutmgr.BreakElement;
  29. import org.apache.fop.layoutmgr.Keep;
  30. import org.apache.fop.layoutmgr.KnuthBlockBox;
  31. import org.apache.fop.layoutmgr.KnuthBox;
  32. import org.apache.fop.layoutmgr.KnuthGlue;
  33. import org.apache.fop.layoutmgr.KnuthPenalty;
  34. import org.apache.fop.layoutmgr.LayoutContext;
  35. import org.apache.fop.layoutmgr.Position;
  36. import org.apache.fop.util.BreakUtil;
  37. /**
  38. * This class processes row groups to create combined element lists for tables.
  39. */
  40. public class TableStepper {
  41. /** Logger **/
  42. private static Log log = LogFactory.getLog(TableStepper.class);
  43. private TableContentLayoutManager tclm;
  44. private EffRow[] rowGroup;
  45. /** Number of columns in the row group. */
  46. private int columnCount;
  47. private int totalHeight;
  48. private int previousRowsLength;
  49. private int activeRowIndex;
  50. private boolean rowFinished;
  51. /** Cells spanning the current row. */
  52. private List activeCells = new LinkedList();
  53. /** Cells that will start the next row. */
  54. private List nextActiveCells = new LinkedList();
  55. /**
  56. * True if the next row is being delayed, that is, if cells spanning the current and
  57. * the next row have steps smaller than the next row's first step. In this case the
  58. * next row may be extended to offer additional break possibilities.
  59. */
  60. private boolean delayingNextRow;
  61. /**
  62. * The first step for a row. This is the minimal step necessary to include some
  63. * content from all the cells starting the row.
  64. */
  65. private int rowFirstStep;
  66. /**
  67. * Flag used to produce an infinite penalty if the height of the current row is
  68. * smaller than the first step for that row (may happen with row-spanning cells).
  69. *
  70. * @see #considerRowLastStep(int)
  71. */
  72. private boolean rowHeightSmallerThanFirstStep;
  73. /**
  74. * The class of the next break. One of {@link Constants#EN_AUTO},
  75. * {@link Constants#EN_COLUMN}, {@link Constants#EN_PAGE},
  76. * {@link Constants#EN_EVEN_PAGE}, {@link Constants#EN_ODD_PAGE}. Defaults to
  77. * EN_AUTO.
  78. */
  79. private int nextBreakClass;
  80. /**
  81. * Main constructor
  82. * @param tclm The parent TableContentLayoutManager
  83. */
  84. public TableStepper(TableContentLayoutManager tclm) {
  85. this.tclm = tclm;
  86. this.columnCount = tclm.getTableLM().getTable().getNumberOfColumns();
  87. }
  88. /**
  89. * Initializes the fields of this instance to handle a new row group.
  90. *
  91. * @param rows the new row group to handle
  92. */
  93. private void setup(EffRow[] rows) {
  94. rowGroup = rows;
  95. previousRowsLength = 0;
  96. activeRowIndex = 0;
  97. activeCells.clear();
  98. nextActiveCells.clear();
  99. delayingNextRow = false;
  100. rowFirstStep = 0;
  101. rowHeightSmallerThanFirstStep = false;
  102. }
  103. private void calcTotalHeight() {
  104. totalHeight = 0;
  105. for (int i = 0; i < rowGroup.length; i++) {
  106. totalHeight += rowGroup[i].getHeight().opt;
  107. }
  108. if (log.isDebugEnabled()) {
  109. log.debug("totalHeight=" + totalHeight);
  110. }
  111. }
  112. private int getMaxRemainingHeight() {
  113. int maxW = 0;
  114. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  115. ActiveCell activeCell = (ActiveCell) iter.next();
  116. int remain = activeCell.getRemainingLength();
  117. PrimaryGridUnit pgu = activeCell.getPrimaryGridUnit();
  118. for (int i = activeRowIndex + 1; i < pgu.getRowIndex() - rowGroup[0].getIndex()
  119. + pgu.getCell().getNumberRowsSpanned(); i++) {
  120. remain -= rowGroup[i].getHeight().opt;
  121. }
  122. maxW = Math.max(maxW, remain);
  123. }
  124. for (int i = activeRowIndex + 1; i < rowGroup.length; i++) {
  125. maxW += rowGroup[i].getHeight().opt;
  126. }
  127. return maxW;
  128. }
  129. /**
  130. * Creates ActiveCell instances for cells starting on the row at the given index.
  131. *
  132. * @param activeCellList the list that will hold the active cells
  133. * @param rowIndex the index of the row from which cells must be activated
  134. */
  135. private void activateCells(List activeCellList, int rowIndex) {
  136. EffRow row = rowGroup[rowIndex];
  137. for (int i = 0; i < columnCount; i++) {
  138. GridUnit gu = row.getGridUnit(i);
  139. if (!gu.isEmpty() && gu.isPrimary()) {
  140. activeCellList.add(new ActiveCell((PrimaryGridUnit) gu, row, rowIndex,
  141. previousRowsLength, getTableLM()));
  142. }
  143. }
  144. }
  145. /**
  146. * Creates the combined element list for a row group.
  147. * @param context Active LayoutContext
  148. * @param rows the row group
  149. * @param bodyType Indicates what type of body is processed (body, header or footer)
  150. * @return the combined element list
  151. */
  152. public LinkedList getCombinedKnuthElementsForRowGroup(LayoutContext context, EffRow[] rows,
  153. int bodyType) {
  154. setup(rows);
  155. activateCells(activeCells, 0);
  156. calcTotalHeight();
  157. int cumulateLength = 0; // Length of the content accumulated before the break
  158. TableContentPosition lastTCPos = null;
  159. LinkedList returnList = new LinkedList();
  160. int laststep = 0;
  161. int step = getFirstStep();
  162. do {
  163. int maxRemainingHeight = getMaxRemainingHeight();
  164. int penaltyOrGlueLen = step + maxRemainingHeight - totalHeight;
  165. int boxLen = step - cumulateLength - Math.max(0, penaltyOrGlueLen)/* penalty, if any */;
  166. cumulateLength += boxLen + Math.max(0, -penaltyOrGlueLen)/* the glue, if any */;
  167. if (log.isDebugEnabled()) {
  168. log.debug("Next step: " + step + " (+" + (step - laststep) + ")");
  169. log.debug(" max remaining height: " + maxRemainingHeight);
  170. if (penaltyOrGlueLen >= 0) {
  171. log.debug(" box = " + boxLen + " penalty = " + penaltyOrGlueLen);
  172. } else {
  173. log.debug(" box = " + boxLen + " glue = " + (-penaltyOrGlueLen));
  174. }
  175. }
  176. LinkedList footnoteList = new LinkedList();
  177. //Put all involved grid units into a list
  178. List cellParts = new java.util.ArrayList(columnCount);
  179. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  180. ActiveCell activeCell = (ActiveCell) iter.next();
  181. CellPart part = activeCell.createCellPart();
  182. cellParts.add(part);
  183. activeCell.addFootnotes(footnoteList);
  184. }
  185. //Create elements for step
  186. TableContentPosition tcpos = new TableContentPosition(getTableLM(),
  187. cellParts, rowGroup[activeRowIndex]);
  188. if (delayingNextRow) {
  189. tcpos.setNewPageRow(rowGroup[activeRowIndex + 1]);
  190. }
  191. if (returnList.size() == 0) {
  192. tcpos.setFlag(TableContentPosition.FIRST_IN_ROWGROUP, true);
  193. }
  194. lastTCPos = tcpos;
  195. // TODO TableStepper should remain as footnote-agnostic as possible
  196. if (footnoteList.isEmpty()) {
  197. returnList.add(new KnuthBox(boxLen, tcpos, false));
  198. } else {
  199. returnList.add(new KnuthBlockBox(boxLen, footnoteList, tcpos, false));
  200. }
  201. int effPenaltyLen = Math.max(0, penaltyOrGlueLen);
  202. TableHFPenaltyPosition penaltyPos = new TableHFPenaltyPosition(getTableLM());
  203. if (bodyType == TableRowIterator.BODY) {
  204. if (!getTableLM().getTable().omitHeaderAtBreak()) {
  205. effPenaltyLen += tclm.getHeaderNetHeight();
  206. penaltyPos.headerElements = tclm.getHeaderElements();
  207. }
  208. if (!getTableLM().getTable().omitFooterAtBreak()) {
  209. effPenaltyLen += tclm.getFooterNetHeight();
  210. penaltyPos.footerElements = tclm.getFooterElements();
  211. }
  212. }
  213. Keep keep = Keep.KEEP_AUTO;
  214. int stepPenalty = 0;
  215. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  216. ActiveCell activeCell = (ActiveCell) iter.next();
  217. keep = keep.compare(activeCell.getKeepWithNext());
  218. stepPenalty = Math.max(stepPenalty, activeCell.getPenaltyValue());
  219. }
  220. if (!rowFinished) {
  221. keep = keep.compare(rowGroup[activeRowIndex].getKeepTogether());
  222. //The above call doesn't take the penalty from the table into account, so...
  223. keep = keep.compare(getTableLM().getKeepTogether());
  224. } else if (activeRowIndex < rowGroup.length - 1) {
  225. keep = keep.compare(rowGroup[activeRowIndex].getKeepWithNext());
  226. keep = keep.compare(rowGroup[activeRowIndex + 1].getKeepWithPrevious());
  227. nextBreakClass = BreakUtil.compareBreakClasses(nextBreakClass,
  228. rowGroup[activeRowIndex].getBreakAfter());
  229. nextBreakClass = BreakUtil.compareBreakClasses(nextBreakClass,
  230. rowGroup[activeRowIndex + 1].getBreakBefore());
  231. }
  232. int p = keep.getPenalty();
  233. if (rowHeightSmallerThanFirstStep) {
  234. rowHeightSmallerThanFirstStep = false;
  235. p = KnuthPenalty.INFINITE;
  236. }
  237. p = Math.max(p, stepPenalty);
  238. int breakClass = keep.getContext();
  239. if (nextBreakClass != Constants.EN_AUTO) {
  240. log.trace("Forced break encountered");
  241. p = -KnuthPenalty.INFINITE; //Overrides any keeps (see 4.8 in XSL 1.0)
  242. breakClass = nextBreakClass;
  243. }
  244. returnList.add(new BreakElement(penaltyPos, effPenaltyLen, p, breakClass, context));
  245. if (penaltyOrGlueLen < 0) {
  246. returnList.add(new KnuthGlue(-penaltyOrGlueLen, 0, 0, new Position(null), true));
  247. }
  248. laststep = step;
  249. step = getNextStep();
  250. } while (step >= 0);
  251. assert !returnList.isEmpty();
  252. lastTCPos.setFlag(TableContentPosition.LAST_IN_ROWGROUP, true);
  253. return returnList;
  254. }
  255. /**
  256. * Returns the first step for the current row group.
  257. *
  258. * @return the first step for the current row group
  259. */
  260. private int getFirstStep() {
  261. computeRowFirstStep(activeCells);
  262. signalRowFirstStep();
  263. int minStep = considerRowLastStep(rowFirstStep);
  264. signalNextStep(minStep);
  265. return minStep;
  266. }
  267. /**
  268. * Returns the next break possibility.
  269. *
  270. * @return the next step
  271. */
  272. private int getNextStep() {
  273. if (rowFinished) {
  274. if (activeRowIndex == rowGroup.length - 1) {
  275. // The row group is finished, no next step
  276. return -1;
  277. }
  278. rowFinished = false;
  279. removeCellsEndingOnCurrentRow();
  280. log.trace("Delaying next row");
  281. delayingNextRow = true;
  282. }
  283. if (delayingNextRow) {
  284. int minStep = computeMinStep();
  285. if (minStep < 0 || minStep >= rowFirstStep
  286. || minStep > rowGroup[activeRowIndex].getExplicitHeight().max) {
  287. if (log.isTraceEnabled()) {
  288. log.trace("Step = " + minStep);
  289. }
  290. delayingNextRow = false;
  291. minStep = rowFirstStep;
  292. switchToNextRow();
  293. signalRowFirstStep();
  294. minStep = considerRowLastStep(minStep);
  295. }
  296. signalNextStep(minStep);
  297. return minStep;
  298. } else {
  299. int minStep = computeMinStep();
  300. minStep = considerRowLastStep(minStep);
  301. signalNextStep(minStep);
  302. return minStep;
  303. }
  304. }
  305. /**
  306. * Computes the minimal necessary step to make the next row fit. That is, so such as
  307. * cell on the next row can contribute some content.
  308. *
  309. * @param cells the cells occupying the next row (may include cells starting on
  310. * previous rows and spanning over this one)
  311. */
  312. private void computeRowFirstStep(List cells) {
  313. for (Iterator iter = cells.iterator(); iter.hasNext();) {
  314. ActiveCell activeCell = (ActiveCell) iter.next();
  315. rowFirstStep = Math.max(rowFirstStep, activeCell.getFirstStep());
  316. }
  317. }
  318. /**
  319. * Computes the next minimal step.
  320. *
  321. * @return the minimal step from the active cells, &lt; 0 if there is no such step
  322. */
  323. private int computeMinStep() {
  324. int minStep = Integer.MAX_VALUE;
  325. boolean stepFound = false;
  326. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  327. ActiveCell activeCell = (ActiveCell) iter.next();
  328. int nextStep = activeCell.getNextStep();
  329. if (nextStep >= 0) {
  330. stepFound = true;
  331. minStep = Math.min(minStep, nextStep);
  332. }
  333. }
  334. if (stepFound) {
  335. return minStep;
  336. } else {
  337. return -1;
  338. }
  339. }
  340. /**
  341. * Signals the first step to the active cells, to allow them to add more content to
  342. * the step if possible.
  343. *
  344. * @see ActiveCell#signalRowFirstStep(int)
  345. */
  346. private void signalRowFirstStep() {
  347. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  348. ActiveCell activeCell = (ActiveCell) iter.next();
  349. activeCell.signalRowFirstStep(rowFirstStep);
  350. }
  351. }
  352. /**
  353. * Signals the next selected step to the active cells.
  354. *
  355. * @param step the next step
  356. */
  357. private void signalNextStep(int step) {
  358. nextBreakClass = Constants.EN_AUTO;
  359. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  360. ActiveCell activeCell = (ActiveCell) iter.next();
  361. nextBreakClass = BreakUtil.compareBreakClasses(nextBreakClass,
  362. activeCell.signalNextStep(step));
  363. }
  364. }
  365. /**
  366. * Determines if the given step will finish the current row, and if so switch to the
  367. * last step for this row.
  368. * <p>If the row is finished then the after borders for the cell may change (their
  369. * conditionalities no longer apply for the cells ending on the current row). Thus the
  370. * final step may grow with respect to the given one.</p>
  371. * <p>In more rare occasions, the given step may correspond to the first step of a
  372. * row-spanning cell, and may be greater than the height of the current row (consider,
  373. * for example, an unbreakable cell spanning three rows). In such a case the returned
  374. * step will correspond to the row height and a flag will be set to produce an
  375. * infinite penalty for this step. This will prevent the breaking algorithm from
  376. * choosing this break, but still allow to create the appropriate TableContentPosition
  377. * for the cells ending on the current row.</p>
  378. *
  379. * @param step the next step
  380. * @return the updated step if any
  381. */
  382. private int considerRowLastStep(int step) {
  383. rowFinished = true;
  384. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  385. ActiveCell activeCell = (ActiveCell) iter.next();
  386. if (activeCell.endsOnRow(activeRowIndex)) {
  387. rowFinished &= activeCell.finishes(step);
  388. }
  389. }
  390. if (rowFinished) {
  391. if (log.isTraceEnabled()) {
  392. log.trace("Step = " + step);
  393. log.trace("Row finished, computing last step");
  394. }
  395. int maxStep = 0;
  396. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  397. ActiveCell activeCell = (ActiveCell) iter.next();
  398. if (activeCell.endsOnRow(activeRowIndex)) {
  399. maxStep = Math.max(maxStep, activeCell.getLastStep());
  400. }
  401. }
  402. if (log.isTraceEnabled()) {
  403. log.trace("Max step: " + maxStep);
  404. }
  405. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  406. ActiveCell activeCell = (ActiveCell) iter.next();
  407. activeCell.endRow(activeRowIndex);
  408. if (!activeCell.endsOnRow(activeRowIndex)) {
  409. activeCell.signalRowLastStep(maxStep);
  410. }
  411. }
  412. if (maxStep < step) {
  413. log.trace("Row height smaller than first step, produced penalty will be infinite");
  414. rowHeightSmallerThanFirstStep = true;
  415. }
  416. step = maxStep;
  417. prepareNextRow();
  418. }
  419. return step;
  420. }
  421. /**
  422. * Pre-activates the cells that will start the next row, and computes the first step
  423. * for that row.
  424. */
  425. private void prepareNextRow() {
  426. if (activeRowIndex < rowGroup.length - 1) {
  427. previousRowsLength += rowGroup[activeRowIndex].getHeight().opt;
  428. activateCells(nextActiveCells, activeRowIndex + 1);
  429. if (log.isTraceEnabled()) {
  430. log.trace("Computing first step for row " + (activeRowIndex + 2));
  431. }
  432. computeRowFirstStep(nextActiveCells);
  433. if (log.isTraceEnabled()) {
  434. log.trace("Next first step = " + rowFirstStep);
  435. }
  436. }
  437. }
  438. private void removeCellsEndingOnCurrentRow() {
  439. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  440. ActiveCell activeCell = (ActiveCell) iter.next();
  441. if (activeCell.endsOnRow(activeRowIndex)) {
  442. iter.remove();
  443. }
  444. }
  445. }
  446. /**
  447. * Actually switches to the next row, increasing activeRowIndex and transferring to
  448. * activeCells the cells starting on the next row.
  449. */
  450. private void switchToNextRow() {
  451. activeRowIndex++;
  452. if (log.isTraceEnabled()) {
  453. log.trace("Switching to row " + (activeRowIndex + 1));
  454. }
  455. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  456. ActiveCell activeCell = (ActiveCell) iter.next();
  457. activeCell.nextRowStarts();
  458. }
  459. activeCells.addAll(nextActiveCells);
  460. nextActiveCells.clear();
  461. }
  462. /** @return the table layout manager */
  463. private TableLayoutManager getTableLM() {
  464. return this.tclm.getTableLM();
  465. }
  466. }