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

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