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.

IFRenderer.java 54KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467
  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. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.render.intermediate;
  19. import java.awt.Color;
  20. import java.awt.Dimension;
  21. import java.awt.Point;
  22. import java.awt.Rectangle;
  23. import java.awt.geom.AffineTransform;
  24. import java.awt.geom.Rectangle2D;
  25. import java.io.IOException;
  26. import java.io.OutputStream;
  27. import java.util.Iterator;
  28. import java.util.List;
  29. import java.util.Locale;
  30. import java.util.Map;
  31. import java.util.Stack;
  32. import javax.xml.transform.stream.StreamResult;
  33. import org.w3c.dom.Document;
  34. import org.xml.sax.SAXException;
  35. import org.apache.commons.logging.Log;
  36. import org.apache.commons.logging.LogFactory;
  37. import org.apache.batik.parser.AWTTransformProducer;
  38. import org.apache.xmlgraphics.xmp.Metadata;
  39. import org.apache.xmlgraphics.xmp.schemas.DublinCoreAdapter;
  40. import org.apache.xmlgraphics.xmp.schemas.DublinCoreSchema;
  41. import org.apache.xmlgraphics.xmp.schemas.XMPBasicAdapter;
  42. import org.apache.xmlgraphics.xmp.schemas.XMPBasicSchema;
  43. import org.apache.fop.Version;
  44. import org.apache.fop.accessibility.StructureTreeElement;
  45. import org.apache.fop.apps.FOPException;
  46. import org.apache.fop.apps.FOUserAgent;
  47. import org.apache.fop.apps.MimeConstants;
  48. import org.apache.fop.area.Area;
  49. import org.apache.fop.area.AreaTreeObject;
  50. import org.apache.fop.area.Block;
  51. import org.apache.fop.area.BlockViewport;
  52. import org.apache.fop.area.BookmarkData;
  53. import org.apache.fop.area.CTM;
  54. import org.apache.fop.area.DestinationData;
  55. import org.apache.fop.area.OffDocumentExtensionAttachment;
  56. import org.apache.fop.area.OffDocumentItem;
  57. import org.apache.fop.area.PageSequence;
  58. import org.apache.fop.area.PageViewport;
  59. import org.apache.fop.area.RegionViewport;
  60. import org.apache.fop.area.Trait;
  61. import org.apache.fop.area.inline.AbstractTextArea;
  62. import org.apache.fop.area.inline.ForeignObject;
  63. import org.apache.fop.area.inline.Image;
  64. import org.apache.fop.area.inline.InlineArea;
  65. import org.apache.fop.area.inline.InlineParent;
  66. import org.apache.fop.area.inline.InlineViewport;
  67. import org.apache.fop.area.inline.Leader;
  68. import org.apache.fop.area.inline.SpaceArea;
  69. import org.apache.fop.area.inline.TextArea;
  70. import org.apache.fop.area.inline.WordArea;
  71. import org.apache.fop.datatypes.URISpecification;
  72. import org.apache.fop.fo.extensions.ExtensionAttachment;
  73. import org.apache.fop.fo.extensions.xmp.XMPMetadata;
  74. import org.apache.fop.fonts.Font;
  75. import org.apache.fop.fonts.FontInfo;
  76. import org.apache.fop.fonts.FontTriplet;
  77. import org.apache.fop.fonts.LazyFont;
  78. import org.apache.fop.fonts.Typeface;
  79. import org.apache.fop.render.AbstractPathOrientedRenderer;
  80. import org.apache.fop.render.Renderer;
  81. import org.apache.fop.render.intermediate.extensions.AbstractAction;
  82. import org.apache.fop.render.intermediate.extensions.ActionSet;
  83. import org.apache.fop.render.intermediate.extensions.Bookmark;
  84. import org.apache.fop.render.intermediate.extensions.BookmarkTree;
  85. import org.apache.fop.render.intermediate.extensions.GoToXYAction;
  86. import org.apache.fop.render.intermediate.extensions.Link;
  87. import org.apache.fop.render.intermediate.extensions.NamedDestination;
  88. import org.apache.fop.render.intermediate.extensions.URIAction;
  89. import org.apache.fop.render.pdf.PDFEventProducer;
  90. import org.apache.fop.traits.BorderProps;
  91. import org.apache.fop.traits.RuleStyle;
  92. /**
  93. * This renderer implementation is an adapter to the {@link IFPainter} interface. It is used
  94. * to generate content using FOP's intermediate format.
  95. */
  96. public class IFRenderer extends AbstractPathOrientedRenderer {
  97. //TODO Many parts of the Renderer infrastructure are using floats (coordinates in points)
  98. //instead of ints (in millipoints). A lot of conversion to and from is performed.
  99. //When the new IF is established, the Renderer infrastructure should be revisited so check
  100. //if optimizations can be done to avoid int->float->int conversions.
  101. /** logging instance */
  102. protected static final Log log = LogFactory.getLog(IFRenderer.class);
  103. /** XML MIME type */
  104. public static final String IF_MIME_TYPE = MimeConstants.MIME_FOP_IF;
  105. private IFDocumentHandler documentHandler;
  106. private IFPainter painter;
  107. /** If not null, the XMLRenderer will mimic another renderer by using its font setup. */
  108. protected Renderer mimic;
  109. private boolean inPageSequence;
  110. private Stack graphicContextStack = new Stack();
  111. private Stack viewportDimensionStack = new Stack();
  112. private IFGraphicContext graphicContext = new IFGraphicContext();
  113. //private Stack groupStack = new Stack();
  114. private Metadata documentMetadata;
  115. /**
  116. * Maps XSL-FO element IDs to their on-page XY-positions
  117. * Must be used in conjunction with the page reference to fully specify the details
  118. * of a "go-to" action.
  119. */
  120. private Map idPositions = new java.util.HashMap();
  121. /**
  122. * The "go-to" actions in idGoTos that are not complete yet
  123. */
  124. private List unfinishedGoTos = new java.util.ArrayList();
  125. // can't use a Set because PDFGoTo.equals returns true if the target is the same,
  126. // even if the object number differs
  127. /** Maps unique PageViewport key to page indices (for link target handling) */
  128. protected Map pageIndices = new java.util.HashMap();
  129. private BookmarkTree bookmarkTree;
  130. private List deferredDestinations = new java.util.ArrayList();
  131. private List deferredLinks = new java.util.ArrayList();
  132. private ActionSet actionSet = new ActionSet();
  133. private TextUtil textUtil = new TextUtil();
  134. private Stack<String> ids = new Stack<String>();
  135. /**
  136. * Main constructor
  137. *
  138. * @param userAgent the user agent that contains configuration details. This cannot be null.
  139. */
  140. public IFRenderer(FOUserAgent userAgent) {
  141. super(userAgent);
  142. }
  143. /** {@inheritDoc} */
  144. public String getMimeType() {
  145. return IF_MIME_TYPE;
  146. }
  147. /**
  148. * Sets the {@link IFDocumentHandler} to be used by the {@link IFRenderer}.
  149. * @param documentHandler the {@link IFDocumentHandler}
  150. */
  151. public void setDocumentHandler(IFDocumentHandler documentHandler) {
  152. this.documentHandler = documentHandler;
  153. }
  154. /** {@inheritDoc} */
  155. public void setupFontInfo(FontInfo inFontInfo) throws FOPException {
  156. if (this.documentHandler == null) {
  157. this.documentHandler = createDefaultDocumentHandler();
  158. }
  159. IFUtil.setupFonts(this.documentHandler, inFontInfo);
  160. this.fontInfo = inFontInfo;
  161. }
  162. private void handleIFException(IFException ife) {
  163. if (ife.getCause() instanceof SAXException) {
  164. throw new RuntimeException(ife.getCause());
  165. } else {
  166. throw new RuntimeException(ife);
  167. }
  168. }
  169. private void handleIFExceptionWithIOException(IFException ife) throws IOException {
  170. Throwable cause = ife.getCause();
  171. if (cause instanceof IOException) {
  172. throw (IOException) cause;
  173. } else {
  174. handleIFException(ife);
  175. }
  176. }
  177. /** {@inheritDoc} */
  178. public boolean supportsOutOfOrder() {
  179. return (this.documentHandler != null
  180. ? this.documentHandler.supportsPagesOutOfOrder() : false);
  181. }
  182. /**
  183. * Returns the document navigation handler if available/supported.
  184. * @return the document navigation handler or null if not supported
  185. */
  186. protected IFDocumentNavigationHandler getDocumentNavigationHandler() {
  187. return this.documentHandler.getDocumentNavigationHandler();
  188. }
  189. /**
  190. * Indicates whether document navigation features are supported by the document handler.
  191. * @return true if document navigation features are available
  192. */
  193. protected boolean hasDocumentNavigation() {
  194. return getDocumentNavigationHandler() != null;
  195. }
  196. /**
  197. * Creates a default {@link IFDocumentHandler} when none has been set.
  198. * @return the default IFDocumentHandler
  199. */
  200. protected IFDocumentHandler createDefaultDocumentHandler() {
  201. FOUserAgent userAgent = getUserAgent();
  202. IFSerializer serializer = new IFSerializer(new IFContext(userAgent));
  203. if (userAgent.isAccessibilityEnabled()) {
  204. userAgent.setStructureTreeEventHandler(serializer.getStructureTreeEventHandler());
  205. }
  206. return serializer;
  207. }
  208. /** {@inheritDoc} */
  209. public void startRenderer(OutputStream outputStream)
  210. throws IOException {
  211. try {
  212. if (outputStream != null) {
  213. StreamResult result = new StreamResult(outputStream);
  214. if (getUserAgent().getOutputFile() != null) {
  215. result.setSystemId(
  216. getUserAgent().getOutputFile().toURI().toURL().toExternalForm());
  217. }
  218. if (this.documentHandler == null) {
  219. this.documentHandler = createDefaultDocumentHandler();
  220. }
  221. this.documentHandler.setResult(result);
  222. }
  223. super.startRenderer(null);
  224. if (log.isDebugEnabled()) {
  225. log.debug("Rendering areas via IF document handler ("
  226. + this.documentHandler.getClass().getName() + ")...");
  227. }
  228. documentHandler.startDocument();
  229. documentHandler.startDocumentHeader();
  230. } catch (IFException e) {
  231. handleIFExceptionWithIOException(e);
  232. }
  233. }
  234. /** {@inheritDoc} */
  235. public void stopRenderer() throws IOException {
  236. try {
  237. if (this.inPageSequence) {
  238. documentHandler.endPageSequence();
  239. this.inPageSequence = false;
  240. }
  241. documentHandler.startDocumentTrailer();
  242. //Wrap up document navigation
  243. if (hasDocumentNavigation()) {
  244. finishOpenGoTos();
  245. Iterator iter = this.deferredDestinations.iterator();
  246. while (iter.hasNext()) {
  247. NamedDestination dest = (NamedDestination)iter.next();
  248. iter.remove();
  249. getDocumentNavigationHandler().renderNamedDestination(dest);
  250. }
  251. if (this.bookmarkTree != null) {
  252. getDocumentNavigationHandler().renderBookmarkTree(this.bookmarkTree);
  253. }
  254. }
  255. documentHandler.endDocumentTrailer();
  256. documentHandler.endDocument();
  257. } catch (IFException e) {
  258. handleIFExceptionWithIOException(e);
  259. }
  260. pageIndices.clear();
  261. idPositions.clear();
  262. actionSet.clear();
  263. super.stopRenderer();
  264. log.debug("Rendering finished.");
  265. }
  266. @Override
  267. public void setDocumentLocale(Locale locale) {
  268. documentHandler.setDocumentLocale(locale);
  269. }
  270. /** {@inheritDoc} */
  271. public void processOffDocumentItem(OffDocumentItem odi) {
  272. if (odi instanceof DestinationData) {
  273. // render Destinations
  274. renderDestination((DestinationData) odi);
  275. } else if (odi instanceof BookmarkData) {
  276. // render Bookmark-Tree
  277. renderBookmarkTree((BookmarkData) odi);
  278. } else if (odi instanceof OffDocumentExtensionAttachment) {
  279. ExtensionAttachment attachment = ((OffDocumentExtensionAttachment)odi).getAttachment();
  280. if (XMPMetadata.CATEGORY.equals(attachment.getCategory())) {
  281. renderXMPMetadata((XMPMetadata)attachment);
  282. } else {
  283. try {
  284. this.documentHandler.handleExtensionObject(attachment);
  285. } catch (IFException ife) {
  286. handleIFException(ife);
  287. }
  288. }
  289. }
  290. }
  291. private void renderDestination(DestinationData dd) {
  292. if (!hasDocumentNavigation()) {
  293. return;
  294. }
  295. String targetID = dd.getIDRef();
  296. if (targetID == null || targetID.length() == 0) {
  297. throw new IllegalArgumentException("DestinationData must contain a ID reference");
  298. }
  299. PageViewport pv = dd.getPageViewport();
  300. if (pv != null) {
  301. GoToXYAction action = getGoToActionForID(targetID, pv.getPageIndex());
  302. NamedDestination namedDestination = new NamedDestination(targetID, action);
  303. this.deferredDestinations.add(namedDestination);
  304. } else {
  305. //Warning already issued by AreaTreeHandler (debug level is sufficient)
  306. log.debug("Unresolved destination item received: " + dd.getIDRef());
  307. }
  308. }
  309. /**
  310. * Renders a Bookmark-Tree object
  311. * @param bookmarks the BookmarkData object containing all the Bookmark-Items
  312. */
  313. protected void renderBookmarkTree(BookmarkData bookmarks) {
  314. assert this.bookmarkTree == null;
  315. if (!hasDocumentNavigation()) {
  316. return;
  317. }
  318. this.bookmarkTree = new BookmarkTree();
  319. for (int i = 0; i < bookmarks.getCount(); i++) {
  320. BookmarkData ext = bookmarks.getSubData(i);
  321. Bookmark b = renderBookmarkItem(ext);
  322. bookmarkTree.addBookmark(b);
  323. }
  324. }
  325. private Bookmark renderBookmarkItem(BookmarkData bookmarkItem) {
  326. String targetID = bookmarkItem.getIDRef();
  327. if (targetID == null || targetID.length() == 0) {
  328. throw new IllegalArgumentException("DestinationData must contain a ID reference");
  329. }
  330. GoToXYAction action = null;
  331. PageViewport pv = bookmarkItem.getPageViewport();
  332. if (pv != null) {
  333. action = getGoToActionForID(targetID, pv.getPageIndex());
  334. } else {
  335. //Warning already issued by AreaTreeHandler (debug level is sufficient)
  336. log.debug("Bookmark with IDRef \"" + targetID + "\" has a null PageViewport.");
  337. }
  338. Bookmark b = new Bookmark(
  339. bookmarkItem.getBookmarkTitle(),
  340. bookmarkItem.showChildItems(),
  341. action);
  342. for (int i = 0; i < bookmarkItem.getCount(); i++) {
  343. b.addChildBookmark(renderBookmarkItem(bookmarkItem.getSubData(i)));
  344. }
  345. return b;
  346. }
  347. private void renderXMPMetadata(XMPMetadata metadata) {
  348. this.documentMetadata = metadata.getMetadata();
  349. }
  350. private GoToXYAction getGoToActionForID(String targetID, int pageIndex) {
  351. // Already a GoToXY present for this target? If not, create.
  352. GoToXYAction action = (GoToXYAction)actionSet.get(targetID);
  353. //GoToXYAction action = (GoToXYAction)idGoTos.get(targetID);
  354. if (action == null) {
  355. /* if (pageIndex < 0) {
  356. //pageIndex = page
  357. } */
  358. Point position = (Point)idPositions.get(targetID);
  359. // can the GoTo already be fully filled in?
  360. if (pageIndex >= 0 && position != null) {
  361. action = new GoToXYAction(targetID, pageIndex, position);
  362. } else {
  363. // Not complete yet, can't use getPDFGoTo:
  364. action = new GoToXYAction(targetID, pageIndex, null);
  365. unfinishedGoTos.add(action);
  366. }
  367. action = (GoToXYAction)actionSet.put(action);
  368. //idGoTos.put(targetID, action);
  369. }
  370. return action;
  371. }
  372. private void finishOpenGoTos() {
  373. int count = unfinishedGoTos.size();
  374. if (count > 0) {
  375. Point defaultPos = new Point(0, 0); // top-o-page
  376. while (!unfinishedGoTos.isEmpty()) {
  377. GoToXYAction action = (GoToXYAction)unfinishedGoTos.get(0);
  378. noteGoToPosition(action, defaultPos);
  379. }
  380. PDFEventProducer eventProducer = PDFEventProducer.Provider.get(
  381. getUserAgent().getEventBroadcaster());
  382. eventProducer.nonFullyResolvedLinkTargets(this, count);
  383. // dysfunctional if pageref is null
  384. }
  385. }
  386. private void noteGoToPosition(GoToXYAction action, Point position) {
  387. action.setTargetLocation(position);
  388. try {
  389. getDocumentNavigationHandler().addResolvedAction(action);
  390. } catch (IFException ife) {
  391. handleIFException(ife);
  392. }
  393. unfinishedGoTos.remove(action);
  394. }
  395. private void noteGoToPosition(GoToXYAction action, PageViewport pv, Point position) {
  396. action.setPageIndex(pv.getPageIndex());
  397. noteGoToPosition(action, position);
  398. }
  399. private void saveAbsolutePosition(String id, PageViewport pv,
  400. int relativeIPP, int relativeBPP, AffineTransform tf) {
  401. Point position = new Point(relativeIPP, relativeBPP);
  402. tf.transform(position, position);
  403. idPositions.put(id, position);
  404. // is there already a GoTo action waiting to be completed?
  405. GoToXYAction action = (GoToXYAction)actionSet.get(id);
  406. if (action != null) {
  407. noteGoToPosition(action, pv, position);
  408. }
  409. }
  410. private void saveAbsolutePosition(String id, int relativeIPP, int relativeBPP) {
  411. saveAbsolutePosition(id, this.currentPageViewport,
  412. relativeIPP, relativeBPP, graphicContext.getTransform());
  413. }
  414. private void saveBlockPosIfTargetable(Block block) {
  415. String id = getTargetableID(block);
  416. if (hasDocumentNavigation() && id != null) {
  417. // FIXME: Like elsewhere in the renderer code, absolute and relative
  418. // directions are happily mixed here. This makes sure that the
  419. // links point to the right location, but it is not correct.
  420. int ipp = block.getXOffset();
  421. int bpp = block.getYOffset() + block.getSpaceBefore();
  422. int positioning = block.getPositioning();
  423. if (!(positioning == Block.FIXED || positioning == Block.ABSOLUTE)) {
  424. ipp += currentIPPosition;
  425. bpp += currentBPPosition;
  426. }
  427. saveAbsolutePosition(id, currentPageViewport, ipp, bpp, graphicContext.getTransform());
  428. }
  429. }
  430. private void saveInlinePosIfTargetable(InlineArea inlineArea) {
  431. String id = getTargetableID(inlineArea);
  432. if (hasDocumentNavigation() && id != null) {
  433. int extraMarginBefore = 5000; // millipoints
  434. int ipp = currentIPPosition;
  435. int bpp = currentBPPosition
  436. + inlineArea.getBlockProgressionOffset() - extraMarginBefore;
  437. saveAbsolutePosition(id, ipp, bpp);
  438. }
  439. }
  440. private String getTargetableID(Area area) {
  441. String id = (String) area.getTrait(Trait.PROD_ID);
  442. if (id == null || id.length() == 0
  443. || !currentPageViewport.isFirstWithID(id)
  444. || idPositions.containsKey(id)) {
  445. return null;
  446. } else {
  447. return id;
  448. }
  449. }
  450. /** {@inheritDoc} */
  451. public void startPageSequence(PageSequence pageSequence) {
  452. try {
  453. if (this.inPageSequence) {
  454. documentHandler.endPageSequence();
  455. documentHandler.getContext().setLanguage(null);
  456. } else {
  457. if (this.documentMetadata == null) {
  458. this.documentMetadata = createDefaultDocumentMetadata();
  459. }
  460. documentHandler.handleExtensionObject(this.documentMetadata);
  461. documentHandler.endDocumentHeader();
  462. this.inPageSequence = true;
  463. }
  464. establishForeignAttributes(pageSequence.getForeignAttributes());
  465. documentHandler.getContext().setLanguage(pageSequence.getLocale());
  466. documentHandler.startPageSequence(null);
  467. resetForeignAttributes();
  468. processExtensionAttachments(pageSequence);
  469. } catch (IFException e) {
  470. handleIFException(e);
  471. }
  472. }
  473. private Metadata createDefaultDocumentMetadata() {
  474. Metadata xmp = new Metadata();
  475. DublinCoreAdapter dc = DublinCoreSchema.getAdapter(xmp);
  476. if (getUserAgent().getTitle() != null) {
  477. dc.setTitle(getUserAgent().getTitle());
  478. }
  479. if (getUserAgent().getAuthor() != null) {
  480. dc.addCreator(getUserAgent().getAuthor());
  481. }
  482. if (getUserAgent().getKeywords() != null) {
  483. dc.addSubject(getUserAgent().getKeywords());
  484. }
  485. XMPBasicAdapter xmpBasic = XMPBasicSchema.getAdapter(xmp);
  486. if (getUserAgent().getProducer() != null) {
  487. xmpBasic.setCreatorTool(getUserAgent().getProducer());
  488. } else {
  489. xmpBasic.setCreatorTool(Version.getVersion());
  490. }
  491. xmpBasic.setMetadataDate(new java.util.Date());
  492. if (getUserAgent().getCreationDate() != null) {
  493. xmpBasic.setCreateDate(getUserAgent().getCreationDate());
  494. } else {
  495. xmpBasic.setCreateDate(xmpBasic.getMetadataDate());
  496. }
  497. return xmp;
  498. }
  499. /** {@inheritDoc} */
  500. public void preparePage(PageViewport page) {
  501. super.preparePage(page);
  502. }
  503. /** {@inheritDoc} */
  504. public void renderPage(PageViewport page) throws IOException, FOPException {
  505. if (log.isTraceEnabled()) {
  506. log.trace("renderPage() " + page);
  507. }
  508. try {
  509. pageIndices.put(page.getKey(), page.getPageIndex());
  510. Rectangle viewArea = page.getViewArea();
  511. Dimension dim = new Dimension(viewArea.width, viewArea.height);
  512. establishForeignAttributes(page.getForeignAttributes());
  513. documentHandler.getContext().setPageIndex(page.getPageIndex());
  514. documentHandler.getContext().setPageNumber(page.getPageNumber());
  515. documentHandler.startPage(page.getPageIndex(), page.getPageNumberString(),
  516. page.getSimplePageMasterName(), dim);
  517. resetForeignAttributes();
  518. documentHandler.startPageHeader();
  519. //Add page attachments to page header
  520. processExtensionAttachments(page);
  521. documentHandler.endPageHeader();
  522. this.painter = documentHandler.startPageContent();
  523. super.renderPage(page);
  524. this.painter = null;
  525. documentHandler.endPageContent();
  526. documentHandler.startPageTrailer();
  527. if (hasDocumentNavigation()) {
  528. Iterator iter = this.deferredLinks.iterator();
  529. while (iter.hasNext()) {
  530. Link link = (Link)iter.next();
  531. iter.remove();
  532. getDocumentNavigationHandler().renderLink(link);
  533. }
  534. }
  535. documentHandler.endPageTrailer();
  536. establishForeignAttributes(page.getForeignAttributes());
  537. documentHandler.endPage();
  538. documentHandler.getContext().setPageIndex(-1);
  539. resetForeignAttributes();
  540. } catch (IFException e) {
  541. handleIFException(e);
  542. }
  543. }
  544. private void processExtensionAttachments(AreaTreeObject area) throws IFException {
  545. if (area.hasExtensionAttachments()) {
  546. for (Iterator iter = area.getExtensionAttachments().iterator();
  547. iter.hasNext();) {
  548. ExtensionAttachment attachment = (ExtensionAttachment) iter.next();
  549. this.documentHandler.handleExtensionObject(attachment);
  550. }
  551. }
  552. }
  553. private void establishForeignAttributes(Map foreignAttributes) {
  554. documentHandler.getContext().setForeignAttributes(foreignAttributes);
  555. }
  556. private void resetForeignAttributes() {
  557. documentHandler.getContext().resetForeignAttributes();
  558. }
  559. private void establishStructureTreeElement(StructureTreeElement structureTreeElement) {
  560. documentHandler.getContext().setStructureTreeElement(structureTreeElement);
  561. }
  562. private void resetStructurePointer() {
  563. documentHandler.getContext().resetStructureTreeElement();
  564. }
  565. /** {@inheritDoc} */
  566. protected void saveGraphicsState() {
  567. graphicContextStack.push(graphicContext);
  568. graphicContext = (IFGraphicContext)graphicContext.clone();
  569. }
  570. /** {@inheritDoc} */
  571. protected void restoreGraphicsState() {
  572. while (graphicContext.getGroupStackSize() > 0) {
  573. IFGraphicContext.Group[] groups = graphicContext.dropGroups();
  574. for (int i = groups.length - 1; i >= 0; i--) {
  575. try {
  576. groups[i].end(painter);
  577. } catch (IFException ife) {
  578. handleIFException(ife);
  579. }
  580. }
  581. }
  582. graphicContext = (IFGraphicContext)graphicContextStack.pop();
  583. }
  584. private void pushGroup(IFGraphicContext.Group group) {
  585. graphicContext.pushGroup(group);
  586. try {
  587. group.start(painter);
  588. } catch (IFException ife) {
  589. handleIFException(ife);
  590. }
  591. }
  592. /** {@inheritDoc} */
  593. protected List breakOutOfStateStack() {
  594. log.debug("Block.FIXED --> break out");
  595. List breakOutList = new java.util.ArrayList();
  596. while (!this.graphicContextStack.empty()) {
  597. //Handle groups
  598. IFGraphicContext.Group[] groups = graphicContext.getGroups();
  599. for (int j = groups.length - 1; j >= 0; j--) {
  600. try {
  601. groups[j].end(painter);
  602. } catch (IFException ife) {
  603. handleIFException(ife);
  604. }
  605. }
  606. breakOutList.add(0, this.graphicContext);
  607. graphicContext = (IFGraphicContext)graphicContextStack.pop();
  608. }
  609. return breakOutList;
  610. }
  611. /** {@inheritDoc} */
  612. protected void restoreStateStackAfterBreakOut(List breakOutList) {
  613. log.debug("Block.FIXED --> restoring context after break-out");
  614. for (int i = 0, c = breakOutList.size(); i < c; i++) {
  615. graphicContextStack.push(graphicContext);
  616. this.graphicContext = (IFGraphicContext)breakOutList.get(i);
  617. //Handle groups
  618. IFGraphicContext.Group[] groups = graphicContext.getGroups();
  619. for (int j = 0, jc = groups.length; j < jc; j++) {
  620. try {
  621. groups[j].start(painter);
  622. } catch (IFException ife) {
  623. handleIFException(ife);
  624. }
  625. }
  626. }
  627. log.debug("restored.");
  628. }
  629. /** {@inheritDoc} */
  630. protected void concatenateTransformationMatrix(AffineTransform at) {
  631. if (!at.isIdentity()) {
  632. concatenateTransformationMatrixMpt(ptToMpt(at), false);
  633. }
  634. }
  635. private void concatenateTransformationMatrixMpt(AffineTransform at, boolean force) {
  636. if (force || !at.isIdentity()) {
  637. if (log.isTraceEnabled()) {
  638. log.trace("-----concatenateTransformationMatrix: " + at);
  639. }
  640. IFGraphicContext.Group group = new IFGraphicContext.Group(at);
  641. pushGroup(group);
  642. }
  643. }
  644. /** {@inheritDoc} */
  645. protected void beginTextObject() {
  646. //nop - Ignore, handled by painter internally
  647. }
  648. /** {@inheritDoc} */
  649. protected void endTextObject() {
  650. //nop - Ignore, handled by painter internally
  651. }
  652. /** {@inheritDoc} */
  653. protected void renderRegionViewport(RegionViewport viewport) {
  654. Dimension dim = new Dimension(viewport.getIPD(), viewport.getBPD());
  655. viewportDimensionStack.push(dim);
  656. super.renderRegionViewport(viewport);
  657. viewportDimensionStack.pop();
  658. }
  659. /** {@inheritDoc} */
  660. protected void renderBlockViewport(BlockViewport bv, List children) {
  661. //Essentially the same code as in the super class but optimized for the IF
  662. // Handle new layer.
  663. boolean inNewLayer = false;
  664. if (maybeStartLayer(bv)) {
  665. inNewLayer = true;
  666. }
  667. //This is the content-rect
  668. Dimension dim = new Dimension(bv.getIPD(), bv.getBPD());
  669. viewportDimensionStack.push(dim);
  670. // save positions
  671. int saveIP = currentIPPosition;
  672. int saveBP = currentBPPosition;
  673. CTM ctm = bv.getCTM();
  674. int borderPaddingStart = bv.getBorderAndPaddingWidthStart();
  675. int borderPaddingBefore = bv.getBorderAndPaddingWidthBefore();
  676. if (bv.getPositioning() == Block.ABSOLUTE
  677. || bv.getPositioning() == Block.FIXED) {
  678. //For FIXED, we need to break out of the current viewports to the
  679. //one established by the page. We save the state stack for restoration
  680. //after the block-container has been painted. See below.
  681. List breakOutList = null;
  682. if (bv.getPositioning() == Block.FIXED) {
  683. breakOutList = breakOutOfStateStack();
  684. }
  685. AffineTransform positionTransform = new AffineTransform();
  686. positionTransform.translate(bv.getXOffset(), bv.getYOffset());
  687. //"left/"top" (bv.getX/YOffset()) specify the position of the content rectangle
  688. positionTransform.translate(-borderPaddingStart, -borderPaddingBefore);
  689. //Free transformation for the block-container viewport
  690. String transf;
  691. transf = bv.getForeignAttributeValue(FOX_TRANSFORM);
  692. if (transf != null) {
  693. AffineTransform freeTransform = AWTTransformProducer.createAffineTransform(transf);
  694. positionTransform.concatenate(freeTransform);
  695. }
  696. saveGraphicsState();
  697. //Viewport position
  698. concatenateTransformationMatrixMpt(positionTransform, false);
  699. //Background and borders
  700. float bpwidth = (borderPaddingStart + bv.getBorderAndPaddingWidthEnd());
  701. float bpheight = (borderPaddingBefore + bv.getBorderAndPaddingWidthAfter());
  702. drawBackAndBorders(bv, 0, 0,
  703. (dim.width + bpwidth) / 1000f, (dim.height + bpheight) / 1000f);
  704. //Shift to content rectangle after border painting
  705. AffineTransform contentRectTransform = new AffineTransform();
  706. contentRectTransform.translate(borderPaddingStart, borderPaddingBefore);
  707. concatenateTransformationMatrixMpt(contentRectTransform, false);
  708. //saveGraphicsState();
  709. //Set up coordinate system for content rectangle
  710. AffineTransform contentTransform = ctm.toAffineTransform();
  711. //concatenateTransformationMatrixMpt(contentTransform);
  712. startViewport(contentTransform, bv.getClipRectangle());
  713. currentIPPosition = 0;
  714. currentBPPosition = 0;
  715. renderBlocks(bv, children);
  716. endViewport();
  717. //restoreGraphicsState();
  718. restoreGraphicsState();
  719. if (breakOutList != null) {
  720. restoreStateStackAfterBreakOut(breakOutList);
  721. }
  722. currentIPPosition = saveIP;
  723. currentBPPosition = saveBP;
  724. } else {
  725. currentBPPosition += bv.getSpaceBefore();
  726. //borders and background in the old coordinate system
  727. handleBlockTraits(bv);
  728. //Advance to start of content area
  729. currentIPPosition += bv.getStartIndent();
  730. CTM tempctm = new CTM(containingIPPosition, currentBPPosition);
  731. ctm = tempctm.multiply(ctm);
  732. //Now adjust for border/padding
  733. currentBPPosition += borderPaddingBefore;
  734. startVParea(ctm, bv.getClipRectangle());
  735. currentIPPosition = 0;
  736. currentBPPosition = 0;
  737. renderBlocks(bv, children);
  738. endVParea();
  739. currentIPPosition = saveIP;
  740. currentBPPosition = saveBP;
  741. currentBPPosition += bv.getAllocBPD();
  742. }
  743. viewportDimensionStack.pop();
  744. maybeEndLayer(bv, inNewLayer);
  745. }
  746. /** {@inheritDoc} */
  747. public void renderInlineViewport(InlineViewport viewport) {
  748. StructureTreeElement structElem
  749. = (StructureTreeElement) viewport.getTrait(Trait.STRUCTURE_TREE_ELEMENT);
  750. establishStructureTreeElement(structElem);
  751. pushID(viewport);
  752. Dimension dim = new Dimension(viewport.getIPD(), viewport.getBPD());
  753. viewportDimensionStack.push(dim);
  754. super.renderInlineViewport(viewport);
  755. viewportDimensionStack.pop();
  756. resetStructurePointer();
  757. popID(viewport);
  758. }
  759. /** {@inheritDoc} */
  760. protected void startVParea(CTM ctm, Rectangle clippingRect) {
  761. if (log.isTraceEnabled()) {
  762. log.trace("startVParea() ctm=" + ctm + ", clippingRect=" + clippingRect);
  763. }
  764. AffineTransform at = new AffineTransform(ctm.toArray());
  765. startViewport(at, clippingRect);
  766. if (log.isTraceEnabled()) {
  767. log.trace("startVPArea: " + at + " --> " + graphicContext.getTransform());
  768. }
  769. }
  770. private void startViewport(AffineTransform at, Rectangle clipRect) {
  771. saveGraphicsState();
  772. try {
  773. IFGraphicContext.Viewport viewport = new IFGraphicContext.Viewport(
  774. at, (Dimension)viewportDimensionStack.peek(), clipRect);
  775. graphicContext.pushGroup(viewport);
  776. viewport.start(painter);
  777. } catch (IFException e) {
  778. handleIFException(e);
  779. }
  780. }
  781. /** {@inheritDoc} */
  782. protected void endVParea() {
  783. log.trace("endVParea()");
  784. endViewport();
  785. if (log.isTraceEnabled()) {
  786. log.trace("endVPArea() --> " + graphicContext.getTransform());
  787. }
  788. }
  789. private void endViewport() {
  790. restoreGraphicsState();
  791. }
  792. /** {@inheritDoc} */
  793. protected void startLayer(String layer) {
  794. if (log.isTraceEnabled()) {
  795. log.trace("startLayer() layer=" + layer);
  796. }
  797. saveGraphicsState();
  798. pushGroup(new IFGraphicContext.Group(layer));
  799. }
  800. /** {@inheritDoc} */
  801. protected void endLayer() {
  802. if (log.isTraceEnabled()) {
  803. log.trace("endLayer()");
  804. }
  805. restoreGraphicsState();
  806. }
  807. /** {@inheritDoc} */
  808. protected void renderInlineArea(InlineArea inlineArea) {
  809. saveInlinePosIfTargetable(inlineArea);
  810. pushID(inlineArea);
  811. super.renderInlineArea(inlineArea);
  812. popID(inlineArea);
  813. }
  814. /** {@inheritDoc} */
  815. public void renderInlineParent(InlineParent ip) {
  816. // stuff we only need if a link must be created:
  817. Rectangle ipRect = null;
  818. AbstractAction action = null;
  819. // make sure the rect is determined *before* calling super!
  820. int ipp = currentIPPosition;
  821. int bpp = currentBPPosition + ip.getBlockProgressionOffset();
  822. ipRect = new Rectangle(ipp, bpp, ip.getIPD(), ip.getBPD());
  823. AffineTransform transform = graphicContext.getTransform();
  824. ipRect = transform.createTransformedShape(ipRect).getBounds();
  825. // render contents
  826. super.renderInlineParent(ip);
  827. boolean linkTraitFound = false;
  828. // try INTERNAL_LINK first
  829. Trait.InternalLink intLink = (Trait.InternalLink) ip.getTrait(Trait.INTERNAL_LINK);
  830. if (intLink != null) {
  831. linkTraitFound = true;
  832. String pvKey = intLink.getPVKey();
  833. String idRef = intLink.getIDRef();
  834. boolean pvKeyOK = pvKey != null && pvKey.length() > 0;
  835. boolean idRefOK = idRef != null && idRef.length() > 0;
  836. if (pvKeyOK && idRefOK) {
  837. Integer pageIndex = (Integer)pageIndices.get(pvKey);
  838. action = getGoToActionForID(idRef, (pageIndex != null ? pageIndex.intValue() : -1));
  839. } else {
  840. //Warnings already issued by AreaTreeHandler
  841. }
  842. }
  843. // no INTERNAL_LINK, look for EXTERNAL_LINK
  844. if (!linkTraitFound) {
  845. Trait.ExternalLink extLink = (Trait.ExternalLink) ip.getTrait(Trait.EXTERNAL_LINK);
  846. if (extLink != null) {
  847. String extDest = extLink.getDestination();
  848. if (extDest != null && extDest.length() > 0) {
  849. linkTraitFound = true;
  850. action = new URIAction(extDest, extLink.newWindow());
  851. action = actionSet.put(action);
  852. }
  853. }
  854. }
  855. // warn if link trait found but not allowed, else create link
  856. if (linkTraitFound) {
  857. StructureTreeElement structElem
  858. = (StructureTreeElement) ip.getTrait(Trait.STRUCTURE_TREE_ELEMENT);
  859. action.setStructureTreeElement(structElem);
  860. Link link = new Link(action, ipRect);
  861. this.deferredLinks.add(link);
  862. }
  863. }
  864. /** {@inheritDoc} */
  865. protected void renderBlock(Block block) {
  866. if (log.isTraceEnabled()) {
  867. log.trace("renderBlock() " + block);
  868. }
  869. saveBlockPosIfTargetable(block);
  870. pushID(block);
  871. IFContext context = documentHandler.getContext();
  872. Locale oldLocale = context.getLanguage();
  873. context.setLanguage(block.getLocale());
  874. String oldLocation = context.getLocation();
  875. context.setLocation(block.getLocation());
  876. super.renderBlock(block);
  877. context.setLocation(oldLocation);
  878. context.setLanguage(oldLocale);
  879. popID(block);
  880. }
  881. private void pushID(Area area) {
  882. String prodID = (String) area.getTrait(Trait.PROD_ID);
  883. if (prodID != null) {
  884. ids.push(prodID);
  885. documentHandler.getContext().setID(prodID);
  886. }
  887. }
  888. private void popID(Area area) {
  889. String prodID = (String) area.getTrait(Trait.PROD_ID);
  890. if (prodID != null) {
  891. ids.pop();
  892. documentHandler.getContext().setID(ids.empty() ? "" : ids.peek());
  893. }
  894. }
  895. private Typeface getTypeface(String fontName) {
  896. Typeface tf = fontInfo.getFonts().get(fontName);
  897. if (tf instanceof LazyFont) {
  898. tf = ((LazyFont)tf).getRealFont();
  899. }
  900. return tf;
  901. }
  902. /** {@inheritDoc} */
  903. protected void renderText(TextArea text) {
  904. if (log.isTraceEnabled()) {
  905. log.trace("renderText() " + text);
  906. }
  907. renderInlineAreaBackAndBorders(text);
  908. Color ct = (Color) text.getTrait(Trait.COLOR);
  909. beginTextObject();
  910. String fontName = getInternalFontNameForArea(text);
  911. int size = ((Integer) text.getTrait(Trait.FONT_SIZE)).intValue();
  912. StructureTreeElement structElem
  913. = (StructureTreeElement) text.getTrait(Trait.STRUCTURE_TREE_ELEMENT);
  914. establishStructureTreeElement(structElem);
  915. // This assumes that *all* CIDFonts use a /ToUnicode mapping
  916. Typeface tf = getTypeface(fontName);
  917. FontTriplet triplet = (FontTriplet)text.getTrait(Trait.FONT);
  918. try {
  919. painter.setFont(triplet.getName(), triplet.getStyle(), triplet.getWeight(),
  920. "normal", size, ct);
  921. } catch (IFException e) {
  922. handleIFException(e);
  923. }
  924. int rx = currentIPPosition + text.getBorderAndPaddingWidthStart();
  925. int bl = currentBPPosition + text.getBlockProgressionOffset() + text.getBaselineOffset();
  926. textUtil.flush();
  927. textUtil.setStartPosition(rx, bl);
  928. textUtil.setSpacing(text.getTextLetterSpaceAdjust(), text.getTextWordSpaceAdjust());
  929. documentHandler.getContext().setHyphenated(text.isHyphenated());
  930. super.renderText(text);
  931. textUtil.flush();
  932. renderTextDecoration(tf, size, text, bl, rx);
  933. documentHandler.getContext().setHyphenated(false);
  934. resetStructurePointer();
  935. }
  936. /** {@inheritDoc} */
  937. protected void renderWord(WordArea word) {
  938. Font font = getFontFromArea(word.getParentArea());
  939. String s = word.getWord();
  940. int[][] dp = word.getGlyphPositionAdjustments();
  941. Area parentArea = word.getParentArea();
  942. assert (parentArea instanceof AbstractTextArea);
  943. if (dp == null) {
  944. renderTextWithAdjustments(s, word.getLetterAdjustArray(), word.isReversed(),
  945. font, (AbstractTextArea) parentArea);
  946. } else if (IFUtil.isDPOnlyDX(dp)) {
  947. renderTextWithAdjustments(s, IFUtil.convertDPToDX(dp), word.isReversed(),
  948. font, (AbstractTextArea) parentArea);
  949. } else {
  950. renderTextWithAdjustments(s, dp, word.isReversed(),
  951. font, (AbstractTextArea) parentArea);
  952. }
  953. super.renderWord(word);
  954. }
  955. /** {@inheritDoc} */
  956. protected void renderSpace(SpaceArea space) {
  957. Font font = getFontFromArea(space.getParentArea());
  958. String s = space.getSpace();
  959. Area parentArea = space.getParentArea();
  960. assert (parentArea instanceof AbstractTextArea);
  961. AbstractTextArea textArea = (AbstractTextArea) parentArea;
  962. renderTextWithAdjustments(s, (int[]) null, false, font, textArea);
  963. /* COMBINED is always false
  964. if (textUtil.COMBINED && space.isAdjustable()) {
  965. //Used for justified text, for example
  966. int tws = textArea.getTextWordSpaceAdjust()
  967. + 2 * textArea.getTextLetterSpaceAdjust();
  968. if (tws != 0) {
  969. textUtil.adjust(tws);
  970. }
  971. }
  972. */
  973. super.renderSpace(space);
  974. }
  975. /**
  976. * Does low-level rendering of text using DX only position adjustments.
  977. * @param s text to render
  978. * @param dx an array of widths for letter adjustment (may be null)
  979. * @param reversed if true then text has been reversed (from logical order)
  980. * @param font to font in use
  981. * @param parentArea the parent text area to retrieve certain traits from
  982. */
  983. private void renderTextWithAdjustments(String s,
  984. int[] dx, boolean reversed,
  985. Font font, AbstractTextArea parentArea) {
  986. int l = s.length();
  987. if (l == 0) {
  988. return;
  989. }
  990. for (int i = 0; i < l; i++) {
  991. char ch = s.charAt(i);
  992. textUtil.addChar(ch);
  993. int glyphAdjust = 0;
  994. /* COMBINED is always false
  995. if (textUtil.COMBINED && font.hasChar(ch)) {
  996. int tls = (i < l - 1 ? parentArea.getTextLetterSpaceAdjust() : 0);
  997. glyphAdjust += tls;
  998. }
  999. */
  1000. if (dx != null && i < l) {
  1001. glyphAdjust += dx[i];
  1002. }
  1003. textUtil.adjust(glyphAdjust);
  1004. }
  1005. }
  1006. /**
  1007. * Does low-level rendering of text using generalized position adjustments.
  1008. * @param s text to render
  1009. * @param dp an array of 4-tuples, expressing [X,Y] placment
  1010. * adjustments and [X,Y] advancement adjustments, in that order (may be null)
  1011. * @param reversed if true then text has been reversed (from logical order)
  1012. * @param font to font in use
  1013. * @param parentArea the parent text area to retrieve certain traits from
  1014. */
  1015. private void renderTextWithAdjustments(String s,
  1016. int[][] dp, boolean reversed,
  1017. Font font, AbstractTextArea parentArea) {
  1018. // assert !textUtil.COMBINED;
  1019. for (int i = 0, n = s.length(); i < n; i++) {
  1020. textUtil.addChar(s.charAt(i));
  1021. if (dp != null) {
  1022. textUtil.adjust(dp[i]);
  1023. }
  1024. }
  1025. }
  1026. private class TextUtil {
  1027. private static final int INITIAL_BUFFER_SIZE = 16;
  1028. private int[][] dp = new int[INITIAL_BUFFER_SIZE][];
  1029. private final StringBuffer text = new StringBuffer();
  1030. private int startx;
  1031. private int starty;
  1032. private int tls;
  1033. private int tws;
  1034. // private final static boolean COMBINED = false; // no longer referenced
  1035. void addChar(char ch) {
  1036. text.append(ch);
  1037. }
  1038. void adjust(int dx) {
  1039. if (dx != 0) {
  1040. adjust(new int[] {
  1041. dx, // xPlaAdjust
  1042. 0, // yPlaAdjust
  1043. dx, // xAdvAdjust
  1044. 0 // yAdvAdjust
  1045. });
  1046. }
  1047. }
  1048. void adjust(int[] pa) {
  1049. if (!IFUtil.isPAIdentity(pa)) {
  1050. int idx = text.length();
  1051. if (idx > dp.length - 1) {
  1052. int newSize = Math.max(dp.length, idx + 1) + INITIAL_BUFFER_SIZE;
  1053. int[][] newDP = new int[newSize][];
  1054. // reuse prior DP[0]...DP[dp.length-1]
  1055. System.arraycopy(dp, 0, newDP, 0, dp.length);
  1056. // switch to new DP, leaving DP[dp.length]...DP[newDP.length-1] unpopulated
  1057. dp = newDP;
  1058. }
  1059. if (dp[idx - 1] == null) {
  1060. dp[idx - 1] = new int[4];
  1061. }
  1062. IFUtil.adjustPA(dp[idx - 1], pa);
  1063. }
  1064. }
  1065. void reset() {
  1066. if (text.length() > 0) {
  1067. text.setLength(0);
  1068. for (int i = 0, n = dp.length; i < n; i++) {
  1069. dp[i] = null;
  1070. }
  1071. }
  1072. }
  1073. void setStartPosition(int x, int y) {
  1074. this.startx = x;
  1075. this.starty = y;
  1076. }
  1077. void setSpacing(int tls, int tws) {
  1078. this.tls = tls;
  1079. this.tws = tws;
  1080. }
  1081. void flush() {
  1082. if (text.length() > 0) {
  1083. try {
  1084. /* if (COMBINED) { // COMBINED is always false
  1085. painter.drawText(startx, starty, 0, 0,
  1086. trimAdjustments(dp, text.length()), text.toString());
  1087. } else { */
  1088. painter.drawText(startx, starty, tls, tws,
  1089. trimAdjustments(dp, text.length()), text.toString());
  1090. /* } */
  1091. } catch (IFException e) {
  1092. handleIFException(e);
  1093. }
  1094. reset();
  1095. }
  1096. }
  1097. /**
  1098. * Trim adjustments array <code>dp</code> to be no greater length than
  1099. * text length, and where trailing all-zero entries are removed.
  1100. * @param dp a position adjustments array (or null)
  1101. * @param textLength the length of the associated text
  1102. * @return either the original value of <code>dp</code> or a copy
  1103. * of its first N significant adjustment entries, such that N is
  1104. * no greater than text length, and the last entry has a non-zero
  1105. * adjustment.
  1106. */
  1107. private int[][] trimAdjustments(int[][] dp, int textLength) {
  1108. if (dp != null) {
  1109. int tl = textLength;
  1110. int pl = dp.length;
  1111. int i = (tl < pl) ? tl : pl;
  1112. while (i > 0) {
  1113. int[] pa = dp [ i - 1 ];
  1114. if ((pa != null) && !IFUtil.isPAIdentity(pa)) {
  1115. break;
  1116. } else {
  1117. i--;
  1118. }
  1119. }
  1120. if (i == 0) {
  1121. dp = null;
  1122. } else if (i < pl) {
  1123. dp = IFUtil.copyDP(dp, 0, i);
  1124. }
  1125. }
  1126. return dp;
  1127. }
  1128. }
  1129. /** {@inheritDoc} */
  1130. public void renderImage(Image image, Rectangle2D pos) {
  1131. drawImage(image.getURL(), pos, image.getForeignAttributes());
  1132. }
  1133. /** {@inheritDoc} */
  1134. protected void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) {
  1135. Rectangle posInt = new Rectangle(
  1136. currentIPPosition + (int)pos.getX(),
  1137. currentBPPosition + (int)pos.getY(),
  1138. (int)pos.getWidth(),
  1139. (int)pos.getHeight());
  1140. uri = URISpecification.getURL(uri);
  1141. try {
  1142. establishForeignAttributes(foreignAttributes);
  1143. painter.drawImage(uri, posInt);
  1144. resetForeignAttributes();
  1145. } catch (IFException ife) {
  1146. handleIFException(ife);
  1147. }
  1148. }
  1149. /** {@inheritDoc} */
  1150. public void renderForeignObject(ForeignObject fo, Rectangle2D pos) {
  1151. endTextObject();
  1152. Rectangle posInt = new Rectangle(
  1153. currentIPPosition + (int)pos.getX(),
  1154. currentBPPosition + (int)pos.getY(),
  1155. (int)pos.getWidth(),
  1156. (int)pos.getHeight());
  1157. Document doc = fo.getDocument();
  1158. try {
  1159. establishForeignAttributes(fo.getForeignAttributes());
  1160. painter.drawImage(doc, posInt);
  1161. resetForeignAttributes();
  1162. } catch (IFException ife) {
  1163. handleIFException(ife);
  1164. }
  1165. }
  1166. /** {@inheritDoc} */
  1167. public void renderLeader(Leader area) {
  1168. renderInlineAreaBackAndBorders(area);
  1169. int style = area.getRuleStyle();
  1170. int ruleThickness = area.getRuleThickness();
  1171. int startx = currentIPPosition + area.getBorderAndPaddingWidthStart();
  1172. int starty = currentBPPosition + area.getBlockProgressionOffset() + (ruleThickness / 2);
  1173. int endx = currentIPPosition
  1174. + area.getBorderAndPaddingWidthStart()
  1175. + area.getIPD();
  1176. Color col = (Color)area.getTrait(Trait.COLOR);
  1177. Point start = new Point(startx, starty);
  1178. Point end = new Point(endx, starty);
  1179. try {
  1180. painter.drawLine(start, end, ruleThickness, col, RuleStyle.valueOf(style));
  1181. } catch (IFException ife) {
  1182. handleIFException(ife);
  1183. }
  1184. super.renderLeader(area);
  1185. }
  1186. /** {@inheritDoc} */
  1187. protected void clip() {
  1188. throw new IllegalStateException("Not used");
  1189. }
  1190. /** {@inheritDoc} */
  1191. protected void clipRect(float x, float y, float width, float height) {
  1192. pushGroup(new IFGraphicContext.Group());
  1193. try {
  1194. painter.clipRect(toMillipointRectangle(x, y, width, height));
  1195. } catch (IFException ife) {
  1196. handleIFException(ife);
  1197. }
  1198. }
  1199. /** {@inheritDoc} */
  1200. protected void clipBackground(float startx, float starty,
  1201. float width, float height,
  1202. BorderProps bpsBefore, BorderProps bpsAfter,
  1203. BorderProps bpsStart, BorderProps bpsEnd) {
  1204. pushGroup(new IFGraphicContext.Group());
  1205. Rectangle rect = toMillipointRectangle(startx, starty, width, height);
  1206. try {
  1207. painter.clipBackground(rect,
  1208. bpsBefore, bpsAfter, bpsStart, bpsEnd);
  1209. } catch (IFException ife) {
  1210. handleIFException(ife);
  1211. }
  1212. }
  1213. /** {@inheritDoc} */
  1214. protected void closePath() {
  1215. throw new IllegalStateException("Not used");
  1216. }
  1217. /** {@inheritDoc} */
  1218. protected void drawBackground(float startx, float starty,
  1219. float width, float height,
  1220. Trait.Background back,
  1221. BorderProps bpsBefore, BorderProps bpsAfter,
  1222. BorderProps bpsStart, BorderProps bpsEnd) {
  1223. if (painter.isBackgroundRequired(bpsBefore, bpsAfter, bpsStart, bpsEnd)) {
  1224. super.drawBackground(startx, starty, width, height,
  1225. back, bpsBefore, bpsAfter,
  1226. bpsStart, bpsEnd);
  1227. }
  1228. }
  1229. /** {@inheritDoc} */
  1230. protected void drawBorders(float startx, float starty,
  1231. float width, float height,
  1232. BorderProps bpsBefore, BorderProps bpsAfter,
  1233. BorderProps bpsStart, BorderProps bpsEnd, int level, Color innerBackgroundColor) {
  1234. Rectangle rect = toMillipointRectangle(startx, starty, width, height);
  1235. try {
  1236. BorderProps bpsTop = bpsBefore;
  1237. BorderProps bpsBottom = bpsAfter;
  1238. BorderProps bpsLeft;
  1239. BorderProps bpsRight;
  1240. if ((level == -1) || ((level & 1) == 0)) {
  1241. bpsLeft = bpsStart;
  1242. bpsRight = bpsEnd;
  1243. } else {
  1244. bpsLeft = bpsEnd;
  1245. bpsRight = bpsStart;
  1246. }
  1247. painter.drawBorderRect(rect, bpsTop, bpsBottom, bpsLeft, bpsRight, innerBackgroundColor);
  1248. } catch (IFException ife) {
  1249. handleIFException(ife);
  1250. }
  1251. }
  1252. /** {@inheritDoc} */
  1253. protected void drawBorderLine(float x1, float y1, float x2, float y2, boolean horz,
  1254. boolean startOrBefore, int style, Color col) {
  1255. //Simplified implementation that is only used by renderTextDecoration()
  1256. //drawBorders() is overridden and uses the Painter's high-level method drawBorderRect()
  1257. updateColor(col, true);
  1258. fillRect(x1, y1, x2 - x1, y2 - y1);
  1259. }
  1260. private int toMillipoints(float coordinate) {
  1261. return Math.round(coordinate * 1000);
  1262. }
  1263. private Rectangle toMillipointRectangle(float x, float y, float width, float height) {
  1264. return new Rectangle(
  1265. toMillipoints(x),
  1266. toMillipoints(y),
  1267. toMillipoints(width),
  1268. toMillipoints(height));
  1269. }
  1270. /** {@inheritDoc} */
  1271. protected void fillRect(float x, float y, float width, float height) {
  1272. try {
  1273. painter.fillRect(
  1274. toMillipointRectangle(x, y, width, height),
  1275. this.graphicContext.getPaint());
  1276. } catch (IFException e) {
  1277. handleIFException(e);
  1278. }
  1279. }
  1280. /** {@inheritDoc} */
  1281. protected void moveTo(float x, float y) {
  1282. throw new IllegalStateException("Not used");
  1283. }
  1284. /** {@inheritDoc} */
  1285. protected void lineTo(float x, float y) {
  1286. throw new IllegalStateException("Not used");
  1287. }
  1288. /** {@inheritDoc} */
  1289. protected void updateColor(Color col, boolean fill) {
  1290. if (fill) {
  1291. this.graphicContext.setPaint(col);
  1292. } else {
  1293. this.graphicContext.setColor(col);
  1294. }
  1295. }
  1296. }