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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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.BlockLevelLayoutManager;
  29. import org.apache.fop.layoutmgr.BreakElement;
  30. import org.apache.fop.layoutmgr.KeepUtil;
  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 (int i = 0; i < rowGroup.length; i++) {
  107. totalHeight += rowGroup[i].getHeight().opt;
  108. }
  109. if (log.isDebugEnabled()) {
  110. log.debug("totalHeight=" + totalHeight);
  111. }
  112. }
  113. private int getMaxRemainingHeight() {
  114. int maxW = 0;
  115. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  116. ActiveCell activeCell = (ActiveCell) iter.next();
  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().opt;
  122. }
  123. maxW = Math.max(maxW, remain);
  124. }
  125. for (int i = activeRowIndex + 1; i < rowGroup.length; i++) {
  126. maxW += rowGroup[i].getHeight().opt;
  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. 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. //Put all involved grid units into a list
  178. int stepPenalty = 0;
  179. List cellParts = new java.util.ArrayList(columnCount);
  180. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  181. ActiveCell activeCell = (ActiveCell) iter.next();
  182. CellPart part = activeCell.createCellPart();
  183. cellParts.add(part);
  184. //Record highest penalty value of part
  185. if (part.end >= 0) {
  186. KnuthElement endEl = (KnuthElement)part.pgu.getElements().get(part.end);
  187. if (endEl instanceof KnuthPenalty) {
  188. stepPenalty = Math.max(stepPenalty, endEl.getP());
  189. }
  190. }
  191. }
  192. //Create elements for step
  193. TableContentPosition tcpos = new TableContentPosition(getTableLM(),
  194. cellParts, rowGroup[activeRowIndex]);
  195. if (delayingNextRow) {
  196. tcpos.setNewPageRow(rowGroup[activeRowIndex + 1]);
  197. }
  198. if (returnList.size() == 0) {
  199. tcpos.setFlag(TableContentPosition.FIRST_IN_ROWGROUP, true);
  200. }
  201. lastTCPos = tcpos;
  202. returnList.add(new KnuthBox(boxLen, tcpos, false));
  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. int strength = BlockLevelLayoutManager.KEEP_AUTO;
  216. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  217. ActiveCell activeCell = (ActiveCell) iter.next();
  218. strength = Math.max(strength, activeCell.getKeepWithNextStrength());
  219. }
  220. if (!rowFinished) {
  221. strength = Math.max(strength, rowGroup[activeRowIndex].getKeepTogetherStrength());
  222. //The above call doesn't take the penalty from the table into account, so...
  223. strength = Math.max(strength, getTableLM().getKeepTogetherStrength());
  224. } else if (activeRowIndex < rowGroup.length - 1) {
  225. strength = Math.max(strength,
  226. rowGroup[activeRowIndex].getKeepWithNextStrength());
  227. strength = Math.max(strength,
  228. rowGroup[activeRowIndex + 1].getKeepWithPreviousStrength());
  229. nextBreakClass = BreakUtil.compareBreakClasses(nextBreakClass,
  230. rowGroup[activeRowIndex].getBreakAfter());
  231. nextBreakClass = BreakUtil.compareBreakClasses(nextBreakClass,
  232. rowGroup[activeRowIndex + 1].getBreakBefore());
  233. }
  234. int p = KeepUtil.getPenaltyForKeep(strength);
  235. if (rowHeightSmallerThanFirstStep) {
  236. rowHeightSmallerThanFirstStep = false;
  237. p = KnuthPenalty.INFINITE;
  238. }
  239. if (p > -KnuthElement.INFINITE) {
  240. p = Math.max(p, stepPenalty);
  241. }
  242. if (nextBreakClass != Constants.EN_AUTO) {
  243. log.trace("Forced break encountered");
  244. p = -KnuthPenalty.INFINITE; //Overrides any keeps (see 4.8 in XSL 1.0)
  245. }
  246. returnList.add(new BreakElement(penaltyPos, effPenaltyLen, p, nextBreakClass, context));
  247. if (penaltyOrGlueLen < 0) {
  248. returnList.add(new KnuthGlue(-penaltyOrGlueLen, 0, 0, new Position(null), true));
  249. }
  250. laststep = step;
  251. step = getNextStep();
  252. } while (step >= 0);
  253. if (!returnList.isEmpty()) {
  254. lastTCPos.setFlag(TableContentPosition.LAST_IN_ROWGROUP, true);
  255. // It's not up to TableStepper to decide whether there can/must be a break
  256. // after the row group or not, but to ancestor stacking elements
  257. assert returnList.getLast() instanceof BreakElement;
  258. returnList.removeLast();
  259. }
  260. return returnList;
  261. }
  262. /**
  263. * Returns the first step for the current row group.
  264. *
  265. * @return the first step for the current row group
  266. */
  267. private int getFirstStep() {
  268. computeRowFirstStep(activeCells);
  269. signalRowFirstStep();
  270. int minStep = considerRowLastStep(rowFirstStep);
  271. signalNextStep(minStep);
  272. return minStep;
  273. }
  274. /**
  275. * Returns the next break possibility.
  276. *
  277. * @return the next step
  278. */
  279. private int getNextStep() {
  280. if (rowFinished) {
  281. if (activeRowIndex == rowGroup.length - 1) {
  282. // The row group is finished, no next step
  283. return -1;
  284. }
  285. rowFinished = false;
  286. removeCellsEndingOnCurrentRow();
  287. log.trace("Delaying next row");
  288. delayingNextRow = true;
  289. }
  290. if (delayingNextRow) {
  291. int minStep = computeMinStep();
  292. if (minStep < 0 || minStep >= rowFirstStep
  293. || minStep > rowGroup[activeRowIndex].getExplicitHeight().max) {
  294. if (log.isTraceEnabled()) {
  295. log.trace("Step = " + minStep);
  296. }
  297. delayingNextRow = false;
  298. minStep = rowFirstStep;
  299. switchToNextRow();
  300. signalRowFirstStep();
  301. minStep = considerRowLastStep(minStep);
  302. }
  303. signalNextStep(minStep);
  304. return minStep;
  305. } else {
  306. int minStep = computeMinStep();
  307. minStep = considerRowLastStep(minStep);
  308. signalNextStep(minStep);
  309. return minStep;
  310. }
  311. }
  312. /**
  313. * Computes the minimal necessary step to make the next row fit. That is, so such as
  314. * cell on the next row can contribute some content.
  315. *
  316. * @param cells the cells occupying the next row (may include cells starting on
  317. * previous rows and spanning over this one)
  318. */
  319. private void computeRowFirstStep(List cells) {
  320. for (Iterator iter = cells.iterator(); iter.hasNext();) {
  321. ActiveCell activeCell = (ActiveCell) iter.next();
  322. rowFirstStep = Math.max(rowFirstStep, activeCell.getFirstStep());
  323. }
  324. }
  325. /**
  326. * Computes the next minimal step.
  327. *
  328. * @return the minimal step from the active cells, &lt; 0 if there is no such step
  329. */
  330. private int computeMinStep() {
  331. int minStep = Integer.MAX_VALUE;
  332. boolean stepFound = false;
  333. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  334. ActiveCell activeCell = (ActiveCell) iter.next();
  335. int nextStep = activeCell.getNextStep();
  336. if (nextStep >= 0) {
  337. stepFound = true;
  338. minStep = Math.min(minStep, nextStep);
  339. }
  340. }
  341. if (stepFound) {
  342. return minStep;
  343. } else {
  344. return -1;
  345. }
  346. }
  347. /**
  348. * Signals the first step to the active cells, to allow them to add more content to
  349. * the step if possible.
  350. *
  351. * @see ActiveCell#signalRowFirstStep(int)
  352. */
  353. private void signalRowFirstStep() {
  354. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  355. ActiveCell activeCell = (ActiveCell) iter.next();
  356. activeCell.signalRowFirstStep(rowFirstStep);
  357. }
  358. }
  359. /**
  360. * Signals the next selected step to the active cells.
  361. *
  362. * @param step the next step
  363. */
  364. private void signalNextStep(int step) {
  365. nextBreakClass = Constants.EN_AUTO;
  366. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  367. ActiveCell activeCell = (ActiveCell) iter.next();
  368. nextBreakClass = BreakUtil.compareBreakClasses(nextBreakClass,
  369. activeCell.signalNextStep(step));
  370. }
  371. }
  372. /**
  373. * Determines if the given step will finish the current row, and if so switch to the
  374. * last step for this row.
  375. * <p>If the row is finished then the after borders for the cell may change (their
  376. * conditionalities no longer apply for the cells ending on the current row). Thus the
  377. * final step may grow with respect to the given one.</p>
  378. * <p>In more rare occasions, the given step may correspond to the first step of a
  379. * row-spanning cell, and may be greater than the height of the current row (consider,
  380. * for example, an unbreakable cell spanning three rows). In such a case the returned
  381. * step will correspond to the row height and a flag will be set to produce an
  382. * infinite penalty for this step. This will prevent the breaking algorithm from
  383. * choosing this break, but still allow to create the appropriate TableContentPosition
  384. * for the cells ending on the current row.</p>
  385. *
  386. * @param step the next step
  387. * @return the updated step if any
  388. */
  389. private int considerRowLastStep(int step) {
  390. rowFinished = true;
  391. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  392. ActiveCell activeCell = (ActiveCell) iter.next();
  393. if (activeCell.endsOnRow(activeRowIndex)) {
  394. rowFinished &= activeCell.finishes(step);
  395. }
  396. }
  397. if (rowFinished) {
  398. if (log.isTraceEnabled()) {
  399. log.trace("Step = " + step);
  400. log.trace("Row finished, computing last step");
  401. }
  402. int maxStep = 0;
  403. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  404. ActiveCell activeCell = (ActiveCell) iter.next();
  405. if (activeCell.endsOnRow(activeRowIndex)) {
  406. maxStep = Math.max(maxStep, activeCell.getLastStep());
  407. }
  408. }
  409. if (log.isTraceEnabled()) {
  410. log.trace("Max step: " + maxStep);
  411. }
  412. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  413. ActiveCell activeCell = (ActiveCell) iter.next();
  414. activeCell.endRow(activeRowIndex);
  415. if (!activeCell.endsOnRow(activeRowIndex)) {
  416. activeCell.signalRowLastStep(maxStep);
  417. }
  418. }
  419. if (maxStep < step) {
  420. log.trace("Row height smaller than first step, produced penalty will be infinite");
  421. rowHeightSmallerThanFirstStep = true;
  422. }
  423. step = maxStep;
  424. prepareNextRow();
  425. }
  426. return step;
  427. }
  428. /**
  429. * Pre-activates the cells that will start the next row, and computes the first step
  430. * for that row.
  431. */
  432. private void prepareNextRow() {
  433. if (activeRowIndex < rowGroup.length - 1) {
  434. previousRowsLength += rowGroup[activeRowIndex].getHeight().opt;
  435. activateCells(nextActiveCells, activeRowIndex + 1);
  436. if (log.isTraceEnabled()) {
  437. log.trace("Computing first step for row " + (activeRowIndex + 2));
  438. }
  439. computeRowFirstStep(nextActiveCells);
  440. if (log.isTraceEnabled()) {
  441. log.trace("Next first step = " + rowFirstStep);
  442. }
  443. }
  444. }
  445. private void removeCellsEndingOnCurrentRow() {
  446. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  447. ActiveCell activeCell = (ActiveCell) iter.next();
  448. if (activeCell.endsOnRow(activeRowIndex)) {
  449. iter.remove();
  450. }
  451. }
  452. }
  453. /**
  454. * Actually switches to the next row, increasing activeRowIndex and transferring to
  455. * activeCells the cells starting on the next row.
  456. */
  457. private void switchToNextRow() {
  458. activeRowIndex++;
  459. if (log.isTraceEnabled()) {
  460. log.trace("Switching to row " + (activeRowIndex + 1));
  461. }
  462. for (Iterator iter = activeCells.iterator(); iter.hasNext();) {
  463. ActiveCell activeCell = (ActiveCell) iter.next();
  464. activeCell.nextRowStarts();
  465. }
  466. activeCells.addAll(nextActiveCells);
  467. nextActiveCells.clear();
  468. }
  469. /** @return the table layout manager */
  470. private TableLayoutManager getTableLM() {
  471. return this.tclm.getTableLM();
  472. }
  473. }