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.

HSSFPatriarch.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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.hssf.usermodel;
  16. import java.io.FileNotFoundException;
  17. import java.util.ArrayList;
  18. import java.util.Collections;
  19. import java.util.HashSet;
  20. import java.util.Iterator;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Set;
  24. import java.util.Spliterator;
  25. import org.apache.poi.ddf.EscherComplexProperty;
  26. import org.apache.poi.ddf.EscherContainerRecord;
  27. import org.apache.poi.ddf.EscherDgRecord;
  28. import org.apache.poi.ddf.EscherOptRecord;
  29. import org.apache.poi.ddf.EscherProperty;
  30. import org.apache.poi.ddf.EscherSpRecord;
  31. import org.apache.poi.ddf.EscherSpgrRecord;
  32. import org.apache.poi.hssf.model.DrawingManager2;
  33. import org.apache.poi.hssf.record.CommonObjectDataSubRecord;
  34. import org.apache.poi.hssf.record.EmbeddedObjectRefSubRecord;
  35. import org.apache.poi.hssf.record.EndSubRecord;
  36. import org.apache.poi.hssf.record.EscherAggregate;
  37. import org.apache.poi.hssf.record.FtCfSubRecord;
  38. import org.apache.poi.hssf.record.FtPioGrbitSubRecord;
  39. import org.apache.poi.hssf.record.NoteRecord;
  40. import org.apache.poi.hssf.record.ObjRecord;
  41. import org.apache.poi.ss.util.CellReference;
  42. import org.apache.poi.poifs.filesystem.DirectoryEntry;
  43. import org.apache.poi.poifs.filesystem.DirectoryNode;
  44. import org.apache.poi.ss.usermodel.ClientAnchor;
  45. import org.apache.poi.ss.usermodel.Drawing;
  46. import org.apache.poi.ss.usermodel.Workbook;
  47. import org.apache.poi.util.HexDump;
  48. import org.apache.poi.util.Internal;
  49. import org.apache.poi.util.StringUtil;
  50. /**
  51. * The patriarch is the toplevel container for shapes in a sheet. It does
  52. * little other than act as a container for other shapes and groups.
  53. */
  54. public final class HSSFPatriarch implements HSSFShapeContainer, Drawing<HSSFShape> {
  55. private final List<HSSFShape> _shapes = new ArrayList<>();
  56. private final EscherSpgrRecord _spgrRecord;
  57. private final EscherContainerRecord _mainSpgrContainer;
  58. /**
  59. * The EscherAggregate we have been bound to.
  60. * (This will handle writing us out into records,
  61. * and building up our shapes from the records)
  62. */
  63. private EscherAggregate _boundAggregate;
  64. private final HSSFSheet _sheet;
  65. /**
  66. * Creates the patriarch.
  67. *
  68. * @param sheet the sheet this patriarch is stored in.
  69. * @param boundAggregate -low level representation of all binary data inside sheet
  70. */
  71. HSSFPatriarch(HSSFSheet sheet, EscherAggregate boundAggregate) {
  72. _sheet = sheet;
  73. _boundAggregate = boundAggregate;
  74. _mainSpgrContainer = _boundAggregate.getEscherContainer().getChildContainers().get(0);
  75. EscherContainerRecord spContainer = (EscherContainerRecord) _boundAggregate.getEscherContainer()
  76. .getChildContainers().get(0).getChild(0);
  77. _spgrRecord = spContainer.getChildById(EscherSpgrRecord.RECORD_ID);
  78. buildShapeTree();
  79. }
  80. /**
  81. * used to clone patriarch
  82. *
  83. * create patriarch from existing one
  84. * @param patriarch - copy all the shapes from this patriarch to new one
  85. * @param sheet where must be located new patriarch
  86. * @return new patriarch with copies of all shapes from the existing patriarch
  87. */
  88. static HSSFPatriarch createPatriarch(HSSFPatriarch patriarch, HSSFSheet sheet){
  89. HSSFPatriarch newPatriarch = new HSSFPatriarch(sheet, new EscherAggregate(true));
  90. newPatriarch.afterCreate();
  91. for (HSSFShape shape: patriarch.getChildren()){
  92. HSSFShape newShape;
  93. if (shape instanceof HSSFShapeGroup){
  94. newShape = ((HSSFShapeGroup)shape).cloneShape(newPatriarch);
  95. } else {
  96. newShape = shape.cloneShape();
  97. }
  98. newPatriarch.onCreate(newShape);
  99. newPatriarch.addShape(newShape);
  100. }
  101. return newPatriarch;
  102. }
  103. /**
  104. * check if any shapes contain wrong data
  105. * At now(13.08.2010) check if patriarch contains 2 or more comments with same coordinates
  106. */
  107. protected void preSerialize(){
  108. Map<Integer, NoteRecord> tailRecords = _boundAggregate.getTailRecords();
  109. /*
  110. * contains coordinates of comments we iterate over
  111. */
  112. Set<String> coordinates = new HashSet<>(tailRecords.size());
  113. for(NoteRecord rec : tailRecords.values()){
  114. String noteRef = new CellReference(rec.getRow(),
  115. rec.getColumn(), true, true).formatAsString(); // A1-style notation
  116. if(coordinates.contains(noteRef )){
  117. throw new IllegalStateException("found multiple cell comments for cell " + noteRef );
  118. } else {
  119. coordinates.add(noteRef);
  120. }
  121. }
  122. }
  123. /**
  124. * @param shape to be removed
  125. * @return true of shape is removed
  126. */
  127. @Override
  128. public boolean removeShape(HSSFShape shape) {
  129. boolean isRemoved = _mainSpgrContainer.removeChildRecord(shape.getEscherContainer());
  130. if (isRemoved){
  131. shape.afterRemove(this);
  132. _shapes.remove(shape);
  133. }
  134. return isRemoved;
  135. }
  136. void afterCreate() {
  137. DrawingManager2 drawingManager = _sheet.getWorkbook().getWorkbook().getDrawingManager();
  138. short dgId = drawingManager.findNewDrawingGroupId();
  139. _boundAggregate.setDgId(dgId);
  140. _boundAggregate.setMainSpRecordId(newShapeId());
  141. drawingManager.incrementDrawingsSaved();
  142. }
  143. /**
  144. * Creates a new group record stored under this patriarch.
  145. *
  146. * @param anchor the client anchor describes how this group is attached
  147. * to the sheet.
  148. * @return the newly created group.
  149. */
  150. public HSSFShapeGroup createGroup(HSSFClientAnchor anchor) {
  151. HSSFShapeGroup group = new HSSFShapeGroup(null, anchor);
  152. addShape(group);
  153. onCreate(group);
  154. return group;
  155. }
  156. /**
  157. * Creates a simple shape. This includes such shapes as lines, rectangles,
  158. * and ovals.
  159. *
  160. * Note: Microsoft Excel seems to sometimes disallow
  161. * higher y1 than y2 or higher x1 than x2 in the anchor, you might need to
  162. * reverse them and draw shapes vertically or horizontally flipped!
  163. *
  164. * @param anchor the client anchor describes how this group is attached
  165. * to the sheet.
  166. * @return the newly created shape.
  167. */
  168. public HSSFSimpleShape createSimpleShape(HSSFClientAnchor anchor) {
  169. HSSFSimpleShape shape = new HSSFSimpleShape(null, anchor);
  170. addShape(shape);
  171. //open existing file
  172. onCreate(shape);
  173. return shape;
  174. }
  175. /**
  176. * Creates a picture.
  177. *
  178. * @param anchor the client anchor describes how this group is attached
  179. * to the sheet.
  180. * @param pictureIndex - pointer to the byte array saved inside workbook in escher bse record
  181. * @return the newly created shape.
  182. */
  183. public HSSFPicture createPicture(HSSFClientAnchor anchor, int pictureIndex) {
  184. HSSFPicture shape = new HSSFPicture(null, anchor);
  185. shape.setPictureIndex(pictureIndex);
  186. addShape(shape);
  187. //open existing file
  188. onCreate(shape);
  189. return shape;
  190. }
  191. /**
  192. *
  193. * @param anchor the client anchor describes how this picture is
  194. * attached to the sheet.
  195. * @param pictureIndex the index of the picture in the workbook collection
  196. * of pictures.
  197. *
  198. * @return newly created shape
  199. */
  200. @Override
  201. public HSSFPicture createPicture(ClientAnchor anchor, int pictureIndex) {
  202. return createPicture((HSSFClientAnchor) anchor, pictureIndex);
  203. }
  204. @Override
  205. public HSSFObjectData createObjectData(ClientAnchor anchor, int storageId, int pictureIndex) {
  206. ObjRecord obj = new ObjRecord();
  207. CommonObjectDataSubRecord ftCmo = new CommonObjectDataSubRecord();
  208. ftCmo.setObjectType(CommonObjectDataSubRecord.OBJECT_TYPE_PICTURE);
  209. // ftCmo.setObjectId(oleShape.getShapeId()); ... will be set by onCreate(...)
  210. ftCmo.setLocked(true);
  211. ftCmo.setPrintable(true);
  212. ftCmo.setAutofill(true);
  213. ftCmo.setAutoline(true);
  214. ftCmo.setReserved1(0);
  215. ftCmo.setReserved2(0);
  216. ftCmo.setReserved3(0);
  217. obj.addSubRecord(ftCmo);
  218. // FtCf (pictFormat)
  219. FtCfSubRecord ftCf = new FtCfSubRecord();
  220. HSSFPictureData pictData = getSheet().getWorkbook().getAllPictures().get(pictureIndex-1);
  221. switch (pictData.getFormat()) {
  222. case Workbook.PICTURE_TYPE_WMF:
  223. case Workbook.PICTURE_TYPE_EMF:
  224. // this needs patch #49658 to be applied to actually work
  225. ftCf.setFlags(FtCfSubRecord.METAFILE_BIT);
  226. break;
  227. case Workbook.PICTURE_TYPE_DIB:
  228. case Workbook.PICTURE_TYPE_PNG:
  229. case Workbook.PICTURE_TYPE_JPEG:
  230. case Workbook.PICTURE_TYPE_PICT:
  231. ftCf.setFlags(FtCfSubRecord.BITMAP_BIT);
  232. break;
  233. default:
  234. throw new IllegalStateException("Invalid picture type: " + pictData.getFormat());
  235. }
  236. obj.addSubRecord(ftCf);
  237. // FtPioGrbit (pictFlags)
  238. FtPioGrbitSubRecord ftPioGrbit = new FtPioGrbitSubRecord();
  239. ftPioGrbit.setFlagByBit(FtPioGrbitSubRecord.AUTO_PICT_BIT, true);
  240. obj.addSubRecord(ftPioGrbit);
  241. EmbeddedObjectRefSubRecord ftPictFmla = new EmbeddedObjectRefSubRecord();
  242. ftPictFmla.setUnknownFormulaData(new byte[]{2, 0, 0, 0, 0});
  243. ftPictFmla.setOleClassname("Paket");
  244. ftPictFmla.setStorageId(storageId);
  245. obj.addSubRecord(ftPictFmla);
  246. obj.addSubRecord(new EndSubRecord());
  247. String entryName = "MBD"+HexDump.toHex(storageId);
  248. DirectoryEntry oleRoot;
  249. try {
  250. DirectoryNode dn = _sheet.getWorkbook().getDirectory();
  251. if (dn == null) {
  252. throw new FileNotFoundException();
  253. }
  254. oleRoot = (DirectoryEntry)dn.getEntry(entryName);
  255. } catch (FileNotFoundException e) {
  256. throw new IllegalStateException("trying to add ole shape without actually adding data first - use HSSFWorkbook.addOlePackage first", e);
  257. }
  258. // create picture shape, which need to be minimal modified for oleshapes
  259. HSSFPicture shape = new HSSFPicture(null, (HSSFClientAnchor)anchor);
  260. shape.setPictureIndex(pictureIndex);
  261. EscherContainerRecord spContainer = shape.getEscherContainer();
  262. EscherSpRecord spRecord = spContainer.getChildById(EscherSpRecord.RECORD_ID);
  263. spRecord.setFlags(spRecord.getFlags() | EscherSpRecord.FLAG_OLESHAPE);
  264. HSSFObjectData oleShape = new HSSFObjectData(spContainer, obj, oleRoot);
  265. addShape(oleShape);
  266. onCreate(oleShape);
  267. return oleShape;
  268. }
  269. /**
  270. * Creates a polygon
  271. *
  272. * @param anchor the client anchor describes how this group is attached
  273. * to the sheet.
  274. * @return the newly created shape.
  275. */
  276. public HSSFPolygon createPolygon(HSSFClientAnchor anchor) {
  277. HSSFPolygon shape = new HSSFPolygon(null, anchor);
  278. addShape(shape);
  279. onCreate(shape);
  280. return shape;
  281. }
  282. /**
  283. * Constructs a textbox under the patriarch.
  284. *
  285. * @param anchor the client anchor describes how this group is attached
  286. * to the sheet.
  287. * @return the newly created textbox.
  288. */
  289. public HSSFTextbox createTextbox(HSSFClientAnchor anchor) {
  290. HSSFTextbox shape = new HSSFTextbox(null, anchor);
  291. addShape(shape);
  292. onCreate(shape);
  293. return shape;
  294. }
  295. /**
  296. * Constructs a cell comment.
  297. *
  298. * @param anchor the client anchor describes how this comment is attached
  299. * to the sheet.
  300. * @return the newly created comment.
  301. */
  302. public HSSFComment createComment(HSSFAnchor anchor) {
  303. HSSFComment shape = new HSSFComment(null, anchor);
  304. addShape(shape);
  305. onCreate(shape);
  306. return shape;
  307. }
  308. /**
  309. * YK: used to create autofilters
  310. *
  311. * @see org.apache.poi.hssf.usermodel.HSSFSheet#setAutoFilter(org.apache.poi.ss.util.CellRangeAddress)
  312. */
  313. HSSFSimpleShape createComboBox(HSSFAnchor anchor) {
  314. HSSFCombobox shape = new HSSFCombobox(null, anchor);
  315. addShape(shape);
  316. onCreate(shape);
  317. return shape;
  318. }
  319. @Override
  320. public HSSFComment createCellComment(ClientAnchor anchor) {
  321. return createComment((HSSFAnchor) anchor);
  322. }
  323. /**
  324. * Returns a unmodifiable list of all shapes contained by the patriarch.
  325. */
  326. @Override
  327. public List<HSSFShape> getChildren() {
  328. return Collections.unmodifiableList(_shapes);
  329. }
  330. /**
  331. * add a shape to this drawing
  332. */
  333. @Override
  334. @Internal
  335. public void addShape(HSSFShape shape) {
  336. shape.setPatriarch(this);
  337. _shapes.add(shape);
  338. }
  339. private void onCreate(HSSFShape shape) {
  340. EscherContainerRecord spgrContainer =
  341. _boundAggregate.getEscherContainer().getChildContainers().get(0);
  342. EscherContainerRecord spContainer = shape.getEscherContainer();
  343. int shapeId = newShapeId();
  344. shape.setShapeId(shapeId);
  345. spgrContainer.addChildRecord(spContainer);
  346. shape.afterInsert(this);
  347. setFlipFlags(shape);
  348. }
  349. /**
  350. * Total count of all children and their children's children.
  351. * @return count of shapes including shapes inside shape groups
  352. */
  353. public int countOfAllChildren() {
  354. int count = _shapes.size();
  355. for (HSSFShape shape : _shapes) {
  356. count += shape.countOfAllChildren();
  357. }
  358. return count;
  359. }
  360. /**
  361. * Sets the coordinate space of this group. All children are constrained
  362. * to these coordinates.
  363. */
  364. @Override
  365. public void setCoordinates(int x1, int y1, int x2, int y2) {
  366. _spgrRecord.setRectY1(y1);
  367. _spgrRecord.setRectY2(y2);
  368. _spgrRecord.setRectX1(x1);
  369. _spgrRecord.setRectX2(x2);
  370. }
  371. /**
  372. * remove all shapes inside patriarch
  373. */
  374. @Override
  375. public void clear() {
  376. ArrayList <HSSFShape> copy = new ArrayList<>(_shapes);
  377. for (HSSFShape shape: copy){
  378. removeShape(shape);
  379. }
  380. }
  381. /**
  382. * @return new unique shapeId
  383. */
  384. int newShapeId() {
  385. DrawingManager2 dm = _sheet.getWorkbook().getWorkbook().getDrawingManager();
  386. EscherDgRecord dg =
  387. _boundAggregate.getEscherContainer().getChildById(EscherDgRecord.RECORD_ID);
  388. return dm.allocateShapeId(dg);
  389. }
  390. /**
  391. * Does this HSSFPatriarch contain a chart?
  392. * (Technically a reference to a chart, since they
  393. * get stored in a different block of records)
  394. * FIXME - detect chart in all cases (only seems
  395. * to work on some charts so far)
  396. */
  397. public boolean containsChart() {
  398. // TODO - support charts properly in usermodel
  399. // We're looking for a EscherOptRecord
  400. EscherOptRecord optRecord = (EscherOptRecord)
  401. _boundAggregate.findFirstWithId(EscherOptRecord.RECORD_ID);
  402. if (optRecord == null) {
  403. // No opt record, can't have chart
  404. return false;
  405. }
  406. for (EscherProperty prop : optRecord.getEscherProperties()) {
  407. if (prop.getPropertyNumber() == 896 && prop.isComplex()) {
  408. EscherComplexProperty cp = (EscherComplexProperty) prop;
  409. String str = StringUtil.getFromUnicodeLE(cp.getComplexData());
  410. if (str.equals("Chart 1\0")) {
  411. return true;
  412. }
  413. }
  414. }
  415. return false;
  416. }
  417. /**
  418. * @return x coordinate of the left up corner
  419. */
  420. @Override
  421. public int getX1() {
  422. return _spgrRecord.getRectX1();
  423. }
  424. /**
  425. * @return y coordinate of the left up corner
  426. */
  427. @Override
  428. public int getY1() {
  429. return _spgrRecord.getRectY1();
  430. }
  431. /**
  432. * @return x coordinate of the right down corner
  433. */
  434. @Override
  435. public int getX2() {
  436. return _spgrRecord.getRectX2();
  437. }
  438. /**
  439. * @return y coordinate of the right down corner
  440. */
  441. @Override
  442. public int getY2() {
  443. return _spgrRecord.getRectY2();
  444. }
  445. /**
  446. * Returns the aggregate escher record we're bound to
  447. * @return - low level representation of sheet drawing data
  448. */
  449. @Internal
  450. public EscherAggregate getBoundAggregate() {
  451. return _boundAggregate;
  452. }
  453. /**
  454. * Creates a new client anchor and sets the top-left and bottom-right
  455. * coordinates of the anchor.
  456. *
  457. * @param dx1 the x coordinate in EMU within the first cell.
  458. * @param dy1 the y coordinate in EMU within the first cell.
  459. * @param dx2 the x coordinate in EMU within the second cell.
  460. * @param dy2 the y coordinate in EMU within the second cell.
  461. * @param col1 the column (0 based) of the first cell.
  462. * @param row1 the row (0 based) of the first cell.
  463. * @param col2 the column (0 based) of the second cell.
  464. * @param row2 the row (0 based) of the second cell.
  465. * @return the newly created client anchor
  466. */
  467. @Override
  468. public HSSFClientAnchor createAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2) {
  469. return new HSSFClientAnchor(dx1, dy1, dx2, dy2, (short) col1, row1, (short) col2, row2);
  470. }
  471. /**
  472. * create shape tree from existing escher records tree
  473. */
  474. void buildShapeTree() {
  475. EscherContainerRecord dgContainer = _boundAggregate.getEscherContainer();
  476. if (dgContainer == null) {
  477. return;
  478. }
  479. EscherContainerRecord spgrConrainer = dgContainer.getChildContainers().get(0);
  480. List<EscherContainerRecord> spgrChildren = spgrConrainer.getChildContainers();
  481. for (int i = 0; i < spgrChildren.size(); i++) {
  482. EscherContainerRecord spContainer = spgrChildren.get(i);
  483. if (i != 0) {
  484. HSSFShapeFactory.createShapeTree(spContainer, _boundAggregate, this, _sheet.getWorkbook().getDirectory());
  485. }
  486. }
  487. }
  488. private void setFlipFlags(HSSFShape shape){
  489. EscherSpRecord sp = shape.getEscherContainer().getChildById(EscherSpRecord.RECORD_ID);
  490. if (shape.getAnchor().isHorizontallyFlipped()) {
  491. sp.setFlags(sp.getFlags() | EscherSpRecord.FLAG_FLIPHORIZ);
  492. }
  493. if (shape.getAnchor().isVerticallyFlipped()) {
  494. sp.setFlags(sp.getFlags() | EscherSpRecord.FLAG_FLIPVERT);
  495. }
  496. }
  497. @Override
  498. public Iterator<HSSFShape> iterator() {
  499. return _shapes.iterator();
  500. }
  501. /**
  502. * @since POI 5.2.0
  503. */
  504. @Override
  505. public Spliterator<HSSFShape> spliterator() {
  506. return _shapes.spliterator();
  507. }
  508. protected HSSFSheet getSheet() {
  509. return _sheet;
  510. }
  511. }