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 20KB

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