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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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.hssf.util.CellReference;
  41. import org.apache.poi.poifs.filesystem.DirectoryEntry;
  42. import org.apache.poi.poifs.filesystem.DirectoryNode;
  43. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  44. import org.apache.poi.ss.usermodel.Chart;
  45. import org.apache.poi.ss.usermodel.ClientAnchor;
  46. import org.apache.poi.ss.usermodel.Drawing;
  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 {
  55. // private static POILogger log = POILogFactory.getLogger(HSSFPatriarch.class);
  56. private final List<HSSFShape> _shapes = new ArrayList<HSSFShape>();
  57. private final EscherSpgrRecord _spgrRecord;
  58. private final EscherContainerRecord _mainSpgrContainer;
  59. /**
  60. * The EscherAggregate we have been bound to.
  61. * (This will handle writing us out into records,
  62. * and building up our shapes from the records)
  63. */
  64. private EscherAggregate _boundAggregate;
  65. private final HSSFSheet _sheet;
  66. /**
  67. * Creates the patriarch.
  68. *
  69. * @param sheet the sheet this patriarch is stored in.
  70. * @param boundAggregate -low level representation of all binary data inside sheet
  71. */
  72. HSSFPatriarch(HSSFSheet sheet, EscherAggregate boundAggregate) {
  73. _sheet = sheet;
  74. _boundAggregate = boundAggregate;
  75. _mainSpgrContainer = _boundAggregate.getEscherContainer().getChildContainers().get(0);
  76. EscherContainerRecord spContainer = (EscherContainerRecord) _boundAggregate.getEscherContainer()
  77. .getChildContainers().get(0).getChild(0);
  78. _spgrRecord = spContainer.getChildById(EscherSpgrRecord.RECORD_ID);
  79. buildShapeTree();
  80. }
  81. /**
  82. * used to clone patriarch
  83. *
  84. * create patriarch from existing one
  85. * @param patriarch - copy all the shapes from this patriarch to new one
  86. * @param sheet where must be located new patriarch
  87. * @return new patriarch with copies of all shapes from the existing patriarch
  88. */
  89. static HSSFPatriarch createPatriarch(HSSFPatriarch patriarch, HSSFSheet sheet){
  90. HSSFPatriarch newPatriarch = new HSSFPatriarch(sheet, new EscherAggregate(true));
  91. newPatriarch.afterCreate();
  92. for (HSSFShape shape: patriarch.getChildren()){
  93. HSSFShape newShape;
  94. if (shape instanceof HSSFShapeGroup){
  95. newShape = ((HSSFShapeGroup)shape).cloneShape(newPatriarch);
  96. } else {
  97. newShape = shape.cloneShape();
  98. }
  99. newPatriarch.onCreate(newShape);
  100. newPatriarch.addShape(newShape);
  101. }
  102. return newPatriarch;
  103. }
  104. /**
  105. * check if any shapes contain wrong data
  106. * At now(13.08.2010) check if patriarch contains 2 or more comments with same coordinates
  107. */
  108. protected void preSerialize(){
  109. Map<Integer, NoteRecord> tailRecords = _boundAggregate.getTailRecords();
  110. /**
  111. * contains coordinates of comments we iterate over
  112. */
  113. Set<String> coordinates = new HashSet<String>(tailRecords.size());
  114. for(NoteRecord rec : tailRecords.values()){
  115. String noteRef = new CellReference(rec.getRow(),
  116. rec.getColumn()).formatAsString(); // A1-style notation
  117. if(coordinates.contains(noteRef )){
  118. throw new IllegalStateException("found multiple cell comments for cell " + noteRef );
  119. } else {
  120. coordinates.add(noteRef);
  121. }
  122. }
  123. }
  124. /**
  125. * @param shape to be removed
  126. * @return true of shape is removed
  127. */
  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. public HSSFPicture createPicture(ClientAnchor anchor, int pictureIndex) {
  201. return createPicture((HSSFClientAnchor) anchor, pictureIndex);
  202. }
  203. /**
  204. * Adds a new OLE Package Shape
  205. *
  206. * @param anchor the client anchor describes how this picture is
  207. * attached to the sheet.
  208. * @param storageId the storageId returned by {@link HSSFWorkbook#addOlePackage(POIFSFileSystem,String,String,String)}
  209. * @param pictureIndex the index of the picture (used as preview image) in the
  210. * workbook collection of pictures.
  211. *
  212. * @return newly created shape
  213. */
  214. public HSSFObjectData createObjectData(HSSFClientAnchor anchor, int storageId, int pictureIndex) {
  215. ObjRecord obj = new ObjRecord();
  216. CommonObjectDataSubRecord ftCmo = new CommonObjectDataSubRecord();
  217. ftCmo.setObjectType(CommonObjectDataSubRecord.OBJECT_TYPE_PICTURE);
  218. // ftCmo.setObjectId(oleShape.getShapeId()); ... will be set by onCreate(...)
  219. ftCmo.setLocked(true);
  220. ftCmo.setPrintable(true);
  221. ftCmo.setAutofill(true);
  222. ftCmo.setAutoline(true);
  223. ftCmo.setReserved1(0);
  224. ftCmo.setReserved2(0);
  225. ftCmo.setReserved3(0);
  226. obj.addSubRecord(ftCmo);
  227. // FtCf (pictFormat)
  228. FtCfSubRecord ftCf = new FtCfSubRecord();
  229. HSSFPictureData pictData = getSheet().getWorkbook().getAllPictures().get(pictureIndex-1);
  230. switch (pictData.getFormat()) {
  231. case HSSFWorkbook.PICTURE_TYPE_WMF:
  232. case HSSFWorkbook.PICTURE_TYPE_EMF:
  233. // this needs patch #49658 to be applied to actually work
  234. ftCf.setFlags(FtCfSubRecord.METAFILE_BIT);
  235. break;
  236. case HSSFWorkbook.PICTURE_TYPE_DIB:
  237. case HSSFWorkbook.PICTURE_TYPE_PNG:
  238. case HSSFWorkbook.PICTURE_TYPE_JPEG:
  239. case HSSFWorkbook.PICTURE_TYPE_PICT:
  240. ftCf.setFlags(FtCfSubRecord.BITMAP_BIT);
  241. break;
  242. }
  243. obj.addSubRecord(ftCf);
  244. // FtPioGrbit (pictFlags)
  245. FtPioGrbitSubRecord ftPioGrbit = new FtPioGrbitSubRecord();
  246. ftPioGrbit.setFlagByBit(FtPioGrbitSubRecord.AUTO_PICT_BIT, true);
  247. obj.addSubRecord(ftPioGrbit);
  248. EmbeddedObjectRefSubRecord ftPictFmla = new EmbeddedObjectRefSubRecord();
  249. ftPictFmla.setUnknownFormulaData(new byte[]{2, 0, 0, 0, 0});
  250. ftPictFmla.setOleClassname("Paket");
  251. ftPictFmla.setStorageId(storageId);
  252. obj.addSubRecord(ftPictFmla);
  253. obj.addSubRecord(new EndSubRecord());
  254. String entryName = "MBD"+HexDump.toHex(storageId);
  255. DirectoryEntry oleRoot;
  256. try {
  257. DirectoryNode dn = _sheet.getWorkbook().getRootDirectory();
  258. if (dn == null) throw new FileNotFoundException();
  259. oleRoot = (DirectoryEntry)dn.getEntry(entryName);
  260. } catch (FileNotFoundException e) {
  261. throw new IllegalStateException("trying to add ole shape without actually adding data first - use HSSFWorkbook.addOlePackage first", e);
  262. }
  263. // create picture shape, which need to be minimal modified for oleshapes
  264. HSSFPicture shape = new HSSFPicture(null, anchor);
  265. shape.setPictureIndex(pictureIndex);
  266. EscherContainerRecord spContainer = shape.getEscherContainer();
  267. EscherSpRecord spRecord = spContainer.getChildById(EscherSpRecord.RECORD_ID);
  268. spRecord.setFlags(spRecord.getFlags() | EscherSpRecord.FLAG_OLESHAPE);
  269. HSSFObjectData oleShape = new HSSFObjectData(spContainer, obj, oleRoot);
  270. addShape(oleShape);
  271. onCreate(oleShape);
  272. return oleShape;
  273. }
  274. /**
  275. * Creates a polygon
  276. *
  277. * @param anchor the client anchor describes how this group is attached
  278. * to the sheet.
  279. * @return the newly created shape.
  280. */
  281. public HSSFPolygon createPolygon(HSSFClientAnchor anchor) {
  282. HSSFPolygon shape = new HSSFPolygon(null, anchor);
  283. addShape(shape);
  284. onCreate(shape);
  285. return shape;
  286. }
  287. /**
  288. * Constructs a textbox under the patriarch.
  289. *
  290. * @param anchor the client anchor describes how this group is attached
  291. * to the sheet.
  292. * @return the newly created textbox.
  293. */
  294. public HSSFTextbox createTextbox(HSSFClientAnchor anchor) {
  295. HSSFTextbox shape = new HSSFTextbox(null, anchor);
  296. addShape(shape);
  297. onCreate(shape);
  298. return shape;
  299. }
  300. /**
  301. * Constructs a cell comment.
  302. *
  303. * @param anchor the client anchor describes how this comment is attached
  304. * to the sheet.
  305. * @return the newly created comment.
  306. */
  307. public HSSFComment createComment(HSSFAnchor anchor) {
  308. HSSFComment shape = new HSSFComment(null, anchor);
  309. addShape(shape);
  310. onCreate(shape);
  311. return shape;
  312. }
  313. /**
  314. * YK: used to create autofilters
  315. *
  316. * @see org.apache.poi.hssf.usermodel.HSSFSheet#setAutoFilter(org.apache.poi.ss.util.CellRangeAddress)
  317. */
  318. HSSFSimpleShape createComboBox(HSSFAnchor anchor) {
  319. HSSFCombobox shape = new HSSFCombobox(null, anchor);
  320. addShape(shape);
  321. onCreate(shape);
  322. return shape;
  323. }
  324. public HSSFComment createCellComment(ClientAnchor anchor) {
  325. return createComment((HSSFAnchor) anchor);
  326. }
  327. /**
  328. * Returns a unmodifiable list of all shapes contained by the patriarch.
  329. */
  330. public List<HSSFShape> getChildren() {
  331. return Collections.unmodifiableList(_shapes);
  332. }
  333. /**
  334. * add a shape to this drawing
  335. */
  336. @Internal
  337. public void addShape(HSSFShape shape) {
  338. shape.setPatriarch(this);
  339. _shapes.add(shape);
  340. }
  341. private void onCreate(HSSFShape shape) {
  342. EscherContainerRecord spgrContainer =
  343. _boundAggregate.getEscherContainer().getChildContainers().get(0);
  344. EscherContainerRecord spContainer = shape.getEscherContainer();
  345. int shapeId = newShapeId();
  346. shape.setShapeId(shapeId);
  347. spgrContainer.addChildRecord(spContainer);
  348. shape.afterInsert(this);
  349. setFlipFlags(shape);
  350. }
  351. /**
  352. * Total count of all children and their children's children.
  353. * @return count of shapes including shapes inside shape groups
  354. */
  355. public int countOfAllChildren() {
  356. int count = _shapes.size();
  357. for (Iterator<HSSFShape> iterator = _shapes.iterator(); iterator.hasNext(); ) {
  358. HSSFShape shape = iterator.next();
  359. count += shape.countOfAllChildren();
  360. }
  361. return count;
  362. }
  363. /**
  364. * Sets the coordinate space of this group. All children are constrained
  365. * to these coordinates.
  366. */
  367. public void setCoordinates(int x1, int y1, int x2, int y2) {
  368. _spgrRecord.setRectY1(y1);
  369. _spgrRecord.setRectY2(y2);
  370. _spgrRecord.setRectX1(x1);
  371. _spgrRecord.setRectX2(x2);
  372. }
  373. /**
  374. * remove all shapes inside patriarch
  375. */
  376. public void clear() {
  377. ArrayList <HSSFShape> copy = new ArrayList<HSSFShape>(_shapes);
  378. for (HSSFShape shape: copy){
  379. removeShape(shape);
  380. }
  381. }
  382. /**
  383. * @return new unique shapeId
  384. */
  385. int newShapeId() {
  386. DrawingManager2 dm = _sheet.getWorkbook().getWorkbook().getDrawingManager();
  387. EscherDgRecord dg =
  388. _boundAggregate.getEscherContainer().getChildById(EscherDgRecord.RECORD_ID);
  389. short drawingGroupId = dg.getDrawingGroupId();
  390. return dm.allocateShapeId(drawingGroupId, dg);
  391. }
  392. /**
  393. * Does this HSSFPatriarch contain a chart?
  394. * (Technically a reference to a chart, since they
  395. * get stored in a different block of records)
  396. * FIXME - detect chart in all cases (only seems
  397. * to work on some charts so far)
  398. */
  399. public boolean containsChart() {
  400. // TODO - support charts properly in usermodel
  401. // We're looking for a EscherOptRecord
  402. EscherOptRecord optRecord = (EscherOptRecord)
  403. _boundAggregate.findFirstWithId(EscherOptRecord.RECORD_ID);
  404. if (optRecord == null) {
  405. // No opt record, can't have chart
  406. return false;
  407. }
  408. for (Iterator<EscherProperty> it = optRecord.getEscherProperties().iterator(); it.hasNext(); ) {
  409. EscherProperty prop = it.next();
  410. if (prop.getPropertyNumber() == 896 && prop.isComplex()) {
  411. EscherComplexProperty cp = (EscherComplexProperty) prop;
  412. String str = StringUtil.getFromUnicodeLE(cp.getComplexData());
  413. if (str.equals("Chart 1\0")) {
  414. return true;
  415. }
  416. }
  417. }
  418. return false;
  419. }
  420. /**
  421. * @return x coordinate of the left up corner
  422. */
  423. public int getX1() {
  424. return _spgrRecord.getRectX1();
  425. }
  426. /**
  427. * @return y coordinate of the left up corner
  428. */
  429. public int getY1() {
  430. return _spgrRecord.getRectY1();
  431. }
  432. /**
  433. * @return x coordinate of the right down corner
  434. */
  435. public int getX2() {
  436. return _spgrRecord.getRectX2();
  437. }
  438. /**
  439. * @return y coordinate of the right down corner
  440. */
  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. protected EscherAggregate _getBoundAggregate() {
  449. return _boundAggregate;
  450. }
  451. /**
  452. * Creates a new client anchor and sets the top-left and bottom-right
  453. * coordinates of the anchor.
  454. *
  455. * @param dx1 the x coordinate in EMU within the first cell.
  456. * @param dy1 the y coordinate in EMU within the first cell.
  457. * @param dx2 the x coordinate in EMU within the second cell.
  458. * @param dy2 the y coordinate in EMU within the second cell.
  459. * @param col1 the column (0 based) of the first cell.
  460. * @param row1 the row (0 based) of the first cell.
  461. * @param col2 the column (0 based) of the second cell.
  462. * @param row2 the row (0 based) of the second cell.
  463. * @return the newly created client anchor
  464. */
  465. public HSSFClientAnchor createAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2) {
  466. return new HSSFClientAnchor(dx1, dy1, dx2, dy2, (short) col1, row1, (short) col2, row2);
  467. }
  468. public Chart createChart(ClientAnchor anchor) {
  469. throw new RuntimeException("NotImplemented");
  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().getRootDirectory());
  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. public Iterator<HSSFShape> iterator() {
  498. return _shapes.iterator();
  499. }
  500. protected HSSFSheet getSheet() {
  501. return _sheet;
  502. }
  503. }