PageRenderTime 72ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/ppt/scratchpad/src/org/apache/poi/hslf/usermodel/SlideShow.java

https://github.com/minstrelsy/POI-Android
Java | 1081 lines | 627 code | 124 blank | 330 comment | 132 complexity | 5d80afff23c354813b0c27bde8e947ac MD5 | raw file
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.hslf.usermodel;
  16. import java.io.ByteArrayOutputStream;
  17. import java.io.File;
  18. import java.io.FileInputStream;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.OutputStream;
  22. import java.util.*;
  23. import org.apache.poi.ddf.EscherBSERecord;
  24. import org.apache.poi.ddf.EscherContainerRecord;
  25. import org.apache.poi.ddf.EscherOptRecord;
  26. import org.apache.poi.ddf.EscherRecord;
  27. import org.apache.poi.hslf.HSLFSlideShow;
  28. import org.apache.poi.hslf.exceptions.CorruptPowerPointFileException;
  29. import org.apache.poi.hslf.exceptions.HSLFException;
  30. import org.apache.poi.hslf.model.*;
  31. import org.apache.poi.hslf.model.Notes;
  32. import org.apache.poi.hslf.model.Slide;
  33. import org.apache.poi.hslf.record.*;
  34. import org.apache.poi.hslf.record.SlideListWithText.SlideAtomsSet;
  35. import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
  36. import org.apache.poi.util.POILogFactory;
  37. import org.apache.poi.util.POILogger;
  38. import and.awt.Dimension;
  39. import and.awt.Rectangle;
  40. import and.awt.geom.Rectangle2D;
  41. import android.graphics.Rect;
  42. /**
  43. * This class is a friendly wrapper on top of the more scary HSLFSlideShow.
  44. *
  45. * TODO: - figure out how to match notes to their correct sheet (will involve
  46. * understanding DocSlideList and DocNotesList) - handle Slide creation cleaner
  47. *
  48. * @author Nick Burch
  49. * @author Yegor kozlov
  50. */
  51. public final class SlideShow {
  52. // What we're based on
  53. private HSLFSlideShow _hslfSlideShow;
  54. // Low level contents, as taken from HSLFSlideShow
  55. private Record[] _records;
  56. // Pointers to the most recent versions of the core records
  57. // (Document, Notes, Slide etc)
  58. private Record[] _mostRecentCoreRecords;
  59. // Lookup between the PersitPtr "sheet" IDs, and the position
  60. // in the mostRecentCoreRecords array
  61. private Hashtable<Integer,Integer> _sheetIdToCoreRecordsLookup;
  62. // Records that are interesting
  63. private Document _documentRecord;
  64. // Friendly objects for people to deal with
  65. private SlideMaster[] _masters;
  66. private TitleMaster[] _titleMasters;
  67. private Slide[] _slides;
  68. private Notes[] _notes;
  69. private FontCollection _fonts;
  70. // For logging
  71. private POILogger logger = POILogFactory.getLogger(this.getClass());
  72. /* ===============================================================
  73. * Setup Code
  74. * ===============================================================
  75. */
  76. /**
  77. * Constructs a Powerpoint document from the underlying
  78. * HSLFSlideShow object. Finds the model stuff from this
  79. *
  80. * @param hslfSlideShow the HSLFSlideShow to base on
  81. */
  82. public SlideShow(HSLFSlideShow hslfSlideShow) {
  83. // Get useful things from our base slideshow
  84. _hslfSlideShow = hslfSlideShow;
  85. _records = _hslfSlideShow.getRecords();
  86. // Handle Parent-aware Records
  87. for (Record record : _records) {
  88. if(record instanceof RecordContainer){
  89. RecordContainer.handleParentAwareRecords((RecordContainer)record);
  90. }
  91. }
  92. // Find the versions of the core records we'll want to use
  93. findMostRecentCoreRecords();
  94. // Build up the model level Slides and Notes
  95. buildSlidesAndNotes();
  96. }
  97. /**
  98. * Constructs a new, empty, Powerpoint document.
  99. */
  100. public SlideShow() {
  101. this(HSLFSlideShow.create());
  102. }
  103. /**
  104. * Constructs a Powerpoint document from an input stream.
  105. */
  106. public SlideShow(InputStream inputStream) throws IOException {
  107. this(new HSLFSlideShow(inputStream));
  108. }
  109. public SlideShow(File file) throws IOException {
  110. this(new HSLFSlideShow(new NPOIFSFileSystem(file)));
  111. }
  112. /**
  113. * Use the PersistPtrHolder entries to figure out what is the "most recent"
  114. * version of all the core records (Document, Notes, Slide etc), and save a
  115. * record of them. Do this by walking from the oldest PersistPtr to the
  116. * newest, overwriting any references found along the way with newer ones
  117. */
  118. private void findMostRecentCoreRecords() {
  119. // To start with, find the most recent in the byte offset domain
  120. Hashtable<Integer,Integer> mostRecentByBytes = new Hashtable<Integer,Integer>();
  121. for (int i = 0; i < _records.length; i++) {
  122. if (_records[i] instanceof PersistPtrHolder) {
  123. PersistPtrHolder pph = (PersistPtrHolder) _records[i];
  124. // If we've already seen any of the "slide" IDs for this
  125. // PersistPtr, remove their old positions
  126. int[] ids = pph.getKnownSlideIDs();
  127. for (int j = 0; j < ids.length; j++) {
  128. Integer id = Integer.valueOf(ids[j]);
  129. if (mostRecentByBytes.containsKey(id)) {
  130. mostRecentByBytes.remove(id);
  131. }
  132. }
  133. // Now, update the byte level locations with their latest values
  134. Hashtable<Integer,Integer> thisSetOfLocations = pph.getSlideLocationsLookup();
  135. for (int j = 0; j < ids.length; j++) {
  136. Integer id = Integer.valueOf(ids[j]);
  137. mostRecentByBytes.put(id, thisSetOfLocations.get(id));
  138. }
  139. }
  140. }
  141. // We now know how many unique special records we have, so init
  142. // the array
  143. _mostRecentCoreRecords = new Record[mostRecentByBytes.size()];
  144. // We'll also want to be able to turn the slide IDs into a position
  145. // in this array
  146. _sheetIdToCoreRecordsLookup = new Hashtable<Integer,Integer>();
  147. int[] allIDs = new int[_mostRecentCoreRecords.length];
  148. Enumeration<Integer> ids = mostRecentByBytes.keys();
  149. for (int i = 0; i < allIDs.length; i++) {
  150. Integer id = ids.nextElement();
  151. allIDs[i] = id.intValue();
  152. }
  153. Arrays.sort(allIDs);
  154. for (int i = 0; i < allIDs.length; i++) {
  155. _sheetIdToCoreRecordsLookup.put(Integer.valueOf(allIDs[i]), Integer.valueOf(i));
  156. }
  157. // Now convert the byte offsets back into record offsets
  158. for (int i = 0; i < _records.length; i++) {
  159. if (_records[i] instanceof PositionDependentRecord) {
  160. PositionDependentRecord pdr = (PositionDependentRecord) _records[i];
  161. Integer recordAt = Integer.valueOf(pdr.getLastOnDiskOffset());
  162. // Is it one we care about?
  163. for (int j = 0; j < allIDs.length; j++) {
  164. Integer thisID = Integer.valueOf(allIDs[j]);
  165. Integer thatRecordAt = mostRecentByBytes.get(thisID);
  166. if (thatRecordAt.equals(recordAt)) {
  167. // Bingo. Now, where do we store it?
  168. Integer storeAtI = _sheetIdToCoreRecordsLookup.get(thisID);
  169. int storeAt = storeAtI.intValue();
  170. // Tell it its Sheet ID, if it cares
  171. if (pdr instanceof PositionDependentRecordContainer) {
  172. PositionDependentRecordContainer pdrc = (PositionDependentRecordContainer) _records[i];
  173. pdrc.setSheetId(thisID.intValue());
  174. }
  175. // Finally, save the record
  176. _mostRecentCoreRecords[storeAt] = _records[i];
  177. }
  178. }
  179. }
  180. }
  181. // Now look for the interesting records in there
  182. for (int i = 0; i < _mostRecentCoreRecords.length; i++) {
  183. // Check there really is a record at this number
  184. if (_mostRecentCoreRecords[i] != null) {
  185. // Find the Document, and interesting things in it
  186. if (_mostRecentCoreRecords[i].getRecordType() == RecordTypes.Document.typeID) {
  187. _documentRecord = (Document) _mostRecentCoreRecords[i];
  188. _fonts = _documentRecord.getEnvironment().getFontCollection();
  189. }
  190. } else {
  191. // No record at this number
  192. // Odd, but not normally a problem
  193. }
  194. }
  195. }
  196. /**
  197. * For a given SlideAtomsSet, return the core record, based on the refID
  198. * from the SlidePersistAtom
  199. */
  200. private Record getCoreRecordForSAS(SlideAtomsSet sas) {
  201. SlidePersistAtom spa = sas.getSlidePersistAtom();
  202. int refID = spa.getRefID();
  203. return getCoreRecordForRefID(refID);
  204. }
  205. /**
  206. * For a given refID (the internal, 0 based numbering scheme), return the
  207. * core record
  208. *
  209. * @param refID
  210. * the refID
  211. */
  212. private Record getCoreRecordForRefID(int refID) {
  213. Integer coreRecordId = _sheetIdToCoreRecordsLookup.get(Integer.valueOf(refID));
  214. if (coreRecordId != null) {
  215. Record r = _mostRecentCoreRecords[coreRecordId.intValue()];
  216. return r;
  217. }
  218. logger.log(POILogger.ERROR,
  219. "We tried to look up a reference to a core record, but there was no core ID for reference ID "
  220. + refID);
  221. return null;
  222. }
  223. /**
  224. * Build up model level Slide and Notes objects, from the underlying
  225. * records.
  226. */
  227. private void buildSlidesAndNotes() {
  228. // Ensure we really found a Document record earlier
  229. // If we didn't, then the file is probably corrupt
  230. if (_documentRecord == null) {
  231. throw new CorruptPowerPointFileException(
  232. "The PowerPoint file didn't contain a Document Record in its PersistPtr blocks. It is probably corrupt.");
  233. }
  234. // Fetch the SlideListWithTexts in the most up-to-date Document Record
  235. //
  236. // As far as we understand it:
  237. // * The first SlideListWithText will contain a SlideAtomsSet
  238. // for each of the master slides
  239. // * The second SlideListWithText will contain a SlideAtomsSet
  240. // for each of the slides, in their current order
  241. // These SlideAtomsSets will normally contain text
  242. // * The third SlideListWithText (if present), will contain a
  243. // SlideAtomsSet for each Notes
  244. // These SlideAtomsSets will not normally contain text
  245. //
  246. // Having indentified the masters, slides and notes + their orders,
  247. // we have to go and find their matching records
  248. // We always use the latest versions of these records, and use the
  249. // SlideAtom/NotesAtom to match them with the StyleAtomSet
  250. SlideListWithText masterSLWT = _documentRecord.getMasterSlideListWithText();
  251. SlideListWithText slidesSLWT = _documentRecord.getSlideSlideListWithText();
  252. SlideListWithText notesSLWT = _documentRecord.getNotesSlideListWithText();
  253. // Find master slides
  254. // These can be MainMaster records, but oddly they can also be
  255. // Slides or Notes, and possibly even other odd stuff....
  256. // About the only thing you can say is that the master details are in
  257. // the first SLWT.
  258. SlideAtomsSet[] masterSets = new SlideAtomsSet[0];
  259. if (masterSLWT != null) {
  260. masterSets = masterSLWT.getSlideAtomsSets();
  261. ArrayList<SlideMaster> mmr = new ArrayList<SlideMaster>();
  262. ArrayList<TitleMaster> tmr = new ArrayList<TitleMaster>();
  263. for (int i = 0; i < masterSets.length; i++) {
  264. Record r = getCoreRecordForSAS(masterSets[i]);
  265. SlideAtomsSet sas = masterSets[i];
  266. int sheetNo = sas.getSlidePersistAtom().getSlideIdentifier();
  267. if (r instanceof org.apache.poi.hslf.record.Slide) {
  268. TitleMaster master = new TitleMaster((org.apache.poi.hslf.record.Slide) r,
  269. sheetNo);
  270. master.setSlideShow(this);
  271. tmr.add(master);
  272. } else if (r instanceof org.apache.poi.hslf.record.MainMaster) {
  273. SlideMaster master = new SlideMaster((org.apache.poi.hslf.record.MainMaster) r,
  274. sheetNo);
  275. master.setSlideShow(this);
  276. mmr.add(master);
  277. }
  278. }
  279. _masters = new SlideMaster[mmr.size()];
  280. mmr.toArray(_masters);
  281. _titleMasters = new TitleMaster[tmr.size()];
  282. tmr.toArray(_titleMasters);
  283. }
  284. // Having sorted out the masters, that leaves the notes and slides
  285. // Start by finding the notes records to go with the entries in
  286. // notesSLWT
  287. org.apache.poi.hslf.record.Notes[] notesRecords;
  288. SlideAtomsSet[] notesSets = new SlideAtomsSet[0];
  289. Hashtable<Integer,Integer> slideIdToNotes = new Hashtable<Integer,Integer>();
  290. if (notesSLWT == null) {
  291. // None
  292. notesRecords = new org.apache.poi.hslf.record.Notes[0];
  293. } else {
  294. // Match up the records and the SlideAtomSets
  295. notesSets = notesSLWT.getSlideAtomsSets();
  296. ArrayList<org.apache.poi.hslf.record.Notes> notesRecordsL =
  297. new ArrayList<org.apache.poi.hslf.record.Notes>();
  298. for (int i = 0; i < notesSets.length; i++) {
  299. // Get the right core record
  300. Record r = getCoreRecordForSAS(notesSets[i]);
  301. // Ensure it really is a notes record
  302. if (r instanceof org.apache.poi.hslf.record.Notes) {
  303. org.apache.poi.hslf.record.Notes notesRecord = (org.apache.poi.hslf.record.Notes) r;
  304. notesRecordsL.add(notesRecord);
  305. // Record the match between slide id and these notes
  306. SlidePersistAtom spa = notesSets[i].getSlidePersistAtom();
  307. Integer slideId = Integer.valueOf(spa.getSlideIdentifier());
  308. slideIdToNotes.put(slideId, Integer.valueOf(i));
  309. } else {
  310. logger.log(POILogger.ERROR, "A Notes SlideAtomSet at " + i
  311. + " said its record was at refID "
  312. + notesSets[i].getSlidePersistAtom().getRefID()
  313. + ", but that was actually a " + r);
  314. }
  315. }
  316. notesRecords = new org.apache.poi.hslf.record.Notes[notesRecordsL.size()];
  317. notesRecords = notesRecordsL.toArray(notesRecords);
  318. }
  319. // Now, do the same thing for our slides
  320. org.apache.poi.hslf.record.Slide[] slidesRecords;
  321. SlideAtomsSet[] slidesSets = new SlideAtomsSet[0];
  322. if (slidesSLWT == null) {
  323. // None
  324. slidesRecords = new org.apache.poi.hslf.record.Slide[0];
  325. } else {
  326. // Match up the records and the SlideAtomSets
  327. slidesSets = slidesSLWT.getSlideAtomsSets();
  328. slidesRecords = new org.apache.poi.hslf.record.Slide[slidesSets.length];
  329. for (int i = 0; i < slidesSets.length; i++) {
  330. // Get the right core record
  331. Record r = getCoreRecordForSAS(slidesSets[i]);
  332. // Ensure it really is a slide record
  333. if (r instanceof org.apache.poi.hslf.record.Slide) {
  334. slidesRecords[i] = (org.apache.poi.hslf.record.Slide) r;
  335. } else {
  336. logger.log(POILogger.ERROR, "A Slide SlideAtomSet at " + i
  337. + " said its record was at refID "
  338. + slidesSets[i].getSlidePersistAtom().getRefID()
  339. + ", but that was actually a " + r);
  340. }
  341. }
  342. }
  343. // Finally, generate model objects for everything
  344. // Notes first
  345. _notes = new Notes[notesRecords.length];
  346. for (int i = 0; i < _notes.length; i++) {
  347. _notes[i] = new Notes(notesRecords[i]);
  348. _notes[i].setSlideShow(this);
  349. }
  350. // Then slides
  351. _slides = new Slide[slidesRecords.length];
  352. for (int i = 0; i < _slides.length; i++) {
  353. SlideAtomsSet sas = slidesSets[i];
  354. int slideIdentifier = sas.getSlidePersistAtom().getSlideIdentifier();
  355. // Do we have a notes for this?
  356. Notes notes = null;
  357. // Slide.SlideAtom.notesId references the corresponding notes slide.
  358. // 0 if slide has no notes.
  359. int noteId = slidesRecords[i].getSlideAtom().getNotesID();
  360. if (noteId != 0) {
  361. Integer notesPos = (Integer) slideIdToNotes.get(Integer.valueOf(noteId));
  362. if (notesPos != null)
  363. notes = _notes[notesPos.intValue()];
  364. else
  365. logger.log(POILogger.ERROR, "Notes not found for noteId=" + noteId);
  366. }
  367. // Now, build our slide
  368. _slides[i] = new Slide(slidesRecords[i], notes, sas, slideIdentifier, (i + 1));
  369. _slides[i].setSlideShow(this);
  370. }
  371. }
  372. /**
  373. * Writes out the slideshow file the is represented by an instance of this
  374. * class
  375. *
  376. * @param out
  377. * The OutputStream to write to.
  378. * @throws IOException
  379. * If there is an unexpected IOException from the passed in
  380. * OutputStream
  381. */
  382. public void write(OutputStream out) throws IOException {
  383. _hslfSlideShow.write(out);
  384. }
  385. /*
  386. * ===============================================================
  387. * Accessor Code
  388. * ===============================================================
  389. */
  390. /**
  391. * Returns an array of the most recent version of all the interesting
  392. * records
  393. */
  394. public Record[] getMostRecentCoreRecords() {
  395. return _mostRecentCoreRecords;
  396. }
  397. /**
  398. * Returns an array of all the normal Slides found in the slideshow
  399. */
  400. public Slide[] getSlides() {
  401. return _slides;
  402. }
  403. /**
  404. * Returns an array of all the normal Notes found in the slideshow
  405. */
  406. public Notes[] getNotes() {
  407. return _notes;
  408. }
  409. /**
  410. * Returns an array of all the normal Slide Masters found in the slideshow
  411. */
  412. public SlideMaster[] getSlidesMasters() {
  413. return _masters;
  414. }
  415. /**
  416. * Returns an array of all the normal Title Masters found in the slideshow
  417. */
  418. public TitleMaster[] getTitleMasters() {
  419. return _titleMasters;
  420. }
  421. /**
  422. * Returns the data of all the pictures attached to the SlideShow
  423. */
  424. public PictureData[] getPictureData() {
  425. return _hslfSlideShow.getPictures();
  426. }
  427. /**
  428. * Returns the data of all the embedded OLE object in the SlideShow
  429. */
  430. public ObjectData[] getEmbeddedObjects() {
  431. return _hslfSlideShow.getEmbeddedObjects();
  432. }
  433. /**
  434. * Returns the data of all the embedded sounds in the SlideShow
  435. */
  436. public SoundData[] getSoundData() {
  437. return SoundData.find(_documentRecord);
  438. }
  439. /**
  440. * Return the current page size
  441. */
  442. public Dimension getPageSize() {
  443. DocumentAtom docatom = _documentRecord.getDocumentAtom();
  444. int pgx = (int) docatom.getSlideSizeX() * Shape.POINT_DPI / Shape.MASTER_DPI;
  445. int pgy = (int) docatom.getSlideSizeY() * Shape.POINT_DPI / Shape.MASTER_DPI;
  446. return new Dimension(pgx, pgy);
  447. }
  448. /**
  449. * Change the current page size
  450. *
  451. * @param pgsize
  452. * page size (in points)
  453. */
  454. public void setPageSize(Dimension pgsize) {
  455. DocumentAtom docatom = _documentRecord.getDocumentAtom();
  456. docatom.setSlideSizeX(pgsize.width * Shape.MASTER_DPI / Shape.POINT_DPI);
  457. docatom.setSlideSizeY(pgsize.height * Shape.MASTER_DPI / Shape.POINT_DPI);
  458. }
  459. /**
  460. * Helper method for usermodel: Get the font collection
  461. */
  462. protected FontCollection getFontCollection() {
  463. return _fonts;
  464. }
  465. /**
  466. * Helper method for usermodel and model: Get the document record
  467. */
  468. public Document getDocumentRecord() {
  469. return _documentRecord;
  470. }
  471. /*
  472. * ===============================================================
  473. * Re-ordering Code
  474. * ===============================================================
  475. */
  476. /**
  477. * Re-orders a slide, to a new position.
  478. *
  479. * @param oldSlideNumber
  480. * The old slide number (1 based)
  481. * @param newSlideNumber
  482. * The new slide number (1 based)
  483. */
  484. public void reorderSlide(int oldSlideNumber, int newSlideNumber) {
  485. // Ensure these numbers are valid
  486. if (oldSlideNumber < 1 || newSlideNumber < 1) {
  487. throw new IllegalArgumentException("Old and new slide numbers must be greater than 0");
  488. }
  489. if (oldSlideNumber > _slides.length || newSlideNumber > _slides.length) {
  490. throw new IllegalArgumentException(
  491. "Old and new slide numbers must not exceed the number of slides ("
  492. + _slides.length + ")");
  493. }
  494. // The order of slides is defined by the order of slide atom sets in the
  495. // SlideListWithText container.
  496. SlideListWithText slwt = _documentRecord.getSlideSlideListWithText();
  497. SlideAtomsSet[] sas = slwt.getSlideAtomsSets();
  498. SlideAtomsSet tmp = sas[oldSlideNumber - 1];
  499. sas[oldSlideNumber - 1] = sas[newSlideNumber - 1];
  500. sas[newSlideNumber - 1] = tmp;
  501. ArrayList<Record> lst = new ArrayList<Record>();
  502. for (int i = 0; i < sas.length; i++) {
  503. lst.add(sas[i].getSlidePersistAtom());
  504. Record[] r = sas[i].getSlideRecords();
  505. for (int j = 0; j < r.length; j++) {
  506. lst.add(r[j]);
  507. }
  508. _slides[i].setSlideNumber(i + 1);
  509. }
  510. Record[] r = lst.toArray(new Record[lst.size()]);
  511. slwt.setChildRecord(r);
  512. }
  513. /**
  514. * Removes the slide at the given index (0-based).
  515. * <p>
  516. * Shifts any subsequent slides to the left (subtracts one from their slide
  517. * numbers).
  518. * </p>
  519. *
  520. * @param index
  521. * the index of the slide to remove (0-based)
  522. * @return the slide that was removed from the slide show.
  523. */
  524. public Slide removeSlide(int index) {
  525. int lastSlideIdx = _slides.length - 1;
  526. if (index < 0 || index > lastSlideIdx) {
  527. throw new IllegalArgumentException("Slide index (" + index + ") is out of range (0.."
  528. + lastSlideIdx + ")");
  529. }
  530. SlideListWithText slwt = _documentRecord.getSlideSlideListWithText();
  531. SlideAtomsSet[] sas = slwt.getSlideAtomsSets();
  532. Slide removedSlide = null;
  533. ArrayList<Record> records = new ArrayList<Record>();
  534. ArrayList<SlideAtomsSet> sa = new ArrayList<SlideAtomsSet>();
  535. ArrayList<Slide> sl = new ArrayList<Slide>();
  536. ArrayList<Notes> nt = new ArrayList<Notes>();
  537. for (Notes notes : getNotes())
  538. nt.add(notes);
  539. for (int i = 0, num = 0; i < _slides.length; i++) {
  540. if (i != index) {
  541. sl.add(_slides[i]);
  542. sa.add(sas[i]);
  543. _slides[i].setSlideNumber(num++);
  544. records.add(sas[i].getSlidePersistAtom());
  545. records.addAll(Arrays.asList(sas[i].getSlideRecords()));
  546. } else {
  547. removedSlide = _slides[i];
  548. nt.remove(_slides[i].getNotesSheet());
  549. }
  550. }
  551. if (sa.size() == 0) {
  552. _documentRecord.removeSlideListWithText(slwt);
  553. } else {
  554. slwt.setSlideAtomsSets(sa.toArray(new SlideAtomsSet[sa.size()]));
  555. slwt.setChildRecord(records.toArray(new Record[records.size()]));
  556. }
  557. _slides = sl.toArray(new Slide[sl.size()]);
  558. // if the removed slide had notes - remove references to them too
  559. if (removedSlide != null) {
  560. int notesId = removedSlide.getSlideRecord().getSlideAtom().getNotesID();
  561. if (notesId != 0) {
  562. SlideListWithText nslwt = _documentRecord.getNotesSlideListWithText();
  563. records = new ArrayList<Record>();
  564. ArrayList<SlideAtomsSet> na = new ArrayList<SlideAtomsSet>();
  565. for (SlideAtomsSet ns : nslwt.getSlideAtomsSets()) {
  566. if (ns.getSlidePersistAtom().getSlideIdentifier() != notesId) {
  567. na.add(ns);
  568. records.add(ns.getSlidePersistAtom());
  569. if (ns.getSlideRecords() != null)
  570. records.addAll(Arrays.asList(ns.getSlideRecords()));
  571. }
  572. }
  573. if (na.size() == 0) {
  574. _documentRecord.removeSlideListWithText(nslwt);
  575. } else {
  576. nslwt.setSlideAtomsSets(na.toArray(new SlideAtomsSet[na.size()]));
  577. nslwt.setChildRecord(records.toArray(new Record[records.size()]));
  578. }
  579. }
  580. }
  581. _notes = nt.toArray(new Notes[nt.size()]);
  582. return removedSlide;
  583. }
  584. /*
  585. * ===============================================================
  586. * Addition Code
  587. * ===============================================================
  588. */
  589. /**
  590. * Create a blank <code>Slide</code>.
  591. *
  592. * @return the created <code>Slide</code>
  593. */
  594. public Slide createSlide() {
  595. SlideListWithText slist = null;
  596. // We need to add the records to the SLWT that deals
  597. // with Slides.
  598. // Add it, if it doesn't exist
  599. slist = _documentRecord.getSlideSlideListWithText();
  600. if (slist == null) {
  601. // Need to add a new one
  602. slist = new SlideListWithText();
  603. slist.setInstance(SlideListWithText.SLIDES);
  604. _documentRecord.addSlideListWithText(slist);
  605. }
  606. // Grab the SlidePersistAtom with the highest Slide Number.
  607. // (Will stay as null if no SlidePersistAtom exists yet in
  608. // the slide, or only master slide's ones do)
  609. SlidePersistAtom prev = null;
  610. SlideAtomsSet[] sas = slist.getSlideAtomsSets();
  611. for (int j = 0; j < sas.length; j++) {
  612. SlidePersistAtom spa = sas[j].getSlidePersistAtom();
  613. if (spa.getSlideIdentifier() < 0) {
  614. // This is for a master slide
  615. // Odd, since we only deal with the Slide SLWT
  616. } else {
  617. // Must be for a real slide
  618. if (prev == null) {
  619. prev = spa;
  620. }
  621. if (prev.getSlideIdentifier() < spa.getSlideIdentifier()) {
  622. prev = spa;
  623. }
  624. }
  625. }
  626. // Set up a new SlidePersistAtom for this slide
  627. SlidePersistAtom sp = new SlidePersistAtom();
  628. // First slideId is always 256
  629. sp.setSlideIdentifier(prev == null ? 256 : (prev.getSlideIdentifier() + 1));
  630. // Add this new SlidePersistAtom to the SlideListWithText
  631. slist.addSlidePersistAtom(sp);
  632. // Create a new Slide
  633. Slide slide = new Slide(sp.getSlideIdentifier(), sp.getRefID(), _slides.length + 1);
  634. slide.setSlideShow(this);
  635. slide.onCreate();
  636. // Add in to the list of Slides
  637. Slide[] s = new Slide[_slides.length + 1];
  638. System.arraycopy(_slides, 0, s, 0, _slides.length);
  639. s[_slides.length] = slide;
  640. _slides = s;
  641. logger.log(POILogger.INFO, "Added slide " + _slides.length + " with ref " + sp.getRefID()
  642. + " and identifier " + sp.getSlideIdentifier());
  643. // Add the core records for this new Slide to the record tree
  644. org.apache.poi.hslf.record.Slide slideRecord = slide.getSlideRecord();
  645. int slideRecordPos = _hslfSlideShow.appendRootLevelRecord(slideRecord);
  646. _records = _hslfSlideShow.getRecords();
  647. // Add the new Slide into the PersistPtr stuff
  648. int offset = 0;
  649. int slideOffset = 0;
  650. PersistPtrHolder ptr = null;
  651. UserEditAtom usr = null;
  652. for (int i = 0; i < _records.length; i++) {
  653. Record record = _records[i];
  654. ByteArrayOutputStream out = new ByteArrayOutputStream();
  655. try {
  656. record.writeOut(out);
  657. } catch (IOException e) {
  658. throw new HSLFException(e);
  659. }
  660. // Grab interesting records as they come past
  661. if (_records[i].getRecordType() == RecordTypes.PersistPtrIncrementalBlock.typeID) {
  662. ptr = (PersistPtrHolder) _records[i];
  663. }
  664. if (_records[i].getRecordType() == RecordTypes.UserEditAtom.typeID) {
  665. usr = (UserEditAtom) _records[i];
  666. }
  667. if (i == slideRecordPos) {
  668. slideOffset = offset;
  669. }
  670. offset += out.size();
  671. }
  672. // persist ID is UserEditAtom.maxPersistWritten + 1
  673. int psrId = usr.getMaxPersistWritten() + 1;
  674. sp.setRefID(psrId);
  675. slideRecord.setSheetId(psrId);
  676. // Last view is now of the slide
  677. usr.setLastViewType((short) UserEditAtom.LAST_VIEW_SLIDE_VIEW);
  678. usr.setMaxPersistWritten(psrId); // increment the number of persit
  679. // objects
  680. // Add the new slide into the last PersistPtr
  681. // (Also need to tell it where it is)
  682. slideRecord.setLastOnDiskOffset(slideOffset);
  683. ptr.addSlideLookup(sp.getRefID(), slideOffset);
  684. logger.log(POILogger.INFO, "New slide ended up at " + slideOffset);
  685. slide.setMasterSheet(_masters[0]);
  686. // All done and added
  687. return slide;
  688. }
  689. /**
  690. * Adds a picture to this presentation and returns the associated index.
  691. *
  692. * @param data
  693. * picture data
  694. * @param format
  695. * the format of the picture. One of constans defined in the
  696. * <code>Picture</code> class.
  697. * @return the index to this picture (1 based).
  698. */
  699. public int addPicture(byte[] data, int format) throws IOException {
  700. byte[] uid = PictureData.getChecksum(data);
  701. EscherContainerRecord bstore;
  702. EscherContainerRecord dggContainer = _documentRecord.getPPDrawingGroup().getDggContainer();
  703. bstore = (EscherContainerRecord) Shape.getEscherChild(dggContainer,
  704. EscherContainerRecord.BSTORE_CONTAINER);
  705. if (bstore == null) {
  706. bstore = new EscherContainerRecord();
  707. bstore.setRecordId(EscherContainerRecord.BSTORE_CONTAINER);
  708. dggContainer.addChildBefore(bstore, EscherOptRecord.RECORD_ID);
  709. } else {
  710. Iterator<EscherRecord> iter = bstore.getChildIterator();
  711. for (int i = 0; iter.hasNext(); i++) {
  712. EscherBSERecord bse = (EscherBSERecord) iter.next();
  713. if (Arrays.equals(bse.getUid(), uid)) {
  714. return i + 1;
  715. }
  716. }
  717. }
  718. PictureData pict = PictureData.create(format);
  719. pict.setData(data);
  720. int offset = _hslfSlideShow.addPicture(pict);
  721. EscherBSERecord bse = new EscherBSERecord();
  722. bse.setRecordId(EscherBSERecord.RECORD_ID);
  723. bse.setOptions((short) (0x0002 | (format << 4)));
  724. bse.setSize(pict.getRawData().length + 8);
  725. bse.setUid(uid);
  726. bse.setBlipTypeMacOS((byte) format);
  727. bse.setBlipTypeWin32((byte) format);
  728. if (format == Picture.EMF)
  729. bse.setBlipTypeMacOS((byte) Picture.PICT);
  730. else if (format == Picture.WMF)
  731. bse.setBlipTypeMacOS((byte) Picture.PICT);
  732. else if (format == Picture.PICT)
  733. bse.setBlipTypeWin32((byte) Picture.WMF);
  734. bse.setRef(0);
  735. bse.setOffset(offset);
  736. bse.setRemainingData(new byte[0]);
  737. bstore.addChildRecord(bse);
  738. int count = bstore.getChildRecords().size();
  739. bstore.setOptions((short) ((count << 4) | 0xF));
  740. return count;
  741. }
  742. /**
  743. * Adds a picture to this presentation and returns the associated index.
  744. *
  745. * @param pict
  746. * the file containing the image to add
  747. * @param format
  748. * the format of the picture. One of constans defined in the
  749. * <code>Picture</code> class.
  750. * @return the index to this picture (1 based).
  751. */
  752. public int addPicture(File pict, int format) throws IOException {
  753. int length = (int) pict.length();
  754. byte[] data = new byte[length];
  755. try {
  756. FileInputStream is = new FileInputStream(pict);
  757. is.read(data);
  758. is.close();
  759. } catch (IOException e) {
  760. throw new HSLFException(e);
  761. }
  762. return addPicture(data, format);
  763. }
  764. /**
  765. * Add a font in this presentation
  766. *
  767. * @param font
  768. * the font to add
  769. * @return 0-based index of the font
  770. */
  771. public int addFont(PPFont font) {
  772. FontCollection fonts = getDocumentRecord().getEnvironment().getFontCollection();
  773. int idx = fonts.getFontIndex(font.getFontName());
  774. if (idx == -1) {
  775. idx = fonts.addFont(font.getFontName(), font.getCharSet(), font.getFontFlags(), font
  776. .getFontType(), font.getPitchAndFamily());
  777. }
  778. return idx;
  779. }
  780. /**
  781. * Get a font by index
  782. *
  783. * @param idx
  784. * 0-based index of the font
  785. * @return of an instance of <code>PPFont</code> or <code>null</code> if not
  786. * found
  787. */
  788. public PPFont getFont(int idx) {
  789. PPFont font = null;
  790. FontCollection fonts = getDocumentRecord().getEnvironment().getFontCollection();
  791. Record[] ch = fonts.getChildRecords();
  792. for (int i = 0; i < ch.length; i++) {
  793. if (ch[i] instanceof FontEntityAtom) {
  794. FontEntityAtom atom = (FontEntityAtom) ch[i];
  795. if (atom.getFontIndex() == idx) {
  796. font = new PPFont(atom);
  797. break;
  798. }
  799. }
  800. }
  801. return font;
  802. }
  803. /**
  804. * get the number of fonts in the presentation
  805. *
  806. * @return number of fonts
  807. */
  808. public int getNumberOfFonts() {
  809. return getDocumentRecord().getEnvironment().getFontCollection().getNumberOfFonts();
  810. }
  811. /**
  812. * Return Header / Footer settings for slides
  813. *
  814. * @return Header / Footer settings for slides
  815. */
  816. public HeadersFooters getSlideHeadersFooters() {
  817. // detect if this ppt was saved in Office2007
  818. String tag = getSlidesMasters()[0].getProgrammableTag();
  819. boolean ppt2007 = "___PPT12".equals(tag);
  820. HeadersFootersContainer hdd = null;
  821. Record[] ch = _documentRecord.getChildRecords();
  822. for (int i = 0; i < ch.length; i++) {
  823. if (ch[i] instanceof HeadersFootersContainer
  824. && ((HeadersFootersContainer) ch[i]).getOptions() == HeadersFootersContainer.SlideHeadersFootersContainer) {
  825. hdd = (HeadersFootersContainer) ch[i];
  826. break;
  827. }
  828. }
  829. boolean newRecord = false;
  830. if (hdd == null) {
  831. hdd = new HeadersFootersContainer(HeadersFootersContainer.SlideHeadersFootersContainer);
  832. newRecord = true;
  833. }
  834. return new HeadersFooters(hdd, this, newRecord, ppt2007);
  835. }
  836. /**
  837. * Return Header / Footer settings for notes
  838. *
  839. * @return Header / Footer settings for notes
  840. */
  841. public HeadersFooters getNotesHeadersFooters() {
  842. // detect if this ppt was saved in Office2007
  843. String tag = getSlidesMasters()[0].getProgrammableTag();
  844. boolean ppt2007 = "___PPT12".equals(tag);
  845. HeadersFootersContainer hdd = null;
  846. Record[] ch = _documentRecord.getChildRecords();
  847. for (int i = 0; i < ch.length; i++) {
  848. if (ch[i] instanceof HeadersFootersContainer
  849. && ((HeadersFootersContainer) ch[i]).getOptions() == HeadersFootersContainer.NotesHeadersFootersContainer) {
  850. hdd = (HeadersFootersContainer) ch[i];
  851. break;
  852. }
  853. }
  854. boolean newRecord = false;
  855. if (hdd == null) {
  856. hdd = new HeadersFootersContainer(HeadersFootersContainer.NotesHeadersFootersContainer);
  857. newRecord = true;
  858. }
  859. if (ppt2007 && _notes.length > 0) {
  860. return new HeadersFooters(hdd, _notes[0], newRecord, ppt2007);
  861. }
  862. return new HeadersFooters(hdd, this, newRecord, ppt2007);
  863. }
  864. /**
  865. * Add a movie in this presentation
  866. *
  867. * @param path
  868. * the path or url to the movie
  869. * @return 0-based index of the movie
  870. */
  871. public int addMovie(String path, int type) {
  872. ExObjList lst = (ExObjList) _documentRecord.findFirstOfType(RecordTypes.ExObjList.typeID);
  873. if (lst == null) {
  874. lst = new ExObjList();
  875. _documentRecord.addChildAfter(lst, _documentRecord.getDocumentAtom());
  876. }
  877. ExObjListAtom objAtom = lst.getExObjListAtom();
  878. // increment the object ID seed
  879. int objectId = (int) objAtom.getObjectIDSeed() + 1;
  880. objAtom.setObjectIDSeed(objectId);
  881. ExMCIMovie mci;
  882. switch (type) {
  883. case MovieShape.MOVIE_MPEG:
  884. mci = new ExMCIMovie();
  885. break;
  886. case MovieShape.MOVIE_AVI:
  887. mci = new ExAviMovie();
  888. break;
  889. default:
  890. throw new IllegalArgumentException("Unsupported Movie: " + type);
  891. }
  892. lst.appendChildRecord(mci);
  893. ExVideoContainer exVideo = mci.getExVideo();
  894. exVideo.getExMediaAtom().setObjectId(objectId);
  895. exVideo.getExMediaAtom().setMask(0xE80000);
  896. exVideo.getPathAtom().setText(path);
  897. return objectId;
  898. }
  899. /**
  900. * Add a control in this presentation
  901. *
  902. * @param name
  903. * name of the control, e.g. "Shockwave Flash Object"
  904. * @param progId
  905. * OLE Programmatic Identifier, e.g.
  906. * "ShockwaveFlash.ShockwaveFlash.9"
  907. * @return 0-based index of the control
  908. */
  909. public int addControl(String name, String progId) {
  910. ExObjList lst = (ExObjList) _documentRecord.findFirstOfType(RecordTypes.ExObjList.typeID);
  911. if (lst == null) {
  912. lst = new ExObjList();
  913. _documentRecord.addChildAfter(lst, _documentRecord.getDocumentAtom());
  914. }
  915. ExObjListAtom objAtom = lst.getExObjListAtom();
  916. // increment the object ID seed
  917. int objectId = (int) objAtom.getObjectIDSeed() + 1;
  918. objAtom.setObjectIDSeed(objectId);
  919. ExControl ctrl = new ExControl();
  920. ExOleObjAtom oleObj = ctrl.getExOleObjAtom();
  921. oleObj.setObjID(objectId);
  922. oleObj.setDrawAspect(ExOleObjAtom.DRAW_ASPECT_VISIBLE);
  923. oleObj.setType(ExOleObjAtom.TYPE_CONTROL);
  924. oleObj.setSubType(ExOleObjAtom.SUBTYPE_DEFAULT);
  925. ctrl.setProgId(progId);
  926. ctrl.setMenuName(name);
  927. ctrl.setClipboardName(name);
  928. lst.addChildAfter(ctrl, objAtom);
  929. return objectId;
  930. }
  931. /**
  932. * Add a hyperlink to this presentation
  933. *
  934. * @return 0-based index of the hyperlink
  935. */
  936. public int addHyperlink(Hyperlink link) {
  937. ExObjList lst = (ExObjList) _documentRecord.findFirstOfType(RecordTypes.ExObjList.typeID);
  938. if (lst == null) {
  939. lst = new ExObjList();
  940. _documentRecord.addChildAfter(lst, _documentRecord.getDocumentAtom());
  941. }
  942. ExObjListAtom objAtom = lst.getExObjListAtom();
  943. // increment the object ID seed
  944. int objectId = (int) objAtom.getObjectIDSeed() + 1;
  945. objAtom.setObjectIDSeed(objectId);
  946. ExHyperlink ctrl = new ExHyperlink();
  947. ExHyperlinkAtom obj = ctrl.getExHyperlinkAtom();
  948. obj.setNumber(objectId);
  949. ctrl.setLinkURL(link.getAddress());
  950. ctrl.setLinkTitle(link.getTitle());
  951. lst.addChildAfter(ctrl, objAtom);
  952. link.setId(objectId);
  953. return objectId;
  954. }
  955. }