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

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