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

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