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

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