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

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