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.

HSLFTable.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.hslf.usermodel;
  16. import java.awt.geom.Rectangle2D;
  17. import java.util.ArrayList;
  18. import java.util.HashSet;
  19. import java.util.List;
  20. import java.util.ListIterator;
  21. import java.util.Set;
  22. import java.util.SortedSet;
  23. import java.util.TreeSet;
  24. import org.apache.poi.ddf.AbstractEscherOptRecord;
  25. import org.apache.poi.ddf.EscherArrayProperty;
  26. import org.apache.poi.ddf.EscherContainerRecord;
  27. import org.apache.poi.ddf.EscherOptRecord;
  28. import org.apache.poi.ddf.EscherProperties;
  29. import org.apache.poi.ddf.EscherSimpleProperty;
  30. import org.apache.poi.hslf.record.RecordTypes;
  31. import org.apache.poi.sl.usermodel.ShapeContainer;
  32. import org.apache.poi.sl.usermodel.TableShape;
  33. import org.apache.poi.util.LittleEndian;
  34. import org.apache.poi.util.Units;
  35. /**
  36. * Represents a table in a PowerPoint presentation
  37. *
  38. * @author Yegor Kozlov
  39. */
  40. public final class HSLFTable extends HSLFGroupShape
  41. implements HSLFShapeContainer, TableShape<HSLFShape,HSLFTextParagraph> {
  42. protected static final int BORDERS_ALL = 5;
  43. protected static final int BORDERS_OUTSIDE = 6;
  44. protected static final int BORDERS_INSIDE = 7;
  45. protected static final int BORDERS_NONE = 8;
  46. protected HSLFTableCell[][] cells;
  47. private int columnCount = -1;
  48. /**
  49. * Create a new Table of the given number of rows and columns
  50. *
  51. * @param numRows the number of rows
  52. * @param numCols the number of columns
  53. */
  54. protected HSLFTable(int numRows, int numCols) {
  55. this(numRows, numCols, null);
  56. }
  57. /**
  58. * Create a new Table of the given number of rows and columns
  59. *
  60. * @param numRows the number of rows
  61. * @param numCols the number of columns
  62. * @param parent the parent shape, or null if table is added to sheet
  63. */
  64. protected HSLFTable(int numRows, int numCols, ShapeContainer<HSLFShape,HSLFTextParagraph> parent) {
  65. super(parent);
  66. if(numRows < 1) {
  67. throw new IllegalArgumentException("The number of rows must be greater than 1");
  68. }
  69. if(numCols < 1) {
  70. throw new IllegalArgumentException("The number of columns must be greater than 1");
  71. }
  72. double x=0, y=0, tblWidth=0, tblHeight=0;
  73. cells = new HSLFTableCell[numRows][numCols];
  74. for (int i = 0; i < cells.length; i++) {
  75. x = 0;
  76. for (int j = 0; j < cells[i].length; j++) {
  77. cells[i][j] = new HSLFTableCell(this);
  78. Rectangle2D anchor = new Rectangle2D.Double(x, y, HSLFTableCell.DEFAULT_WIDTH, HSLFTableCell.DEFAULT_HEIGHT);
  79. cells[i][j].setAnchor(anchor);
  80. x += HSLFTableCell.DEFAULT_WIDTH;
  81. }
  82. y += HSLFTableCell.DEFAULT_HEIGHT;
  83. }
  84. tblWidth = x;
  85. tblHeight = y;
  86. setExteriorAnchor(new Rectangle2D.Double(0, 0, tblWidth, tblHeight));
  87. EscherContainerRecord spCont = (EscherContainerRecord) getSpContainer().getChild(0);
  88. AbstractEscherOptRecord opt = new EscherOptRecord();
  89. opt.setRecordId(RecordTypes.EscherUserDefined.typeID);
  90. opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GROUPSHAPE__TABLEPROPERTIES, 1));
  91. EscherArrayProperty p = new EscherArrayProperty((short)(0x4000 | EscherProperties.GROUPSHAPE__TABLEROWPROPERTIES), false, null);
  92. p.setSizeOfElements(0x0004);
  93. p.setNumberOfElementsInArray(numRows);
  94. p.setNumberOfElementsInMemory(numRows);
  95. opt.addEscherProperty(p);
  96. spCont.addChildBefore(opt, RecordTypes.EscherClientAnchor.typeID);
  97. }
  98. /**
  99. * Create a Table object and initialize it from the supplied Record container.
  100. *
  101. * @param escherRecord <code>EscherSpContainer</code> container which holds information about this shape
  102. * @param parent the parent of the shape
  103. */
  104. protected HSLFTable(EscherContainerRecord escherRecord, ShapeContainer<HSLFShape,HSLFTextParagraph> parent) {
  105. super(escherRecord, parent);
  106. }
  107. @Override
  108. public HSLFTableCell getCell(int row, int col) {
  109. if (row < 0 || cells.length <= row) {
  110. return null;
  111. }
  112. HSLFTableCell[] r = cells[row];
  113. if (r == null || col < 0 || r.length <= col) {
  114. // empty row
  115. return null;
  116. }
  117. // cell can be potentially empty ...
  118. return r[col];
  119. }
  120. @Override
  121. public int getNumberOfColumns() {
  122. if (columnCount == -1) {
  123. // check all rows in case of merged rows
  124. for (HSLFTableCell[] hc : cells) {
  125. if (hc != null) {
  126. columnCount = Math.max(columnCount, hc.length);
  127. }
  128. }
  129. }
  130. return columnCount;
  131. }
  132. @Override
  133. public int getNumberOfRows() {
  134. return cells.length;
  135. }
  136. @Override
  137. protected void afterInsert(HSLFSheet sh){
  138. super.afterInsert(sh);
  139. Set<HSLFLine> lineSet = new HashSet<HSLFLine>();
  140. for (HSLFTableCell row[] : cells) {
  141. for (HSLFTableCell c : row) {
  142. addShape(c);
  143. for (HSLFLine bt : new HSLFLine[]{ c.borderTop, c.borderRight, c.borderBottom, c.borderLeft }) {
  144. if (bt != null) {
  145. lineSet.add(bt);
  146. }
  147. }
  148. }
  149. }
  150. for (HSLFLine l : lineSet) {
  151. addShape(l);
  152. }
  153. updateRowHeightsProperty();
  154. }
  155. private void cellListToArray() {
  156. List<HSLFTableCell> htc = new ArrayList<HSLFTableCell>();
  157. for (HSLFShape h : getShapes()) {
  158. if (h instanceof HSLFTableCell) {
  159. htc.add((HSLFTableCell)h);
  160. }
  161. }
  162. if (htc.isEmpty()) {
  163. throw new IllegalStateException("HSLFTable without HSLFTableCells");
  164. }
  165. SortedSet<Double> colSet = new TreeSet<Double>();
  166. SortedSet<Double> rowSet = new TreeSet<Double>();
  167. // #1 pass - determine cols and rows
  168. for (HSLFTableCell sh : htc) {
  169. Rectangle2D anchor = sh.getAnchor();
  170. colSet.add(anchor.getX());
  171. rowSet.add(anchor.getY());
  172. }
  173. cells = new HSLFTableCell[rowSet.size()][colSet.size()];
  174. List<Double> colLst = new ArrayList<Double>(colSet);
  175. List<Double> rowLst = new ArrayList<Double>(rowSet);
  176. // #2 pass - assign shape to table cells
  177. for (HSLFTableCell sh : htc) {
  178. Rectangle2D anchor = sh.getAnchor();
  179. int row = rowLst.indexOf(anchor.getY());
  180. int col = colLst.indexOf(anchor.getX());
  181. assert(row != -1 && col != -1);
  182. cells[row][col] = sh;
  183. // determine gridSpan / rowSpan
  184. int gridSpan = calcSpan(colLst, anchor.getWidth(), col);
  185. int rowSpan = calcSpan(rowLst, anchor.getHeight(), row);
  186. sh.setGridSpan(gridSpan);
  187. sh.setRowSpan(rowSpan);
  188. }
  189. }
  190. private int calcSpan(List<Double> spaces, double totalSpace, int idx) {
  191. int span = 1;
  192. ListIterator<Double> li = spaces.listIterator(idx);
  193. double start = li.next();
  194. while (li.hasNext() && li.next()-start < totalSpace) {
  195. span++;
  196. }
  197. return span;
  198. }
  199. static class LineRect {
  200. final HSLFLine l;
  201. final double lx1, lx2, ly1, ly2;
  202. LineRect(HSLFLine l) {
  203. this.l = l;
  204. Rectangle2D r = l.getAnchor();
  205. lx1 = r.getMinX();
  206. lx2 = r.getMaxX();
  207. ly1 = r.getMinY();
  208. ly2 = r.getMaxY();
  209. }
  210. int leftFit(double x1, double x2, double y1, double y2) {
  211. return (int)(Math.abs(x1-lx1)+Math.abs(y1-ly1)+Math.abs(x1-lx2)+Math.abs(y2-ly2));
  212. }
  213. int topFit(double x1, double x2, double y1, double y2) {
  214. return (int)(Math.abs(x1-lx1)+Math.abs(y1-ly1)+Math.abs(x2-lx2)+Math.abs(y1-ly2));
  215. }
  216. int rightFit(double x1, double x2, double y1, double y2) {
  217. return (int)(Math.abs(x2-lx1)+Math.abs(y1-ly1)+Math.abs(x2-lx2)+Math.abs(y2-ly2));
  218. }
  219. int bottomFit(double x1, double x2, double y1, double y2) {
  220. return (int)(Math.abs(x1-lx1)+Math.abs(y2-ly1)+Math.abs(x2-lx2)+Math.abs(y2-ly2));
  221. }
  222. }
  223. private void fitLinesToCells() {
  224. List<LineRect> lines = new ArrayList<LineRect>();
  225. for (HSLFShape h : getShapes()) {
  226. if (h instanceof HSLFLine) {
  227. lines.add(new LineRect((HSLFLine)h));
  228. }
  229. }
  230. final int threshold = 5;
  231. // TODO: this only works for non-rotated tables
  232. for (HSLFTableCell[] tca : cells) {
  233. for (HSLFTableCell tc : tca) {
  234. if (tc == null) {
  235. continue;
  236. }
  237. final Rectangle2D cellAnchor = tc.getAnchor();
  238. /**
  239. * x1/y1 --------+
  240. * | |
  241. * +---------x2/y2
  242. */
  243. final double x1 = cellAnchor.getMinX();
  244. final double x2 = cellAnchor.getMaxX();
  245. final double y1 = cellAnchor.getMinY();
  246. final double y2 = cellAnchor.getMaxY();
  247. LineRect lline = null, tline = null, rline = null, bline = null;
  248. int lfit = Integer.MAX_VALUE, tfit = Integer.MAX_VALUE, rfit = Integer.MAX_VALUE, bfit = Integer.MAX_VALUE;
  249. for (LineRect lr : lines) {
  250. // calculate border fit
  251. int lfitx = lr.leftFit(x1, x2, y1, y2);
  252. if (lfitx < lfit) {
  253. lfit = lfitx;
  254. lline = lr;
  255. }
  256. int tfitx = lr.topFit(x1, x2, y1, y2);
  257. if (tfitx < tfit) {
  258. tfit = tfitx;
  259. tline = lr;
  260. }
  261. int rfitx = lr.rightFit(x1, x2, y1, y2);
  262. if (rfitx < rfit) {
  263. rfit = rfitx;
  264. rline = lr;
  265. }
  266. int bfitx = lr.bottomFit(x1, x2, y1, y2);
  267. if (bfitx < bfit) {
  268. bfit = bfitx;
  269. bline = lr;
  270. }
  271. }
  272. if (lfit < threshold && lline != null) {
  273. tc.borderLeft = lline.l;
  274. }
  275. if (tfit < threshold && tline != null) {
  276. tc.borderTop = tline.l;
  277. }
  278. if (rfit < threshold && rline != null) {
  279. tc.borderRight = rline.l;
  280. }
  281. if (bfit < threshold && bline != null) {
  282. tc.borderBottom = bline.l;
  283. }
  284. }
  285. }
  286. }
  287. protected void initTable(){
  288. cellListToArray();
  289. fitLinesToCells();
  290. }
  291. /**
  292. * Assign the <code>SlideShow</code> this shape belongs to
  293. *
  294. * @param sheet owner of this shape
  295. */
  296. @Override
  297. public void setSheet(HSLFSheet sheet){
  298. super.setSheet(sheet);
  299. if (cells == null) {
  300. initTable();
  301. } else {
  302. for (HSLFTableCell cols[] : cells) {
  303. for (HSLFTableCell col : cols) {
  304. col.setSheet(sheet);
  305. }
  306. }
  307. }
  308. }
  309. @Override
  310. public double getRowHeight(int row) {
  311. if (row < 0 || row >= cells.length) {
  312. throw new IllegalArgumentException("Row index '"+row+"' is not within range [0-"+(cells.length-1)+"]");
  313. }
  314. return cells[row][0].getAnchor().getHeight();
  315. }
  316. @Override
  317. public void setRowHeight(int row, double height) {
  318. if (row < 0 || row >= cells.length) {
  319. throw new IllegalArgumentException("Row index '"+row+"' is not within range [0-"+(cells.length-1)+"]");
  320. }
  321. int pxHeight = Units.pointsToPixel(height);
  322. double currentHeight = cells[row][0].getAnchor().getHeight();
  323. double dy = pxHeight - currentHeight;
  324. for (int i = row; i < cells.length; i++) {
  325. for (int j = 0; j < cells[i].length; j++) {
  326. Rectangle2D anchor = cells[i][j].getAnchor();
  327. if(i == row) {
  328. anchor.setRect(anchor.getX(), anchor.getY(), anchor.getWidth(), pxHeight);
  329. } else {
  330. anchor.setRect(anchor.getX(), anchor.getY()+dy, anchor.getWidth(), pxHeight);
  331. }
  332. cells[i][j].setAnchor(anchor);
  333. }
  334. }
  335. Rectangle2D tblanchor = getAnchor();
  336. tblanchor.setRect(tblanchor.getX(), tblanchor.getY(), tblanchor.getWidth(), tblanchor.getHeight() + dy);
  337. setExteriorAnchor(tblanchor);
  338. }
  339. @Override
  340. public double getColumnWidth(int col) {
  341. if (col < 0 || col >= cells[0].length) {
  342. throw new IllegalArgumentException("Column index '"+col+"' is not within range [0-"+(cells[0].length-1)+"]");
  343. }
  344. // TODO: check for merged cols
  345. double width = cells[0][col].getAnchor().getWidth();
  346. return width;
  347. }
  348. @Override
  349. public void setColumnWidth(int col, final double width){
  350. if (col < 0 || col >= cells[0].length) {
  351. throw new IllegalArgumentException("Column index '"+col+"' is not within range [0-"+(cells[0].length-1)+"]");
  352. }
  353. double currentWidth = cells[0][col].getAnchor().getWidth();
  354. double dx = width - currentWidth;
  355. for (HSLFTableCell cols[] : cells) {
  356. Rectangle2D anchor = cols[col].getAnchor();
  357. anchor.setRect(anchor.getX(), anchor.getY(), width, anchor.getHeight());
  358. cols[col].setAnchor(anchor);
  359. if (col < cols.length - 1) {
  360. for (int j = col+1; j < cols.length; j++) {
  361. anchor = cols[j].getAnchor();
  362. anchor.setRect(anchor.getX()+dx, anchor.getY(), anchor.getWidth(), anchor.getHeight());
  363. cols[j].setAnchor(anchor);
  364. }
  365. }
  366. }
  367. Rectangle2D tblanchor = getAnchor();
  368. tblanchor.setRect(tblanchor.getX(), tblanchor.getY(), tblanchor.getWidth() + dx, tblanchor.getHeight());
  369. setExteriorAnchor(tblanchor);
  370. }
  371. protected HSLFTableCell getRelativeCell(HSLFTableCell origin, int row, int col) {
  372. int thisRow = 0, thisCol = 0;
  373. boolean found = false;
  374. outer: for (HSLFTableCell[] tca : cells) {
  375. thisCol = 0;
  376. for (HSLFTableCell tc : tca) {
  377. if (tc == origin) {
  378. found = true;
  379. break outer;
  380. }
  381. thisCol++;
  382. }
  383. thisRow++;
  384. }
  385. int otherRow = thisRow + row;
  386. int otherCol = thisCol + col;
  387. return (found
  388. && 0 <= otherRow && otherRow < cells.length
  389. && 0 <= otherCol && otherCol < cells[otherRow].length)
  390. ? cells[otherRow][otherCol] : null;
  391. }
  392. @Override
  393. protected void moveAndScale(Rectangle2D anchorDest){
  394. super.moveAndScale(anchorDest);
  395. updateRowHeightsProperty();
  396. }
  397. private void updateRowHeightsProperty() {
  398. AbstractEscherOptRecord opt = getEscherOptRecord();
  399. EscherArrayProperty p = opt.lookup(EscherProperties.GROUPSHAPE__TABLEROWPROPERTIES);
  400. byte[] val = new byte[4];
  401. for (int rowIdx = 0; rowIdx < cells.length; rowIdx++) {
  402. int rowHeight = Units.pointsToMaster(cells[rowIdx][0].getAnchor().getHeight());
  403. LittleEndian.putInt(val, 0, rowHeight);
  404. p.setElement(rowIdx, val);
  405. }
  406. }
  407. }