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

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