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.

HSLFSlideShow.java 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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;
  16. import java.io.ByteArrayInputStream;
  17. import java.io.ByteArrayOutputStream;
  18. import java.io.FileInputStream;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.OutputStream;
  22. import java.util.ArrayList;
  23. import java.util.HashMap;
  24. import java.util.Hashtable;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.NavigableMap;
  28. import java.util.TreeMap;
  29. import org.apache.poi.POIDocument;
  30. import org.apache.poi.hslf.exceptions.CorruptPowerPointFileException;
  31. import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException;
  32. import org.apache.poi.hslf.exceptions.HSLFException;
  33. import org.apache.poi.hslf.record.CurrentUserAtom;
  34. import org.apache.poi.hslf.record.ExOleObjStg;
  35. import org.apache.poi.hslf.record.PersistPtrHolder;
  36. import org.apache.poi.hslf.record.PersistRecord;
  37. import org.apache.poi.hslf.record.PositionDependentRecord;
  38. import org.apache.poi.hslf.record.Record;
  39. import org.apache.poi.hslf.record.RecordTypes;
  40. import org.apache.poi.hslf.record.UserEditAtom;
  41. import org.apache.poi.hslf.usermodel.ObjectData;
  42. import org.apache.poi.hslf.usermodel.PictureData;
  43. import org.apache.poi.poifs.filesystem.DirectoryNode;
  44. import org.apache.poi.poifs.filesystem.DocumentEntry;
  45. import org.apache.poi.poifs.filesystem.DocumentInputStream;
  46. import org.apache.poi.poifs.filesystem.EntryUtils;
  47. import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
  48. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  49. import org.apache.poi.util.LittleEndian;
  50. import org.apache.poi.util.POILogFactory;
  51. import org.apache.poi.util.POILogger;
  52. /**
  53. * This class contains the main functionality for the Powerpoint file
  54. * "reader". It is only a very basic class for now
  55. *
  56. * @author Nick Burch
  57. */
  58. public final class HSLFSlideShow extends POIDocument {
  59. public static final int UNSET_OFFSET = -1;
  60. // For logging
  61. private POILogger logger = POILogFactory.getLogger(this.getClass());
  62. // Holds metadata on where things are in our document
  63. private CurrentUserAtom currentUser;
  64. // Low level contents of the file
  65. private byte[] _docstream;
  66. // Low level contents
  67. private Record[] _records;
  68. // Raw Pictures contained in the pictures stream
  69. private List<PictureData> _pictures;
  70. // Embedded objects stored in storage records in the document stream, lazily populated.
  71. private ObjectData[] _objects;
  72. /**
  73. * Returns the underlying POIFSFileSystem for the document
  74. * that is open.
  75. */
  76. protected POIFSFileSystem getPOIFSFileSystem() {
  77. return directory.getFileSystem();
  78. }
  79. /**
  80. * Returns the directory in the underlying POIFSFileSystem for the
  81. * document that is open.
  82. */
  83. protected DirectoryNode getPOIFSDirectory() {
  84. return directory;
  85. }
  86. /**
  87. * Constructs a Powerpoint document from fileName. Parses the document
  88. * and places all the important stuff into data structures.
  89. *
  90. * @param fileName The name of the file to read.
  91. * @throws IOException if there is a problem while parsing the document.
  92. */
  93. public HSLFSlideShow(String fileName) throws IOException
  94. {
  95. this(new FileInputStream(fileName));
  96. }
  97. /**
  98. * Constructs a Powerpoint document from an input stream. Parses the
  99. * document and places all the important stuff into data structures.
  100. *
  101. * @param inputStream the source of the data
  102. * @throws IOException if there is a problem while parsing the document.
  103. */
  104. public HSLFSlideShow(InputStream inputStream) throws IOException {
  105. //do Ole stuff
  106. this(new POIFSFileSystem(inputStream));
  107. }
  108. /**
  109. * Constructs a Powerpoint document from a POIFS Filesystem. Parses the
  110. * document and places all the important stuff into data structures.
  111. *
  112. * @param filesystem the POIFS FileSystem to read from
  113. * @throws IOException if there is a problem while parsing the document.
  114. */
  115. public HSLFSlideShow(POIFSFileSystem filesystem) throws IOException
  116. {
  117. this(filesystem.getRoot());
  118. }
  119. /**
  120. * Constructs a Powerpoint document from a POIFS Filesystem. Parses the
  121. * document and places all the important stuff into data structures.
  122. *
  123. * @param filesystem the POIFS FileSystem to read from
  124. * @throws IOException if there is a problem while parsing the document.
  125. */
  126. public HSLFSlideShow(NPOIFSFileSystem filesystem) throws IOException
  127. {
  128. this(filesystem.getRoot());
  129. }
  130. /**
  131. * Constructs a Powerpoint document from a specific point in a
  132. * POIFS Filesystem. Parses the document and places all the
  133. * important stuff into data structures.
  134. *
  135. * @deprecated Use {@link #HSLFSlideShow(DirectoryNode)} instead
  136. * @param dir the POIFS directory to read from
  137. * @param filesystem the POIFS FileSystem to read from
  138. * @throws IOException if there is a problem while parsing the document.
  139. */
  140. @Deprecated
  141. public HSLFSlideShow(DirectoryNode dir, POIFSFileSystem filesystem) throws IOException
  142. {
  143. this(dir);
  144. }
  145. /**
  146. * Constructs a Powerpoint document from a specific point in a
  147. * POIFS Filesystem. Parses the document and places all the
  148. * important stuff into data structures.
  149. *
  150. * @param dir the POIFS directory to read from
  151. * @throws IOException if there is a problem while parsing the document.
  152. */
  153. public HSLFSlideShow(DirectoryNode dir) throws IOException
  154. {
  155. super(dir);
  156. // First up, grab the "Current User" stream
  157. // We need this before we can detect Encrypted Documents
  158. readCurrentUserStream();
  159. // Next up, grab the data that makes up the
  160. // PowerPoint stream
  161. readPowerPointStream();
  162. // Check to see if we have an encrypted document,
  163. // bailing out if we do
  164. boolean encrypted = EncryptedSlideShow.checkIfEncrypted(this);
  165. if(encrypted) {
  166. throw new EncryptedPowerPointFileException("Encrypted PowerPoint files are not supported");
  167. }
  168. // Now, build records based on the PowerPoint stream
  169. buildRecords();
  170. // Look for any other streams
  171. readOtherStreams();
  172. }
  173. /**
  174. * Constructs a new, empty, Powerpoint document.
  175. */
  176. public static final HSLFSlideShow create() {
  177. InputStream is = HSLFSlideShow.class.getResourceAsStream("data/empty.ppt");
  178. if (is == null) {
  179. throw new RuntimeException("Missing resource 'empty.ppt'");
  180. }
  181. try {
  182. return new HSLFSlideShow(is);
  183. } catch (IOException e) {
  184. throw new RuntimeException(e);
  185. }
  186. }
  187. /**
  188. * Extracts the main PowerPoint document stream from the
  189. * POI file, ready to be passed
  190. *
  191. * @throws IOException
  192. */
  193. private void readPowerPointStream() throws IOException
  194. {
  195. // Get the main document stream
  196. DocumentEntry docProps =
  197. (DocumentEntry)directory.getEntry("PowerPoint Document");
  198. // Grab the document stream
  199. _docstream = new byte[docProps.getSize()];
  200. directory.createDocumentInputStream("PowerPoint Document").read(_docstream);
  201. }
  202. /**
  203. * Builds the list of records, based on the contents
  204. * of the PowerPoint stream
  205. */
  206. private void buildRecords()
  207. {
  208. // The format of records in a powerpoint file are:
  209. // <little endian 2 byte "info">
  210. // <little endian 2 byte "type">
  211. // <little endian 4 byte "length">
  212. // If it has a zero length, following it will be another record
  213. // <xx xx yy yy 00 00 00 00> <xx xx yy yy zz zz zz zz>
  214. // If it has a length, depending on its type it may have children or data
  215. // If it has children, these will follow straight away
  216. // <xx xx yy yy zz zz zz zz <xx xx yy yy zz zz zz zz>>
  217. // If it has data, this will come straigh after, and run for the length
  218. // <xx xx yy yy zz zz zz zz dd dd dd dd dd dd dd>
  219. // All lengths given exclude the 8 byte record header
  220. // (Data records are known as Atoms)
  221. // Document should start with:
  222. // 0F 00 E8 03 ## ## ## ##
  223. // (type 1000 = document, info 00 0f is normal, rest is document length)
  224. // 01 00 E9 03 28 00 00 00
  225. // (type 1001 = document atom, info 00 01 normal, 28 bytes long)
  226. // 80 16 00 00 E0 10 00 00 xx xx xx xx xx xx xx xx
  227. // 05 00 00 00 0A 00 00 00 xx xx xx
  228. // (the contents of the document atom, not sure what it means yet)
  229. // (records then follow)
  230. // When parsing a document, look to see if you know about that type
  231. // of the current record. If you know it's a type that has children,
  232. // process the record's data area looking for more records
  233. // If you know about the type and it doesn't have children, either do
  234. // something with the data (eg TextRun) or skip over it
  235. // If you don't know about the type, play safe and skip over it (using
  236. // its length to know where the next record will start)
  237. //
  238. _records = read(_docstream, (int)currentUser.getCurrentEditOffset());
  239. }
  240. private Record[] read(byte[] docstream, int usrOffset){
  241. //sort found records by offset.
  242. //(it is not necessary but SlideShow.findMostRecentCoreRecords() expects them sorted)
  243. NavigableMap<Integer,Record> records = new TreeMap<Integer,Record>(); // offset -> record
  244. Map<Integer,Integer> persistIds = new HashMap<Integer,Integer>(); // offset -> persistId
  245. initRecordOffsets(docstream, usrOffset, records, persistIds);
  246. for (Map.Entry<Integer,Record> entry : records.entrySet()) {
  247. Integer offset = entry.getKey();
  248. Record record = entry.getValue();
  249. Integer persistId = persistIds.get(offset);
  250. if (record == null) {
  251. // all plain records have been already added,
  252. // only new records need to be decrypted (tbd #35897)
  253. record = Record.buildRecordAtOffset(docstream, offset);
  254. entry.setValue(record);
  255. }
  256. if (record instanceof PersistRecord) {
  257. ((PersistRecord)record).setPersistId(persistId);
  258. }
  259. }
  260. return records.values().toArray(new Record[records.size()]);
  261. }
  262. private void initRecordOffsets(byte[] docstream, int usrOffset, NavigableMap<Integer,Record> recordMap, Map<Integer,Integer> offset2id) {
  263. while (usrOffset != 0){
  264. UserEditAtom usr = (UserEditAtom) Record.buildRecordAtOffset(docstream, usrOffset);
  265. recordMap.put(usrOffset, usr);
  266. int psrOffset = usr.getPersistPointersOffset();
  267. PersistPtrHolder ptr = (PersistPtrHolder)Record.buildRecordAtOffset(docstream, psrOffset);
  268. recordMap.put(psrOffset, ptr);
  269. for(Map.Entry<Integer,Integer> entry : ptr.getSlideLocationsLookup().entrySet()) {
  270. Integer offset = entry.getValue();
  271. Integer id = entry.getKey();
  272. recordMap.put(offset, null); // reserve a slot for the record
  273. offset2id.put(offset, id);
  274. }
  275. usrOffset = usr.getLastUserEditAtomOffset();
  276. // check for corrupted user edit atom and try to repair it
  277. // if the next user edit atom offset is already known, we would go into an endless loop
  278. if (usrOffset > 0 && recordMap.containsKey(usrOffset)) {
  279. // a user edit atom is usually located 36 byte before the smallest known record offset
  280. usrOffset = recordMap.firstKey()-36;
  281. // check that we really are located on a user edit atom
  282. int ver_inst = LittleEndian.getUShort(docstream, usrOffset);
  283. int type = LittleEndian.getUShort(docstream, usrOffset+2);
  284. int len = LittleEndian.getInt(docstream, usrOffset+4);
  285. if (ver_inst == 0 && type == 4085 && (len == 0x1C || len == 0x20)) {
  286. logger.log(POILogger.WARN, "Repairing invalid user edit atom");
  287. usr.setLastUserEditAtomOffset(usrOffset);
  288. } else {
  289. throw new CorruptPowerPointFileException("Powerpoint document contains invalid user edit atom");
  290. }
  291. }
  292. }
  293. }
  294. /**
  295. * Find the "Current User" stream, and load it
  296. */
  297. private void readCurrentUserStream() {
  298. try {
  299. currentUser = new CurrentUserAtom(directory);
  300. } catch(IOException ie) {
  301. logger.log(POILogger.ERROR, "Error finding Current User Atom:\n" + ie);
  302. currentUser = new CurrentUserAtom();
  303. }
  304. }
  305. /**
  306. * Find any other streams from the filesystem, and load them
  307. */
  308. private void readOtherStreams() {
  309. // Currently, there aren't any
  310. }
  311. /**
  312. * Find and read in pictures contained in this presentation.
  313. * This is lazily called as and when we want to touch pictures.
  314. */
  315. @SuppressWarnings("unused")
  316. private void readPictures() throws IOException {
  317. _pictures = new ArrayList<PictureData>();
  318. // if the presentation doesn't contain pictures - will use a null set instead
  319. if (!directory.hasEntry("Pictures")) return;
  320. DocumentEntry entry = (DocumentEntry)directory.getEntry("Pictures");
  321. byte[] pictstream = new byte[entry.getSize()];
  322. DocumentInputStream is = directory.createDocumentInputStream(entry);
  323. is.read(pictstream);
  324. is.close();
  325. int pos = 0;
  326. // An empty picture record (length 0) will take up 8 bytes
  327. while (pos <= (pictstream.length-8)) {
  328. int offset = pos;
  329. // Image signature
  330. int signature = LittleEndian.getUShort(pictstream, pos);
  331. pos += LittleEndian.SHORT_SIZE;
  332. // Image type + 0xF018
  333. int type = LittleEndian.getUShort(pictstream, pos);
  334. pos += LittleEndian.SHORT_SIZE;
  335. // Image size (excluding the 8 byte header)
  336. int imgsize = LittleEndian.getInt(pictstream, pos);
  337. pos += LittleEndian.INT_SIZE;
  338. // When parsing the BStoreDelay stream, [MS-ODRAW] says that we
  339. // should terminate if the type isn't 0xf007 or 0xf018->0xf117
  340. if (!((type == 0xf007) || (type >= 0xf018 && type <= 0xf117)))
  341. break;
  342. // The image size must be 0 or greater
  343. // (0 is allowed, but odd, since we do wind on by the header each
  344. // time, so we won't get stuck)
  345. if(imgsize < 0) {
  346. throw new CorruptPowerPointFileException("The file contains a picture, at position " + _pictures.size() + ", which has a negatively sized data length, so we can't trust any of the picture data");
  347. }
  348. // If they type (including the bonus 0xF018) is 0, skip it
  349. if(type == 0) {
  350. logger.log(POILogger.ERROR, "Problem reading picture: Invalid image type 0, on picture with length " + imgsize + ".\nYou document will probably become corrupted if you save it!");
  351. logger.log(POILogger.ERROR, "" + pos);
  352. } else {
  353. // Build the PictureData object from the data
  354. try {
  355. PictureData pict = PictureData.create(type - 0xF018);
  356. // Copy the data, ready to pass to PictureData
  357. byte[] imgdata = new byte[imgsize];
  358. System.arraycopy(pictstream, pos, imgdata, 0, imgdata.length);
  359. pict.setRawData(imgdata);
  360. pict.setOffset(offset);
  361. _pictures.add(pict);
  362. } catch(IllegalArgumentException e) {
  363. logger.log(POILogger.ERROR, "Problem reading picture: " + e + "\nYou document will probably become corrupted if you save it!");
  364. }
  365. }
  366. pos += imgsize;
  367. }
  368. }
  369. /**
  370. * This is a helper functions, which is needed for adding new position dependent records
  371. * or finally write the slideshow to a file.
  372. *
  373. * @param os the stream to write to, if null only the references are updated
  374. * @param interestingRecords a map of interesting records (PersistPtrHolder and UserEditAtom)
  375. * referenced by their RecordType. Only the very last of each type will be saved to the map.
  376. * May be null, if not needed.
  377. * @throws IOException
  378. */
  379. public void updateAndWriteDependantRecords(OutputStream os, Map<RecordTypes.Type,PositionDependentRecord> interestingRecords)
  380. throws IOException {
  381. // For position dependent records, hold where they were and now are
  382. // As we go along, update, and hand over, to any Position Dependent
  383. // records we happen across
  384. Hashtable<Integer,Integer> oldToNewPositions = new Hashtable<Integer,Integer>();
  385. // First pass - figure out where all the position dependent
  386. // records are going to end up, in the new scheme
  387. // (Annoyingly, some powerpoint files have PersistPtrHolders
  388. // that reference slides after the PersistPtrHolder)
  389. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  390. for (Record record : _records) {
  391. if(record instanceof PositionDependentRecord) {
  392. PositionDependentRecord pdr = (PositionDependentRecord)record;
  393. int oldPos = pdr.getLastOnDiskOffset();
  394. int newPos = baos.size();
  395. pdr.setLastOnDiskOffset(newPos);
  396. if (oldPos != UNSET_OFFSET) {
  397. // new records don't need a mapping, as they aren't in a relation yet
  398. oldToNewPositions.put(Integer.valueOf(oldPos),Integer.valueOf(newPos));
  399. }
  400. }
  401. // Dummy write out, so the position winds on properly
  402. record.writeOut(baos);
  403. }
  404. baos = null;
  405. // For now, we're only handling PositionDependentRecord's that
  406. // happen at the top level.
  407. // In future, we'll need the handle them everywhere, but that's
  408. // a bit trickier
  409. UserEditAtom usr = null;
  410. for (Record record : _records) {
  411. if (record instanceof PositionDependentRecord) {
  412. // We've already figured out their new location, and
  413. // told them that
  414. // Tell them of the positions of the other records though
  415. PositionDependentRecord pdr = (PositionDependentRecord)record;
  416. pdr.updateOtherRecordReferences(oldToNewPositions);
  417. // Grab interesting records as they come past
  418. // this will only save the very last record of each type
  419. RecordTypes.Type saveme = null;
  420. int recordType = (int)record.getRecordType();
  421. if (recordType == RecordTypes.PersistPtrIncrementalBlock.typeID) {
  422. saveme = RecordTypes.PersistPtrIncrementalBlock;
  423. } else if (recordType == RecordTypes.UserEditAtom.typeID) {
  424. saveme = RecordTypes.UserEditAtom;
  425. usr = (UserEditAtom)pdr;
  426. }
  427. if (interestingRecords != null && saveme != null) {
  428. interestingRecords.put(saveme,pdr);
  429. }
  430. }
  431. // Whatever happens, write out that record tree
  432. if (os != null) {
  433. record.writeOut(os);
  434. }
  435. }
  436. // Update and write out the Current User atom
  437. int oldLastUserEditAtomPos = (int)currentUser.getCurrentEditOffset();
  438. Integer newLastUserEditAtomPos = oldToNewPositions.get(oldLastUserEditAtomPos);
  439. if(usr == null || newLastUserEditAtomPos == null || usr.getLastOnDiskOffset() != newLastUserEditAtomPos) {
  440. throw new HSLFException("Couldn't find the new location of the last UserEditAtom that used to be at " + oldLastUserEditAtomPos);
  441. }
  442. currentUser.setCurrentEditOffset(usr.getLastOnDiskOffset());
  443. }
  444. /**
  445. * Writes out the slideshow file the is represented by an instance
  446. * of this class.
  447. * It will write out the common OLE2 streams. If you require all
  448. * streams to be written out, pass in preserveNodes
  449. * @param out The OutputStream to write to.
  450. * @throws IOException If there is an unexpected IOException from
  451. * the passed in OutputStream
  452. */
  453. public void write(OutputStream out) throws IOException {
  454. // Write out, but only the common streams
  455. write(out,false);
  456. }
  457. /**
  458. * Writes out the slideshow file the is represented by an instance
  459. * of this class.
  460. * If you require all streams to be written out (eg Marcos, embeded
  461. * documents), then set preserveNodes to true
  462. * @param out The OutputStream to write to.
  463. * @param preserveNodes Should all OLE2 streams be written back out, or only the common ones?
  464. * @throws IOException If there is an unexpected IOException from
  465. * the passed in OutputStream
  466. */
  467. public void write(OutputStream out, boolean preserveNodes) throws IOException {
  468. // Get a new Filesystem to write into
  469. POIFSFileSystem outFS = new POIFSFileSystem();
  470. // The list of entries we've written out
  471. List<String> writtenEntries = new ArrayList<String>(1);
  472. // Write out the Property Streams
  473. writeProperties(outFS, writtenEntries);
  474. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  475. // For position dependent records, hold where they were and now are
  476. // As we go along, update, and hand over, to any Position Dependent
  477. // records we happen across
  478. updateAndWriteDependantRecords(baos, null);
  479. // Update our cached copy of the bytes that make up the PPT stream
  480. _docstream = baos.toByteArray();
  481. // Write the PPT stream into the POIFS layer
  482. ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
  483. outFS.createDocument(bais,"PowerPoint Document");
  484. writtenEntries.add("PowerPoint Document");
  485. currentUser.writeToFS(outFS);
  486. writtenEntries.add("Current User");
  487. // Write any pictures, into another stream
  488. if(_pictures == null) {
  489. readPictures();
  490. }
  491. if (_pictures.size() > 0) {
  492. ByteArrayOutputStream pict = new ByteArrayOutputStream();
  493. for (PictureData p : _pictures) {
  494. p.write(pict);
  495. }
  496. outFS.createDocument(
  497. new ByteArrayInputStream(pict.toByteArray()), "Pictures"
  498. );
  499. writtenEntries.add("Pictures");
  500. }
  501. // If requested, write out any other streams we spot
  502. if(preserveNodes) {
  503. EntryUtils.copyNodes(directory.getFileSystem(), outFS, writtenEntries);
  504. }
  505. // Send the POIFSFileSystem object out to the underlying stream
  506. outFS.writeFilesystem(out);
  507. }
  508. /* ******************* adding methods follow ********************* */
  509. /**
  510. * Adds a new root level record, at the end, but before the last
  511. * PersistPtrIncrementalBlock.
  512. */
  513. public synchronized int appendRootLevelRecord(Record newRecord) {
  514. int addedAt = -1;
  515. Record[] r = new Record[_records.length+1];
  516. boolean added = false;
  517. for(int i=(_records.length-1); i>=0; i--) {
  518. if(added) {
  519. // Just copy over
  520. r[i] = _records[i];
  521. } else {
  522. r[(i+1)] = _records[i];
  523. if(_records[i] instanceof PersistPtrHolder) {
  524. r[i] = newRecord;
  525. added = true;
  526. addedAt = i;
  527. }
  528. }
  529. }
  530. _records = r;
  531. return addedAt;
  532. }
  533. /**
  534. * Add a new picture to this presentation.
  535. *
  536. * @return offset of this picture in the Pictures stream
  537. */
  538. public int addPicture(PictureData img) {
  539. // Process any existing pictures if we haven't yet
  540. if(_pictures == null) {
  541. try {
  542. readPictures();
  543. } catch(IOException e) {
  544. throw new CorruptPowerPointFileException(e.getMessage());
  545. }
  546. }
  547. // Add the new picture in
  548. int offset = 0;
  549. if(_pictures.size() > 0) {
  550. PictureData prev = _pictures.get(_pictures.size() - 1);
  551. offset = prev.getOffset() + prev.getRawData().length + 8;
  552. }
  553. img.setOffset(offset);
  554. _pictures.add(img);
  555. return offset;
  556. }
  557. /* ******************* fetching methods follow ********************* */
  558. /**
  559. * Returns an array of all the records found in the slideshow
  560. */
  561. public Record[] getRecords() { return _records; }
  562. /**
  563. * Returns an array of the bytes of the file. Only correct after a
  564. * call to open or write - at all other times might be wrong!
  565. */
  566. public byte[] getUnderlyingBytes() { return _docstream; }
  567. /**
  568. * Fetch the Current User Atom of the document
  569. */
  570. public CurrentUserAtom getCurrentUserAtom() { return currentUser; }
  571. /**
  572. * Return array of pictures contained in this presentation
  573. *
  574. * @return array with the read pictures or <code>null</code> if the
  575. * presentation doesn't contain pictures.
  576. */
  577. public PictureData[] getPictures() {
  578. if(_pictures == null) {
  579. try {
  580. readPictures();
  581. } catch(IOException e) {
  582. throw new CorruptPowerPointFileException(e.getMessage());
  583. }
  584. }
  585. return _pictures.toArray(new PictureData[_pictures.size()]);
  586. }
  587. /**
  588. * Gets embedded object data from the slide show.
  589. *
  590. * @return the embedded objects.
  591. */
  592. public ObjectData[] getEmbeddedObjects() {
  593. if (_objects == null) {
  594. List<ObjectData> objects = new ArrayList<ObjectData>();
  595. for (Record r : _records) {
  596. if (r instanceof ExOleObjStg) {
  597. objects.add(new ObjectData((ExOleObjStg)r));
  598. }
  599. }
  600. _objects = objects.toArray(new ObjectData[objects.size()]);
  601. }
  602. return _objects;
  603. }
  604. }