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.

HSLFTextParagraph.java 62KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747
  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 static org.apache.poi.hslf.record.RecordTypes.OutlineTextRefAtom;
  17. import java.awt.Color;
  18. import java.io.IOException;
  19. import java.util.ArrayList;
  20. import java.util.Arrays;
  21. import java.util.Iterator;
  22. import java.util.List;
  23. import java.util.function.Consumer;
  24. import java.util.stream.Collectors;
  25. import org.apache.poi.common.usermodel.fonts.FontGroup;
  26. import org.apache.poi.common.usermodel.fonts.FontInfo;
  27. import org.apache.poi.hslf.exceptions.HSLFException;
  28. import org.apache.poi.hslf.model.textproperties.BitMaskTextProp;
  29. import org.apache.poi.hslf.model.textproperties.FontAlignmentProp;
  30. import org.apache.poi.hslf.model.textproperties.HSLFTabStop;
  31. import org.apache.poi.hslf.model.textproperties.HSLFTabStopPropCollection;
  32. import org.apache.poi.hslf.model.textproperties.IndentProp;
  33. import org.apache.poi.hslf.model.textproperties.ParagraphFlagsTextProp;
  34. import org.apache.poi.hslf.model.textproperties.TextAlignmentProp;
  35. import org.apache.poi.hslf.model.textproperties.TextPFException9;
  36. import org.apache.poi.hslf.model.textproperties.TextProp;
  37. import org.apache.poi.hslf.model.textproperties.TextPropCollection;
  38. import org.apache.poi.hslf.model.textproperties.TextPropCollection.TextPropType;
  39. import org.apache.poi.hslf.record.ColorSchemeAtom;
  40. import org.apache.poi.hslf.record.EscherTextboxWrapper;
  41. import org.apache.poi.hslf.record.InteractiveInfo;
  42. import org.apache.poi.hslf.record.MasterTextPropAtom;
  43. import org.apache.poi.hslf.record.OutlineTextRefAtom;
  44. import org.apache.poi.hslf.record.PPDrawing;
  45. import org.apache.poi.hslf.record.RecordContainer;
  46. import org.apache.poi.hslf.record.RecordTypes;
  47. import org.apache.poi.hslf.record.RoundTripHFPlaceholder12;
  48. import org.apache.poi.hslf.record.SlideListWithText;
  49. import org.apache.poi.hslf.record.SlidePersistAtom;
  50. import org.apache.poi.hslf.record.StyleTextProp9Atom;
  51. import org.apache.poi.hslf.record.StyleTextPropAtom;
  52. import org.apache.poi.hslf.record.TextBytesAtom;
  53. import org.apache.poi.hslf.record.TextCharsAtom;
  54. import org.apache.poi.hslf.record.TextHeaderAtom;
  55. import org.apache.poi.hslf.record.TextRulerAtom;
  56. import org.apache.poi.hslf.record.TextSpecInfoAtom;
  57. import org.apache.poi.hslf.record.TxInteractiveInfoAtom;
  58. import org.apache.poi.sl.draw.DrawPaint;
  59. import org.apache.poi.sl.usermodel.AutoNumberingScheme;
  60. import org.apache.poi.sl.usermodel.PaintStyle;
  61. import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint;
  62. import org.apache.poi.sl.usermodel.Placeholder;
  63. import org.apache.poi.sl.usermodel.TabStop;
  64. import org.apache.poi.sl.usermodel.TabStop.TabStopType;
  65. import org.apache.poi.sl.usermodel.TextParagraph;
  66. import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder;
  67. import org.apache.poi.util.POILogFactory;
  68. import org.apache.poi.util.POILogger;
  69. import org.apache.poi.util.StringUtil;
  70. import org.apache.poi.util.Units;
  71. /**
  72. * This class represents a run of text in a powerpoint document. That
  73. * run could be text on a sheet, or text in a note.
  74. * It is only a very basic class for now
  75. */
  76. public final class HSLFTextParagraph implements TextParagraph<HSLFShape,HSLFTextParagraph,HSLFTextRun> {
  77. protected static final POILogger logger = POILogFactory.getLogger(HSLFTextParagraph.class);
  78. /**
  79. * How to align the text
  80. */
  81. /* package */static final int AlignLeft = 0;
  82. /* package */static final int AlignCenter = 1;
  83. /* package */static final int AlignRight = 2;
  84. /* package */static final int AlignJustify = 3;
  85. // Note: These fields are protected to help with unit testing
  86. // Other classes shouldn't really go playing with them!
  87. private final TextHeaderAtom _headerAtom;
  88. private TextBytesAtom _byteAtom;
  89. private TextCharsAtom _charAtom;
  90. private TextPropCollection _paragraphStyle;
  91. protected TextRulerAtom _ruler;
  92. protected final List<HSLFTextRun> _runs = new ArrayList<>();
  93. protected HSLFTextShape _parentShape;
  94. private HSLFSheet _sheet;
  95. private int shapeId;
  96. private StyleTextProp9Atom styleTextProp9Atom;
  97. private boolean _dirty;
  98. private final List<HSLFTextParagraph> parentList;
  99. private class HSLFTabStopDecorator implements TabStop {
  100. final HSLFTabStop tabStop;
  101. HSLFTabStopDecorator(final HSLFTabStop tabStop) {
  102. this.tabStop = tabStop;
  103. }
  104. public double getPositionInPoints() {
  105. return tabStop.getPositionInPoints();
  106. }
  107. public void setPositionInPoints(double position) {
  108. tabStop.setPositionInPoints(position);
  109. setDirty();
  110. }
  111. public TabStopType getType() {
  112. return tabStop.getType();
  113. }
  114. public void setType(TabStopType type) {
  115. tabStop.setType(type);
  116. setDirty();
  117. }
  118. }
  119. /**
  120. * Constructs a Text Run from a Unicode text block.
  121. * Either a {@link TextCharsAtom} or a {@link TextBytesAtom} needs to be provided.
  122. *
  123. * @param tha the TextHeaderAtom that defines what's what
  124. * @param tba the TextBytesAtom containing the text or null if {@link TextCharsAtom} is provided
  125. * @param tca the TextCharsAtom containing the text or null if {@link TextBytesAtom} is provided
  126. * @param parentList the list which contains this paragraph
  127. */
  128. /* package */ HSLFTextParagraph(
  129. TextHeaderAtom tha,
  130. TextBytesAtom tba,
  131. TextCharsAtom tca,
  132. List<HSLFTextParagraph> parentList
  133. ) {
  134. if (tha == null) {
  135. throw new IllegalArgumentException("TextHeaderAtom must be set.");
  136. }
  137. _headerAtom = tha;
  138. _byteAtom = tba;
  139. _charAtom = tca;
  140. this.parentList = parentList;
  141. setParagraphStyle(new TextPropCollection(1, TextPropType.paragraph));
  142. }
  143. /* package */HSLFTextParagraph(HSLFTextParagraph other) {
  144. _headerAtom = other._headerAtom;
  145. _byteAtom = other._byteAtom;
  146. _charAtom = other._charAtom;
  147. _parentShape = other._parentShape;
  148. _sheet = other._sheet;
  149. _ruler = other._ruler;
  150. shapeId = other.shapeId;
  151. parentList = other.parentList;
  152. setParagraphStyle(other._paragraphStyle);
  153. }
  154. public void addTextRun(HSLFTextRun run) {
  155. _runs.add(run);
  156. }
  157. @Override
  158. public List<HSLFTextRun> getTextRuns() {
  159. return _runs;
  160. }
  161. public TextPropCollection getParagraphStyle() {
  162. return _paragraphStyle;
  163. }
  164. public void setParagraphStyle(TextPropCollection paragraphStyle) {
  165. _paragraphStyle = paragraphStyle;
  166. }
  167. /**
  168. * Supply the Sheet we belong to, which might have an assigned SlideShow
  169. * Also passes it on to our child RichTextRuns
  170. */
  171. public static void supplySheet(List<HSLFTextParagraph> paragraphs, HSLFSheet sheet) {
  172. if (paragraphs == null) {
  173. return;
  174. }
  175. for (HSLFTextParagraph p : paragraphs) {
  176. p.supplySheet(sheet);
  177. }
  178. assert(sheet.getSlideShow() != null);
  179. }
  180. /**
  181. * Supply the Sheet we belong to, which might have an assigned SlideShow
  182. * Also passes it on to our child RichTextRuns
  183. */
  184. private void supplySheet(HSLFSheet sheet) {
  185. this._sheet = sheet;
  186. for (HSLFTextRun rt : _runs) {
  187. rt.updateSheet();
  188. }
  189. }
  190. public HSLFSheet getSheet() {
  191. return this._sheet;
  192. }
  193. /**
  194. * @return Shape ID
  195. */
  196. protected int getShapeId() {
  197. return shapeId;
  198. }
  199. /**
  200. * @param id Shape ID
  201. */
  202. protected void setShapeId(int id) {
  203. shapeId = id;
  204. }
  205. /**
  206. * @return 0-based index of the text run in the SLWT container
  207. */
  208. protected int getIndex() {
  209. return (_headerAtom != null) ? _headerAtom.getIndex() : -1;
  210. }
  211. /**
  212. * Sets the index of the paragraph in the SLWT container
  213. *
  214. * @param index
  215. */
  216. protected void setIndex(int index) {
  217. if (_headerAtom != null) {
  218. _headerAtom.setIndex(index);
  219. }
  220. }
  221. /**
  222. * Returns the type of the text, from the TextHeaderAtom.
  223. * Possible values can be seen from TextHeaderAtom
  224. * @see org.apache.poi.hslf.record.TextHeaderAtom
  225. */
  226. public int getRunType() {
  227. return (_headerAtom != null) ? _headerAtom.getTextType() : -1;
  228. }
  229. public void setRunType(int runType) {
  230. if (_headerAtom != null) {
  231. _headerAtom.setTextType(runType);
  232. }
  233. }
  234. /**
  235. * Is this Text Run one from a {@link PPDrawing}, or is it
  236. * one from the {@link SlideListWithText}?
  237. */
  238. public boolean isDrawingBased() {
  239. return (getIndex() == -1);
  240. }
  241. public TextRulerAtom getTextRuler() {
  242. return _ruler;
  243. }
  244. public TextRulerAtom createTextRuler() {
  245. _ruler = getTextRuler();
  246. if (_ruler == null) {
  247. _ruler = TextRulerAtom.getParagraphInstance();
  248. org.apache.poi.hslf.record.Record childAfter = _byteAtom;
  249. if (childAfter == null) {
  250. childAfter = _charAtom;
  251. }
  252. if (childAfter == null) {
  253. childAfter = _headerAtom;
  254. }
  255. _headerAtom.getParentRecord().addChildAfter(_ruler, childAfter);
  256. }
  257. return _ruler;
  258. }
  259. /**
  260. * Returns records that make up the list of text paragraphs
  261. * (there can be misc InteractiveInfo, TxInteractiveInfo and other records)
  262. *
  263. * @return text run records
  264. */
  265. public org.apache.poi.hslf.record.Record[] getRecords() {
  266. org.apache.poi.hslf.record.Record[] r = _headerAtom.getParentRecord().getChildRecords();
  267. return getRecords(r, new int[] { 0 }, _headerAtom);
  268. }
  269. private static org.apache.poi.hslf.record.Record[] getRecords(org.apache.poi.hslf.record.Record[] records, int[] startIdx, TextHeaderAtom headerAtom) {
  270. if (records == null) {
  271. throw new NullPointerException("records need to be set.");
  272. }
  273. for (; startIdx[0] < records.length; startIdx[0]++) {
  274. org.apache.poi.hslf.record.Record r = records[startIdx[0]];
  275. if (r instanceof TextHeaderAtom && (headerAtom == null || r == headerAtom)) {
  276. break;
  277. }
  278. }
  279. if (startIdx[0] >= records.length) {
  280. logger.log(POILogger.INFO, "header atom wasn't found - container might contain only an OutlineTextRefAtom");
  281. return new org.apache.poi.hslf.record.Record[0];
  282. }
  283. int length;
  284. for (length = 1; startIdx[0] + length < records.length; length++) {
  285. org.apache.poi.hslf.record.Record r = records[startIdx[0]+length];
  286. if (r instanceof TextHeaderAtom || r instanceof SlidePersistAtom) {
  287. break;
  288. }
  289. }
  290. org.apache.poi.hslf.record.Record[] result = Arrays.copyOfRange(records, startIdx[0], startIdx[0]+length, org.apache.poi.hslf.record.Record[].class);
  291. startIdx[0] += length;
  292. return result;
  293. }
  294. /** Numbered List info */
  295. public void setStyleTextProp9Atom(final StyleTextProp9Atom styleTextProp9Atom) {
  296. this.styleTextProp9Atom = styleTextProp9Atom;
  297. }
  298. /** Numbered List info */
  299. public StyleTextProp9Atom getStyleTextProp9Atom() {
  300. return this.styleTextProp9Atom;
  301. }
  302. @Override
  303. public Iterator<HSLFTextRun> iterator() {
  304. return _runs.iterator();
  305. }
  306. @Override
  307. public Double getLeftMargin() {
  308. Integer val = null;
  309. if (_ruler != null) {
  310. Integer[] toList = _ruler.getTextOffsets();
  311. val = (toList.length > getIndentLevel()) ? toList[getIndentLevel()] : null;
  312. }
  313. if (val == null) {
  314. TextProp tp = getPropVal(_paragraphStyle, "text.offset");
  315. val = (tp == null) ? null : tp.getValue();
  316. }
  317. return (val == null) ? null : Units.masterToPoints(val);
  318. }
  319. @Override
  320. public void setLeftMargin(Double leftMargin) {
  321. Integer val = (leftMargin == null) ? null : Units.pointsToMaster(leftMargin);
  322. setParagraphTextPropVal("text.offset", val);
  323. }
  324. @Override
  325. public Double getRightMargin() {
  326. // TODO: find out, how to determine this value
  327. return null;
  328. }
  329. @Override
  330. public void setRightMargin(Double rightMargin) {
  331. // TODO: find out, how to set this value
  332. }
  333. @Override
  334. public Double getIndent() {
  335. Integer val = null;
  336. if (_ruler != null) {
  337. Integer[] toList = _ruler.getBulletOffsets();
  338. val = (toList.length > getIndentLevel()) ? toList[getIndentLevel()] : null;
  339. }
  340. if (val == null) {
  341. TextProp tp = getPropVal(_paragraphStyle, "bullet.offset");
  342. val = (tp == null) ? null : tp.getValue();
  343. }
  344. return (val == null) ? null : Units.masterToPoints(val);
  345. }
  346. @Override
  347. public void setIndent(Double indent) {
  348. Integer val = (indent == null) ? null : Units.pointsToMaster(indent);
  349. setParagraphTextPropVal("bullet.offset", val);
  350. }
  351. @Override
  352. public String getDefaultFontFamily() {
  353. FontInfo fontInfo = null;
  354. if (!_runs.isEmpty()) {
  355. HSLFTextRun tr = _runs.get(0);
  356. fontInfo = tr.getFontInfo(null);
  357. // fallback to LATIN if the font for the font group wasn't defined
  358. if (fontInfo == null) {
  359. fontInfo = tr.getFontInfo(FontGroup.LATIN);
  360. }
  361. }
  362. if (fontInfo == null) {
  363. fontInfo = HSLFFontInfoPredefined.ARIAL;
  364. }
  365. return fontInfo.getTypeface();
  366. }
  367. @Override
  368. public Double getDefaultFontSize() {
  369. Double d = null;
  370. if (!_runs.isEmpty()) {
  371. d = _runs.get(0).getFontSize();
  372. }
  373. return (d != null) ? d : 12d;
  374. }
  375. @Override
  376. public void setTextAlign(TextAlign align) {
  377. Integer alignInt = null;
  378. if (align != null) {
  379. switch (align) {
  380. default:
  381. case LEFT: alignInt = TextAlignmentProp.LEFT;break;
  382. case CENTER: alignInt = TextAlignmentProp.CENTER; break;
  383. case RIGHT: alignInt = TextAlignmentProp.RIGHT; break;
  384. case DIST: alignInt = TextAlignmentProp.DISTRIBUTED; break;
  385. case JUSTIFY: alignInt = TextAlignmentProp.JUSTIFY; break;
  386. case JUSTIFY_LOW: alignInt = TextAlignmentProp.JUSTIFYLOW; break;
  387. case THAI_DIST: alignInt = TextAlignmentProp.THAIDISTRIBUTED; break;
  388. }
  389. }
  390. setParagraphTextPropVal("alignment", alignInt);
  391. }
  392. @Override
  393. public TextAlign getTextAlign() {
  394. TextProp tp = getPropVal(_paragraphStyle, "alignment");
  395. if (tp == null) {
  396. return null;
  397. }
  398. switch (tp.getValue()) {
  399. default:
  400. case TextAlignmentProp.LEFT: return TextAlign.LEFT;
  401. case TextAlignmentProp.CENTER: return TextAlign.CENTER;
  402. case TextAlignmentProp.RIGHT: return TextAlign.RIGHT;
  403. case TextAlignmentProp.JUSTIFY: return TextAlign.JUSTIFY;
  404. case TextAlignmentProp.JUSTIFYLOW: return TextAlign.JUSTIFY_LOW;
  405. case TextAlignmentProp.DISTRIBUTED: return TextAlign.DIST;
  406. case TextAlignmentProp.THAIDISTRIBUTED: return TextAlign.THAI_DIST;
  407. }
  408. }
  409. @Override
  410. public FontAlign getFontAlign() {
  411. TextProp tp = getPropVal(_paragraphStyle, FontAlignmentProp.NAME);
  412. if (tp == null) {
  413. return null;
  414. }
  415. switch (tp.getValue()) {
  416. case FontAlignmentProp.BASELINE: return FontAlign.BASELINE;
  417. case FontAlignmentProp.TOP: return FontAlign.TOP;
  418. case FontAlignmentProp.CENTER: return FontAlign.CENTER;
  419. case FontAlignmentProp.BOTTOM: return FontAlign.BOTTOM;
  420. default: return FontAlign.AUTO;
  421. }
  422. }
  423. public AutoNumberingScheme getAutoNumberingScheme() {
  424. if (styleTextProp9Atom == null) {
  425. return null;
  426. }
  427. TextPFException9[] ant = styleTextProp9Atom.getAutoNumberTypes();
  428. int level = getIndentLevel();
  429. if (ant == null || level == -1 || level >= ant.length) {
  430. return null;
  431. }
  432. return ant[level].getAutoNumberScheme();
  433. }
  434. public Integer getAutoNumberingStartAt() {
  435. if (styleTextProp9Atom == null) {
  436. return null;
  437. }
  438. TextPFException9[] ant = styleTextProp9Atom.getAutoNumberTypes();
  439. int level = getIndentLevel();
  440. if (ant == null || level >= ant.length) {
  441. return null;
  442. }
  443. Short startAt = ant[level].getAutoNumberStartNumber();
  444. assert(startAt != null);
  445. return startAt.intValue();
  446. }
  447. @Override
  448. public BulletStyle getBulletStyle() {
  449. if (!isBullet() && getAutoNumberingScheme() == null) {
  450. return null;
  451. }
  452. return new BulletStyle() {
  453. @Override
  454. public String getBulletCharacter() {
  455. Character chr = HSLFTextParagraph.this.getBulletChar();
  456. return (chr == null || chr == 0) ? "" : "" + chr;
  457. }
  458. @Override
  459. public String getBulletFont() {
  460. return HSLFTextParagraph.this.getBulletFont();
  461. }
  462. @Override
  463. public Double getBulletFontSize() {
  464. return HSLFTextParagraph.this.getBulletSize();
  465. }
  466. @Override
  467. public void setBulletFontColor(Color color) {
  468. setBulletFontColor(DrawPaint.createSolidPaint(color));
  469. }
  470. @Override
  471. public void setBulletFontColor(PaintStyle color) {
  472. if (!(color instanceof SolidPaint)) {
  473. throw new IllegalArgumentException("HSLF only supports SolidPaint");
  474. }
  475. SolidPaint sp = (SolidPaint)color;
  476. Color col = DrawPaint.applyColorTransform(sp.getSolidColor());
  477. HSLFTextParagraph.this.setBulletColor(col);
  478. }
  479. @Override
  480. public PaintStyle getBulletFontColor() {
  481. Color col = HSLFTextParagraph.this.getBulletColor();
  482. return DrawPaint.createSolidPaint(col);
  483. }
  484. @Override
  485. public AutoNumberingScheme getAutoNumberingScheme() {
  486. return HSLFTextParagraph.this.getAutoNumberingScheme();
  487. }
  488. @Override
  489. public Integer getAutoNumberingStartAt() {
  490. return HSLFTextParagraph.this.getAutoNumberingStartAt();
  491. }
  492. };
  493. }
  494. @Override
  495. public void setBulletStyle(Object... styles) {
  496. if (styles.length == 0) {
  497. setBullet(false);
  498. } else {
  499. setBullet(true);
  500. for (Object ostyle : styles) {
  501. if (ostyle instanceof Number) {
  502. setBulletSize(((Number)ostyle).doubleValue());
  503. } else if (ostyle instanceof Color) {
  504. setBulletColor((Color)ostyle);
  505. } else if (ostyle instanceof Character) {
  506. setBulletChar((Character)ostyle);
  507. } else if (ostyle instanceof String) {
  508. setBulletFont((String)ostyle);
  509. } else if (ostyle instanceof AutoNumberingScheme) {
  510. throw new HSLFException("setting bullet auto-numberin scheme for HSLF not supported ... yet");
  511. }
  512. }
  513. }
  514. }
  515. @Override
  516. public HSLFTextShape getParentShape() {
  517. return _parentShape;
  518. }
  519. public void setParentShape(HSLFTextShape parentShape) {
  520. _parentShape = parentShape;
  521. }
  522. @Override
  523. public int getIndentLevel() {
  524. return _paragraphStyle == null ? 0 : _paragraphStyle.getIndentLevel();
  525. }
  526. @Override
  527. public void setIndentLevel(int level) {
  528. if( _paragraphStyle != null ) {
  529. _paragraphStyle.setIndentLevel((short)level);
  530. }
  531. }
  532. /**
  533. * Sets whether this rich text run has bullets
  534. */
  535. public void setBullet(boolean flag) {
  536. setFlag(ParagraphFlagsTextProp.BULLET_IDX, flag);
  537. }
  538. /**
  539. * Returns whether this rich text run has bullets
  540. */
  541. public boolean isBullet() {
  542. return getFlag(ParagraphFlagsTextProp.BULLET_IDX);
  543. }
  544. /**
  545. * Sets the bullet character
  546. */
  547. public void setBulletChar(Character c) {
  548. Integer val = (c == null) ? null : (int)c.charValue();
  549. setParagraphTextPropVal("bullet.char", val);
  550. }
  551. /**
  552. * Returns the bullet character
  553. */
  554. public Character getBulletChar() {
  555. TextProp tp = getPropVal(_paragraphStyle, "bullet.char");
  556. return (tp == null) ? null : (char)tp.getValue();
  557. }
  558. /**
  559. * Sets the bullet size
  560. */
  561. public void setBulletSize(Double size) {
  562. setPctOrPoints("bullet.size", size);
  563. }
  564. /**
  565. * Returns the bullet size, null if unset
  566. */
  567. public Double getBulletSize() {
  568. return getPctOrPoints("bullet.size");
  569. }
  570. /**
  571. * Sets the bullet color
  572. */
  573. public void setBulletColor(Color color) {
  574. Integer val = (color == null) ? null : new Color(color.getBlue(), color.getGreen(), color.getRed(), 254).getRGB();
  575. setParagraphTextPropVal("bullet.color", val);
  576. setFlag(ParagraphFlagsTextProp.BULLET_HARDCOLOR_IDX, (color != null));
  577. }
  578. /**
  579. * Returns the bullet color
  580. */
  581. public Color getBulletColor() {
  582. TextProp tp = getPropVal(_paragraphStyle, "bullet.color");
  583. boolean hasColor = getFlag(ParagraphFlagsTextProp.BULLET_HARDCOLOR_IDX);
  584. if (tp == null || !hasColor) {
  585. // if bullet color is undefined, return color of first run
  586. if (_runs.isEmpty()) {
  587. return null;
  588. }
  589. SolidPaint sp = _runs.get(0).getFontColor();
  590. if(sp == null) {
  591. return null;
  592. }
  593. return DrawPaint.applyColorTransform(sp.getSolidColor());
  594. }
  595. return getColorFromColorIndexStruct(tp.getValue(), _sheet);
  596. }
  597. /**
  598. * Sets the bullet font
  599. */
  600. public void setBulletFont(String typeface) {
  601. if (typeface == null) {
  602. setPropVal(_paragraphStyle, "bullet.font", null);
  603. setFlag(ParagraphFlagsTextProp.BULLET_HARDFONT_IDX, false);
  604. return;
  605. }
  606. HSLFFontInfo fi = new HSLFFontInfo(typeface);
  607. fi = getSheet().getSlideShow().addFont(fi);
  608. setParagraphTextPropVal("bullet.font", fi.getIndex());
  609. setFlag(ParagraphFlagsTextProp.BULLET_HARDFONT_IDX, true);
  610. }
  611. /**
  612. * Returns the bullet font
  613. */
  614. public String getBulletFont() {
  615. TextProp tp = getPropVal(_paragraphStyle, "bullet.font");
  616. boolean hasFont = getFlag(ParagraphFlagsTextProp.BULLET_HARDFONT_IDX);
  617. if (tp == null || !hasFont) {
  618. return getDefaultFontFamily();
  619. }
  620. HSLFFontInfo ppFont = getSheet().getSlideShow().getFont(tp.getValue());
  621. assert(ppFont != null);
  622. return ppFont.getTypeface();
  623. }
  624. @Override
  625. public void setLineSpacing(Double lineSpacing) {
  626. setPctOrPoints("linespacing", lineSpacing);
  627. }
  628. @Override
  629. public Double getLineSpacing() {
  630. return getPctOrPoints("linespacing");
  631. }
  632. @Override
  633. public void setSpaceBefore(Double spaceBefore) {
  634. setPctOrPoints("spacebefore", spaceBefore);
  635. }
  636. @Override
  637. public Double getSpaceBefore() {
  638. return getPctOrPoints("spacebefore");
  639. }
  640. @Override
  641. public void setSpaceAfter(Double spaceAfter) {
  642. setPctOrPoints("spaceafter", spaceAfter);
  643. }
  644. @Override
  645. public Double getSpaceAfter() {
  646. return getPctOrPoints("spaceafter");
  647. }
  648. @Override
  649. public Double getDefaultTabSize() {
  650. // TODO: implement
  651. return null;
  652. }
  653. @Override
  654. public List<? extends TabStop> getTabStops() {
  655. final List<HSLFTabStop> tabStops;
  656. final TextRulerAtom textRuler;
  657. if (getSheet() instanceof HSLFSlideMaster) {
  658. final HSLFTabStopPropCollection tpc = getMasterPropVal(_paragraphStyle, HSLFTabStopPropCollection.NAME);
  659. if (tpc == null) {
  660. return null;
  661. }
  662. tabStops = tpc.getTabStops();
  663. textRuler = null;
  664. } else {
  665. textRuler = (TextRulerAtom)_headerAtom.getParentRecord().findFirstOfType(RecordTypes.TextRulerAtom.typeID);
  666. if (textRuler == null) {
  667. return null;
  668. }
  669. tabStops = textRuler.getTabStops();
  670. }
  671. return tabStops.stream().map((tabStop) -> new HSLFTabStopDecorator(tabStop)).collect(Collectors.toList());
  672. }
  673. @Override
  674. public void addTabStops(final double positionInPoints, final TabStopType tabStopType) {
  675. final HSLFTabStop ts = new HSLFTabStop(0, tabStopType);
  676. ts.setPositionInPoints(positionInPoints);
  677. if (getSheet() instanceof HSLFSlideMaster) {
  678. final Consumer<HSLFTabStopPropCollection> con = (tp) -> tp.addTabStop(ts);
  679. setPropValInner(_paragraphStyle, HSLFTabStopPropCollection.NAME, con);
  680. } else {
  681. final RecordContainer cont = _headerAtom.getParentRecord();
  682. TextRulerAtom textRuler = (TextRulerAtom)cont.findFirstOfType(RecordTypes.TextRulerAtom.typeID);
  683. if (textRuler == null) {
  684. textRuler = TextRulerAtom.getParagraphInstance();
  685. cont.appendChildRecord(textRuler);
  686. }
  687. textRuler.getTabStops().add(ts);
  688. }
  689. }
  690. @Override
  691. public void clearTabStops() {
  692. if (getSheet() instanceof HSLFSlideMaster) {
  693. setPropValInner(_paragraphStyle, HSLFTabStopPropCollection.NAME, null);
  694. } else {
  695. final RecordContainer cont = _headerAtom.getParentRecord();
  696. final TextRulerAtom textRuler = (TextRulerAtom)cont.findFirstOfType(RecordTypes.TextRulerAtom.typeID);
  697. if (textRuler == null) {
  698. return;
  699. }
  700. textRuler.getTabStops().clear();
  701. }
  702. }
  703. private Double getPctOrPoints(String propName) {
  704. TextProp tp = getPropVal(_paragraphStyle, propName);
  705. if (tp == null) {
  706. return null;
  707. }
  708. int val = tp.getValue();
  709. return (val < 0) ? Units.masterToPoints(val) : val;
  710. }
  711. private void setPctOrPoints(String propName, Double dval) {
  712. Integer ival = null;
  713. if (dval != null) {
  714. ival = (dval < 0) ? Units.pointsToMaster(dval) : dval.intValue();
  715. }
  716. setParagraphTextPropVal(propName, ival);
  717. }
  718. private boolean getFlag(int index) {
  719. BitMaskTextProp tp = getPropVal(_paragraphStyle, ParagraphFlagsTextProp.NAME);
  720. return (tp == null) ? false : tp.getSubValue(index);
  721. }
  722. private void setFlag(int index, boolean value) {
  723. BitMaskTextProp tp = (BitMaskTextProp)_paragraphStyle.addWithName(ParagraphFlagsTextProp.NAME);
  724. tp.setSubValue(value, index);
  725. setDirty();
  726. }
  727. /**
  728. * Fetch the value of the given Paragraph related TextProp. Returns null if
  729. * that TextProp isn't present. If the TextProp isn't present, the value
  730. * from the appropriate Master Sheet will apply.
  731. *
  732. * The propName can be a comma-separated list, in case multiple equivalent values
  733. * are queried
  734. */
  735. protected <T extends TextProp> T getPropVal(TextPropCollection props, String propName) {
  736. String[] propNames = propName.split(",");
  737. for (String pn : propNames) {
  738. T prop = props.findByName(pn);
  739. if (isValidProp(prop)) {
  740. return prop;
  741. }
  742. }
  743. return getMasterPropVal(props, propName);
  744. }
  745. private <T extends TextProp> T getMasterPropVal(final TextPropCollection props, final String propName) {
  746. boolean isChar = props.getTextPropType() == TextPropType.character;
  747. // check if we can delegate to master for the property
  748. if (!isChar) {
  749. BitMaskTextProp maskProp = props.findByName(ParagraphFlagsTextProp.NAME);
  750. boolean hardAttribute = (maskProp != null && maskProp.getValue() == 0);
  751. if (hardAttribute) {
  752. return null;
  753. }
  754. }
  755. final String[] propNames = propName.split(",");
  756. final HSLFSheet sheet = getSheet();
  757. final int txtype = getRunType();
  758. final HSLFMasterSheet master;
  759. if (sheet instanceof HSLFMasterSheet) {
  760. master = (HSLFMasterSheet)sheet;
  761. } else {
  762. master = sheet.getMasterSheet();
  763. if (master == null) {
  764. logger.log(POILogger.WARN, "MasterSheet is not available");
  765. return null;
  766. }
  767. }
  768. for (String pn : propNames) {
  769. TextPropCollection masterProps = master.getPropCollection(txtype, getIndentLevel(), pn, isChar);
  770. if (masterProps != null) {
  771. T prop = masterProps.findByName(pn);
  772. if (isValidProp(prop)) {
  773. return prop;
  774. }
  775. }
  776. }
  777. return null;
  778. }
  779. private static boolean isValidProp(TextProp prop) {
  780. // Font properties (maybe other too???) can have an index of -1
  781. // so we check the master for this font index then
  782. return prop != null && (!prop.getName().contains("font") || prop.getValue() != -1);
  783. }
  784. /**
  785. * Returns the named TextProp, either by fetching it (if it exists) or
  786. * adding it (if it didn't)
  787. *
  788. * @param props the TextPropCollection to fetch from / add into
  789. * @param name the name of the TextProp to fetch/add
  790. * @param val the value, null if unset
  791. */
  792. protected void setPropVal(final TextPropCollection props, final String name, final Integer val) {
  793. setPropValInner(props, name, val == null ? null : tp -> tp.setValue(val));
  794. }
  795. private void setPropValInner(final TextPropCollection props, final String name, Consumer<? extends TextProp> handler) {
  796. final boolean isChar = props.getTextPropType() == TextPropType.character;
  797. final TextPropCollection pc;
  798. if (_sheet instanceof HSLFMasterSheet) {
  799. pc = ((HSLFMasterSheet)_sheet).getPropCollection(getRunType(), getIndentLevel(), "*", isChar);
  800. if (pc == null) {
  801. throw new HSLFException("Master text property collection can't be determined.");
  802. }
  803. } else {
  804. pc = props;
  805. }
  806. if (handler == null) {
  807. pc.removeByName(name);
  808. } else {
  809. // Fetch / Add the TextProp
  810. handler.accept(pc.addWithName(name));
  811. }
  812. setDirty();
  813. }
  814. /**
  815. * Check and add linebreaks to text runs leading other paragraphs
  816. */
  817. protected static void fixLineEndings(List<HSLFTextParagraph> paragraphs) {
  818. HSLFTextRun lastRun = null;
  819. for (HSLFTextParagraph p : paragraphs) {
  820. if (lastRun != null && !lastRun.getRawText().endsWith("\r")) {
  821. lastRun.setText(lastRun.getRawText() + "\r");
  822. }
  823. List<HSLFTextRun> ltr = p.getTextRuns();
  824. if (ltr.isEmpty()) {
  825. throw new HSLFException("paragraph without textruns found");
  826. }
  827. lastRun = ltr.get(ltr.size() - 1);
  828. assert (lastRun.getRawText() != null);
  829. }
  830. }
  831. /**
  832. * Search for a StyleTextPropAtom is for this text header (list of paragraphs)
  833. *
  834. * @param header the header
  835. * @param textLen the length of the rawtext, or -1 if the length is not known
  836. */
  837. private static StyleTextPropAtom findStyleAtomPresent(TextHeaderAtom header, int textLen) {
  838. boolean afterHeader = false;
  839. StyleTextPropAtom style = null;
  840. for (org.apache.poi.hslf.record.Record record : header.getParentRecord().getChildRecords()) {
  841. long rt = record.getRecordType();
  842. if (afterHeader && rt == RecordTypes.TextHeaderAtom.typeID) {
  843. // already on the next header, quit searching
  844. break;
  845. }
  846. afterHeader |= (header == record);
  847. if (afterHeader && rt == RecordTypes.StyleTextPropAtom.typeID) {
  848. // found it
  849. style = (StyleTextPropAtom) record;
  850. }
  851. }
  852. if (style == null) {
  853. logger.log(POILogger.INFO, "styles atom doesn't exist. Creating dummy record for later saving.");
  854. style = new StyleTextPropAtom((textLen < 0) ? 1 : textLen);
  855. } else {
  856. if (textLen >= 0) {
  857. style.setParentTextSize(textLen);
  858. }
  859. }
  860. return style;
  861. }
  862. /**
  863. * Saves the modified paragraphs/textrun to the records.
  864. * Also updates the styles to the correct text length.
  865. */
  866. protected static void storeText(List<HSLFTextParagraph> paragraphs) {
  867. fixLineEndings(paragraphs);
  868. updateTextAtom(paragraphs);
  869. updateStyles(paragraphs);
  870. updateHyperlinks(paragraphs);
  871. refreshRecords(paragraphs);
  872. for (HSLFTextParagraph p : paragraphs) {
  873. p._dirty = false;
  874. }
  875. }
  876. /**
  877. * Set the correct text atom depending on the multibyte usage
  878. */
  879. private static void updateTextAtom(List<HSLFTextParagraph> paragraphs) {
  880. final String rawText = toInternalString(getRawText(paragraphs));
  881. // Will it fit in a 8 bit atom?
  882. boolean isUnicode = StringUtil.hasMultibyte(rawText);
  883. // isUnicode = true;
  884. TextHeaderAtom headerAtom = paragraphs.get(0)._headerAtom;
  885. TextBytesAtom byteAtom = paragraphs.get(0)._byteAtom;
  886. TextCharsAtom charAtom = paragraphs.get(0)._charAtom;
  887. StyleTextPropAtom styleAtom = findStyleAtomPresent(headerAtom, rawText.length());
  888. // Store in the appropriate record
  889. org.apache.poi.hslf.record.Record oldRecord = null, newRecord;
  890. if (isUnicode) {
  891. if (byteAtom != null || charAtom == null) {
  892. oldRecord = byteAtom;
  893. charAtom = new TextCharsAtom();
  894. }
  895. newRecord = charAtom;
  896. charAtom.setText(rawText);
  897. } else {
  898. if (charAtom != null || byteAtom == null) {
  899. oldRecord = charAtom;
  900. byteAtom = new TextBytesAtom();
  901. }
  902. newRecord = byteAtom;
  903. byte[] byteText = new byte[rawText.length()];
  904. StringUtil.putCompressedUnicode(rawText, byteText, 0);
  905. byteAtom.setText(byteText);
  906. }
  907. assert (newRecord != null);
  908. RecordContainer _txtbox = headerAtom.getParentRecord();
  909. org.apache.poi.hslf.record.Record[] cr = _txtbox.getChildRecords();
  910. int /* headerIdx = -1, */ textIdx = -1, styleIdx = -1;
  911. for (int i = 0; i < cr.length; i++) {
  912. org.apache.poi.hslf.record.Record r = cr[i];
  913. if (r == headerAtom) {
  914. // headerIdx = i;
  915. } else if (r == oldRecord || r == newRecord) {
  916. textIdx = i;
  917. } else if (r == styleAtom) {
  918. styleIdx = i;
  919. }
  920. }
  921. if (textIdx == -1) {
  922. // the old record was never registered, ignore it
  923. _txtbox.addChildAfter(newRecord, headerAtom);
  924. // textIdx = headerIdx + 1;
  925. } else {
  926. // swap not appropriated records - noop if unchanged
  927. cr[textIdx] = newRecord;
  928. }
  929. if (styleIdx == -1) {
  930. // Add the new StyleTextPropAtom after the TextCharsAtom / TextBytesAtom
  931. _txtbox.addChildAfter(styleAtom, newRecord);
  932. }
  933. for (HSLFTextParagraph p : paragraphs) {
  934. if (newRecord == byteAtom) {
  935. p._byteAtom = byteAtom;
  936. p._charAtom = null;
  937. } else {
  938. p._byteAtom = null;
  939. p._charAtom = charAtom;
  940. }
  941. }
  942. }
  943. /**
  944. * Update paragraph and character styles - merges them when subsequential styles match
  945. */
  946. private static void updateStyles(List<HSLFTextParagraph> paragraphs) {
  947. final String rawText = toInternalString(getRawText(paragraphs));
  948. TextHeaderAtom headerAtom = paragraphs.get(0)._headerAtom;
  949. StyleTextPropAtom styleAtom = findStyleAtomPresent(headerAtom, rawText.length());
  950. // Update the text length for its Paragraph and Character stylings
  951. // * reset the length, to the new string's length
  952. // * add on +1 if the last block
  953. styleAtom.clearStyles();
  954. TextPropCollection lastPTPC = null, lastRTPC = null, ptpc = null, rtpc = null;
  955. for (HSLFTextParagraph para : paragraphs) {
  956. ptpc = para.getParagraphStyle();
  957. ptpc.updateTextSize(0);
  958. if (!ptpc.equals(lastPTPC)) {
  959. lastPTPC = ptpc.copy();
  960. lastPTPC.updateTextSize(0);
  961. styleAtom.addParagraphTextPropCollection(lastPTPC);
  962. }
  963. for (HSLFTextRun tr : para.getTextRuns()) {
  964. rtpc = tr.getCharacterStyle();
  965. rtpc.updateTextSize(0);
  966. if (!rtpc.equals(lastRTPC)) {
  967. lastRTPC = rtpc.copy();
  968. lastRTPC.updateTextSize(0);
  969. styleAtom.addCharacterTextPropCollection(lastRTPC);
  970. }
  971. int len = tr.getLength();
  972. ptpc.updateTextSize(ptpc.getCharactersCovered() + len);
  973. rtpc.updateTextSize(len);
  974. lastPTPC.updateTextSize(lastPTPC.getCharactersCovered() + len);
  975. lastRTPC.updateTextSize(lastRTPC.getCharactersCovered() + len);
  976. }
  977. }
  978. if (lastPTPC == null || lastRTPC == null || ptpc == null || rtpc == null) { // NOSONAR
  979. throw new HSLFException("Not all TextPropCollection could be determined.");
  980. }
  981. ptpc.updateTextSize(ptpc.getCharactersCovered() + 1);
  982. rtpc.updateTextSize(rtpc.getCharactersCovered() + 1);
  983. lastPTPC.updateTextSize(lastPTPC.getCharactersCovered() + 1);
  984. lastRTPC.updateTextSize(lastRTPC.getCharactersCovered() + 1);
  985. // If TextSpecInfoAtom is present, we must update the text size in it,
  986. // otherwise the ppt will be corrupted
  987. for (org.apache.poi.hslf.record.Record r : paragraphs.get(0).getRecords()) {
  988. if (r instanceof TextSpecInfoAtom) {
  989. ((TextSpecInfoAtom) r).setParentSize(rawText.length() + 1);
  990. break;
  991. }
  992. }
  993. }
  994. private static void updateHyperlinks(List<HSLFTextParagraph> paragraphs) {
  995. TextHeaderAtom headerAtom = paragraphs.get(0)._headerAtom;
  996. RecordContainer _txtbox = headerAtom.getParentRecord();
  997. // remove existing hyperlink records
  998. for (org.apache.poi.hslf.record.Record r : _txtbox.getChildRecords()) {
  999. if (r instanceof InteractiveInfo || r instanceof TxInteractiveInfoAtom) {
  1000. _txtbox.removeChild(r);
  1001. }
  1002. }
  1003. // now go through all the textruns and check for hyperlinks
  1004. HSLFHyperlink lastLink = null;
  1005. for (HSLFTextParagraph para : paragraphs) {
  1006. for (HSLFTextRun run : para) {
  1007. HSLFHyperlink thisLink = run.getHyperlink();
  1008. if (thisLink != null && thisLink == lastLink) {
  1009. // the hyperlink extends over this text run, increase its length
  1010. // TODO: the text run might be longer than the hyperlink
  1011. thisLink.setEndIndex(thisLink.getEndIndex()+run.getLength());
  1012. } else {
  1013. if (lastLink != null) {
  1014. InteractiveInfo info = lastLink.getInfo();
  1015. TxInteractiveInfoAtom txinfo = lastLink.getTextRunInfo();
  1016. assert(info != null && txinfo != null);
  1017. _txtbox.appendChildRecord(info);
  1018. _txtbox.appendChildRecord(txinfo);
  1019. }
  1020. }
  1021. lastLink = thisLink;
  1022. }
  1023. }
  1024. if (lastLink != null) {
  1025. InteractiveInfo info = lastLink.getInfo();
  1026. TxInteractiveInfoAtom txinfo = lastLink.getTextRunInfo();
  1027. assert(info != null && txinfo != null);
  1028. _txtbox.appendChildRecord(info);
  1029. _txtbox.appendChildRecord(txinfo);
  1030. }
  1031. }
  1032. /**
  1033. * Writes the textbox records back to the document record
  1034. */
  1035. private static void refreshRecords(List<HSLFTextParagraph> paragraphs) {
  1036. TextHeaderAtom headerAtom = paragraphs.get(0)._headerAtom;
  1037. RecordContainer _txtbox = headerAtom.getParentRecord();
  1038. if (_txtbox instanceof EscherTextboxWrapper) {
  1039. try {
  1040. _txtbox.writeOut(null);
  1041. } catch (IOException e) {
  1042. throw new HSLFException("failed dummy write", e);
  1043. }
  1044. }
  1045. }
  1046. /**
  1047. * Adds the supplied text onto the end of the TextParagraphs,
  1048. * creating a new RichTextRun for it to sit in.
  1049. *
  1050. * @param text the text string used by this object.
  1051. */
  1052. protected static HSLFTextRun appendText(List<HSLFTextParagraph> paragraphs, String text, boolean newParagraph) {
  1053. text = toInternalString(text);
  1054. // check paragraphs
  1055. assert(!paragraphs.isEmpty() && !paragraphs.get(0).getTextRuns().isEmpty());
  1056. HSLFTextParagraph htp = paragraphs.get(paragraphs.size() - 1);
  1057. HSLFTextRun htr = htp.getTextRuns().get(htp.getTextRuns().size() - 1);
  1058. boolean addParagraph = newParagraph;
  1059. for (String rawText : text.split("(?<=\r)")) {
  1060. // special case, if last text paragraph or run is empty, we will reuse it
  1061. boolean lastRunEmpty = (htr.getLength() == 0);
  1062. boolean lastParaEmpty = lastRunEmpty && (htp.getTextRuns().size() == 1);
  1063. if (addParagraph && !lastParaEmpty) {
  1064. TextPropCollection tpc = htp.getParagraphStyle();
  1065. HSLFTextParagraph prevHtp = htp;
  1066. htp = new HSLFTextParagraph(htp._headerAtom, htp._byteAtom, htp._charAtom, paragraphs);
  1067. htp.setParagraphStyle(tpc.copy());
  1068. htp.setParentShape(prevHtp.getParentShape());
  1069. htp.setShapeId(prevHtp.getShapeId());
  1070. htp.supplySheet(prevHtp.getSheet());
  1071. paragraphs.add(htp);
  1072. }
  1073. addParagraph = true;
  1074. if (!lastRunEmpty) {
  1075. TextPropCollection tpc = htr.getCharacterStyle();
  1076. htr = new HSLFTextRun(htp);
  1077. htr.setCharacterStyle(tpc.copy());
  1078. htp.addTextRun(htr);
  1079. }
  1080. htr.setText(rawText);
  1081. }
  1082. storeText(paragraphs);
  1083. return htr;
  1084. }
  1085. /**
  1086. * Sets (overwrites) the current text.
  1087. * Uses the properties of the first paragraph / textrun
  1088. *
  1089. * @param text the text string used by this object.
  1090. */
  1091. public static HSLFTextRun setText(List<HSLFTextParagraph> paragraphs, String text) {
  1092. // check paragraphs
  1093. assert(!paragraphs.isEmpty() && !paragraphs.get(0).getTextRuns().isEmpty());
  1094. Iterator<HSLFTextParagraph> paraIter = paragraphs.iterator();
  1095. HSLFTextParagraph htp = paraIter.hasNext() ? paraIter.next() : null; // keep first
  1096. assert (htp != null);
  1097. while (paraIter.hasNext()) {
  1098. paraIter.next();
  1099. paraIter.remove();
  1100. }
  1101. Iterator<HSLFTextRun> runIter = htp.getTextRuns().iterator();
  1102. if (runIter.hasNext()) {
  1103. HSLFTextRun htr = runIter.next();
  1104. htr.setText("");
  1105. while (runIter.hasNext()) {
  1106. runIter.next();
  1107. runIter.remove();
  1108. }
  1109. } else {
  1110. HSLFTextRun trun = new HSLFTextRun(htp);
  1111. htp.addTextRun(trun);
  1112. }
  1113. return appendText(paragraphs, text, false);
  1114. }
  1115. public static String getText(List<HSLFTextParagraph> paragraphs) {
  1116. assert (!paragraphs.isEmpty());
  1117. String rawText = getRawText(paragraphs);
  1118. return toExternalString(rawText, paragraphs.get(0).getRunType());
  1119. }
  1120. public static String getRawText(List<HSLFTextParagraph> paragraphs) {
  1121. StringBuilder sb = new StringBuilder();
  1122. for (HSLFTextParagraph p : paragraphs) {
  1123. for (HSLFTextRun r : p.getTextRuns()) {
  1124. sb.append(r.getRawText());
  1125. }
  1126. }
  1127. return sb.toString();
  1128. }
  1129. @Override
  1130. public String toString() {
  1131. StringBuilder sb = new StringBuilder();
  1132. for (HSLFTextRun r : getTextRuns()) {
  1133. sb.append(r.getRawText());
  1134. }
  1135. return toExternalString(sb.toString(), getRunType());
  1136. }
  1137. /**
  1138. * Returns a new string with line breaks converted into internal ppt
  1139. * representation
  1140. */
  1141. protected static String toInternalString(String s) {
  1142. return s.replaceAll("\\r?\\n", "\r");
  1143. }
  1144. /**
  1145. * Converts raw text from the text paragraphs to a formatted string,
  1146. * i.e. it converts certain control characters used in the raw txt
  1147. *
  1148. * @param rawText the raw text
  1149. * @param runType the run type of the shape, paragraph or headerAtom.
  1150. * use -1 if unknown
  1151. * @return the formatted string
  1152. */
  1153. public static String toExternalString(String rawText, int runType) {
  1154. // PowerPoint seems to store files with \r as the line break
  1155. // The messes things up on everything but a Mac, so translate
  1156. // them to \n
  1157. String text = rawText.replace('\r', '\n');
  1158. // 0xB acts like carriage return in page titles and like blank in the others
  1159. final char repl = (runType == -1 ||
  1160. runType == TextPlaceholder.TITLE.nativeId ||
  1161. runType == TextPlaceholder.CENTER_TITLE.nativeId) ? '\n' : ' ';
  1162. return text.replace('\u000b', repl);
  1163. }
  1164. /**
  1165. * For a given PPDrawing, grab all the TextRuns
  1166. */
  1167. public static List<List<HSLFTextParagraph>> findTextParagraphs(PPDrawing ppdrawing, HSLFSheet sheet) {
  1168. List<List<HSLFTextParagraph>> runsV = new ArrayList<>();
  1169. for (EscherTextboxWrapper wrapper : ppdrawing.getTextboxWrappers()) {
  1170. List<HSLFTextParagraph> p = findTextParagraphs(wrapper, sheet);
  1171. if (p != null) {
  1172. runsV.add(p);
  1173. }
  1174. }
  1175. return runsV;
  1176. }
  1177. /**
  1178. * Scans through the supplied record array, looking for
  1179. * a TextHeaderAtom followed by one of a TextBytesAtom or
  1180. * a TextCharsAtom. Builds up TextRuns from these
  1181. *
  1182. * @param wrapper an EscherTextboxWrapper
  1183. */
  1184. protected static List<HSLFTextParagraph> findTextParagraphs(EscherTextboxWrapper wrapper, HSLFSheet sheet) {
  1185. // propagate parents to parent-aware records
  1186. RecordContainer.handleParentAwareRecords(wrapper);
  1187. int shapeId = wrapper.getShapeId();
  1188. List<HSLFTextParagraph> rv = null;
  1189. OutlineTextRefAtom ota = (OutlineTextRefAtom)wrapper.findFirstOfType(OutlineTextRefAtom.typeID);
  1190. if (ota != null) {
  1191. // if we are based on an outline, there are no further records to be parsed from the wrapper
  1192. if (sheet == null) {
  1193. throw new HSLFException("Outline atom reference can't be solved without a sheet record");
  1194. }
  1195. List<List<HSLFTextParagraph>> sheetRuns = sheet.getTextParagraphs();
  1196. assert (sheetRuns != null);
  1197. int idx = ota.getTextIndex();
  1198. for (List<HSLFTextParagraph> r : sheetRuns) {
  1199. if (r.isEmpty()) {
  1200. continue;
  1201. }
  1202. int ridx = r.get(0).getIndex();
  1203. if (ridx > idx) {
  1204. break;
  1205. }
  1206. if (ridx == idx) {
  1207. if (rv == null) {
  1208. rv = r;
  1209. } else {
  1210. // create a new container
  1211. // TODO: ... is this case really happening?
  1212. rv = new ArrayList<>(rv);
  1213. rv.addAll(r);
  1214. }
  1215. }
  1216. }
  1217. if (rv == null || rv.isEmpty()) {
  1218. logger.log(POILogger.WARN, "text run not found for OutlineTextRefAtom.TextIndex=" + idx);
  1219. }
  1220. } else {
  1221. if (sheet != null) {
  1222. // check sheet runs first, so we get exactly the same paragraph list
  1223. List<List<HSLFTextParagraph>> sheetRuns = sheet.getTextParagraphs();
  1224. assert (sheetRuns != null);
  1225. for (List<HSLFTextParagraph> paras : sheetRuns) {
  1226. if (!paras.isEmpty() && paras.get(0)._headerAtom.getParentRecord() == wrapper) {
  1227. rv = paras;
  1228. break;
  1229. }
  1230. }
  1231. }
  1232. if (rv == null) {
  1233. // if we haven't found the wrapper in the sheet runs, create a new paragraph list from its record
  1234. List<List<HSLFTextParagraph>> rvl = findTextParagraphs(wrapper.getChildRecords());
  1235. switch (rvl.size()) {
  1236. case 0: break; // nothing found
  1237. case 1: rv = rvl.get(0); break; // normal case
  1238. default:
  1239. throw new HSLFException("TextBox contains more than one list of paragraphs.");
  1240. }
  1241. }
  1242. }
  1243. if (rv != null) {
  1244. StyleTextProp9Atom styleTextProp9Atom = wrapper.getStyleTextProp9Atom();
  1245. for (HSLFTextParagraph htp : rv) {
  1246. htp.setShapeId(shapeId);
  1247. htp.setStyleTextProp9Atom(styleTextProp9Atom);
  1248. }
  1249. }
  1250. return rv;
  1251. }
  1252. /**
  1253. * Scans through the supplied record array, looking for
  1254. * a TextHeaderAtom followed by one of a TextBytesAtom or
  1255. * a TextCharsAtom. Builds up TextRuns from these
  1256. *
  1257. * @param records the records to build from
  1258. */
  1259. protected static List<List<HSLFTextParagraph>> findTextParagraphs(org.apache.poi.hslf.record.Record[] records) {
  1260. List<List<HSLFTextParagraph>> paragraphCollection = new ArrayList<>();
  1261. int[] recordIdx = { 0 };
  1262. for (int slwtIndex = 0; recordIdx[0] < records.length; slwtIndex++) {
  1263. TextHeaderAtom header = null;
  1264. TextBytesAtom tbytes = null;
  1265. TextCharsAtom tchars = null;
  1266. TextRulerAtom ruler = null;
  1267. MasterTextPropAtom indents = null;
  1268. for (org.apache.poi.hslf.record.Record r : getRecords(records, recordIdx, null)) {
  1269. long rt = r.getRecordType();
  1270. if (RecordTypes.TextHeaderAtom.typeID == rt) {
  1271. header = (TextHeaderAtom) r;
  1272. } else if (RecordTypes.TextBytesAtom.typeID == rt) {
  1273. tbytes = (TextBytesAtom) r;
  1274. } else if (RecordTypes.TextCharsAtom.typeID == rt) {
  1275. tchars = (TextCharsAtom) r;
  1276. } else if (RecordTypes.TextRulerAtom.typeID == rt) {
  1277. ruler = (TextRulerAtom) r;
  1278. } else if (RecordTypes.MasterTextPropAtom.typeID == rt) {
  1279. indents = (MasterTextPropAtom) r;
  1280. }
  1281. // don't search for RecordTypes.StyleTextPropAtom.typeID here ... see findStyleAtomPresent below
  1282. }
  1283. if (header == null) {
  1284. break;
  1285. }
  1286. if (header.getParentRecord() instanceof SlideListWithText) {
  1287. // runs found in PPDrawing are not linked with SlideListWithTexts
  1288. header.setIndex(slwtIndex);
  1289. }
  1290. if (tbytes == null && tchars == null) {
  1291. tbytes = new TextBytesAtom();
  1292. // don't add record yet - set it in storeText
  1293. logger.log(POILogger.INFO, "bytes nor chars atom doesn't exist. Creating dummy record for later saving.");
  1294. }
  1295. String rawText = (tchars != null) ? tchars.getText() : tbytes.getText();
  1296. StyleTextPropAtom styles = findStyleAtomPresent(header, rawText.length());
  1297. List<HSLFTextParagraph> paragraphs = new ArrayList<>();
  1298. paragraphCollection.add(paragraphs);
  1299. // split, but keep delimiter
  1300. for (String para : rawText.split("(?<=\r)")) {
  1301. HSLFTextParagraph tpara = new HSLFTextParagraph(header, tbytes, tchars, paragraphs);
  1302. paragraphs.add(tpara);
  1303. tpara._ruler = ruler;
  1304. tpara.getParagraphStyle().updateTextSize(para.length());
  1305. HSLFTextRun trun = new HSLFTextRun(tpara);
  1306. tpara.addTextRun(trun);
  1307. trun.setText(para);
  1308. }
  1309. applyCharacterStyles(paragraphs, styles.getCharacterStyles());
  1310. applyParagraphStyles(paragraphs, styles.getParagraphStyles());
  1311. if (indents != null) {
  1312. applyParagraphIndents(paragraphs, indents.getIndents());
  1313. }
  1314. }
  1315. if (paragraphCollection.isEmpty()) {
  1316. logger.log(POILogger.DEBUG, "No text records found.");
  1317. }
  1318. return paragraphCollection;
  1319. }
  1320. protected static void applyHyperlinks(List<HSLFTextParagraph> paragraphs) {
  1321. List<HSLFHyperlink> links = HSLFHyperlink.find(paragraphs);
  1322. for (HSLFHyperlink h : links) {
  1323. int csIdx = 0;
  1324. for (HSLFTextParagraph p : paragraphs) {
  1325. if (csIdx > h.getEndIndex()) {
  1326. break;
  1327. }
  1328. List<HSLFTextRun> runs = p.getTextRuns();
  1329. for (int rlen=0,rIdx=0; rIdx < runs.size(); csIdx+=rlen, rIdx++) {
  1330. HSLFTextRun run = runs.get(rIdx);
  1331. rlen = run.getLength();
  1332. if (csIdx < h.getEndIndex() && h.getStartIndex() < csIdx+rlen) {
  1333. String rawText = run.getRawText();
  1334. int startIdx = h.getStartIndex()-csIdx;
  1335. if (startIdx > 0) {
  1336. // hyperlink starts within current textrun
  1337. HSLFTextRun newRun = new HSLFTextRun(p);
  1338. newRun.setCharacterStyle(run.getCharacterStyle());
  1339. newRun.setText(rawText.substring(startIdx));
  1340. run.setText(rawText.substring(0, startIdx));
  1341. runs.add(rIdx+1, newRun);
  1342. rlen = startIdx;
  1343. continue;
  1344. }
  1345. int endIdx = Math.min(rlen, h.getEndIndex()-h.getStartIndex());
  1346. if (endIdx < rlen) {
  1347. // hyperlink ends before end of current textrun
  1348. HSLFTextRun newRun = new HSLFTextRun(p);
  1349. newRun.setCharacterStyle(run.getCharacterStyle());
  1350. newRun.setText(rawText.substring(0, endIdx));
  1351. run.setText(rawText.substring(endIdx));
  1352. runs.add(rIdx, newRun);
  1353. rlen = endIdx;
  1354. run = newRun;
  1355. }
  1356. run.setHyperlink(h);
  1357. }
  1358. }
  1359. }
  1360. }
  1361. }
  1362. protected static void applyCharacterStyles(List<HSLFTextParagraph> paragraphs, List<TextPropCollection> charStyles) {
  1363. int paraIdx = 0, runIdx = 0;
  1364. HSLFTextRun trun;
  1365. for (int csIdx = 0; csIdx < charStyles.size(); csIdx++) {
  1366. TextPropCollection p = charStyles.get(csIdx);
  1367. for (int ccRun = 0, ccStyle = p.getCharactersCovered(); ccRun < ccStyle;) {
  1368. HSLFTextParagraph para = paragraphs.get(paraIdx);
  1369. List<HSLFTextRun> runs = para.getTextRuns();
  1370. trun = runs.get(runIdx);
  1371. final int len = trun.getLength();
  1372. if (ccRun + len <= ccStyle) {
  1373. ccRun += len;
  1374. } else {
  1375. String text = trun.getRawText();
  1376. trun.setText(text.substring(0, ccStyle - ccRun));
  1377. HSLFTextRun nextRun = new HSLFTextRun(para);
  1378. nextRun.setText(text.substring(ccStyle - ccRun));
  1379. runs.add(runIdx + 1, nextRun);
  1380. ccRun += ccStyle - ccRun;
  1381. }
  1382. trun.setCharacterStyle(p);
  1383. if (paraIdx == paragraphs.size()-1 && runIdx == runs.size()-1) {
  1384. if (csIdx < charStyles.size() - 1) {
  1385. // special case, empty trailing text run
  1386. HSLFTextRun nextRun = new HSLFTextRun(para);
  1387. nextRun.setText("");
  1388. runs.add(nextRun);
  1389. ccRun++;
  1390. } else {
  1391. // need to add +1 to the last run of the last paragraph
  1392. trun.getCharacterStyle().updateTextSize(trun.getLength()+1);
  1393. ccRun++;
  1394. }
  1395. }
  1396. // need to compare it again, in case a run has been added after
  1397. if (++runIdx == runs.size()) {
  1398. paraIdx++;
  1399. runIdx = 0;
  1400. }
  1401. }
  1402. }
  1403. }
  1404. protected static void applyParagraphStyles(List<HSLFTextParagraph> paragraphs, List<TextPropCollection> paraStyles) {
  1405. int paraIdx = 0;
  1406. for (TextPropCollection p : paraStyles) {
  1407. for (int ccPara = 0, ccStyle = p.getCharactersCovered(); ccPara < ccStyle; paraIdx++) {
  1408. if (paraIdx >= paragraphs.size()) {
  1409. return;
  1410. }
  1411. HSLFTextParagraph htp = paragraphs.get(paraIdx);
  1412. TextPropCollection pCopy = p.copy();
  1413. htp.setParagraphStyle(pCopy);
  1414. int len = 0;
  1415. for (HSLFTextRun trun : htp.getTextRuns()) {
  1416. len += trun.getLength();
  1417. }
  1418. if (paraIdx == paragraphs.size()-1) {
  1419. len++;
  1420. }
  1421. pCopy.updateTextSize(len);
  1422. ccPara += len;
  1423. }
  1424. }
  1425. }
  1426. protected static void applyParagraphIndents(List<HSLFTextParagraph> paragraphs, List<IndentProp> paraStyles) {
  1427. int paraIdx = 0;
  1428. for (IndentProp p : paraStyles) {
  1429. for (int ccPara = 0, ccStyle = p.getCharactersCovered(); ccPara < ccStyle; paraIdx++) {
  1430. if (paraIdx >= paragraphs.size() || ccPara >= ccStyle-1) {
  1431. return;
  1432. }
  1433. HSLFTextParagraph para = paragraphs.get(paraIdx);
  1434. int len = 0;
  1435. for (HSLFTextRun trun : para.getTextRuns()) {
  1436. len += trun.getLength();
  1437. }
  1438. para.setIndentLevel(p.getIndentLevel());
  1439. ccPara += len + 1;
  1440. }
  1441. }
  1442. }
  1443. public EscherTextboxWrapper getTextboxWrapper() {
  1444. return (EscherTextboxWrapper) _headerAtom.getParentRecord();
  1445. }
  1446. protected static Color getColorFromColorIndexStruct(int rgb, HSLFSheet sheet) {
  1447. int cidx = rgb >>> 24;
  1448. Color tmp;
  1449. switch (cidx) {
  1450. // Background ... Accent 3 color
  1451. case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
  1452. if (sheet == null) {
  1453. return null;
  1454. }
  1455. ColorSchemeAtom ca = sheet.getColorScheme();
  1456. tmp = new Color(ca.getColor(cidx), true);
  1457. break;
  1458. // Color is an sRGB value specified by red, green, and blue fields.
  1459. case 0xFE:
  1460. tmp = new Color(rgb, true);
  1461. break;
  1462. // Color is undefined.
  1463. default:
  1464. case 0xFF:
  1465. return null;
  1466. }
  1467. return new Color(tmp.getBlue(), tmp.getGreen(), tmp.getRed());
  1468. }
  1469. /**
  1470. * Sets the value of the given Paragraph TextProp, add if required
  1471. * @param propName The name of the Paragraph TextProp
  1472. * @param val The value to set for the TextProp
  1473. */
  1474. public void setParagraphTextPropVal(String propName, Integer val) {
  1475. setPropVal(_paragraphStyle, propName, val);
  1476. setDirty();
  1477. }
  1478. /**
  1479. * marks this paragraph dirty, so its records will be renewed on save
  1480. */
  1481. public void setDirty() {
  1482. _dirty = true;
  1483. }
  1484. public boolean isDirty() {
  1485. return _dirty;
  1486. }
  1487. /**
  1488. * Calculates the start index of the given text run
  1489. *
  1490. * @param textrun the text run to search for
  1491. * @return the start index with the paragraph collection or -1 if not found
  1492. */
  1493. /* package */ int getStartIdxOfTextRun(HSLFTextRun textrun) {
  1494. int idx = 0;
  1495. for (HSLFTextParagraph p : parentList) {
  1496. for (HSLFTextRun r : p) {
  1497. if (r == textrun) {
  1498. return idx;
  1499. }
  1500. idx += r.getLength();
  1501. }
  1502. }
  1503. return -1;
  1504. }
  1505. /**
  1506. * {@inheritDoc}
  1507. *
  1508. * @see RoundTripHFPlaceholder12
  1509. */
  1510. @Override
  1511. public boolean isHeaderOrFooter() {
  1512. HSLFTextShape s = getParentShape();
  1513. if (s == null) {
  1514. return false;
  1515. }
  1516. Placeholder ph = s.getPlaceholder();
  1517. if (ph == null) {
  1518. return false;
  1519. }
  1520. switch (ph) {
  1521. case DATETIME:
  1522. case SLIDE_NUMBER:
  1523. case FOOTER:
  1524. case HEADER:
  1525. return true;
  1526. default:
  1527. return false;
  1528. }
  1529. }
  1530. }