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

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