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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465
  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, documentHandler.getContext());
  362. } else {
  363. // Not complete yet, can't use getPDFGoTo:
  364. action = new GoToXYAction(targetID, pageIndex, null, documentHandler.getContext());
  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 (ExtensionAttachment attachment : area.getExtensionAttachments()) {
  547. this.documentHandler.handleExtensionObject(attachment);
  548. }
  549. }
  550. }
  551. private void establishForeignAttributes(Map foreignAttributes) {
  552. documentHandler.getContext().setForeignAttributes(foreignAttributes);
  553. }
  554. private void resetForeignAttributes() {
  555. documentHandler.getContext().resetForeignAttributes();
  556. }
  557. private void establishStructureTreeElement(StructureTreeElement structureTreeElement) {
  558. documentHandler.getContext().setStructureTreeElement(structureTreeElement);
  559. }
  560. private void resetStructurePointer() {
  561. documentHandler.getContext().resetStructureTreeElement();
  562. }
  563. /** {@inheritDoc} */
  564. protected void saveGraphicsState() {
  565. graphicContextStack.push(graphicContext);
  566. graphicContext = (IFGraphicContext)graphicContext.clone();
  567. }
  568. /** {@inheritDoc} */
  569. protected void restoreGraphicsState() {
  570. while (graphicContext.getGroupStackSize() > 0) {
  571. IFGraphicContext.Group[] groups = graphicContext.dropGroups();
  572. for (int i = groups.length - 1; i >= 0; i--) {
  573. try {
  574. groups[i].end(painter);
  575. } catch (IFException ife) {
  576. handleIFException(ife);
  577. }
  578. }
  579. }
  580. graphicContext = (IFGraphicContext)graphicContextStack.pop();
  581. }
  582. private void pushGroup(IFGraphicContext.Group group) {
  583. graphicContext.pushGroup(group);
  584. try {
  585. group.start(painter);
  586. } catch (IFException ife) {
  587. handleIFException(ife);
  588. }
  589. }
  590. /** {@inheritDoc} */
  591. protected List breakOutOfStateStack() {
  592. log.debug("Block.FIXED --> break out");
  593. List breakOutList = new java.util.ArrayList();
  594. while (!this.graphicContextStack.empty()) {
  595. //Handle groups
  596. IFGraphicContext.Group[] groups = graphicContext.getGroups();
  597. for (int j = groups.length - 1; j >= 0; j--) {
  598. try {
  599. groups[j].end(painter);
  600. } catch (IFException ife) {
  601. handleIFException(ife);
  602. }
  603. }
  604. breakOutList.add(0, this.graphicContext);
  605. graphicContext = (IFGraphicContext)graphicContextStack.pop();
  606. }
  607. return breakOutList;
  608. }
  609. /** {@inheritDoc} */
  610. protected void restoreStateStackAfterBreakOut(List breakOutList) {
  611. log.debug("Block.FIXED --> restoring context after break-out");
  612. for (Object aBreakOutList : breakOutList) {
  613. graphicContextStack.push(graphicContext);
  614. this.graphicContext = (IFGraphicContext) aBreakOutList;
  615. //Handle groups
  616. IFGraphicContext.Group[] groups = graphicContext.getGroups();
  617. for (IFGraphicContext.Group group : groups) {
  618. try {
  619. group.start(painter);
  620. } catch (IFException ife) {
  621. handleIFException(ife);
  622. }
  623. }
  624. }
  625. log.debug("restored.");
  626. }
  627. /** {@inheritDoc} */
  628. protected void concatenateTransformationMatrix(AffineTransform at) {
  629. if (!at.isIdentity()) {
  630. concatenateTransformationMatrixMpt(ptToMpt(at), false);
  631. }
  632. }
  633. private void concatenateTransformationMatrixMpt(AffineTransform at, boolean force) {
  634. if (force || !at.isIdentity()) {
  635. if (log.isTraceEnabled()) {
  636. log.trace("-----concatenateTransformationMatrix: " + at);
  637. }
  638. IFGraphicContext.Group group = new IFGraphicContext.Group(at);
  639. pushGroup(group);
  640. }
  641. }
  642. /** {@inheritDoc} */
  643. protected void beginTextObject() {
  644. //nop - Ignore, handled by painter internally
  645. }
  646. /** {@inheritDoc} */
  647. protected void endTextObject() {
  648. //nop - Ignore, handled by painter internally
  649. }
  650. /** {@inheritDoc} */
  651. protected void renderRegionViewport(RegionViewport viewport) {
  652. Dimension dim = new Dimension(viewport.getIPD(), viewport.getBPD());
  653. viewportDimensionStack.push(dim);
  654. super.renderRegionViewport(viewport);
  655. viewportDimensionStack.pop();
  656. }
  657. /** {@inheritDoc} */
  658. protected void renderBlockViewport(BlockViewport bv, List children) {
  659. //Essentially the same code as in the super class but optimized for the IF
  660. // Handle new layer.
  661. boolean inNewLayer = false;
  662. if (maybeStartLayer(bv)) {
  663. inNewLayer = true;
  664. }
  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. maybeEndLayer(bv, inNewLayer);
  743. }
  744. /** {@inheritDoc} */
  745. public void renderInlineViewport(InlineViewport viewport) {
  746. StructureTreeElement structElem
  747. = (StructureTreeElement) viewport.getTrait(Trait.STRUCTURE_TREE_ELEMENT);
  748. establishStructureTreeElement(structElem);
  749. pushID(viewport);
  750. Dimension dim = new Dimension(viewport.getIPD(), viewport.getBPD());
  751. viewportDimensionStack.push(dim);
  752. super.renderInlineViewport(viewport);
  753. viewportDimensionStack.pop();
  754. resetStructurePointer();
  755. popID(viewport);
  756. }
  757. /** {@inheritDoc} */
  758. protected void startVParea(CTM ctm, Rectangle clippingRect) {
  759. if (log.isTraceEnabled()) {
  760. log.trace("startVParea() ctm=" + ctm + ", clippingRect=" + clippingRect);
  761. }
  762. AffineTransform at = new AffineTransform(ctm.toArray());
  763. startViewport(at, clippingRect);
  764. if (log.isTraceEnabled()) {
  765. log.trace("startVPArea: " + at + " --> " + graphicContext.getTransform());
  766. }
  767. }
  768. private void startViewport(AffineTransform at, Rectangle clipRect) {
  769. saveGraphicsState();
  770. try {
  771. IFGraphicContext.Viewport viewport = new IFGraphicContext.Viewport(
  772. at, (Dimension)viewportDimensionStack.peek(), clipRect);
  773. graphicContext.pushGroup(viewport);
  774. viewport.start(painter);
  775. } catch (IFException e) {
  776. handleIFException(e);
  777. }
  778. }
  779. /** {@inheritDoc} */
  780. protected void endVParea() {
  781. log.trace("endVParea()");
  782. endViewport();
  783. if (log.isTraceEnabled()) {
  784. log.trace("endVPArea() --> " + graphicContext.getTransform());
  785. }
  786. }
  787. private void endViewport() {
  788. restoreGraphicsState();
  789. }
  790. /** {@inheritDoc} */
  791. protected void startLayer(String layer) {
  792. if (log.isTraceEnabled()) {
  793. log.trace("startLayer() layer=" + layer);
  794. }
  795. saveGraphicsState();
  796. pushGroup(new IFGraphicContext.Group(layer));
  797. }
  798. /** {@inheritDoc} */
  799. protected void endLayer() {
  800. if (log.isTraceEnabled()) {
  801. log.trace("endLayer()");
  802. }
  803. restoreGraphicsState();
  804. }
  805. /** {@inheritDoc} */
  806. protected void renderInlineArea(InlineArea inlineArea) {
  807. saveInlinePosIfTargetable(inlineArea);
  808. pushID(inlineArea);
  809. super.renderInlineArea(inlineArea);
  810. popID(inlineArea);
  811. }
  812. /** {@inheritDoc} */
  813. public void renderInlineParent(InlineParent ip) {
  814. // stuff we only need if a link must be created:
  815. Rectangle ipRect = null;
  816. AbstractAction action = null;
  817. // make sure the rect is determined *before* calling super!
  818. int ipp = currentIPPosition;
  819. int bpp = currentBPPosition + ip.getBlockProgressionOffset();
  820. ipRect = new Rectangle(ipp, bpp, ip.getIPD(), ip.getBPD());
  821. AffineTransform transform = graphicContext.getTransform();
  822. ipRect = transform.createTransformedShape(ipRect).getBounds();
  823. // render contents
  824. super.renderInlineParent(ip);
  825. boolean linkTraitFound = false;
  826. // try INTERNAL_LINK first
  827. Trait.InternalLink intLink = (Trait.InternalLink) ip.getTrait(Trait.INTERNAL_LINK);
  828. if (intLink != null) {
  829. linkTraitFound = true;
  830. String pvKey = intLink.getPVKey();
  831. String idRef = intLink.getIDRef();
  832. boolean pvKeyOK = pvKey != null && pvKey.length() > 0;
  833. boolean idRefOK = idRef != null && idRef.length() > 0;
  834. if (pvKeyOK && idRefOK) {
  835. Integer pageIndex = (Integer)pageIndices.get(pvKey);
  836. action = getGoToActionForID(idRef, (pageIndex != null ? pageIndex : -1));
  837. } else {
  838. //Warnings already issued by AreaTreeHandler
  839. }
  840. }
  841. // no INTERNAL_LINK, look for EXTERNAL_LINK
  842. if (!linkTraitFound) {
  843. Trait.ExternalLink extLink = (Trait.ExternalLink) ip.getTrait(Trait.EXTERNAL_LINK);
  844. if (extLink != null) {
  845. String extDest = extLink.getDestination();
  846. if (extDest != null && extDest.length() > 0) {
  847. linkTraitFound = true;
  848. action = new URIAction(extDest, extLink.newWindow());
  849. action = actionSet.put(action);
  850. }
  851. }
  852. }
  853. // warn if link trait found but not allowed, else create link
  854. if (linkTraitFound) {
  855. StructureTreeElement structElem
  856. = (StructureTreeElement) ip.getTrait(Trait.STRUCTURE_TREE_ELEMENT);
  857. action.setStructureTreeElement(structElem);
  858. Link link = new Link(action, ipRect);
  859. this.deferredLinks.add(link);
  860. }
  861. }
  862. /** {@inheritDoc} */
  863. protected void renderBlock(Block block) {
  864. if (log.isTraceEnabled()) {
  865. log.trace("renderBlock() " + block);
  866. }
  867. saveBlockPosIfTargetable(block);
  868. pushID(block);
  869. IFContext context = documentHandler.getContext();
  870. Locale oldLocale = context.getLanguage();
  871. context.setLanguage(block.getLocale());
  872. String oldLocation = context.getLocation();
  873. context.setLocation(block.getLocation());
  874. super.renderBlock(block);
  875. context.setLocation(oldLocation);
  876. context.setLanguage(oldLocale);
  877. popID(block);
  878. }
  879. private void pushID(Area area) {
  880. String prodID = (String) area.getTrait(Trait.PROD_ID);
  881. if (prodID != null) {
  882. ids.push(prodID);
  883. documentHandler.getContext().setID(prodID);
  884. }
  885. }
  886. private void popID(Area area) {
  887. String prodID = (String) area.getTrait(Trait.PROD_ID);
  888. if (prodID != null) {
  889. ids.pop();
  890. documentHandler.getContext().setID(ids.empty() ? "" : ids.peek());
  891. }
  892. }
  893. private Typeface getTypeface(String fontName) {
  894. Typeface tf = fontInfo.getFonts().get(fontName);
  895. if (tf instanceof LazyFont) {
  896. tf = ((LazyFont)tf).getRealFont();
  897. }
  898. return tf;
  899. }
  900. /** {@inheritDoc} */
  901. protected void renderText(TextArea text) {
  902. if (log.isTraceEnabled()) {
  903. log.trace("renderText() " + text);
  904. }
  905. renderInlineAreaBackAndBorders(text);
  906. Color ct = (Color) text.getTrait(Trait.COLOR);
  907. beginTextObject();
  908. String fontName = getInternalFontNameForArea(text);
  909. int size = (Integer) text.getTrait(Trait.FONT_SIZE);
  910. StructureTreeElement structElem
  911. = (StructureTreeElement) text.getTrait(Trait.STRUCTURE_TREE_ELEMENT);
  912. establishStructureTreeElement(structElem);
  913. // This assumes that *all* CIDFonts use a /ToUnicode mapping
  914. Typeface tf = getTypeface(fontName);
  915. FontTriplet triplet = (FontTriplet)text.getTrait(Trait.FONT);
  916. try {
  917. painter.setFont(triplet.getName(), triplet.getStyle(), triplet.getWeight(),
  918. "normal", size, ct);
  919. } catch (IFException e) {
  920. handleIFException(e);
  921. }
  922. int rx = currentIPPosition + text.getBorderAndPaddingWidthStart();
  923. int bl = currentBPPosition + text.getBlockProgressionOffset() + text.getBaselineOffset();
  924. textUtil.flush();
  925. textUtil.setStartPosition(rx, bl);
  926. textUtil.setSpacing(text.getTextLetterSpaceAdjust(), text.getTextWordSpaceAdjust());
  927. documentHandler.getContext().setHyphenated(text.isHyphenated());
  928. super.renderText(text);
  929. textUtil.flush();
  930. renderTextDecoration(tf, size, text, bl, rx);
  931. documentHandler.getContext().setHyphenated(false);
  932. resetStructurePointer();
  933. }
  934. /** {@inheritDoc} */
  935. protected void renderWord(WordArea word) {
  936. Font font = getFontFromArea(word.getParentArea());
  937. String s = word.getWord();
  938. int[][] dp = word.getGlyphPositionAdjustments();
  939. Area parentArea = word.getParentArea();
  940. assert (parentArea instanceof AbstractTextArea);
  941. if (dp == null) {
  942. renderTextWithAdjustments(s, word.getLetterAdjustArray(), word.isReversed(),
  943. font, (AbstractTextArea) parentArea);
  944. } else if (IFUtil.isDPOnlyDX(dp)) {
  945. renderTextWithAdjustments(s, IFUtil.convertDPToDX(dp), word.isReversed(),
  946. font, (AbstractTextArea) parentArea);
  947. } else {
  948. renderTextWithAdjustments(s, dp, word.isReversed(),
  949. font, (AbstractTextArea) parentArea);
  950. }
  951. super.renderWord(word);
  952. }
  953. /** {@inheritDoc} */
  954. protected void renderSpace(SpaceArea space) {
  955. Font font = getFontFromArea(space.getParentArea());
  956. String s = space.getSpace();
  957. Area parentArea = space.getParentArea();
  958. assert (parentArea instanceof AbstractTextArea);
  959. AbstractTextArea textArea = (AbstractTextArea) parentArea;
  960. renderTextWithAdjustments(s, (int[]) null, false, font, textArea);
  961. /* COMBINED is always false
  962. if (textUtil.COMBINED && space.isAdjustable()) {
  963. //Used for justified text, for example
  964. int tws = textArea.getTextWordSpaceAdjust()
  965. + 2 * textArea.getTextLetterSpaceAdjust();
  966. if (tws != 0) {
  967. textUtil.adjust(tws);
  968. }
  969. }
  970. */
  971. super.renderSpace(space);
  972. }
  973. /**
  974. * Does low-level rendering of text using DX only position adjustments.
  975. * @param s text to render
  976. * @param dx an array of widths for letter adjustment (may be null)
  977. * @param reversed if true then text has been reversed (from logical order)
  978. * @param font to font in use
  979. * @param parentArea the parent text area to retrieve certain traits from
  980. */
  981. private void renderTextWithAdjustments(String s,
  982. int[] dx, boolean reversed,
  983. Font font, AbstractTextArea parentArea) {
  984. int l = s.length();
  985. if (l == 0) {
  986. return;
  987. }
  988. for (int i = 0; i < l; i++) {
  989. char ch = s.charAt(i);
  990. textUtil.addChar(ch);
  991. int glyphAdjust = 0;
  992. /* COMBINED is always false
  993. if (textUtil.COMBINED && font.hasChar(ch)) {
  994. int tls = (i < l - 1 ? parentArea.getTextLetterSpaceAdjust() : 0);
  995. glyphAdjust += tls;
  996. }
  997. */
  998. if (dx != null && i < l) {
  999. glyphAdjust += dx[i];
  1000. }
  1001. textUtil.adjust(glyphAdjust);
  1002. }
  1003. }
  1004. /**
  1005. * Does low-level rendering of text using generalized position adjustments.
  1006. * @param s text to render
  1007. * @param dp an array of 4-tuples, expressing [X,Y] placment
  1008. * adjustments and [X,Y] advancement adjustments, in that order (may be null)
  1009. * @param reversed if true then text has been reversed (from logical order)
  1010. * @param font to font in use
  1011. * @param parentArea the parent text area to retrieve certain traits from
  1012. */
  1013. private void renderTextWithAdjustments(String s,
  1014. int[][] dp, boolean reversed,
  1015. Font font, AbstractTextArea parentArea) {
  1016. // assert !textUtil.COMBINED;
  1017. for (int i = 0, n = s.length(); i < n; i++) {
  1018. textUtil.addChar(s.charAt(i));
  1019. if (dp != null) {
  1020. textUtil.adjust(dp[i]);
  1021. }
  1022. }
  1023. }
  1024. private class TextUtil {
  1025. private static final int INITIAL_BUFFER_SIZE = 16;
  1026. private int[][] dp = new int[INITIAL_BUFFER_SIZE][];
  1027. private final StringBuffer text = new StringBuffer();
  1028. private int startx;
  1029. private int starty;
  1030. private int tls;
  1031. private int tws;
  1032. // private final static boolean COMBINED = false; // no longer referenced
  1033. void addChar(char ch) {
  1034. text.append(ch);
  1035. }
  1036. void adjust(int dx) {
  1037. if (dx != 0) {
  1038. adjust(new int[] {
  1039. dx, // xPlaAdjust
  1040. 0, // yPlaAdjust
  1041. dx, // xAdvAdjust
  1042. 0 // yAdvAdjust
  1043. });
  1044. }
  1045. }
  1046. void adjust(int[] pa) {
  1047. if (!IFUtil.isPAIdentity(pa)) {
  1048. int idx = text.length();
  1049. if (idx > dp.length - 1) {
  1050. int newSize = Math.max(dp.length, idx + 1) + INITIAL_BUFFER_SIZE;
  1051. int[][] newDP = new int[newSize][];
  1052. // reuse prior DP[0]...DP[dp.length-1]
  1053. System.arraycopy(dp, 0, newDP, 0, dp.length);
  1054. // switch to new DP, leaving DP[dp.length]...DP[newDP.length-1] unpopulated
  1055. dp = newDP;
  1056. }
  1057. if (dp[idx - 1] == null) {
  1058. dp[idx - 1] = new int[4];
  1059. }
  1060. IFUtil.adjustPA(dp[idx - 1], pa);
  1061. }
  1062. }
  1063. void reset() {
  1064. if (text.length() > 0) {
  1065. text.setLength(0);
  1066. for (int i = 0, n = dp.length; i < n; i++) {
  1067. dp[i] = null;
  1068. }
  1069. }
  1070. }
  1071. void setStartPosition(int x, int y) {
  1072. this.startx = x;
  1073. this.starty = y;
  1074. }
  1075. void setSpacing(int tls, int tws) {
  1076. this.tls = tls;
  1077. this.tws = tws;
  1078. }
  1079. void flush() {
  1080. if (text.length() > 0) {
  1081. try {
  1082. /* if (COMBINED) { // COMBINED is always false
  1083. painter.drawText(startx, starty, 0, 0,
  1084. trimAdjustments(dp, text.length()), text.toString());
  1085. } else { */
  1086. painter.drawText(startx, starty, tls, tws,
  1087. trimAdjustments(dp, text.length()), text.toString());
  1088. /* } */
  1089. } catch (IFException e) {
  1090. handleIFException(e);
  1091. }
  1092. reset();
  1093. }
  1094. }
  1095. /**
  1096. * Trim adjustments array <code>dp</code> to be no greater length than
  1097. * text length, and where trailing all-zero entries are removed.
  1098. * @param dp a position adjustments array (or null)
  1099. * @param textLength the length of the associated text
  1100. * @return either the original value of <code>dp</code> or a copy
  1101. * of its first N significant adjustment entries, such that N is
  1102. * no greater than text length, and the last entry has a non-zero
  1103. * adjustment.
  1104. */
  1105. private int[][] trimAdjustments(int[][] dp, int textLength) {
  1106. if (dp != null) {
  1107. int tl = textLength;
  1108. int pl = dp.length;
  1109. int i = (tl < pl) ? tl : pl;
  1110. while (i > 0) {
  1111. int[] pa = dp [ i - 1 ];
  1112. if ((pa != null) && !IFUtil.isPAIdentity(pa)) {
  1113. break;
  1114. } else {
  1115. i--;
  1116. }
  1117. }
  1118. if (i == 0) {
  1119. dp = null;
  1120. } else if (i < pl) {
  1121. dp = IFUtil.copyDP(dp, 0, i);
  1122. }
  1123. }
  1124. return dp;
  1125. }
  1126. }
  1127. /** {@inheritDoc} */
  1128. public void renderImage(Image image, Rectangle2D pos) {
  1129. drawImage(image.getURL(), pos, image.getForeignAttributes());
  1130. }
  1131. /** {@inheritDoc} */
  1132. protected void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) {
  1133. Rectangle posInt = new Rectangle(
  1134. currentIPPosition + (int)pos.getX(),
  1135. currentBPPosition + (int)pos.getY(),
  1136. (int)pos.getWidth(),
  1137. (int)pos.getHeight());
  1138. uri = URISpecification.getURL(uri);
  1139. try {
  1140. establishForeignAttributes(foreignAttributes);
  1141. painter.drawImage(uri, posInt);
  1142. resetForeignAttributes();
  1143. } catch (IFException ife) {
  1144. handleIFException(ife);
  1145. }
  1146. }
  1147. /** {@inheritDoc} */
  1148. public void renderForeignObject(ForeignObject fo, Rectangle2D pos) {
  1149. endTextObject();
  1150. Rectangle posInt = new Rectangle(
  1151. currentIPPosition + (int)pos.getX(),
  1152. currentBPPosition + (int)pos.getY(),
  1153. (int)pos.getWidth(),
  1154. (int)pos.getHeight());
  1155. Document doc = fo.getDocument();
  1156. try {
  1157. establishForeignAttributes(fo.getForeignAttributes());
  1158. painter.drawImage(doc, posInt);
  1159. resetForeignAttributes();
  1160. } catch (IFException ife) {
  1161. handleIFException(ife);
  1162. }
  1163. }
  1164. /** {@inheritDoc} */
  1165. public void renderLeader(Leader area) {
  1166. renderInlineAreaBackAndBorders(area);
  1167. int style = area.getRuleStyle();
  1168. int ruleThickness = area.getRuleThickness();
  1169. int startx = currentIPPosition + area.getBorderAndPaddingWidthStart();
  1170. int starty = currentBPPosition + area.getBlockProgressionOffset() + (ruleThickness / 2);
  1171. int endx = currentIPPosition
  1172. + area.getBorderAndPaddingWidthStart()
  1173. + area.getIPD();
  1174. Color col = (Color)area.getTrait(Trait.COLOR);
  1175. Point start = new Point(startx, starty);
  1176. Point end = new Point(endx, starty);
  1177. try {
  1178. painter.drawLine(start, end, ruleThickness, col, RuleStyle.valueOf(style));
  1179. } catch (IFException ife) {
  1180. handleIFException(ife);
  1181. }
  1182. super.renderLeader(area);
  1183. }
  1184. /** {@inheritDoc} */
  1185. protected void clip() {
  1186. throw new IllegalStateException("Not used");
  1187. }
  1188. /** {@inheritDoc} */
  1189. protected void clipRect(float x, float y, float width, float height) {
  1190. pushGroup(new IFGraphicContext.Group());
  1191. try {
  1192. painter.clipRect(toMillipointRectangle(x, y, width, height));
  1193. } catch (IFException ife) {
  1194. handleIFException(ife);
  1195. }
  1196. }
  1197. /** {@inheritDoc} */
  1198. protected void clipBackground(float startx, float starty,
  1199. float width, float height,
  1200. BorderProps bpsBefore, BorderProps bpsAfter,
  1201. BorderProps bpsStart, BorderProps bpsEnd) {
  1202. pushGroup(new IFGraphicContext.Group());
  1203. Rectangle rect = toMillipointRectangle(startx, starty, width, height);
  1204. try {
  1205. painter.clipBackground(rect,
  1206. bpsBefore, bpsAfter, bpsStart, bpsEnd);
  1207. } catch (IFException ife) {
  1208. handleIFException(ife);
  1209. }
  1210. }
  1211. /** {@inheritDoc} */
  1212. protected void closePath() {
  1213. throw new IllegalStateException("Not used");
  1214. }
  1215. /** {@inheritDoc} */
  1216. protected void drawBackground(float startx, float starty,
  1217. float width, float height,
  1218. Trait.Background back,
  1219. BorderProps bpsBefore, BorderProps bpsAfter,
  1220. BorderProps bpsStart, BorderProps bpsEnd) {
  1221. if (painter.isBackgroundRequired(bpsBefore, bpsAfter, bpsStart, bpsEnd)) {
  1222. super.drawBackground(startx, starty, width, height,
  1223. back, bpsBefore, bpsAfter,
  1224. bpsStart, bpsEnd);
  1225. }
  1226. }
  1227. /** {@inheritDoc} */
  1228. protected void drawBorders(float startx, float starty,
  1229. float width, float height,
  1230. BorderProps bpsBefore, BorderProps bpsAfter,
  1231. BorderProps bpsStart, BorderProps bpsEnd, int level, Color innerBackgroundColor) {
  1232. Rectangle rect = toMillipointRectangle(startx, starty, width, height);
  1233. try {
  1234. BorderProps bpsTop = bpsBefore;
  1235. BorderProps bpsBottom = bpsAfter;
  1236. BorderProps bpsLeft;
  1237. BorderProps bpsRight;
  1238. if ((level == -1) || ((level & 1) == 0)) {
  1239. bpsLeft = bpsStart;
  1240. bpsRight = bpsEnd;
  1241. } else {
  1242. bpsLeft = bpsEnd;
  1243. bpsRight = bpsStart;
  1244. }
  1245. painter.drawBorderRect(rect, bpsTop, bpsBottom, bpsLeft, bpsRight, innerBackgroundColor);
  1246. } catch (IFException ife) {
  1247. handleIFException(ife);
  1248. }
  1249. }
  1250. /** {@inheritDoc} */
  1251. protected void drawBorderLine(float x1, float y1, float x2, float y2, boolean horz,
  1252. boolean startOrBefore, int style, Color col) {
  1253. //Simplified implementation that is only used by renderTextDecoration()
  1254. //drawBorders() is overridden and uses the Painter's high-level method drawBorderRect()
  1255. updateColor(col, true);
  1256. fillRect(x1, y1, x2 - x1, y2 - y1);
  1257. }
  1258. private int toMillipoints(float coordinate) {
  1259. return Math.round(coordinate * 1000);
  1260. }
  1261. private Rectangle toMillipointRectangle(float x, float y, float width, float height) {
  1262. return new Rectangle(
  1263. toMillipoints(x),
  1264. toMillipoints(y),
  1265. toMillipoints(width),
  1266. toMillipoints(height));
  1267. }
  1268. /** {@inheritDoc} */
  1269. protected void fillRect(float x, float y, float width, float height) {
  1270. try {
  1271. painter.fillRect(
  1272. toMillipointRectangle(x, y, width, height),
  1273. this.graphicContext.getPaint());
  1274. } catch (IFException e) {
  1275. handleIFException(e);
  1276. }
  1277. }
  1278. /** {@inheritDoc} */
  1279. protected void moveTo(float x, float y) {
  1280. throw new IllegalStateException("Not used");
  1281. }
  1282. /** {@inheritDoc} */
  1283. protected void lineTo(float x, float y) {
  1284. throw new IllegalStateException("Not used");
  1285. }
  1286. /** {@inheritDoc} */
  1287. protected void updateColor(Color col, boolean fill) {
  1288. if (fill) {
  1289. this.graphicContext.setPaint(col);
  1290. } else {
  1291. this.graphicContext.setColor(col);
  1292. }
  1293. }
  1294. }