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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.hslf.usermodel;
  16. import static org.apache.poi.hslf.record.RecordTypes.OutlineTextRefAtom;
  17. import java.awt.Color;
  18. import java.io.IOException;
  19. import java.util.ArrayList;
  20. import java.util.Arrays;
  21. import java.util.Iterator;
  22. import java.util.List;
  23. import org.apache.poi.hslf.exceptions.HSLFException;
  24. import org.apache.poi.hslf.model.PPFont;
  25. import org.apache.poi.hslf.model.textproperties.BitMaskTextProp;
  26. import org.apache.poi.hslf.model.textproperties.FontAlignmentProp;
  27. import org.apache.poi.hslf.model.textproperties.IndentProp;
  28. import org.apache.poi.hslf.model.textproperties.ParagraphFlagsTextProp;
  29. import org.apache.poi.hslf.model.textproperties.TextAlignmentProp;
  30. import org.apache.poi.hslf.model.textproperties.TextPFException9;
  31. import org.apache.poi.hslf.model.textproperties.TextProp;
  32. import org.apache.poi.hslf.model.textproperties.TextPropCollection;
  33. import org.apache.poi.hslf.model.textproperties.TextPropCollection.TextPropType;
  34. import org.apache.poi.hslf.record.ColorSchemeAtom;
  35. import org.apache.poi.hslf.record.EscherTextboxWrapper;
  36. import org.apache.poi.hslf.record.FontCollection;
  37. import org.apache.poi.hslf.record.MasterTextPropAtom;
  38. import org.apache.poi.hslf.record.OutlineTextRefAtom;
  39. import org.apache.poi.hslf.record.PPDrawing;
  40. import org.apache.poi.hslf.record.Record;
  41. import org.apache.poi.hslf.record.RecordContainer;
  42. import org.apache.poi.hslf.record.RecordTypes;
  43. import org.apache.poi.hslf.record.SlideListWithText;
  44. import org.apache.poi.hslf.record.SlidePersistAtom;
  45. import org.apache.poi.hslf.record.StyleTextProp9Atom;
  46. import org.apache.poi.hslf.record.StyleTextPropAtom;
  47. import org.apache.poi.hslf.record.TextBytesAtom;
  48. import org.apache.poi.hslf.record.TextCharsAtom;
  49. import org.apache.poi.hslf.record.TextHeaderAtom;
  50. import org.apache.poi.hslf.record.TextRulerAtom;
  51. import org.apache.poi.hslf.record.TextSpecInfoAtom;
  52. import org.apache.poi.sl.draw.DrawPaint;
  53. import org.apache.poi.sl.usermodel.AutoNumberingScheme;
  54. import org.apache.poi.sl.usermodel.PaintStyle;
  55. import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint;
  56. import org.apache.poi.sl.usermodel.TextParagraph;
  57. import org.apache.poi.util.Internal;
  58. import org.apache.poi.util.LocaleUtil;
  59. import org.apache.poi.util.POILogFactory;
  60. import org.apache.poi.util.POILogger;
  61. import org.apache.poi.util.StringUtil;
  62. import org.apache.poi.util.Units;
  63. /**
  64. * This class represents a run of text in a powerpoint document. That
  65. * run could be text on a sheet, or text in a note.
  66. * It is only a very basic class for now
  67. *
  68. * @author Nick Burch
  69. */
  70. public final class HSLFTextParagraph implements TextParagraph<HSLFShape,HSLFTextParagraph,HSLFTextRun> {
  71. protected static final POILogger logger = POILogFactory.getLogger(HSLFTextParagraph.class);
  72. /**
  73. * How to align the text
  74. */
  75. /* package */static final int AlignLeft = 0;
  76. /* package */static final int AlignCenter = 1;
  77. /* package */static final int AlignRight = 2;
  78. /* package */static final int AlignJustify = 3;
  79. // Note: These fields are protected to help with unit testing
  80. // Other classes shouldn't really go playing with them!
  81. private final TextHeaderAtom _headerAtom;
  82. private TextBytesAtom _byteAtom;
  83. private TextCharsAtom _charAtom;
  84. private TextPropCollection _paragraphStyle = new TextPropCollection(1, TextPropType.paragraph);
  85. protected TextRulerAtom _ruler;
  86. protected final List<HSLFTextRun> _runs = new ArrayList<HSLFTextRun>();
  87. protected HSLFTextShape _parentShape;
  88. private HSLFSheet _sheet;
  89. private int shapeId;
  90. private StyleTextProp9Atom styleTextProp9Atom;
  91. private boolean _dirty = false;
  92. /**
  93. * Constructs a Text Run from a Unicode text block.
  94. * Either a {@link TextCharsAtom} or a {@link TextBytesAtom} needs to be provided.
  95. *
  96. * @param tha the TextHeaderAtom that defines what's what
  97. * @param tba the TextBytesAtom containing the text or null if {@link TextCharsAtom} is provided
  98. * @param tca the TextCharsAtom containing the text or null if {@link TextBytesAtom} is provided
  99. */
  100. /* package */ HSLFTextParagraph(
  101. TextHeaderAtom tha,
  102. TextBytesAtom tba,
  103. TextCharsAtom tca
  104. ) {
  105. if (tha == null) {
  106. throw new IllegalArgumentException("TextHeaderAtom must be set.");
  107. }
  108. _headerAtom = tha;
  109. _byteAtom = tba;
  110. _charAtom = tca;
  111. }
  112. /* package */HSLFTextParagraph(HSLFTextParagraph other) {
  113. _headerAtom = other._headerAtom;
  114. _byteAtom = other._byteAtom;
  115. _charAtom = other._charAtom;
  116. _parentShape = other._parentShape;
  117. _sheet = other._sheet;
  118. _ruler = other._ruler;
  119. shapeId = other.shapeId;
  120. _paragraphStyle.copy(other._paragraphStyle);
  121. }
  122. public void addTextRun(HSLFTextRun run) {
  123. _runs.add(run);
  124. }
  125. @Override
  126. public List<HSLFTextRun> getTextRuns() {
  127. return _runs;
  128. }
  129. public TextPropCollection getParagraphStyle() {
  130. return _paragraphStyle;
  131. }
  132. public void setParagraphStyle(TextPropCollection paragraphStyle) {
  133. _paragraphStyle.copy(paragraphStyle);
  134. }
  135. /**
  136. * Setting a master style reference
  137. *
  138. * @param paragraphStyle the master style reference
  139. *
  140. * @since POI 3.14-Beta1
  141. */
  142. @Internal
  143. /* package */ void setMasterStyleReference(TextPropCollection paragraphStyle) {
  144. _paragraphStyle = paragraphStyle;
  145. }
  146. /**
  147. * Supply the Sheet we belong to, which might have an assigned SlideShow
  148. * Also passes it on to our child RichTextRuns
  149. */
  150. public void supplySheet(HSLFSheet sheet) {
  151. this._sheet = sheet;
  152. if (_runs == null) return;
  153. for (HSLFTextRun rt : _runs) {
  154. rt.updateSheet();
  155. }
  156. }
  157. public HSLFSheet getSheet() {
  158. return this._sheet;
  159. }
  160. /**
  161. * @return Shape ID
  162. */
  163. protected int getShapeId() {
  164. return shapeId;
  165. }
  166. /**
  167. * @param id Shape ID
  168. */
  169. protected void setShapeId(int id) {
  170. shapeId = id;
  171. }
  172. /**
  173. * @return 0-based index of the text run in the SLWT container
  174. */
  175. protected int getIndex() {
  176. return (_headerAtom != null) ? _headerAtom.getIndex() : -1;
  177. }
  178. /**
  179. * Sets the index of the paragraph in the SLWT container
  180. *
  181. * @param index
  182. */
  183. protected void setIndex(int index) {
  184. if (_headerAtom != null) _headerAtom.setIndex(index);
  185. }
  186. /**
  187. * Returns the type of the text, from the TextHeaderAtom.
  188. * Possible values can be seen from TextHeaderAtom
  189. * @see org.apache.poi.hslf.record.TextHeaderAtom
  190. */
  191. public int getRunType() {
  192. return (_headerAtom != null) ? _headerAtom.getTextType() : -1;
  193. }
  194. public void setRunType(int runType) {
  195. if (_headerAtom != null) _headerAtom.setTextType(runType);
  196. }
  197. /**
  198. * Is this Text Run one from a {@link PPDrawing}, or is it
  199. * one from the {@link SlideListWithText}?
  200. */
  201. public boolean isDrawingBased() {
  202. return (getIndex() == -1);
  203. }
  204. public TextRulerAtom getTextRuler() {
  205. return _ruler;
  206. }
  207. public TextRulerAtom createTextRuler() {
  208. _ruler = getTextRuler();
  209. if (_ruler == null) {
  210. _ruler = TextRulerAtom.getParagraphInstance();
  211. Record childAfter = _byteAtom;
  212. if (childAfter == null) childAfter = _charAtom;
  213. if (childAfter == null) childAfter = _headerAtom;
  214. _headerAtom.getParentRecord().addChildAfter(_ruler, childAfter);
  215. }
  216. return _ruler;
  217. }
  218. /**
  219. * Returns records that make up the list of text paragraphs
  220. * (there can be misc InteractiveInfo, TxInteractiveInfo and other records)
  221. *
  222. * @return text run records
  223. */
  224. public Record[] getRecords() {
  225. Record r[] = _headerAtom.getParentRecord().getChildRecords();
  226. return getRecords(r, new int[] { 0 }, _headerAtom);
  227. }
  228. private static Record[] getRecords(Record[] records, int[] startIdx, TextHeaderAtom headerAtom) {
  229. if (records == null) {
  230. throw new NullPointerException("records need to be set.");
  231. }
  232. for (; startIdx[0] < records.length; startIdx[0]++) {
  233. Record r = records[startIdx[0]];
  234. if (r instanceof TextHeaderAtom && (headerAtom == null || r == headerAtom)) break;
  235. }
  236. if (startIdx[0] >= records.length) {
  237. logger.log(POILogger.INFO, "header atom wasn't found - container might contain only an OutlineTextRefAtom");
  238. return new Record[0];
  239. }
  240. int length;
  241. for (length = 1; startIdx[0] + length < records.length; length++) {
  242. Record r = records[startIdx[0]+length];
  243. if (r instanceof TextHeaderAtom || r instanceof SlidePersistAtom) break;
  244. }
  245. Record result[] = new Record[length];
  246. System.arraycopy(records, startIdx[0], result, 0, length);
  247. startIdx[0] += length;
  248. return result;
  249. }
  250. /** Numbered List info */
  251. public void setStyleTextProp9Atom(final StyleTextProp9Atom styleTextProp9Atom) {
  252. this.styleTextProp9Atom = styleTextProp9Atom;
  253. }
  254. /** Numbered List info */
  255. public StyleTextProp9Atom getStyleTextProp9Atom() {
  256. return this.styleTextProp9Atom;
  257. }
  258. @Override
  259. public Iterator<HSLFTextRun> iterator() {
  260. return _runs.iterator();
  261. }
  262. @Override
  263. public Double getLeftMargin() {
  264. TextProp val = getPropVal(_paragraphStyle, "text.offset", this);
  265. return (val == null) ? null : Units.masterToPoints(val.getValue());
  266. }
  267. @Override
  268. public void setLeftMargin(Double leftMargin) {
  269. Integer val = (leftMargin == null) ? null : Units.pointsToMaster(leftMargin);
  270. setParagraphTextPropVal("text.offset", val);
  271. }
  272. @Override
  273. public Double getRightMargin() {
  274. // TODO: find out, how to determine this value
  275. return null;
  276. }
  277. @Override
  278. public void setRightMargin(Double rightMargin) {
  279. // TODO: find out, how to set this value
  280. }
  281. @Override
  282. public Double getIndent() {
  283. TextProp val = getPropVal(_paragraphStyle, "bullet.offset", this);
  284. return (val == null) ? null : Units.masterToPoints(val.getValue());
  285. }
  286. @Override
  287. public void setIndent(Double indent) {
  288. Integer val = (indent == null) ? null : Units.pointsToMaster(indent);
  289. setParagraphTextPropVal("bullet.offset", val);
  290. }
  291. @Override
  292. public String getDefaultFontFamily() {
  293. String typeface = null;
  294. if (!_runs.isEmpty()) {
  295. typeface = _runs.get(0).getFontFamily();
  296. }
  297. return (typeface != null) ? typeface : "Arial";
  298. }
  299. @Override
  300. public Double getDefaultFontSize() {
  301. Double d = null;
  302. if (!_runs.isEmpty()) {
  303. d = _runs.get(0).getFontSize();
  304. }
  305. return (d != null) ? d : 12d;
  306. }
  307. @Override
  308. public void setTextAlign(TextAlign align) {
  309. Integer alignInt = null;
  310. if (align != null) switch (align) {
  311. default:
  312. case LEFT: alignInt = TextAlignmentProp.LEFT;break;
  313. case CENTER: alignInt = TextAlignmentProp.CENTER; break;
  314. case RIGHT: alignInt = TextAlignmentProp.RIGHT; break;
  315. case DIST: alignInt = TextAlignmentProp.DISTRIBUTED; break;
  316. case JUSTIFY: alignInt = TextAlignmentProp.JUSTIFY; break;
  317. case JUSTIFY_LOW: alignInt = TextAlignmentProp.JUSTIFYLOW; break;
  318. case THAI_DIST: alignInt = TextAlignmentProp.THAIDISTRIBUTED; break;
  319. }
  320. setParagraphTextPropVal("alignment", alignInt);
  321. }
  322. @Override
  323. public TextAlign getTextAlign() {
  324. TextProp tp = getPropVal(_paragraphStyle, "alignment", this);
  325. if (tp == null) return null;
  326. switch (tp.getValue()) {
  327. default:
  328. case TextAlignmentProp.LEFT: return TextAlign.LEFT;
  329. case TextAlignmentProp.CENTER: return TextAlign.CENTER;
  330. case TextAlignmentProp.RIGHT: return TextAlign.RIGHT;
  331. case TextAlignmentProp.JUSTIFY: return TextAlign.JUSTIFY;
  332. case TextAlignmentProp.JUSTIFYLOW: return TextAlign.JUSTIFY_LOW;
  333. case TextAlignmentProp.DISTRIBUTED: return TextAlign.DIST;
  334. case TextAlignmentProp.THAIDISTRIBUTED: return TextAlign.THAI_DIST;
  335. }
  336. }
  337. @Override
  338. public FontAlign getFontAlign() {
  339. TextProp tp = getPropVal(_paragraphStyle, FontAlignmentProp.NAME, this);
  340. if (tp == null) return null;
  341. switch (tp.getValue()) {
  342. case FontAlignmentProp.BASELINE: return FontAlign.BASELINE;
  343. case FontAlignmentProp.TOP: return FontAlign.TOP;
  344. case FontAlignmentProp.CENTER: return FontAlign.CENTER;
  345. case FontAlignmentProp.BOTTOM: return FontAlign.BOTTOM;
  346. default: return FontAlign.AUTO;
  347. }
  348. }
  349. public AutoNumberingScheme getAutoNumberingScheme() {
  350. if (styleTextProp9Atom == null) return null;
  351. TextPFException9[] ant = styleTextProp9Atom.getAutoNumberTypes();
  352. int level = getIndentLevel();
  353. if (ant == null || level == -1 || level >= ant.length) return null;
  354. return ant[level].getAutoNumberScheme();
  355. }
  356. public Integer getAutoNumberingStartAt() {
  357. if (styleTextProp9Atom == null) return null;
  358. TextPFException9[] ant = styleTextProp9Atom.getAutoNumberTypes();
  359. int level = getIndentLevel();
  360. if (ant == null || level >= ant.length) return null;
  361. Short startAt = ant[level].getAutoNumberStartNumber();
  362. assert(startAt != null);
  363. return startAt.intValue();
  364. }
  365. @Override
  366. public BulletStyle getBulletStyle() {
  367. if (!isBullet() && getAutoNumberingScheme() == null) return null;
  368. return new BulletStyle() {
  369. @Override
  370. public String getBulletCharacter() {
  371. Character chr = HSLFTextParagraph.this.getBulletChar();
  372. return (chr == null || chr == 0) ? "" : "" + chr;
  373. }
  374. @Override
  375. public String getBulletFont() {
  376. return HSLFTextParagraph.this.getBulletFont();
  377. }
  378. @Override
  379. public Double getBulletFontSize() {
  380. return HSLFTextParagraph.this.getBulletSize();
  381. }
  382. @Override
  383. public void setBulletFontColor(Color color) {
  384. setBulletFontColor(DrawPaint.createSolidPaint(color));
  385. }
  386. @Override
  387. public void setBulletFontColor(PaintStyle color) {
  388. if (!(color instanceof SolidPaint)) {
  389. throw new IllegalArgumentException("HSLF only supports SolidPaint");
  390. }
  391. SolidPaint sp = (SolidPaint)color;
  392. Color col = DrawPaint.applyColorTransform(sp.getSolidColor());
  393. HSLFTextParagraph.this.setBulletColor(col);
  394. }
  395. @Override
  396. public PaintStyle getBulletFontColor() {
  397. Color col = HSLFTextParagraph.this.getBulletColor();
  398. return DrawPaint.createSolidPaint(col);
  399. }
  400. @Override
  401. public AutoNumberingScheme getAutoNumberingScheme() {
  402. return HSLFTextParagraph.this.getAutoNumberingScheme();
  403. }
  404. @Override
  405. public Integer getAutoNumberingStartAt() {
  406. return HSLFTextParagraph.this.getAutoNumberingStartAt();
  407. }
  408. };
  409. }
  410. @Override
  411. public void setBulletStyle(Object... styles) {
  412. if (styles.length == 0) {
  413. setBullet(false);
  414. } else {
  415. setBullet(true);
  416. for (Object ostyle : styles) {
  417. if (ostyle instanceof Number) {
  418. setBulletSize(((Number)ostyle).doubleValue());
  419. } else if (ostyle instanceof Color) {
  420. setBulletColor((Color)ostyle);
  421. } else if (ostyle instanceof Character) {
  422. setBulletChar((Character)ostyle);
  423. } else if (ostyle instanceof String) {
  424. setBulletFont((String)ostyle);
  425. } else if (ostyle instanceof AutoNumberingScheme) {
  426. throw new HSLFException("setting bullet auto-numberin scheme for HSLF not supported ... yet");
  427. }
  428. }
  429. }
  430. }
  431. @Override
  432. public HSLFTextShape getParentShape() {
  433. return _parentShape;
  434. }
  435. public void setParentShape(HSLFTextShape parentShape) {
  436. _parentShape = parentShape;
  437. }
  438. @Override
  439. public int getIndentLevel() {
  440. return _paragraphStyle == null ? 0 : _paragraphStyle.getIndentLevel();
  441. }
  442. @Override
  443. public void setIndentLevel(int level) {
  444. if( _paragraphStyle != null ) _paragraphStyle.setIndentLevel((short)level);
  445. }
  446. /**
  447. * Sets whether this rich text run has bullets
  448. */
  449. public void setBullet(boolean flag) {
  450. setFlag(ParagraphFlagsTextProp.BULLET_IDX, flag);
  451. }
  452. /**
  453. * Returns whether this rich text run has bullets
  454. */
  455. public boolean isBullet() {
  456. return getFlag(ParagraphFlagsTextProp.BULLET_IDX);
  457. }
  458. /**
  459. * Sets the bullet character
  460. */
  461. public void setBulletChar(Character c) {
  462. Integer val = (c == null) ? null : (int)c.charValue();
  463. setParagraphTextPropVal("bullet.char", val);
  464. }
  465. /**
  466. * Returns the bullet character
  467. */
  468. public Character getBulletChar() {
  469. TextProp tp = getPropVal(_paragraphStyle, "bullet.char", this);
  470. return (tp == null) ? null : (char)tp.getValue();
  471. }
  472. /**
  473. * Sets the bullet size
  474. */
  475. public void setBulletSize(Double size) {
  476. setPctOrPoints("bullet.size", size);
  477. }
  478. /**
  479. * Returns the bullet size, null if unset
  480. */
  481. public Double getBulletSize() {
  482. return getPctOrPoints("bullet.size");
  483. }
  484. /**
  485. * Sets the bullet color
  486. */
  487. public void setBulletColor(Color color) {
  488. Integer val = (color == null) ? null : new Color(color.getBlue(), color.getGreen(), color.getRed(), 254).getRGB();
  489. setParagraphTextPropVal("bullet.color", val);
  490. setFlag(ParagraphFlagsTextProp.BULLET_HARDCOLOR_IDX, (color != null));
  491. }
  492. /**
  493. * Returns the bullet color
  494. */
  495. public Color getBulletColor() {
  496. TextProp tp = getPropVal(_paragraphStyle, "bullet.color", this);
  497. boolean hasColor = getFlag(ParagraphFlagsTextProp.BULLET_HARDCOLOR_IDX);
  498. if (tp == null || !hasColor) {
  499. // if bullet color is undefined, return color of first run
  500. if (_runs.isEmpty()) return null;
  501. SolidPaint sp = _runs.get(0).getFontColor();
  502. return DrawPaint.applyColorTransform(sp.getSolidColor());
  503. }
  504. return getColorFromColorIndexStruct(tp.getValue(), _sheet);
  505. }
  506. /**
  507. * Sets the bullet font
  508. */
  509. public void setBulletFont(String typeface) {
  510. if (typeface == null) {
  511. setPropVal(_paragraphStyle, "bullet.font", null);
  512. setFlag(ParagraphFlagsTextProp.BULLET_HARDFONT_IDX, false);
  513. }
  514. FontCollection fc = getSheet().getSlideShow().getFontCollection();
  515. int idx = fc.addFont(typeface);
  516. setParagraphTextPropVal("bullet.font", idx);
  517. setFlag(ParagraphFlagsTextProp.BULLET_HARDFONT_IDX, true);
  518. }
  519. /**
  520. * Returns the bullet font
  521. */
  522. public String getBulletFont() {
  523. TextProp tp = getPropVal(_paragraphStyle, "bullet.font", this);
  524. boolean hasFont = getFlag(ParagraphFlagsTextProp.BULLET_HARDFONT_IDX);
  525. if (tp == null || !hasFont) return getDefaultFontFamily();
  526. PPFont ppFont = getSheet().getSlideShow().getFont(tp.getValue());
  527. assert(ppFont != null);
  528. return ppFont.getFontName();
  529. }
  530. @Override
  531. public void setLineSpacing(Double lineSpacing) {
  532. setPctOrPoints("linespacing", lineSpacing);
  533. }
  534. @Override
  535. public Double getLineSpacing() {
  536. return getPctOrPoints("linespacing");
  537. }
  538. @Override
  539. public void setSpaceBefore(Double spaceBefore) {
  540. setPctOrPoints("spacebefore", spaceBefore);
  541. }
  542. @Override
  543. public Double getSpaceBefore() {
  544. return getPctOrPoints("spacebefore");
  545. }
  546. @Override
  547. public void setSpaceAfter(Double spaceAfter) {
  548. setPctOrPoints("spaceafter", spaceAfter);
  549. }
  550. @Override
  551. public Double getSpaceAfter() {
  552. return getPctOrPoints("spaceafter");
  553. }
  554. @Override
  555. public Double getDefaultTabSize() {
  556. // TODO: implement
  557. return null;
  558. }
  559. private Double getPctOrPoints(String propName) {
  560. TextProp tp = getPropVal(_paragraphStyle, propName, this);
  561. if (tp == null) return null;
  562. int val = tp.getValue();
  563. return (val < 0) ? Units.masterToPoints(val) : val;
  564. }
  565. private void setPctOrPoints(String propName, Double dval) {
  566. Integer ival = null;
  567. if (dval != null) {
  568. ival = (dval < 0) ? Units.pointsToMaster(dval) : dval.intValue();
  569. }
  570. setParagraphTextPropVal(propName, ival);
  571. }
  572. private boolean getFlag(int index) {
  573. BitMaskTextProp tp = (BitMaskTextProp)getPropVal(_paragraphStyle, ParagraphFlagsTextProp.NAME, this);
  574. return (tp == null) ? false : tp.getSubValue(index);
  575. }
  576. private void setFlag(int index, boolean value) {
  577. BitMaskTextProp tp = (BitMaskTextProp)_paragraphStyle.addWithName(ParagraphFlagsTextProp.NAME);
  578. tp.setSubValue(value, index);
  579. setDirty();
  580. }
  581. /**
  582. * Fetch the value of the given Paragraph related TextProp. Returns null if
  583. * that TextProp isn't present. If the TextProp isn't present, the value
  584. * from the appropriate Master Sheet will apply.
  585. *
  586. * The propName can be a comma-separated list, in case multiple equivalent values
  587. * are queried
  588. */
  589. protected static TextProp getPropVal(TextPropCollection props, String propName, HSLFTextParagraph paragraph) {
  590. String propNames[] = propName.split(",");
  591. for (String pn : propNames) {
  592. TextProp prop = props.findByName(pn);
  593. if (prop != null) return prop;
  594. }
  595. BitMaskTextProp maskProp = (BitMaskTextProp) props.findByName(ParagraphFlagsTextProp.NAME);
  596. boolean hardAttribute = (maskProp != null && maskProp.getValue() == 0);
  597. if (hardAttribute) return null;
  598. HSLFSheet sheet = paragraph.getSheet();
  599. int txtype = paragraph.getRunType();
  600. HSLFMasterSheet master = sheet.getMasterSheet();
  601. if (master == null) {
  602. logger.log(POILogger.WARN, "MasterSheet is not available");
  603. return null;
  604. }
  605. boolean isChar = props.getTextPropType() == TextPropType.character;
  606. for (String pn : propNames) {
  607. TextProp prop = master.getStyleAttribute(txtype, paragraph.getIndentLevel(), pn, isChar);
  608. if (prop != null) return prop;
  609. }
  610. return null;
  611. }
  612. /**
  613. * Returns the named TextProp, either by fetching it (if it exists) or
  614. * adding it (if it didn't)
  615. *
  616. * @param props the TextPropCollection to fetch from / add into
  617. * @param name the name of the TextProp to fetch/add
  618. * @param val the value, null if unset
  619. */
  620. protected static void setPropVal(TextPropCollection props, String name, Integer val) {
  621. if (val == null) {
  622. props.removeByName(name);
  623. return;
  624. }
  625. // Fetch / Add the TextProp
  626. TextProp tp = props.addWithName(name);
  627. tp.setValue(val);
  628. }
  629. /**
  630. * Check and add linebreaks to text runs leading other paragraphs
  631. *
  632. * @param paragraphs
  633. */
  634. protected static void fixLineEndings(List<HSLFTextParagraph> paragraphs) {
  635. HSLFTextRun lastRun = null;
  636. for (HSLFTextParagraph p : paragraphs) {
  637. if (lastRun != null && !lastRun.getRawText().endsWith("\r")) {
  638. lastRun.setText(lastRun.getRawText() + "\r");
  639. }
  640. List<HSLFTextRun> ltr = p.getTextRuns();
  641. if (ltr.isEmpty()) {
  642. throw new RuntimeException("paragraph without textruns found");
  643. }
  644. lastRun = ltr.get(ltr.size() - 1);
  645. assert (lastRun.getRawText() != null);
  646. }
  647. }
  648. /**
  649. * Search for a StyleTextPropAtom is for this text header (list of paragraphs)
  650. *
  651. * @param header the header
  652. * @param textLen the length of the rawtext, or -1 if the length is not known
  653. */
  654. private static StyleTextPropAtom findStyleAtomPresent(TextHeaderAtom header, int textLen) {
  655. boolean afterHeader = false;
  656. StyleTextPropAtom style = null;
  657. for (Record record : header.getParentRecord().getChildRecords()) {
  658. long rt = record.getRecordType();
  659. if (afterHeader && rt == RecordTypes.TextHeaderAtom.typeID) {
  660. // already on the next header, quit searching
  661. break;
  662. }
  663. afterHeader |= (header == record);
  664. if (afterHeader && rt == RecordTypes.StyleTextPropAtom.typeID) {
  665. // found it
  666. style = (StyleTextPropAtom) record;
  667. }
  668. }
  669. if (style == null) {
  670. logger.log(POILogger.INFO, "styles atom doesn't exist. Creating dummy record for later saving.");
  671. style = new StyleTextPropAtom((textLen < 0) ? 1 : textLen);
  672. } else {
  673. if (textLen >= 0) {
  674. style.setParentTextSize(textLen);
  675. }
  676. }
  677. return style;
  678. }
  679. /**
  680. * Saves the modified paragraphs/textrun to the records.
  681. * Also updates the styles to the correct text length.
  682. */
  683. protected static void storeText(List<HSLFTextParagraph> paragraphs) {
  684. fixLineEndings(paragraphs);
  685. String rawText = toInternalString(getRawText(paragraphs));
  686. // Will it fit in a 8 bit atom?
  687. boolean isUnicode = StringUtil.hasMultibyte(rawText);
  688. // isUnicode = true;
  689. TextHeaderAtom headerAtom = paragraphs.get(0)._headerAtom;
  690. TextBytesAtom byteAtom = paragraphs.get(0)._byteAtom;
  691. TextCharsAtom charAtom = paragraphs.get(0)._charAtom;
  692. StyleTextPropAtom styleAtom = findStyleAtomPresent(headerAtom, rawText.length());
  693. // Store in the appropriate record
  694. Record oldRecord = null, newRecord = null;
  695. if (isUnicode) {
  696. if (byteAtom != null || charAtom == null) {
  697. oldRecord = byteAtom;
  698. charAtom = new TextCharsAtom();
  699. }
  700. newRecord = charAtom;
  701. charAtom.setText(rawText);
  702. } else {
  703. if (charAtom != null || byteAtom == null) {
  704. oldRecord = charAtom;
  705. byteAtom = new TextBytesAtom();
  706. }
  707. newRecord = byteAtom;
  708. byte[] byteText = new byte[rawText.length()];
  709. StringUtil.putCompressedUnicode(rawText, byteText, 0);
  710. byteAtom.setText(byteText);
  711. }
  712. assert (newRecord != null);
  713. RecordContainer _txtbox = headerAtom.getParentRecord();
  714. Record[] cr = _txtbox.getChildRecords();
  715. int /* headerIdx = -1, */ textIdx = -1, styleIdx = -1;
  716. for (int i = 0; i < cr.length; i++) {
  717. Record r = cr[i];
  718. if (r == headerAtom) ; // headerIdx = i;
  719. else if (r == oldRecord || r == newRecord) textIdx = i;
  720. else if (r == styleAtom) styleIdx = i;
  721. }
  722. if (textIdx == -1) {
  723. // the old record was never registered, ignore it
  724. _txtbox.addChildAfter(newRecord, headerAtom);
  725. // textIdx = headerIdx + 1;
  726. } else {
  727. // swap not appropriated records - noop if unchanged
  728. cr[textIdx] = newRecord;
  729. }
  730. if (styleIdx == -1) {
  731. // Add the new StyleTextPropAtom after the TextCharsAtom / TextBytesAtom
  732. _txtbox.addChildAfter(styleAtom, newRecord);
  733. }
  734. for (HSLFTextParagraph p : paragraphs) {
  735. if (newRecord == byteAtom) {
  736. p._byteAtom = byteAtom;
  737. p._charAtom = null;
  738. } else {
  739. p._byteAtom = null;
  740. p._charAtom = charAtom;
  741. }
  742. }
  743. // Update the text length for its Paragraph and Character stylings
  744. // * reset the length, to the new string's length
  745. // * add on +1 if the last block
  746. styleAtom.clearStyles();
  747. TextPropCollection lastPTPC = null, lastRTPC = null, ptpc = null, rtpc = null;
  748. for (HSLFTextParagraph para : paragraphs) {
  749. ptpc = para.getParagraphStyle();
  750. ptpc.updateTextSize(0);
  751. if (!ptpc.equals(lastPTPC)) {
  752. lastPTPC = styleAtom.addParagraphTextPropCollection(0);
  753. lastPTPC.copy(ptpc);
  754. }
  755. for (HSLFTextRun tr : para.getTextRuns()) {
  756. rtpc = tr.getCharacterStyle();
  757. rtpc.updateTextSize(0);
  758. if (!rtpc.equals(lastRTPC)) {
  759. lastRTPC = styleAtom.addCharacterTextPropCollection(0);
  760. lastRTPC.copy(rtpc);
  761. }
  762. int len = tr.getLength();
  763. ptpc.updateTextSize(ptpc.getCharactersCovered() + len);
  764. rtpc.updateTextSize(len);
  765. lastPTPC.updateTextSize(lastPTPC.getCharactersCovered() + len);
  766. lastRTPC.updateTextSize(lastRTPC.getCharactersCovered() + len);
  767. }
  768. }
  769. assert (lastPTPC != null && lastRTPC != null && ptpc != null && rtpc != null);
  770. ptpc.updateTextSize(ptpc.getCharactersCovered() + 1);
  771. rtpc.updateTextSize(rtpc.getCharactersCovered() + 1);
  772. lastPTPC.updateTextSize(lastPTPC.getCharactersCovered() + 1);
  773. lastRTPC.updateTextSize(lastRTPC.getCharactersCovered() + 1);
  774. /**
  775. * If TextSpecInfoAtom is present, we must update the text size in it,
  776. * otherwise the ppt will be corrupted
  777. */
  778. for (Record r : paragraphs.get(0).getRecords()) {
  779. if (r instanceof TextSpecInfoAtom) {
  780. ((TextSpecInfoAtom) r).setParentSize(rawText.length() + 1);
  781. break;
  782. }
  783. }
  784. if (_txtbox instanceof EscherTextboxWrapper) {
  785. try {
  786. ((EscherTextboxWrapper) _txtbox).writeOut(null);
  787. } catch (IOException e) {
  788. throw new RuntimeException("failed dummy write", e);
  789. }
  790. }
  791. for (HSLFTextParagraph p : paragraphs) {
  792. p._dirty = false;
  793. }
  794. }
  795. /**
  796. * Adds the supplied text onto the end of the TextParagraphs,
  797. * creating a new RichTextRun for it to sit in.
  798. *
  799. * @param text the text string used by this object.
  800. */
  801. protected static HSLFTextRun appendText(List<HSLFTextParagraph> paragraphs, String text, boolean newParagraph) {
  802. text = toInternalString(text);
  803. // check paragraphs
  804. assert(!paragraphs.isEmpty() && !paragraphs.get(0).getTextRuns().isEmpty());
  805. HSLFTextParagraph htp = paragraphs.get(paragraphs.size() - 1);
  806. HSLFTextRun htr = htp.getTextRuns().get(htp.getTextRuns().size() - 1);
  807. boolean addParagraph = newParagraph;
  808. for (String rawText : text.split("(?<=\r)")) {
  809. // special case, if last text paragraph or run is empty, we will reuse it
  810. boolean lastRunEmpty = (htr.getLength() == 0);
  811. boolean lastParaEmpty = lastRunEmpty && (htp.getTextRuns().size() == 1);
  812. if (addParagraph && !lastParaEmpty) {
  813. TextPropCollection tpc = htp.getParagraphStyle();
  814. HSLFTextParagraph prevHtp = htp;
  815. htp = new HSLFTextParagraph(htp._headerAtom, htp._byteAtom, htp._charAtom);
  816. htp.getParagraphStyle().copy(tpc);
  817. htp.setParentShape(prevHtp.getParentShape());
  818. htp.setShapeId(prevHtp.getShapeId());
  819. htp.supplySheet(prevHtp.getSheet());
  820. paragraphs.add(htp);
  821. }
  822. addParagraph = true;
  823. if (!lastRunEmpty) {
  824. TextPropCollection tpc = htr.getCharacterStyle();
  825. htr = new HSLFTextRun(htp);
  826. htr.getCharacterStyle().copy(tpc);
  827. htp.addTextRun(htr);
  828. }
  829. htr.setText(rawText);
  830. }
  831. storeText(paragraphs);
  832. return htr;
  833. }
  834. /**
  835. * Sets (overwrites) the current text.
  836. * Uses the properties of the first paragraph / textrun
  837. *
  838. * @param text the text string used by this object.
  839. */
  840. public static HSLFTextRun setText(List<HSLFTextParagraph> paragraphs, String text) {
  841. // check paragraphs
  842. assert(!paragraphs.isEmpty() && !paragraphs.get(0).getTextRuns().isEmpty());
  843. Iterator<HSLFTextParagraph> paraIter = paragraphs.iterator();
  844. HSLFTextParagraph htp = paraIter.next(); // keep first
  845. assert (htp != null);
  846. while (paraIter.hasNext()) {
  847. paraIter.next();
  848. paraIter.remove();
  849. }
  850. Iterator<HSLFTextRun> runIter = htp.getTextRuns().iterator();
  851. if (runIter.hasNext()) {
  852. HSLFTextRun htr = runIter.next();
  853. htr.setText("");
  854. while (runIter.hasNext()) {
  855. runIter.next();
  856. runIter.remove();
  857. }
  858. } else {
  859. HSLFTextRun trun = new HSLFTextRun(htp);
  860. htp.addTextRun(trun);
  861. }
  862. return appendText(paragraphs, text, false);
  863. }
  864. public static String getText(List<HSLFTextParagraph> paragraphs) {
  865. assert (!paragraphs.isEmpty());
  866. String rawText = getRawText(paragraphs);
  867. return toExternalString(rawText, paragraphs.get(0).getRunType());
  868. }
  869. public static String getRawText(List<HSLFTextParagraph> paragraphs) {
  870. StringBuilder sb = new StringBuilder();
  871. for (HSLFTextParagraph p : paragraphs) {
  872. for (HSLFTextRun r : p.getTextRuns()) {
  873. sb.append(r.getRawText());
  874. }
  875. }
  876. return sb.toString();
  877. }
  878. @Override
  879. public String toString() {
  880. StringBuilder sb = new StringBuilder();
  881. for (HSLFTextRun r : getTextRuns()) {
  882. sb.append(r.getRawText());
  883. }
  884. return toExternalString(sb.toString(), getRunType());
  885. }
  886. /**
  887. * Returns a new string with line breaks converted into internal ppt
  888. * representation
  889. */
  890. protected static String toInternalString(String s) {
  891. String ns = s.replaceAll("\\r?\\n", "\r");
  892. return ns;
  893. }
  894. /**
  895. * Converts raw text from the text paragraphs to a formatted string,
  896. * i.e. it converts certain control characters used in the raw txt
  897. *
  898. * @param rawText the raw text
  899. * @param runType the run type of the shape, paragraph or headerAtom.
  900. * use -1 if unknown
  901. * @return the formatted string
  902. */
  903. public static String toExternalString(String rawText, int runType) {
  904. // PowerPoint seems to store files with \r as the line break
  905. // The messes things up on everything but a Mac, so translate
  906. // them to \n
  907. String text = rawText.replace('\r', '\n');
  908. switch (runType) {
  909. // 0xB acts like cariage return in page titles and like blank in the
  910. // others
  911. case -1:
  912. case org.apache.poi.hslf.record.TextHeaderAtom.TITLE_TYPE:
  913. case org.apache.poi.hslf.record.TextHeaderAtom.CENTER_TITLE_TYPE:
  914. text = text.replace((char) 0x0B, '\n');
  915. break;
  916. default:
  917. text = text.replace((char) 0x0B, ' ');
  918. break;
  919. }
  920. return text;
  921. }
  922. /**
  923. * For a given PPDrawing, grab all the TextRuns
  924. */
  925. public static List<List<HSLFTextParagraph>> findTextParagraphs(PPDrawing ppdrawing, HSLFSheet sheet) {
  926. List<List<HSLFTextParagraph>> runsV = new ArrayList<List<HSLFTextParagraph>>();
  927. for (EscherTextboxWrapper wrapper : ppdrawing.getTextboxWrappers()) {
  928. List<HSLFTextParagraph> p = findTextParagraphs(wrapper, sheet);
  929. if (p != null) runsV.add(p);
  930. }
  931. return runsV;
  932. }
  933. /**
  934. * Scans through the supplied record array, looking for
  935. * a TextHeaderAtom followed by one of a TextBytesAtom or
  936. * a TextCharsAtom. Builds up TextRuns from these
  937. *
  938. * @param wrapper an EscherTextboxWrapper
  939. */
  940. protected static List<HSLFTextParagraph> findTextParagraphs(EscherTextboxWrapper wrapper, HSLFSheet sheet) {
  941. // propagate parents to parent-aware records
  942. RecordContainer.handleParentAwareRecords(wrapper);
  943. int shapeId = wrapper.getShapeId();
  944. List<HSLFTextParagraph> rv = null;
  945. OutlineTextRefAtom ota = (OutlineTextRefAtom)wrapper.findFirstOfType(OutlineTextRefAtom.typeID);
  946. if (ota != null) {
  947. // if we are based on an outline, there are no further records to be parsed from the wrapper
  948. if (sheet == null) {
  949. throw new RuntimeException("Outline atom reference can't be solved without a sheet record");
  950. }
  951. List<List<HSLFTextParagraph>> sheetRuns = sheet.getTextParagraphs();
  952. assert (sheetRuns != null);
  953. int idx = ota.getTextIndex();
  954. for (List<HSLFTextParagraph> r : sheetRuns) {
  955. if (r.isEmpty()) continue;
  956. int ridx = r.get(0).getIndex();
  957. if (ridx > idx) break;
  958. if (ridx == idx) {
  959. if (rv == null) {
  960. rv = r;
  961. } else {
  962. // create a new container
  963. // TODO: ... is this case really happening?
  964. rv = new ArrayList<HSLFTextParagraph>(rv);
  965. rv.addAll(r);
  966. }
  967. }
  968. }
  969. if (rv == null || rv.isEmpty()) {
  970. logger.log(POILogger.WARN, "text run not found for OutlineTextRefAtom.TextIndex=" + idx);
  971. }
  972. } else {
  973. if (sheet != null) {
  974. // check sheet runs first, so we get exactly the same paragraph list
  975. List<List<HSLFTextParagraph>> sheetRuns = sheet.getTextParagraphs();
  976. assert (sheetRuns != null);
  977. for (List<HSLFTextParagraph> paras : sheetRuns) {
  978. if (!paras.isEmpty() && paras.get(0)._headerAtom.getParentRecord() == wrapper) {
  979. rv = paras;
  980. break;
  981. }
  982. }
  983. }
  984. if (rv == null) {
  985. // if we haven't found the wrapper in the sheet runs, create a new paragraph list from its record
  986. List<List<HSLFTextParagraph>> rvl = findTextParagraphs(wrapper.getChildRecords());
  987. switch (rvl.size()) {
  988. case 0: break; // nothing found
  989. case 1: rv = rvl.get(0); break; // normal case
  990. default:
  991. throw new RuntimeException("TextBox contains more than one list of paragraphs.");
  992. }
  993. }
  994. }
  995. if (rv != null) {
  996. StyleTextProp9Atom styleTextProp9Atom = wrapper.getStyleTextProp9Atom();
  997. for (HSLFTextParagraph htp : rv) {
  998. htp.setShapeId(shapeId);
  999. htp.setStyleTextProp9Atom(styleTextProp9Atom);
  1000. }
  1001. }
  1002. return rv;
  1003. }
  1004. /**
  1005. * Scans through the supplied record array, looking for
  1006. * a TextHeaderAtom followed by one of a TextBytesAtom or
  1007. * a TextCharsAtom. Builds up TextRuns from these
  1008. *
  1009. * @param records the records to build from
  1010. */
  1011. protected static List<List<HSLFTextParagraph>> findTextParagraphs(Record[] records) {
  1012. List<List<HSLFTextParagraph>> paragraphCollection = new ArrayList<List<HSLFTextParagraph>>();
  1013. int[] recordIdx = { 0 };
  1014. for (int slwtIndex = 0; recordIdx[0] < records.length; slwtIndex++) {
  1015. TextHeaderAtom header = null;
  1016. TextBytesAtom tbytes = null;
  1017. TextCharsAtom tchars = null;
  1018. TextRulerAtom ruler = null;
  1019. MasterTextPropAtom indents = null;
  1020. for (Record r : getRecords(records, recordIdx, null)) {
  1021. long rt = r.getRecordType();
  1022. if (RecordTypes.TextHeaderAtom.typeID == rt) {
  1023. header = (TextHeaderAtom) r;
  1024. } else if (RecordTypes.TextBytesAtom.typeID == rt) {
  1025. tbytes = (TextBytesAtom) r;
  1026. } else if (RecordTypes.TextCharsAtom.typeID == rt) {
  1027. tchars = (TextCharsAtom) r;
  1028. } else if (RecordTypes.TextRulerAtom.typeID == rt) {
  1029. ruler = (TextRulerAtom) r;
  1030. } else if (RecordTypes.MasterTextPropAtom.typeID == rt) {
  1031. indents = (MasterTextPropAtom) r;
  1032. }
  1033. // don't search for RecordTypes.StyleTextPropAtom.typeID here ... see findStyleAtomPresent below
  1034. }
  1035. if (header == null) break;
  1036. if (header.getParentRecord() instanceof SlideListWithText) {
  1037. // runs found in PPDrawing are not linked with SlideListWithTexts
  1038. header.setIndex(slwtIndex);
  1039. }
  1040. if (tbytes == null && tchars == null) {
  1041. tbytes = new TextBytesAtom();
  1042. // don't add record yet - set it in storeText
  1043. logger.log(POILogger.INFO, "bytes nor chars atom doesn't exist. Creating dummy record for later saving.");
  1044. }
  1045. String rawText = (tchars != null) ? tchars.getText() : tbytes.getText();
  1046. StyleTextPropAtom styles = findStyleAtomPresent(header, rawText.length());
  1047. List<HSLFTextParagraph> paragraphs = new ArrayList<HSLFTextParagraph>();
  1048. paragraphCollection.add(paragraphs);
  1049. // split, but keep delimiter
  1050. for (String para : rawText.split("(?<=\r)")) {
  1051. HSLFTextParagraph tpara = new HSLFTextParagraph(header, tbytes, tchars);
  1052. paragraphs.add(tpara);
  1053. tpara._ruler = ruler;
  1054. tpara.getParagraphStyle().updateTextSize(para.length());
  1055. HSLFTextRun trun = new HSLFTextRun(tpara);
  1056. tpara.addTextRun(trun);
  1057. trun.setText(para);
  1058. }
  1059. applyCharacterStyles(paragraphs, styles.getCharacterStyles());
  1060. applyParagraphStyles(paragraphs, styles.getParagraphStyles());
  1061. if (indents != null) {
  1062. applyParagraphIndents(paragraphs, indents.getIndents());
  1063. }
  1064. }
  1065. if (paragraphCollection.isEmpty()) {
  1066. logger.log(POILogger.DEBUG, "No text records found.");
  1067. }
  1068. return paragraphCollection;
  1069. }
  1070. protected static void applyCharacterStyles(List<HSLFTextParagraph> paragraphs, List<TextPropCollection> charStyles) {
  1071. int paraIdx = 0, runIdx = 0;
  1072. HSLFTextRun trun;
  1073. for (int csIdx = 0; csIdx < charStyles.size(); csIdx++) {
  1074. TextPropCollection p = charStyles.get(csIdx);
  1075. for (int ccRun = 0, ccStyle = p.getCharactersCovered(); ccRun < ccStyle;) {
  1076. HSLFTextParagraph para = paragraphs.get(paraIdx);
  1077. List<HSLFTextRun> runs = para.getTextRuns();
  1078. trun = runs.get(runIdx);
  1079. final int len = trun.getLength();
  1080. if (ccRun + len <= ccStyle) {
  1081. ccRun += len;
  1082. } else {
  1083. String text = trun.getRawText();
  1084. trun.setText(text.substring(0, ccStyle - ccRun));
  1085. HSLFTextRun nextRun = new HSLFTextRun(para);
  1086. nextRun.setText(text.substring(ccStyle - ccRun));
  1087. runs.add(runIdx + 1, nextRun);
  1088. ccRun += ccStyle - ccRun;
  1089. }
  1090. trun.setCharacterStyle(p);
  1091. if (paraIdx == paragraphs.size()-1 && runIdx == runs.size()-1) {
  1092. if (csIdx < charStyles.size() - 1) {
  1093. // special case, empty trailing text run
  1094. HSLFTextRun nextRun = new HSLFTextRun(para);
  1095. nextRun.setText("");
  1096. runs.add(nextRun);
  1097. ccRun++;
  1098. } else {
  1099. // need to add +1 to the last run of the last paragraph
  1100. trun.getCharacterStyle().updateTextSize(trun.getLength()+1);
  1101. ccRun++;
  1102. }
  1103. }
  1104. // need to compare it again, in case a run has been added after
  1105. if (++runIdx == runs.size()) {
  1106. paraIdx++;
  1107. runIdx = 0;
  1108. }
  1109. }
  1110. }
  1111. }
  1112. protected static void applyParagraphStyles(List<HSLFTextParagraph> paragraphs, List<TextPropCollection> paraStyles) {
  1113. int paraIdx = 0;
  1114. for (TextPropCollection p : paraStyles) {
  1115. for (int ccPara = 0, ccStyle = p.getCharactersCovered(); ccPara < ccStyle; paraIdx++) {
  1116. if (paraIdx >= paragraphs.size()) return;
  1117. HSLFTextParagraph htp = paragraphs.get(paraIdx);
  1118. TextPropCollection pCopy = new TextPropCollection(0, TextPropType.paragraph);
  1119. pCopy.copy(p);
  1120. htp.setParagraphStyle(pCopy);
  1121. int len = 0;
  1122. for (HSLFTextRun trun : htp.getTextRuns()) {
  1123. len += trun.getLength();
  1124. }
  1125. if (paraIdx == paragraphs.size()-1) len++;
  1126. pCopy.updateTextSize(len);
  1127. ccPara += len;
  1128. }
  1129. }
  1130. }
  1131. protected static void applyParagraphIndents(List<HSLFTextParagraph> paragraphs, List<IndentProp> paraStyles) {
  1132. int paraIdx = 0;
  1133. for (IndentProp p : paraStyles) {
  1134. for (int ccPara = 0, ccStyle = p.getCharactersCovered(); ccPara < ccStyle; paraIdx++) {
  1135. if (paraIdx >= paragraphs.size() || ccPara >= ccStyle-1) return;
  1136. HSLFTextParagraph para = paragraphs.get(paraIdx);
  1137. int len = 0;
  1138. for (HSLFTextRun trun : para.getTextRuns()) {
  1139. len += trun.getLength();
  1140. }
  1141. para.setIndentLevel(p.getIndentLevel());
  1142. ccPara += len + 1;
  1143. }
  1144. }
  1145. }
  1146. protected static List<HSLFTextParagraph> createEmptyParagraph() {
  1147. EscherTextboxWrapper wrapper = new EscherTextboxWrapper();
  1148. return createEmptyParagraph(wrapper);
  1149. }
  1150. protected static List<HSLFTextParagraph> createEmptyParagraph(EscherTextboxWrapper wrapper) {
  1151. TextHeaderAtom tha = new TextHeaderAtom();
  1152. tha.setParentRecord(wrapper);
  1153. wrapper.appendChildRecord(tha);
  1154. TextBytesAtom tba = new TextBytesAtom();
  1155. tba.setText("".getBytes(LocaleUtil.CHARSET_1252));
  1156. wrapper.appendChildRecord(tba);
  1157. StyleTextPropAtom sta = new StyleTextPropAtom(1);
  1158. TextPropCollection paraStyle = sta.addParagraphTextPropCollection(1);
  1159. TextPropCollection charStyle = sta.addCharacterTextPropCollection(1);
  1160. wrapper.appendChildRecord(sta);
  1161. HSLFTextParagraph htp = new HSLFTextParagraph(tha, tba, null);
  1162. htp.setParagraphStyle(paraStyle);
  1163. HSLFTextRun htr = new HSLFTextRun(htp);
  1164. htr.setCharacterStyle(charStyle);
  1165. htr.setText("");
  1166. htp.addTextRun(htr);
  1167. return Arrays.asList(htp);
  1168. }
  1169. public EscherTextboxWrapper getTextboxWrapper() {
  1170. return (EscherTextboxWrapper) _headerAtom.getParentRecord();
  1171. }
  1172. protected static Color getColorFromColorIndexStruct(int rgb, HSLFSheet sheet) {
  1173. int cidx = rgb >>> 24;
  1174. Color tmp;
  1175. switch (cidx) {
  1176. // Background ... Accent 3 color
  1177. case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
  1178. if (sheet == null) return null;
  1179. ColorSchemeAtom ca = sheet.getColorScheme();
  1180. tmp = new Color(ca.getColor(cidx), true);
  1181. break;
  1182. // Color is an sRGB value specified by red, green, and blue fields.
  1183. case 0xFE:
  1184. tmp = new Color(rgb, true);
  1185. break;
  1186. // Color is undefined.
  1187. default:
  1188. case 0xFF:
  1189. return null;
  1190. }
  1191. return new Color(tmp.getBlue(), tmp.getGreen(), tmp.getRed());
  1192. }
  1193. /**
  1194. * Sets the value of the given Paragraph TextProp, add if required
  1195. * @param propName The name of the Paragraph TextProp
  1196. * @param val The value to set for the TextProp
  1197. */
  1198. public void setParagraphTextPropVal(String propName, Integer val) {
  1199. setPropVal(_paragraphStyle, propName, val);
  1200. setDirty();
  1201. }
  1202. /**
  1203. * marks this paragraph dirty, so its records will be renewed on save
  1204. */
  1205. public void setDirty() {
  1206. _dirty = true;
  1207. }
  1208. public boolean isDirty() {
  1209. return _dirty;
  1210. }
  1211. }