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

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