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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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 (EffRow aRowGroup : rowGroup) {
  106. totalHeight += aRowGroup.getHeight().getOpt();
  107. }
  108. if (log.isDebugEnabled()) {
  109. log.debug("totalHeight=" + totalHeight);
  110. }
  111. }
  112. private int getMaxRemainingHeight() {
  113. int maxW = 0;
  114. for (Object activeCell1 : activeCells) {
  115. ActiveCell activeCell = (ActiveCell) activeCell1;
  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().getOpt();
  121. }
  122. maxW = Math.max(maxW, remain);
  123. }
  124. for (int i = activeRowIndex + 1; i < rowGroup.length; i++) {
  125. maxW += rowGroup[i].getHeight().getOpt();
  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. assert (gu instanceof PrimaryGridUnit);
  141. activeCellList.add(new ActiveCell((PrimaryGridUnit) gu, row, rowIndex,
  142. previousRowsLength, getTableLM()));
  143. }
  144. }
  145. }
  146. /**
  147. * Creates the combined element list for a row group.
  148. * @param context Active LayoutContext
  149. * @param rows the row group
  150. * @param bodyType Indicates what type of body is processed (body, header or footer)
  151. * @return the combined element list
  152. */
  153. public LinkedList getCombinedKnuthElementsForRowGroup(LayoutContext context, EffRow[] rows,
  154. int bodyType) {
  155. setup(rows);
  156. activateCells(activeCells, 0);
  157. calcTotalHeight();
  158. int cumulateLength = 0; // Length of the content accumulated before the break
  159. TableContentPosition lastTCPos = null;
  160. LinkedList returnList = new LinkedList();
  161. int laststep = 0;
  162. int step = getFirstStep();
  163. do {
  164. int maxRemainingHeight = getMaxRemainingHeight();
  165. int penaltyOrGlueLen = step + maxRemainingHeight - totalHeight;
  166. int boxLen = step - cumulateLength - Math.max(0, penaltyOrGlueLen)/* penalty, if any */;
  167. cumulateLength += boxLen + Math.max(0, -penaltyOrGlueLen)/* the glue, if any */;
  168. if (log.isDebugEnabled()) {
  169. log.debug("Next step: " + step + " (+" + (step - laststep) + ")");
  170. log.debug(" max remaining height: " + maxRemainingHeight);
  171. if (penaltyOrGlueLen >= 0) {
  172. log.debug(" box = " + boxLen + " penalty = " + penaltyOrGlueLen);
  173. } else {
  174. log.debug(" box = " + boxLen + " glue = " + (-penaltyOrGlueLen));
  175. }
  176. }
  177. LinkedList footnoteList = new LinkedList();
  178. //Put all involved grid units into a list
  179. List cellParts = new java.util.ArrayList(activeCells.size());
  180. for (Object activeCell2 : activeCells) {
  181. ActiveCell activeCell = (ActiveCell) activeCell2;
  182. CellPart part = activeCell.createCellPart();
  183. cellParts.add(part);
  184. activeCell.addFootnotes(footnoteList);
  185. }
  186. //Create elements for step
  187. TableContentPosition tcpos = new TableContentPosition(getTableLM(),
  188. cellParts, rowGroup[activeRowIndex]);
  189. if (delayingNextRow) {
  190. tcpos.setNewPageRow(rowGroup[activeRowIndex + 1]);
  191. }
  192. if (returnList.size() == 0) {
  193. tcpos.setFlag(TableContentPosition.FIRST_IN_ROWGROUP, true);
  194. }
  195. lastTCPos = tcpos;
  196. // TODO TableStepper should remain as footnote-agnostic as possible
  197. if (footnoteList.isEmpty()) {
  198. returnList.add(new KnuthBox(boxLen, tcpos, false));
  199. } else {
  200. returnList.add(new KnuthBlockBox(boxLen, footnoteList, tcpos, false));
  201. }
  202. int effPenaltyLen = Math.max(0, penaltyOrGlueLen);
  203. TableHFPenaltyPosition penaltyPos = new TableHFPenaltyPosition(getTableLM());
  204. if (bodyType == TableRowIterator.BODY) {
  205. if (!getTableLM().getTable().omitHeaderAtBreak()) {
  206. effPenaltyLen += tclm.getHeaderNetHeight();
  207. penaltyPos.headerElements = tclm.getHeaderElements();
  208. }
  209. if (!getTableLM().getTable().omitFooterAtBreak()) {
  210. effPenaltyLen += tclm.getFooterNetHeight();
  211. penaltyPos.footerElements = tclm.getFooterElements();
  212. }
  213. }
  214. Keep keep = getTableLM().getKeepTogether();
  215. int stepPenalty = 0;
  216. for (Object activeCell1 : activeCells) {
  217. ActiveCell activeCell = (ActiveCell) activeCell1;
  218. keep = keep.compare(activeCell.getKeepWithNext());
  219. stepPenalty = Math.max(stepPenalty, activeCell.getPenaltyValue());
  220. }
  221. if (!rowFinished) {
  222. keep = keep.compare(rowGroup[activeRowIndex].getKeepTogether());
  223. } else if (activeRowIndex < rowGroup.length - 1) {
  224. keep = keep.compare(rowGroup[activeRowIndex].getKeepWithNext());
  225. keep = keep.compare(rowGroup[activeRowIndex + 1].getKeepWithPrevious());
  226. nextBreakClass = BreakUtil.compareBreakClasses(nextBreakClass,
  227. rowGroup[activeRowIndex].getBreakAfter());
  228. nextBreakClass = BreakUtil.compareBreakClasses(nextBreakClass,
  229. rowGroup[activeRowIndex + 1].getBreakBefore());
  230. }
  231. int p = keep.getPenalty();
  232. if (rowHeightSmallerThanFirstStep) {
  233. rowHeightSmallerThanFirstStep = false;
  234. p = KnuthPenalty.INFINITE;
  235. }
  236. p = Math.max(p, stepPenalty);
  237. int breakClass = keep.getContext();
  238. if (nextBreakClass != Constants.EN_AUTO) {
  239. log.trace("Forced break encountered");
  240. p = -KnuthPenalty.INFINITE; //Overrides any keeps (see 4.8 in XSL 1.0)
  241. breakClass = nextBreakClass;
  242. }
  243. returnList.add(new BreakElement(penaltyPos, effPenaltyLen, p, breakClass, context));
  244. laststep = step;
  245. step = getNextStep();
  246. if (penaltyOrGlueLen < 0) {
  247. if (step < 0) {
  248. returnList.add(new KnuthGlue(0, -penaltyOrGlueLen, 0, new Position(null), true));
  249. } else {
  250. returnList.add(new KnuthGlue(-penaltyOrGlueLen, 0, 0, new Position(null), true));
  251. }
  252. }
  253. } while (step >= 0);
  254. assert !returnList.isEmpty();
  255. lastTCPos.setFlag(TableContentPosition.LAST_IN_ROWGROUP, true);
  256. return returnList;
  257. }
  258. /**
  259. * Returns the first step for the current row group.
  260. *
  261. * @return the first step for the current row group
  262. */
  263. private int getFirstStep() {
  264. computeRowFirstStep(activeCells);
  265. signalRowFirstStep();
  266. int minStep = considerRowLastStep(rowFirstStep);
  267. signalNextStep(minStep);
  268. return minStep;
  269. }
  270. /**
  271. * Returns the next break possibility.
  272. *
  273. * @return the next step
  274. */
  275. private int getNextStep() {
  276. if (rowFinished) {
  277. if (activeRowIndex == rowGroup.length - 1) {
  278. // The row group is finished, no next step
  279. return -1;
  280. }
  281. rowFinished = false;
  282. removeCellsEndingOnCurrentRow();
  283. log.trace("Delaying next row");
  284. delayingNextRow = true;
  285. }
  286. if (delayingNextRow) {
  287. int minStep = computeMinStep();
  288. if (minStep < 0 || minStep >= rowFirstStep
  289. || minStep > rowGroup[activeRowIndex].getExplicitHeight().getMax()) {
  290. if (log.isTraceEnabled()) {
  291. log.trace("Step = " + minStep);
  292. }
  293. delayingNextRow = false;
  294. minStep = rowFirstStep;
  295. switchToNextRow();
  296. signalRowFirstStep();
  297. minStep = considerRowLastStep(minStep);
  298. }
  299. signalNextStep(minStep);
  300. return minStep;
  301. } else {
  302. int minStep = computeMinStep();
  303. minStep = considerRowLastStep(minStep);
  304. signalNextStep(minStep);
  305. return minStep;
  306. }
  307. }
  308. /**
  309. * Computes the minimal necessary step to make the next row fit. That is, so such as
  310. * cell on the next row can contribute some content.
  311. *
  312. * @param cells the cells occupying the next row (may include cells starting on
  313. * previous rows and spanning over this one)
  314. */
  315. private void computeRowFirstStep(List cells) {
  316. for (Object cell : cells) {
  317. ActiveCell activeCell = (ActiveCell) cell;
  318. rowFirstStep = Math.max(rowFirstStep, activeCell.getFirstStep());
  319. }
  320. }
  321. /**
  322. * Computes the next minimal step.
  323. *
  324. * @return the minimal step from the active cells, &lt; 0 if there is no such step
  325. */
  326. private int computeMinStep() {
  327. int minStep = Integer.MAX_VALUE;
  328. boolean stepFound = false;
  329. for (Object activeCell1 : activeCells) {
  330. ActiveCell activeCell = (ActiveCell) activeCell1;
  331. int nextStep = activeCell.getNextStep();
  332. if (nextStep >= 0) {
  333. stepFound = true;
  334. minStep = Math.min(minStep, nextStep);
  335. }
  336. }
  337. if (stepFound) {
  338. return minStep;
  339. } else {
  340. return -1;
  341. }
  342. }
  343. /**
  344. * Signals the first step to the active cells, to allow them to add more content to
  345. * the step if possible.
  346. *
  347. * @see ActiveCell#signalRowFirstStep(int)
  348. */
  349. private void signalRowFirstStep() {
  350. for (Object activeCell1 : activeCells) {
  351. ActiveCell activeCell = (ActiveCell) activeCell1;
  352. activeCell.signalRowFirstStep(rowFirstStep);
  353. }
  354. }
  355. /**
  356. * Signals the next selected step to the active cells.
  357. *
  358. * @param step the next step
  359. */
  360. private void signalNextStep(int step) {
  361. nextBreakClass = Constants.EN_AUTO;
  362. for (Object activeCell1 : activeCells) {
  363. ActiveCell activeCell = (ActiveCell) activeCell1;
  364. nextBreakClass = BreakUtil.compareBreakClasses(nextBreakClass,
  365. activeCell.signalNextStep(step));
  366. }
  367. }
  368. /**
  369. * Determines if the given step will finish the current row, and if so switch to the
  370. * last step for this row.
  371. * <p>If the row is finished then the after borders for the cell may change (their
  372. * conditionalities no longer apply for the cells ending on the current row). Thus the
  373. * final step may grow with respect to the given one.</p>
  374. * <p>In more rare occasions, the given step may correspond to the first step of a
  375. * row-spanning cell, and may be greater than the height of the current row (consider,
  376. * for example, an unbreakable cell spanning three rows). In such a case the returned
  377. * step will correspond to the row height and a flag will be set to produce an
  378. * infinite penalty for this step. This will prevent the breaking algorithm from
  379. * choosing this break, but still allow to create the appropriate TableContentPosition
  380. * for the cells ending on the current row.</p>
  381. *
  382. * @param step the next step
  383. * @return the updated step if any
  384. */
  385. private int considerRowLastStep(int step) {
  386. rowFinished = true;
  387. for (Object activeCell3 : activeCells) {
  388. ActiveCell activeCell = (ActiveCell) activeCell3;
  389. if (activeCell.endsOnRow(activeRowIndex)) {
  390. if (!activeCell.finishes(step)) {
  391. rowFinished = false;
  392. }
  393. }
  394. }
  395. if (rowFinished) {
  396. if (log.isTraceEnabled()) {
  397. log.trace("Step = " + step);
  398. log.trace("Row finished, computing last step");
  399. }
  400. int maxStep = 0;
  401. for (Object activeCell2 : activeCells) {
  402. ActiveCell activeCell = (ActiveCell) activeCell2;
  403. if (activeCell.endsOnRow(activeRowIndex)) {
  404. maxStep = Math.max(maxStep, activeCell.getLastStep());
  405. }
  406. }
  407. if (log.isTraceEnabled()) {
  408. log.trace("Max step: " + maxStep);
  409. }
  410. for (Object activeCell1 : activeCells) {
  411. ActiveCell activeCell = (ActiveCell) activeCell1;
  412. activeCell.endRow(activeRowIndex);
  413. if (!activeCell.endsOnRow(activeRowIndex)) {
  414. activeCell.signalRowLastStep(maxStep);
  415. }
  416. }
  417. if (maxStep < step) {
  418. log.trace("Row height smaller than first step, produced penalty will be infinite");
  419. rowHeightSmallerThanFirstStep = true;
  420. }
  421. step = maxStep;
  422. prepareNextRow();
  423. }
  424. return step;
  425. }
  426. /**
  427. * Pre-activates the cells that will start the next row, and computes the first step
  428. * for that row.
  429. */
  430. private void prepareNextRow() {
  431. if (activeRowIndex < rowGroup.length - 1) {
  432. previousRowsLength += rowGroup[activeRowIndex].getHeight().getOpt();
  433. activateCells(nextActiveCells, activeRowIndex + 1);
  434. if (log.isTraceEnabled()) {
  435. log.trace("Computing first step for row " + (activeRowIndex + 2));
  436. }
  437. computeRowFirstStep(nextActiveCells);
  438. if (log.isTraceEnabled()) {
  439. log.trace("Next first step = " + rowFirstStep);
  440. }
  441. }
  442. }
  443. private void removeCellsEndingOnCurrentRow() {
  444. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  445. ActiveCell activeCell = (ActiveCell) iter.next();
  446. if (activeCell.endsOnRow(activeRowIndex)) {
  447. iter.remove();
  448. }
  449. }
  450. }
  451. /**
  452. * Actually switches to the next row, increasing activeRowIndex and transferring to
  453. * activeCells the cells starting on the next row.
  454. */
  455. private void switchToNextRow() {
  456. activeRowIndex++;
  457. if (log.isTraceEnabled()) {
  458. log.trace("Switching to row " + (activeRowIndex + 1));
  459. }
  460. for (Object activeCell1 : activeCells) {
  461. ActiveCell activeCell = (ActiveCell) activeCell1;
  462. activeCell.nextRowStarts();
  463. }
  464. activeCells.addAll(nextActiveCells);
  465. nextActiveCells.clear();
  466. }
  467. /** @return the table layout manager */
  468. private TableLayoutManager getTableLM() {
  469. return this.tclm.getTableLM();
  470. }
  471. }