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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  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.Arrays;
  28. import java.util.Iterator;
  29. import java.util.List;
  30. import java.util.Locale;
  31. import java.util.Map;
  32. import java.util.Stack;
  33. import javax.xml.transform.stream.StreamResult;
  34. import org.w3c.dom.Document;
  35. import org.xml.sax.SAXException;
  36. import org.apache.batik.parser.AWTTransformProducer;
  37. import org.apache.commons.logging.Log;
  38. import org.apache.commons.logging.LogFactory;
  39. import org.apache.xmlgraphics.xmp.Metadata;
  40. import org.apache.xmlgraphics.xmp.schemas.DublinCoreAdapter;
  41. import org.apache.xmlgraphics.xmp.schemas.DublinCoreSchema;
  42. import org.apache.xmlgraphics.xmp.schemas.XMPBasicAdapter;
  43. import org.apache.xmlgraphics.xmp.schemas.XMPBasicSchema;
  44. import org.apache.fop.Version;
  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 = false;
  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. public IFRenderer() {
  139. }
  140. /** {@inheritDoc} */
  141. public String getMimeType() {
  142. return IF_MIME_TYPE;
  143. }
  144. /**
  145. * Sets the {@link IFDocumentHandler} to be used by the {@link IFRenderer}.
  146. * @param documentHandler the {@link IFDocumentHandler}
  147. */
  148. public void setDocumentHandler(IFDocumentHandler documentHandler) {
  149. this.documentHandler = documentHandler;
  150. }
  151. /** {@inheritDoc} */
  152. public void setupFontInfo(FontInfo inFontInfo) throws FOPException {
  153. if (this.documentHandler == null) {
  154. this.documentHandler = createDefaultDocumentHandler();
  155. }
  156. IFUtil.setupFonts(this.documentHandler, inFontInfo);
  157. this.fontInfo = inFontInfo;
  158. }
  159. private void handleIFException(IFException ife) {
  160. if (ife.getCause() instanceof SAXException) {
  161. throw new RuntimeException(ife.getCause());
  162. } else {
  163. throw new RuntimeException(ife);
  164. }
  165. }
  166. private void handleIFExceptionWithIOException(IFException ife) throws IOException {
  167. if (ife.getCause() instanceof IOException) {
  168. throw (IOException)ife.getCause();
  169. } else {
  170. handleIFException(ife);
  171. }
  172. }
  173. /** {@inheritDoc} */
  174. public boolean supportsOutOfOrder() {
  175. return (this.documentHandler != null
  176. ? this.documentHandler.supportsPagesOutOfOrder() : false);
  177. }
  178. /**
  179. * Returns the document navigation handler if available/supported.
  180. * @return the document navigation handler or null if not supported
  181. */
  182. protected IFDocumentNavigationHandler getDocumentNavigationHandler() {
  183. return this.documentHandler.getDocumentNavigationHandler();
  184. }
  185. /**
  186. * Indicates whether document navigation features are supported by the document handler.
  187. * @return true if document navigation features are available
  188. */
  189. protected boolean hasDocumentNavigation() {
  190. return getDocumentNavigationHandler() != null;
  191. }
  192. /**
  193. * Creates a default {@link IFDocumentHandler} when none has been set.
  194. * @return the default IFDocumentHandler
  195. */
  196. protected IFDocumentHandler createDefaultDocumentHandler() {
  197. IFSerializer serializer = new IFSerializer();
  198. FOUserAgent userAgent = getUserAgent();
  199. serializer.setContext(new IFContext(userAgent));
  200. if (userAgent.isAccessibilityEnabled()) {
  201. userAgent.setStructureTreeEventHandler(serializer.getStructureTreeEventHandler());
  202. }
  203. return serializer;
  204. }
  205. /** {@inheritDoc} */
  206. public void startRenderer(OutputStream outputStream)
  207. throws IOException {
  208. try {
  209. if (outputStream != null) {
  210. StreamResult result = new StreamResult(outputStream);
  211. if (getUserAgent().getOutputFile() != null) {
  212. result.setSystemId(
  213. getUserAgent().getOutputFile().toURI().toURL().toExternalForm());
  214. }
  215. if (this.documentHandler == null) {
  216. this.documentHandler = createDefaultDocumentHandler();
  217. }
  218. this.documentHandler.setResult(result);
  219. }
  220. super.startRenderer(null);
  221. if (log.isDebugEnabled()) {
  222. log.debug("Rendering areas via IF document handler ("
  223. + this.documentHandler.getClass().getName() + ")...");
  224. }
  225. documentHandler.startDocument();
  226. documentHandler.startDocumentHeader();
  227. } catch (IFException e) {
  228. handleIFExceptionWithIOException(e);
  229. }
  230. }
  231. /** {@inheritDoc} */
  232. public void stopRenderer() throws IOException {
  233. try {
  234. if (this.inPageSequence) {
  235. documentHandler.endPageSequence();
  236. this.inPageSequence = false;
  237. }
  238. documentHandler.startDocumentTrailer();
  239. //Wrap up document navigation
  240. if (hasDocumentNavigation()) {
  241. finishOpenGoTos();
  242. Iterator iter = this.deferredDestinations.iterator();
  243. while (iter.hasNext()) {
  244. NamedDestination dest = (NamedDestination)iter.next();
  245. iter.remove();
  246. getDocumentNavigationHandler().renderNamedDestination(dest);
  247. }
  248. if (this.bookmarkTree != null) {
  249. getDocumentNavigationHandler().renderBookmarkTree(this.bookmarkTree);
  250. }
  251. }
  252. documentHandler.endDocumentTrailer();
  253. documentHandler.endDocument();
  254. } catch (IFException e) {
  255. handleIFExceptionWithIOException(e);
  256. }
  257. pageIndices.clear();
  258. idPositions.clear();
  259. actionSet.clear();
  260. super.stopRenderer();
  261. log.debug("Rendering finished.");
  262. }
  263. @Override
  264. public void setDocumentLocale(Locale locale) {
  265. documentHandler.setDocumentLocale(locale);
  266. }
  267. /** {@inheritDoc} */
  268. public void processOffDocumentItem(OffDocumentItem odi) {
  269. if (odi instanceof DestinationData) {
  270. // render Destinations
  271. renderDestination((DestinationData) odi);
  272. } else if (odi instanceof BookmarkData) {
  273. // render Bookmark-Tree
  274. renderBookmarkTree((BookmarkData) odi);
  275. } else if (odi instanceof OffDocumentExtensionAttachment) {
  276. ExtensionAttachment attachment = ((OffDocumentExtensionAttachment)odi).getAttachment();
  277. if (XMPMetadata.CATEGORY.equals(attachment.getCategory())) {
  278. renderXMPMetadata((XMPMetadata)attachment);
  279. } else {
  280. try {
  281. this.documentHandler.handleExtensionObject(attachment);
  282. } catch (IFException ife) {
  283. handleIFException(ife);
  284. }
  285. }
  286. }
  287. }
  288. private void renderDestination(DestinationData dd) {
  289. if (!hasDocumentNavigation()) {
  290. return;
  291. }
  292. String targetID = dd.getIDRef();
  293. if (targetID == null || targetID.length() == 0) {
  294. throw new IllegalArgumentException("DestinationData must contain a ID reference");
  295. }
  296. PageViewport pv = dd.getPageViewport();
  297. if (pv != null) {
  298. GoToXYAction action = getGoToActionForID(targetID, pv.getPageIndex());
  299. NamedDestination namedDestination = new NamedDestination(targetID, action);
  300. this.deferredDestinations.add(namedDestination);
  301. } else {
  302. //Warning already issued by AreaTreeHandler (debug level is sufficient)
  303. log.debug("Unresolved destination item received: " + dd.getIDRef());
  304. }
  305. }
  306. /**
  307. * Renders a Bookmark-Tree object
  308. * @param bookmarks the BookmarkData object containing all the Bookmark-Items
  309. */
  310. protected void renderBookmarkTree(BookmarkData bookmarks) {
  311. assert this.bookmarkTree == null;
  312. if (!hasDocumentNavigation()) {
  313. return;
  314. }
  315. this.bookmarkTree = new BookmarkTree();
  316. for (int i = 0; i < bookmarks.getCount(); i++) {
  317. BookmarkData ext = bookmarks.getSubData(i);
  318. Bookmark b = renderBookmarkItem(ext);
  319. bookmarkTree.addBookmark(b);
  320. }
  321. }
  322. private Bookmark renderBookmarkItem(BookmarkData bookmarkItem) {
  323. String targetID = bookmarkItem.getIDRef();
  324. if (targetID == null || targetID.length() == 0) {
  325. throw new IllegalArgumentException("DestinationData must contain a ID reference");
  326. }
  327. GoToXYAction action = null;
  328. PageViewport pv = bookmarkItem.getPageViewport();
  329. if (pv != null) {
  330. action = getGoToActionForID(targetID, pv.getPageIndex());
  331. } else {
  332. //Warning already issued by AreaTreeHandler (debug level is sufficient)
  333. log.debug("Bookmark with IDRef \"" + targetID + "\" has a null PageViewport.");
  334. }
  335. Bookmark b = new Bookmark(
  336. bookmarkItem.getBookmarkTitle(),
  337. bookmarkItem.showChildItems(),
  338. action);
  339. for (int i = 0; i < bookmarkItem.getCount(); i++) {
  340. b.addChildBookmark(renderBookmarkItem(bookmarkItem.getSubData(i)));
  341. }
  342. return b;
  343. }
  344. private void renderXMPMetadata(XMPMetadata metadata) {
  345. this.documentMetadata = metadata.getMetadata();
  346. }
  347. private GoToXYAction getGoToActionForID(String targetID, int pageIndex) {
  348. // Already a GoToXY present for this target? If not, create.
  349. GoToXYAction action = (GoToXYAction)actionSet.get(targetID);
  350. //GoToXYAction action = (GoToXYAction)idGoTos.get(targetID);
  351. if (action == null) {
  352. if (pageIndex < 0) {
  353. //pageIndex = page
  354. }
  355. Point position = (Point)idPositions.get(targetID);
  356. // can the GoTo already be fully filled in?
  357. if (pageIndex >= 0 && position != null) {
  358. action = new GoToXYAction(targetID, pageIndex, position);
  359. } else {
  360. // Not complete yet, can't use getPDFGoTo:
  361. action = new GoToXYAction(targetID, pageIndex, null);
  362. unfinishedGoTos.add(action);
  363. }
  364. action = (GoToXYAction)actionSet.put(action);
  365. //idGoTos.put(targetID, action);
  366. }
  367. return action;
  368. }
  369. private void finishOpenGoTos() {
  370. int count = unfinishedGoTos.size();
  371. if (count > 0) {
  372. Point defaultPos = new Point(0, 0); // top-o-page
  373. while (!unfinishedGoTos.isEmpty()) {
  374. GoToXYAction action = (GoToXYAction)unfinishedGoTos.get(0);
  375. noteGoToPosition(action, defaultPos);
  376. }
  377. PDFEventProducer eventProducer = PDFEventProducer.Provider.get(
  378. getUserAgent().getEventBroadcaster());
  379. eventProducer.nonFullyResolvedLinkTargets(this, count);
  380. // dysfunctional if pageref is null
  381. }
  382. }
  383. private void noteGoToPosition(GoToXYAction action, Point position) {
  384. action.setTargetLocation(position);
  385. try {
  386. getDocumentNavigationHandler().addResolvedAction(action);
  387. } catch (IFException ife) {
  388. handleIFException(ife);
  389. }
  390. unfinishedGoTos.remove(action);
  391. }
  392. private void noteGoToPosition(GoToXYAction action, PageViewport pv, Point position) {
  393. action.setPageIndex(pv.getPageIndex());
  394. noteGoToPosition(action, position);
  395. }
  396. private void saveAbsolutePosition(String id, PageViewport pv,
  397. int relativeIPP, int relativeBPP, AffineTransform tf) {
  398. Point position = new Point(relativeIPP, relativeBPP);
  399. tf.transform(position, position);
  400. idPositions.put(id, position);
  401. // is there already a GoTo action waiting to be completed?
  402. GoToXYAction action = (GoToXYAction)actionSet.get(id);
  403. if (action != null) {
  404. noteGoToPosition(action, pv, position);
  405. }
  406. }
  407. private void saveAbsolutePosition(String id, int relativeIPP, int relativeBPP) {
  408. saveAbsolutePosition(id, this.currentPageViewport,
  409. relativeIPP, relativeBPP, graphicContext.getTransform());
  410. }
  411. private void saveBlockPosIfTargetable(Block block) {
  412. String id = getTargetableID(block);
  413. if (hasDocumentNavigation() && id != null) {
  414. // FIXME: Like elsewhere in the renderer code, absolute and relative
  415. // directions are happily mixed here. This makes sure that the
  416. // links point to the right location, but it is not correct.
  417. int ipp = block.getXOffset();
  418. int bpp = block.getYOffset() + block.getSpaceBefore();
  419. int positioning = block.getPositioning();
  420. if (!(positioning == Block.FIXED || positioning == Block.ABSOLUTE)) {
  421. ipp += currentIPPosition;
  422. bpp += currentBPPosition;
  423. }
  424. saveAbsolutePosition(id, currentPageViewport, ipp, bpp, graphicContext.getTransform());
  425. }
  426. }
  427. private void saveInlinePosIfTargetable(InlineArea inlineArea) {
  428. String id = getTargetableID(inlineArea);
  429. if (hasDocumentNavigation() && id != null) {
  430. int extraMarginBefore = 5000; // millipoints
  431. int ipp = currentIPPosition;
  432. int bpp = currentBPPosition + inlineArea.getOffset() - extraMarginBefore;
  433. saveAbsolutePosition(id, ipp, bpp);
  434. }
  435. }
  436. private String getTargetableID(Area area) {
  437. String id = (String) area.getTrait(Trait.PROD_ID);
  438. if (id == null || id.length() == 0
  439. || !currentPageViewport.isFirstWithID(id)
  440. || idPositions.containsKey(id)) {
  441. return null;
  442. } else {
  443. return id;
  444. }
  445. }
  446. /** {@inheritDoc} */
  447. public void startPageSequence(PageSequence pageSequence) {
  448. try {
  449. if (this.inPageSequence) {
  450. documentHandler.endPageSequence();
  451. documentHandler.getContext().setLanguage(null);
  452. } else {
  453. if (this.documentMetadata == null) {
  454. this.documentMetadata = createDefaultDocumentMetadata();
  455. }
  456. documentHandler.handleExtensionObject(this.documentMetadata);
  457. documentHandler.endDocumentHeader();
  458. this.inPageSequence = true;
  459. }
  460. establishForeignAttributes(pageSequence.getForeignAttributes());
  461. documentHandler.getContext().setLanguage(toLocale(pageSequence));
  462. documentHandler.startPageSequence(null);
  463. resetForeignAttributes();
  464. processExtensionAttachments(pageSequence);
  465. } catch (IFException e) {
  466. handleIFException(e);
  467. }
  468. }
  469. private Locale toLocale(PageSequence pageSequence) {
  470. if (pageSequence.getLanguage() != null) {
  471. if (pageSequence.getCountry() != null) {
  472. return new Locale(pageSequence.getLanguage(), pageSequence.getCountry());
  473. } else {
  474. return new Locale(pageSequence.getLanguage());
  475. }
  476. }
  477. return null;
  478. }
  479. private Metadata createDefaultDocumentMetadata() {
  480. Metadata xmp = new Metadata();
  481. DublinCoreAdapter dc = DublinCoreSchema.getAdapter(xmp);
  482. if (getUserAgent().getTitle() != null) {
  483. dc.setTitle(getUserAgent().getTitle());
  484. }
  485. if (getUserAgent().getAuthor() != null) {
  486. dc.addCreator(getUserAgent().getAuthor());
  487. }
  488. if (getUserAgent().getKeywords() != null) {
  489. dc.addSubject(getUserAgent().getKeywords());
  490. }
  491. XMPBasicAdapter xmpBasic = XMPBasicSchema.getAdapter(xmp);
  492. if (getUserAgent().getProducer() != null) {
  493. xmpBasic.setCreatorTool(getUserAgent().getProducer());
  494. } else {
  495. xmpBasic.setCreatorTool(Version.getVersion());
  496. }
  497. xmpBasic.setMetadataDate(new java.util.Date());
  498. if (getUserAgent().getCreationDate() != null) {
  499. xmpBasic.setCreateDate(getUserAgent().getCreationDate());
  500. } else {
  501. xmpBasic.setCreateDate(xmpBasic.getMetadataDate());
  502. }
  503. return xmp;
  504. }
  505. /** {@inheritDoc} */
  506. public void preparePage(PageViewport page) {
  507. super.preparePage(page);
  508. }
  509. /** {@inheritDoc} */
  510. public void renderPage(PageViewport page) throws IOException, FOPException {
  511. if (log.isTraceEnabled()) {
  512. log.trace("renderPage() " + page);
  513. }
  514. try {
  515. pageIndices.put(page.getKey(), new Integer(page.getPageIndex()));
  516. Rectangle viewArea = page.getViewArea();
  517. Dimension dim = new Dimension(viewArea.width, viewArea.height);
  518. establishForeignAttributes(page.getForeignAttributes());
  519. documentHandler.startPage(page.getPageIndex(), page.getPageNumberString(),
  520. page.getSimplePageMasterName(), dim);
  521. resetForeignAttributes();
  522. documentHandler.startPageHeader();
  523. //Add page attachments to page header
  524. processExtensionAttachments(page);
  525. documentHandler.endPageHeader();
  526. this.painter = documentHandler.startPageContent();
  527. super.renderPage(page);
  528. this.painter = null;
  529. documentHandler.endPageContent();
  530. documentHandler.startPageTrailer();
  531. if (hasDocumentNavigation()) {
  532. Iterator iter = this.deferredLinks.iterator();
  533. while (iter.hasNext()) {
  534. Link link = (Link)iter.next();
  535. iter.remove();
  536. getDocumentNavigationHandler().renderLink(link);
  537. }
  538. }
  539. documentHandler.endPageTrailer();
  540. establishForeignAttributes(page.getForeignAttributes());
  541. documentHandler.endPage();
  542. resetForeignAttributes();
  543. } catch (IFException e) {
  544. handleIFException(e);
  545. }
  546. }
  547. private void processExtensionAttachments(AreaTreeObject area) throws IFException {
  548. if (area.hasExtensionAttachments()) {
  549. for (Iterator iter = area.getExtensionAttachments().iterator();
  550. iter.hasNext();) {
  551. ExtensionAttachment attachment = (ExtensionAttachment) iter.next();
  552. this.documentHandler.handleExtensionObject(attachment);
  553. }
  554. }
  555. }
  556. private void establishForeignAttributes(Map foreignAttributes) {
  557. documentHandler.getContext().setForeignAttributes(foreignAttributes);
  558. }
  559. private void resetForeignAttributes() {
  560. documentHandler.getContext().resetForeignAttributes();
  561. }
  562. private void establishStructurePointer(String ptr) {
  563. documentHandler.getContext().setStructurePointer(ptr);
  564. }
  565. private void resetStructurePointer() {
  566. documentHandler.getContext().resetStructurePointer();
  567. }
  568. /** {@inheritDoc} */
  569. protected void saveGraphicsState() {
  570. graphicContextStack.push(graphicContext);
  571. graphicContext = (IFGraphicContext)graphicContext.clone();
  572. }
  573. /** {@inheritDoc} */
  574. protected void restoreGraphicsState() {
  575. while (graphicContext.getGroupStackSize() > 0) {
  576. IFGraphicContext.Group[] groups = graphicContext.dropGroups();
  577. for (int i = groups.length - 1; i >= 0; i--) {
  578. try {
  579. groups[i].end(painter);
  580. } catch (IFException ife) {
  581. handleIFException(ife);
  582. }
  583. }
  584. }
  585. graphicContext = (IFGraphicContext)graphicContextStack.pop();
  586. }
  587. private void pushGroup(IFGraphicContext.Group group) {
  588. graphicContext.pushGroup(group);
  589. try {
  590. group.start(painter);
  591. } catch (IFException ife) {
  592. handleIFException(ife);
  593. }
  594. }
  595. /** {@inheritDoc} */
  596. protected List breakOutOfStateStack() {
  597. log.debug("Block.FIXED --> break out");
  598. List breakOutList = new java.util.ArrayList();
  599. while (!this.graphicContextStack.empty()) {
  600. //Handle groups
  601. IFGraphicContext.Group[] groups = graphicContext.getGroups();
  602. for (int j = groups.length - 1; j >= 0; j--) {
  603. try {
  604. groups[j].end(painter);
  605. } catch (IFException ife) {
  606. handleIFException(ife);
  607. }
  608. }
  609. breakOutList.add(0, this.graphicContext);
  610. graphicContext = (IFGraphicContext)graphicContextStack.pop();
  611. }
  612. return breakOutList;
  613. }
  614. /** {@inheritDoc} */
  615. protected void restoreStateStackAfterBreakOut(List breakOutList) {
  616. log.debug("Block.FIXED --> restoring context after break-out");
  617. for (int i = 0, c = breakOutList.size(); i < c; i++) {
  618. graphicContextStack.push(graphicContext);
  619. this.graphicContext = (IFGraphicContext)breakOutList.get(i);
  620. //Handle groups
  621. IFGraphicContext.Group[] groups = graphicContext.getGroups();
  622. for (int j = 0, jc = groups.length; j < jc; j++) {
  623. try {
  624. groups[j].start(painter);
  625. } catch (IFException ife) {
  626. handleIFException(ife);
  627. }
  628. }
  629. }
  630. log.debug("restored.");
  631. }
  632. /** {@inheritDoc} */
  633. protected void concatenateTransformationMatrix(AffineTransform at) {
  634. if (!at.isIdentity()) {
  635. concatenateTransformationMatrixMpt(ptToMpt(at), false);
  636. }
  637. }
  638. private void concatenateTransformationMatrixMpt(AffineTransform at, boolean force) {
  639. if (force || !at.isIdentity()) {
  640. if (log.isTraceEnabled()) {
  641. log.trace("-----concatenateTransformationMatrix: " + at);
  642. }
  643. IFGraphicContext.Group group = new IFGraphicContext.Group(at);
  644. pushGroup(group);
  645. }
  646. }
  647. /** {@inheritDoc} */
  648. protected void beginTextObject() {
  649. //nop - Ignore, handled by painter internally
  650. }
  651. /** {@inheritDoc} */
  652. protected void endTextObject() {
  653. //nop - Ignore, handled by painter internally
  654. }
  655. /** {@inheritDoc} */
  656. protected void renderRegionViewport(RegionViewport viewport) {
  657. Dimension dim = new Dimension(viewport.getIPD(), viewport.getBPD());
  658. viewportDimensionStack.push(dim);
  659. super.renderRegionViewport(viewport);
  660. viewportDimensionStack.pop();
  661. }
  662. /** {@inheritDoc} */
  663. protected void renderBlockViewport(BlockViewport bv, List children) {
  664. //Essentially the same code as in the super class but optimized for the IF
  665. //This is the content-rect
  666. Dimension dim = new Dimension(bv.getIPD(), bv.getBPD());
  667. viewportDimensionStack.push(dim);
  668. // save positions
  669. int saveIP = currentIPPosition;
  670. int saveBP = currentBPPosition;
  671. CTM ctm = bv.getCTM();
  672. int borderPaddingStart = bv.getBorderAndPaddingWidthStart();
  673. int borderPaddingBefore = bv.getBorderAndPaddingWidthBefore();
  674. if (bv.getPositioning() == Block.ABSOLUTE
  675. || bv.getPositioning() == Block.FIXED) {
  676. //For FIXED, we need to break out of the current viewports to the
  677. //one established by the page. We save the state stack for restoration
  678. //after the block-container has been painted. See below.
  679. List breakOutList = null;
  680. if (bv.getPositioning() == Block.FIXED) {
  681. breakOutList = breakOutOfStateStack();
  682. }
  683. AffineTransform positionTransform = new AffineTransform();
  684. positionTransform.translate(bv.getXOffset(), bv.getYOffset());
  685. //"left/"top" (bv.getX/YOffset()) specify the position of the content rectangle
  686. positionTransform.translate(-borderPaddingStart, -borderPaddingBefore);
  687. //Free transformation for the block-container viewport
  688. String transf;
  689. transf = bv.getForeignAttributeValue(FOX_TRANSFORM);
  690. if (transf != null) {
  691. AffineTransform freeTransform = AWTTransformProducer.createAffineTransform(transf);
  692. positionTransform.concatenate(freeTransform);
  693. }
  694. saveGraphicsState();
  695. //Viewport position
  696. concatenateTransformationMatrixMpt(positionTransform, false);
  697. //Background and borders
  698. float bpwidth = (borderPaddingStart + bv.getBorderAndPaddingWidthEnd());
  699. float bpheight = (borderPaddingBefore + bv.getBorderAndPaddingWidthAfter());
  700. drawBackAndBorders(bv, 0, 0,
  701. (dim.width + bpwidth) / 1000f, (dim.height + bpheight) / 1000f);
  702. //Shift to content rectangle after border painting
  703. AffineTransform contentRectTransform = new AffineTransform();
  704. contentRectTransform.translate(borderPaddingStart, borderPaddingBefore);
  705. concatenateTransformationMatrixMpt(contentRectTransform, false);
  706. //saveGraphicsState();
  707. //Set up coordinate system for content rectangle
  708. AffineTransform contentTransform = ctm.toAffineTransform();
  709. //concatenateTransformationMatrixMpt(contentTransform);
  710. startViewport(contentTransform, bv.getClipRectangle());
  711. currentIPPosition = 0;
  712. currentBPPosition = 0;
  713. renderBlocks(bv, children);
  714. endViewport();
  715. //restoreGraphicsState();
  716. restoreGraphicsState();
  717. if (breakOutList != null) {
  718. restoreStateStackAfterBreakOut(breakOutList);
  719. }
  720. currentIPPosition = saveIP;
  721. currentBPPosition = saveBP;
  722. } else {
  723. currentBPPosition += bv.getSpaceBefore();
  724. //borders and background in the old coordinate system
  725. handleBlockTraits(bv);
  726. //Advance to start of content area
  727. currentIPPosition += bv.getStartIndent();
  728. CTM tempctm = new CTM(containingIPPosition, currentBPPosition);
  729. ctm = tempctm.multiply(ctm);
  730. //Now adjust for border/padding
  731. currentBPPosition += borderPaddingBefore;
  732. startVParea(ctm, bv.getClipRectangle());
  733. currentIPPosition = 0;
  734. currentBPPosition = 0;
  735. renderBlocks(bv, children);
  736. endVParea();
  737. currentIPPosition = saveIP;
  738. currentBPPosition = saveBP;
  739. currentBPPosition += bv.getAllocBPD();
  740. }
  741. viewportDimensionStack.pop();
  742. }
  743. /** {@inheritDoc} */
  744. public void renderInlineViewport(InlineViewport viewport) {
  745. String ptr = (String) viewport.getTrait(Trait.PTR);
  746. establishStructurePointer(ptr);
  747. pushdID(viewport);
  748. Dimension dim = new Dimension(viewport.getIPD(), viewport.getBPD());
  749. viewportDimensionStack.push(dim);
  750. super.renderInlineViewport(viewport);
  751. viewportDimensionStack.pop();
  752. resetStructurePointer();
  753. popID(viewport);
  754. }
  755. /** {@inheritDoc} */
  756. protected void startVParea(CTM ctm, Rectangle clippingRect) {
  757. if (log.isTraceEnabled()) {
  758. log.trace("startVParea() ctm=" + ctm + ", clippingRect=" + clippingRect);
  759. }
  760. AffineTransform at = new AffineTransform(ctm.toArray());
  761. startViewport(at, clippingRect);
  762. if (log.isTraceEnabled()) {
  763. log.trace("startVPArea: " + at + " --> " + graphicContext.getTransform());
  764. }
  765. }
  766. private void startViewport(AffineTransform at, Rectangle clipRect) {
  767. saveGraphicsState();
  768. try {
  769. IFGraphicContext.Viewport viewport = new IFGraphicContext.Viewport(
  770. at, (Dimension)viewportDimensionStack.peek(), clipRect);
  771. graphicContext.pushGroup(viewport);
  772. viewport.start(painter);
  773. } catch (IFException e) {
  774. handleIFException(e);
  775. }
  776. }
  777. /** {@inheritDoc} */
  778. protected void endVParea() {
  779. log.trace("endVParea()");
  780. endViewport();
  781. if (log.isTraceEnabled()) {
  782. log.trace("endVPArea() --> " + graphicContext.getTransform());
  783. }
  784. }
  785. private void endViewport() {
  786. restoreGraphicsState();
  787. }
  788. /** {@inheritDoc} */
  789. protected void renderInlineArea(InlineArea inlineArea) {
  790. saveInlinePosIfTargetable(inlineArea);
  791. pushdID(inlineArea);
  792. super.renderInlineArea(inlineArea);
  793. popID(inlineArea);
  794. }
  795. /** {@inheritDoc} */
  796. public void renderInlineParent(InlineParent ip) {
  797. // stuff we only need if a link must be created:
  798. Rectangle ipRect = null;
  799. AbstractAction action = null;
  800. String ptr = (String) ip.getTrait(Trait.PTR); // used for accessibility
  801. // make sure the rect is determined *before* calling super!
  802. int ipp = currentIPPosition;
  803. int bpp = currentBPPosition + ip.getOffset();
  804. ipRect = new Rectangle(ipp, bpp, ip.getIPD(), ip.getBPD());
  805. AffineTransform transform = graphicContext.getTransform();
  806. ipRect = transform.createTransformedShape(ipRect).getBounds();
  807. // render contents
  808. super.renderInlineParent(ip);
  809. boolean linkTraitFound = false;
  810. // try INTERNAL_LINK first
  811. Trait.InternalLink intLink = (Trait.InternalLink) ip.getTrait(Trait.INTERNAL_LINK);
  812. if (intLink != null) {
  813. linkTraitFound = true;
  814. String pvKey = intLink.getPVKey();
  815. String idRef = intLink.getIDRef();
  816. boolean pvKeyOK = pvKey != null && pvKey.length() > 0;
  817. boolean idRefOK = idRef != null && idRef.length() > 0;
  818. if (pvKeyOK && idRefOK) {
  819. Integer pageIndex = (Integer)pageIndices.get(pvKey);
  820. action = getGoToActionForID(idRef, (pageIndex != null ? pageIndex.intValue() : -1));
  821. } else {
  822. //Warnings already issued by AreaTreeHandler
  823. }
  824. }
  825. // no INTERNAL_LINK, look for EXTERNAL_LINK
  826. if (!linkTraitFound) {
  827. Trait.ExternalLink extLink = (Trait.ExternalLink) ip.getTrait(Trait.EXTERNAL_LINK);
  828. if (extLink != null) {
  829. String extDest = extLink.getDestination();
  830. if (extDest != null && extDest.length() > 0) {
  831. linkTraitFound = true;
  832. action = new URIAction(extDest, extLink.newWindow());
  833. action = actionSet.put(action);
  834. }
  835. }
  836. }
  837. // warn if link trait found but not allowed, else create link
  838. if (linkTraitFound) {
  839. action.setStructurePointer(ptr); // used for accessibility
  840. Link link = new Link(action, ipRect);
  841. this.deferredLinks.add(link);
  842. }
  843. }
  844. /** {@inheritDoc} */
  845. protected void renderBlock(Block block) {
  846. if (log.isTraceEnabled()) {
  847. log.trace("renderBlock() " + block);
  848. }
  849. saveBlockPosIfTargetable(block);
  850. pushdID(block);
  851. super.renderBlock(block);
  852. popID(block);
  853. }
  854. private void pushdID(Area area) {
  855. String prodID = (String) area.getTrait(Trait.PROD_ID);
  856. if (prodID != null) {
  857. ids.push(prodID);
  858. documentHandler.getContext().setID(prodID);
  859. }
  860. }
  861. private void popID(Area area) {
  862. String prodID = (String) area.getTrait(Trait.PROD_ID);
  863. if (prodID != null) {
  864. ids.pop();
  865. documentHandler.getContext().setID(ids.empty() ? "" : ids.peek());
  866. }
  867. }
  868. private Typeface getTypeface(String fontName) {
  869. Typeface tf = (Typeface) fontInfo.getFonts().get(fontName);
  870. if (tf instanceof LazyFont) {
  871. tf = ((LazyFont)tf).getRealFont();
  872. }
  873. return tf;
  874. }
  875. /** {@inheritDoc} */
  876. protected void renderText(TextArea text) {
  877. if (log.isTraceEnabled()) {
  878. log.trace("renderText() " + text);
  879. }
  880. renderInlineAreaBackAndBorders(text);
  881. Color ct = (Color) text.getTrait(Trait.COLOR);
  882. beginTextObject();
  883. String fontName = getInternalFontNameForArea(text);
  884. int size = ((Integer) text.getTrait(Trait.FONT_SIZE)).intValue();
  885. String ptr = (String)text.getTrait(Trait.PTR); // used for accessibility
  886. establishStructurePointer(ptr);
  887. // This assumes that *all* CIDFonts use a /ToUnicode mapping
  888. Typeface tf = getTypeface(fontName);
  889. FontTriplet triplet = (FontTriplet)text.getTrait(Trait.FONT);
  890. try {
  891. painter.setFont(triplet.getName(), triplet.getStyle(), new Integer(triplet.getWeight()),
  892. "normal", new Integer(size), ct);
  893. } catch (IFException e) {
  894. handleIFException(e);
  895. }
  896. int rx = currentIPPosition + text.getBorderAndPaddingWidthStart();
  897. int bl = currentBPPosition + text.getOffset() + text.getBaselineOffset();
  898. textUtil.flush();
  899. textUtil.setStartPosition(rx, bl);
  900. textUtil.setSpacing(text.getTextLetterSpaceAdjust(), text.getTextWordSpaceAdjust());
  901. super.renderText(text);
  902. textUtil.flush();
  903. renderTextDecoration(tf, size, text, bl, rx);
  904. resetStructurePointer();
  905. }
  906. /** {@inheritDoc} */
  907. protected void renderWord(WordArea word) {
  908. Font font = getFontFromArea(word.getParentArea());
  909. String s = word.getWord();
  910. renderText(s, word.getLetterAdjustArray(),
  911. font, (AbstractTextArea)word.getParentArea());
  912. super.renderWord(word);
  913. }
  914. /** {@inheritDoc} */
  915. protected void renderSpace(SpaceArea space) {
  916. Font font = getFontFromArea(space.getParentArea());
  917. String s = space.getSpace();
  918. AbstractTextArea textArea = (AbstractTextArea)space.getParentArea();
  919. renderText(s, null, font, textArea);
  920. if (textUtil.combined && space.isAdjustable()) {
  921. //Used for justified text, for example
  922. int tws = textArea.getTextWordSpaceAdjust()
  923. + 2 * textArea.getTextLetterSpaceAdjust();
  924. if (tws != 0) {
  925. textUtil.adjust(tws);
  926. }
  927. }
  928. super.renderSpace(space);
  929. }
  930. /**
  931. * Does low-level rendering of text.
  932. * @param s text to render
  933. * @param letterAdjust an array of widths for letter adjustment (may be null)
  934. * @param font to font in use
  935. * @param parentArea the parent text area to retrieve certain traits from
  936. */
  937. protected void renderText(String s,
  938. int[] letterAdjust,
  939. Font font, AbstractTextArea parentArea) {
  940. int l = s.length();
  941. if (l == 0) {
  942. return;
  943. }
  944. if (letterAdjust != null) {
  945. textUtil.adjust(letterAdjust[0]);
  946. }
  947. for (int i = 0; i < l; i++) {
  948. char ch = s.charAt(i);
  949. textUtil.addChar(ch);
  950. int glyphAdjust = 0;
  951. if (textUtil.combined && font.hasChar(ch)) {
  952. int tls = (i < l - 1 ? parentArea.getTextLetterSpaceAdjust() : 0);
  953. glyphAdjust += tls;
  954. }
  955. if (letterAdjust != null && i < l - 1) {
  956. glyphAdjust += letterAdjust[i + 1];
  957. }
  958. textUtil.adjust(glyphAdjust);
  959. }
  960. }
  961. private class TextUtil {
  962. private static final int INITIAL_BUFFER_SIZE = 16;
  963. private int[] dx = new int[INITIAL_BUFFER_SIZE];
  964. private int lastDXPos = 0;
  965. private final StringBuffer text = new StringBuffer();
  966. private int startx, starty;
  967. private int tls, tws;
  968. private final boolean combined = false;
  969. void addChar(char ch) {
  970. text.append(ch);
  971. }
  972. void adjust(int adjust) {
  973. if (adjust != 0) {
  974. int idx = text.length();
  975. if (idx > dx.length - 1) {
  976. int newSize = Math.max(dx.length, idx + 1) + INITIAL_BUFFER_SIZE;
  977. int[] newDX = new int[newSize];
  978. System.arraycopy(dx, 0, newDX, 0, dx.length);
  979. dx = newDX;
  980. }
  981. dx[idx] += adjust;
  982. lastDXPos = idx;
  983. }
  984. }
  985. void reset() {
  986. if (text.length() > 0) {
  987. text.setLength(0);
  988. Arrays.fill(dx, 0);
  989. lastDXPos = 0;
  990. }
  991. }
  992. void setStartPosition(int x, int y) {
  993. this.startx = x;
  994. this.starty = y;
  995. }
  996. void setSpacing(int tls, int tws) {
  997. this.tls = tls;
  998. this.tws = tws;
  999. }
  1000. void flush() {
  1001. if (text.length() > 0) {
  1002. try {
  1003. int[] effDX = null;
  1004. if (lastDXPos > 0) {
  1005. int size = lastDXPos + 1;
  1006. effDX = new int[size];
  1007. System.arraycopy(dx, 0, effDX, 0, size);
  1008. }
  1009. if (combined) {
  1010. painter.drawText(startx, starty, 0, 0, effDX, text.toString());
  1011. } else {
  1012. painter.drawText(startx, starty, tls, tws, effDX, text.toString());
  1013. }
  1014. } catch (IFException e) {
  1015. handleIFException(e);
  1016. }
  1017. reset();
  1018. }
  1019. }
  1020. }
  1021. /** {@inheritDoc} */
  1022. public void renderImage(Image image, Rectangle2D pos) {
  1023. drawImage(image.getURL(), pos, image.getForeignAttributes());
  1024. }
  1025. /** {@inheritDoc} */
  1026. protected void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) {
  1027. Rectangle posInt = new Rectangle(
  1028. currentIPPosition + (int)pos.getX(),
  1029. currentBPPosition + (int)pos.getY(),
  1030. (int)pos.getWidth(),
  1031. (int)pos.getHeight());
  1032. uri = URISpecification.getURL(uri);
  1033. try {
  1034. establishForeignAttributes(foreignAttributes);
  1035. painter.drawImage(uri, posInt);
  1036. resetForeignAttributes();
  1037. } catch (IFException ife) {
  1038. handleIFException(ife);
  1039. }
  1040. }
  1041. /** {@inheritDoc} */
  1042. public void renderForeignObject(ForeignObject fo, Rectangle2D pos) {
  1043. endTextObject();
  1044. Rectangle posInt = new Rectangle(
  1045. currentIPPosition + (int)pos.getX(),
  1046. currentBPPosition + (int)pos.getY(),
  1047. (int)pos.getWidth(),
  1048. (int)pos.getHeight());
  1049. Document doc = fo.getDocument();
  1050. try {
  1051. establishForeignAttributes(fo.getForeignAttributes());
  1052. painter.drawImage(doc, posInt);
  1053. resetForeignAttributes();
  1054. } catch (IFException ife) {
  1055. handleIFException(ife);
  1056. }
  1057. }
  1058. /** {@inheritDoc} */
  1059. public void renderLeader(Leader area) {
  1060. renderInlineAreaBackAndBorders(area);
  1061. int style = area.getRuleStyle();
  1062. int ruleThickness = area.getRuleThickness();
  1063. int startx = currentIPPosition + area.getBorderAndPaddingWidthStart();
  1064. int starty = currentBPPosition + area.getOffset() + (ruleThickness / 2);
  1065. int endx = currentIPPosition
  1066. + area.getBorderAndPaddingWidthStart()
  1067. + area.getIPD();
  1068. Color col = (Color)area.getTrait(Trait.COLOR);
  1069. Point start = new Point(startx, starty);
  1070. Point end = new Point(endx, starty);
  1071. try {
  1072. painter.drawLine(start, end, ruleThickness, col, RuleStyle.valueOf(style));
  1073. } catch (IFException ife) {
  1074. handleIFException(ife);
  1075. }
  1076. super.renderLeader(area);
  1077. }
  1078. /** {@inheritDoc} */
  1079. protected void clip() {
  1080. throw new IllegalStateException("Not used");
  1081. }
  1082. /** {@inheritDoc} */
  1083. protected void clipRect(float x, float y, float width, float height) {
  1084. pushGroup(new IFGraphicContext.Group());
  1085. try {
  1086. painter.clipRect(toMillipointRectangle(x, y, width, height));
  1087. } catch (IFException ife) {
  1088. handleIFException(ife);
  1089. }
  1090. }
  1091. /** {@inheritDoc} */
  1092. protected void closePath() {
  1093. throw new IllegalStateException("Not used");
  1094. }
  1095. /** {@inheritDoc} */
  1096. protected void drawBorders( // CSOK: ParameterNumber
  1097. float startx, float starty,
  1098. float width, float height,
  1099. BorderProps bpsBefore, BorderProps bpsAfter,
  1100. BorderProps bpsStart, BorderProps bpsEnd) {
  1101. Rectangle rect = toMillipointRectangle(startx, starty, width, height);
  1102. try {
  1103. painter.drawBorderRect(rect, bpsBefore, bpsAfter, bpsStart, bpsEnd);
  1104. } catch (IFException ife) {
  1105. handleIFException(ife);
  1106. }
  1107. }
  1108. /** {@inheritDoc} */
  1109. protected void drawBorderLine( // CSOK: ParameterNumber
  1110. float x1, float y1, float x2, float y2, boolean horz,
  1111. boolean startOrBefore, int style, Color col) {
  1112. //Simplified implementation that is only used by renderTextDecoration()
  1113. //drawBorders() is overridden and uses the Painter's high-level method drawBorderRect()
  1114. updateColor(col, true);
  1115. fillRect(x1, y1, x2 - x1, y2 - y1);
  1116. }
  1117. private int toMillipoints(float coordinate) {
  1118. return Math.round(coordinate * 1000);
  1119. }
  1120. private Rectangle toMillipointRectangle(float x, float y, float width, float height) {
  1121. return new Rectangle(
  1122. toMillipoints(x),
  1123. toMillipoints(y),
  1124. toMillipoints(width),
  1125. toMillipoints(height));
  1126. }
  1127. /** {@inheritDoc} */
  1128. protected void fillRect(float x, float y, float width, float height) {
  1129. try {
  1130. painter.fillRect(
  1131. toMillipointRectangle(x, y, width, height),
  1132. this.graphicContext.getPaint());
  1133. } catch (IFException e) {
  1134. handleIFException(e);
  1135. }
  1136. }
  1137. /** {@inheritDoc} */
  1138. protected void moveTo(float x, float y) {
  1139. throw new IllegalStateException("Not used");
  1140. }
  1141. /** {@inheritDoc} */
  1142. protected void lineTo(float x, float y) {
  1143. throw new IllegalStateException("Not used");
  1144. }
  1145. /** {@inheritDoc} */
  1146. protected void updateColor(Color col, boolean fill) {
  1147. if (fill) {
  1148. this.graphicContext.setPaint(col);
  1149. } else {
  1150. this.graphicContext.setColor(col);
  1151. }
  1152. }
  1153. }