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

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