You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IFRenderer.java 54KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469
  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, final 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, new GoToXYAction.PageIndexRelative() {
  362. public int getPageIndexRelative() {
  363. return pageIndex - documentHandler.getContext().getPageIndex();
  364. }
  365. });
  366. } else {
  367. // Not complete yet, can't use getPDFGoTo:
  368. action = new GoToXYAction(targetID, pageIndex, null, null);
  369. unfinishedGoTos.add(action);
  370. }
  371. action = (GoToXYAction)actionSet.put(action);
  372. //idGoTos.put(targetID, action);
  373. }
  374. return action;
  375. }
  376. private void finishOpenGoTos() {
  377. int count = unfinishedGoTos.size();
  378. if (count > 0) {
  379. Point defaultPos = new Point(0, 0); // top-o-page
  380. while (!unfinishedGoTos.isEmpty()) {
  381. GoToXYAction action = (GoToXYAction)unfinishedGoTos.get(0);
  382. noteGoToPosition(action, defaultPos);
  383. }
  384. PDFEventProducer eventProducer = PDFEventProducer.Provider.get(
  385. getUserAgent().getEventBroadcaster());
  386. eventProducer.nonFullyResolvedLinkTargets(this, count);
  387. // dysfunctional if pageref is null
  388. }
  389. }
  390. private void noteGoToPosition(GoToXYAction action, Point position) {
  391. action.setTargetLocation(position);
  392. try {
  393. getDocumentNavigationHandler().addResolvedAction(action);
  394. } catch (IFException ife) {
  395. handleIFException(ife);
  396. }
  397. unfinishedGoTos.remove(action);
  398. }
  399. private void noteGoToPosition(GoToXYAction action, PageViewport pv, Point position) {
  400. action.setPageIndex(pv.getPageIndex());
  401. noteGoToPosition(action, position);
  402. }
  403. private void saveAbsolutePosition(String id, PageViewport pv,
  404. int relativeIPP, int relativeBPP, AffineTransform tf) {
  405. Point position = new Point(relativeIPP, relativeBPP);
  406. tf.transform(position, position);
  407. idPositions.put(id, position);
  408. // is there already a GoTo action waiting to be completed?
  409. GoToXYAction action = (GoToXYAction)actionSet.get(id);
  410. if (action != null) {
  411. noteGoToPosition(action, pv, position);
  412. }
  413. }
  414. private void saveAbsolutePosition(String id, int relativeIPP, int relativeBPP) {
  415. saveAbsolutePosition(id, this.currentPageViewport,
  416. relativeIPP, relativeBPP, graphicContext.getTransform());
  417. }
  418. private void saveBlockPosIfTargetable(Block block) {
  419. String id = getTargetableID(block);
  420. if (hasDocumentNavigation() && id != null) {
  421. // FIXME: Like elsewhere in the renderer code, absolute and relative
  422. // directions are happily mixed here. This makes sure that the
  423. // links point to the right location, but it is not correct.
  424. int ipp = block.getXOffset();
  425. int bpp = block.getYOffset() + block.getSpaceBefore();
  426. int positioning = block.getPositioning();
  427. if (!(positioning == Block.FIXED || positioning == Block.ABSOLUTE)) {
  428. ipp += currentIPPosition;
  429. bpp += currentBPPosition;
  430. }
  431. saveAbsolutePosition(id, currentPageViewport, ipp, bpp, graphicContext.getTransform());
  432. }
  433. }
  434. private void saveInlinePosIfTargetable(InlineArea inlineArea) {
  435. String id = getTargetableID(inlineArea);
  436. if (hasDocumentNavigation() && id != null) {
  437. int extraMarginBefore = 5000; // millipoints
  438. int ipp = currentIPPosition;
  439. int bpp = currentBPPosition
  440. + inlineArea.getBlockProgressionOffset() - extraMarginBefore;
  441. saveAbsolutePosition(id, ipp, bpp);
  442. }
  443. }
  444. private String getTargetableID(Area area) {
  445. String id = (String) area.getTrait(Trait.PROD_ID);
  446. if (id == null || id.length() == 0
  447. || !currentPageViewport.isFirstWithID(id)
  448. || idPositions.containsKey(id)) {
  449. return null;
  450. } else {
  451. return id;
  452. }
  453. }
  454. /** {@inheritDoc} */
  455. public void startPageSequence(PageSequence pageSequence) {
  456. try {
  457. if (this.inPageSequence) {
  458. documentHandler.endPageSequence();
  459. documentHandler.getContext().setLanguage(null);
  460. } else {
  461. if (this.documentMetadata == null) {
  462. this.documentMetadata = createDefaultDocumentMetadata();
  463. }
  464. documentHandler.handleExtensionObject(this.documentMetadata);
  465. documentHandler.endDocumentHeader();
  466. this.inPageSequence = true;
  467. }
  468. establishForeignAttributes(pageSequence.getForeignAttributes());
  469. documentHandler.getContext().setLanguage(pageSequence.getLocale());
  470. documentHandler.startPageSequence(null);
  471. resetForeignAttributes();
  472. processExtensionAttachments(pageSequence);
  473. } catch (IFException e) {
  474. handleIFException(e);
  475. }
  476. }
  477. private Metadata createDefaultDocumentMetadata() {
  478. Metadata xmp = new Metadata();
  479. DublinCoreAdapter dc = DublinCoreSchema.getAdapter(xmp);
  480. if (getUserAgent().getTitle() != null) {
  481. dc.setTitle(getUserAgent().getTitle());
  482. }
  483. if (getUserAgent().getAuthor() != null) {
  484. dc.addCreator(getUserAgent().getAuthor());
  485. }
  486. if (getUserAgent().getKeywords() != null) {
  487. dc.addSubject(getUserAgent().getKeywords());
  488. }
  489. XMPBasicAdapter xmpBasic = XMPBasicSchema.getAdapter(xmp);
  490. if (getUserAgent().getProducer() != null) {
  491. xmpBasic.setCreatorTool(getUserAgent().getProducer());
  492. } else {
  493. xmpBasic.setCreatorTool(Version.getVersion());
  494. }
  495. xmpBasic.setMetadataDate(new java.util.Date());
  496. if (getUserAgent().getCreationDate() != null) {
  497. xmpBasic.setCreateDate(getUserAgent().getCreationDate());
  498. } else {
  499. xmpBasic.setCreateDate(xmpBasic.getMetadataDate());
  500. }
  501. return xmp;
  502. }
  503. /** {@inheritDoc} */
  504. public void preparePage(PageViewport page) {
  505. super.preparePage(page);
  506. }
  507. /** {@inheritDoc} */
  508. public void renderPage(PageViewport page) throws IOException, FOPException {
  509. if (log.isTraceEnabled()) {
  510. log.trace("renderPage() " + page);
  511. }
  512. try {
  513. pageIndices.put(page.getKey(), page.getPageIndex());
  514. Rectangle viewArea = page.getViewArea();
  515. Dimension dim = new Dimension(viewArea.width, viewArea.height);
  516. establishForeignAttributes(page.getForeignAttributes());
  517. documentHandler.getContext().setPageIndex(page.getPageIndex());
  518. documentHandler.getContext().setPageNumber(page.getPageNumber());
  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. documentHandler.getContext().setPageIndex(-1);
  543. resetForeignAttributes();
  544. } catch (IFException e) {
  545. handleIFException(e);
  546. }
  547. }
  548. private void processExtensionAttachments(AreaTreeObject area) throws IFException {
  549. if (area.hasExtensionAttachments()) {
  550. for (ExtensionAttachment attachment : area.getExtensionAttachments()) {
  551. this.documentHandler.handleExtensionObject(attachment);
  552. }
  553. }
  554. }
  555. private void establishForeignAttributes(Map foreignAttributes) {
  556. documentHandler.getContext().setForeignAttributes(foreignAttributes);
  557. }
  558. private void resetForeignAttributes() {
  559. documentHandler.getContext().resetForeignAttributes();
  560. }
  561. private void establishStructureTreeElement(StructureTreeElement structureTreeElement) {
  562. documentHandler.getContext().setStructureTreeElement(structureTreeElement);
  563. }
  564. private void resetStructurePointer() {
  565. documentHandler.getContext().resetStructureTreeElement();
  566. }
  567. /** {@inheritDoc} */
  568. protected void saveGraphicsState() {
  569. graphicContextStack.push(graphicContext);
  570. graphicContext = (IFGraphicContext)graphicContext.clone();
  571. }
  572. /** {@inheritDoc} */
  573. protected void restoreGraphicsState() {
  574. while (graphicContext.getGroupStackSize() > 0) {
  575. IFGraphicContext.Group[] groups = graphicContext.dropGroups();
  576. for (int i = groups.length - 1; i >= 0; i--) {
  577. try {
  578. groups[i].end(painter);
  579. } catch (IFException ife) {
  580. handleIFException(ife);
  581. }
  582. }
  583. }
  584. graphicContext = (IFGraphicContext)graphicContextStack.pop();
  585. }
  586. private void pushGroup(IFGraphicContext.Group group) {
  587. graphicContext.pushGroup(group);
  588. try {
  589. group.start(painter);
  590. } catch (IFException ife) {
  591. handleIFException(ife);
  592. }
  593. }
  594. /** {@inheritDoc} */
  595. protected List breakOutOfStateStack() {
  596. log.debug("Block.FIXED --> break out");
  597. List breakOutList = new java.util.ArrayList();
  598. while (!this.graphicContextStack.empty()) {
  599. //Handle groups
  600. IFGraphicContext.Group[] groups = graphicContext.getGroups();
  601. for (int j = groups.length - 1; j >= 0; j--) {
  602. try {
  603. groups[j].end(painter);
  604. } catch (IFException ife) {
  605. handleIFException(ife);
  606. }
  607. }
  608. breakOutList.add(0, this.graphicContext);
  609. graphicContext = (IFGraphicContext)graphicContextStack.pop();
  610. }
  611. return breakOutList;
  612. }
  613. /** {@inheritDoc} */
  614. protected void restoreStateStackAfterBreakOut(List breakOutList) {
  615. log.debug("Block.FIXED --> restoring context after break-out");
  616. for (Object aBreakOutList : breakOutList) {
  617. graphicContextStack.push(graphicContext);
  618. this.graphicContext = (IFGraphicContext) aBreakOutList;
  619. //Handle groups
  620. IFGraphicContext.Group[] groups = graphicContext.getGroups();
  621. for (IFGraphicContext.Group group : groups) {
  622. try {
  623. group.start(painter);
  624. } catch (IFException ife) {
  625. handleIFException(ife);
  626. }
  627. }
  628. }
  629. log.debug("restored.");
  630. }
  631. /** {@inheritDoc} */
  632. protected void concatenateTransformationMatrix(AffineTransform at) {
  633. if (!at.isIdentity()) {
  634. concatenateTransformationMatrixMpt(ptToMpt(at), false);
  635. }
  636. }
  637. private void concatenateTransformationMatrixMpt(AffineTransform at, boolean force) {
  638. if (force || !at.isIdentity()) {
  639. if (log.isTraceEnabled()) {
  640. log.trace("-----concatenateTransformationMatrix: " + at);
  641. }
  642. IFGraphicContext.Group group = new IFGraphicContext.Group(at);
  643. pushGroup(group);
  644. }
  645. }
  646. /** {@inheritDoc} */
  647. protected void beginTextObject() {
  648. //nop - Ignore, handled by painter internally
  649. }
  650. /** {@inheritDoc} */
  651. protected void endTextObject() {
  652. //nop - Ignore, handled by painter internally
  653. }
  654. /** {@inheritDoc} */
  655. protected void renderRegionViewport(RegionViewport viewport) {
  656. Dimension dim = new Dimension(viewport.getIPD(), viewport.getBPD());
  657. viewportDimensionStack.push(dim);
  658. super.renderRegionViewport(viewport);
  659. viewportDimensionStack.pop();
  660. }
  661. /** {@inheritDoc} */
  662. protected void renderBlockViewport(BlockViewport bv, List children) {
  663. //Essentially the same code as in the super class but optimized for the IF
  664. // Handle new layer.
  665. boolean inNewLayer = false;
  666. if (maybeStartLayer(bv)) {
  667. inNewLayer = true;
  668. }
  669. //This is the content-rect
  670. Dimension dim = new Dimension(bv.getIPD(), bv.getBPD());
  671. viewportDimensionStack.push(dim);
  672. // save positions
  673. int saveIP = currentIPPosition;
  674. int saveBP = currentBPPosition;
  675. CTM ctm = bv.getCTM();
  676. int borderPaddingStart = bv.getBorderAndPaddingWidthStart();
  677. int borderPaddingBefore = bv.getBorderAndPaddingWidthBefore();
  678. if (bv.getPositioning() == Block.ABSOLUTE
  679. || bv.getPositioning() == Block.FIXED) {
  680. //For FIXED, we need to break out of the current viewports to the
  681. //one established by the page. We save the state stack for restoration
  682. //after the block-container has been painted. See below.
  683. List breakOutList = null;
  684. if (bv.getPositioning() == Block.FIXED) {
  685. breakOutList = breakOutOfStateStack();
  686. }
  687. AffineTransform positionTransform = new AffineTransform();
  688. positionTransform.translate(bv.getXOffset(), bv.getYOffset());
  689. //"left/"top" (bv.getX/YOffset()) specify the position of the content rectangle
  690. positionTransform.translate(-borderPaddingStart, -borderPaddingBefore);
  691. //Free transformation for the block-container viewport
  692. String transf;
  693. transf = bv.getForeignAttributeValue(FOX_TRANSFORM);
  694. if (transf != null) {
  695. AffineTransform freeTransform = AWTTransformProducer.createAffineTransform(transf);
  696. positionTransform.concatenate(freeTransform);
  697. }
  698. saveGraphicsState();
  699. //Viewport position
  700. concatenateTransformationMatrixMpt(positionTransform, false);
  701. //Background and borders
  702. float bpwidth = (borderPaddingStart + bv.getBorderAndPaddingWidthEnd());
  703. float bpheight = (borderPaddingBefore + bv.getBorderAndPaddingWidthAfter());
  704. drawBackAndBorders(bv, 0, 0,
  705. (dim.width + bpwidth) / 1000f, (dim.height + bpheight) / 1000f);
  706. //Shift to content rectangle after border painting
  707. AffineTransform contentRectTransform = new AffineTransform();
  708. contentRectTransform.translate(borderPaddingStart, borderPaddingBefore);
  709. concatenateTransformationMatrixMpt(contentRectTransform, false);
  710. //saveGraphicsState();
  711. //Set up coordinate system for content rectangle
  712. AffineTransform contentTransform = ctm.toAffineTransform();
  713. //concatenateTransformationMatrixMpt(contentTransform);
  714. startViewport(contentTransform, bv.getClipRectangle());
  715. currentIPPosition = 0;
  716. currentBPPosition = 0;
  717. renderBlocks(bv, children);
  718. endViewport();
  719. //restoreGraphicsState();
  720. restoreGraphicsState();
  721. if (breakOutList != null) {
  722. restoreStateStackAfterBreakOut(breakOutList);
  723. }
  724. currentIPPosition = saveIP;
  725. currentBPPosition = saveBP;
  726. } else {
  727. currentBPPosition += bv.getSpaceBefore();
  728. //borders and background in the old coordinate system
  729. handleBlockTraits(bv);
  730. //Advance to start of content area
  731. currentIPPosition += bv.getStartIndent();
  732. CTM tempctm = new CTM(containingIPPosition, currentBPPosition);
  733. ctm = tempctm.multiply(ctm);
  734. //Now adjust for border/padding
  735. currentBPPosition += borderPaddingBefore;
  736. startVParea(ctm, bv.getClipRectangle());
  737. currentIPPosition = 0;
  738. currentBPPosition = 0;
  739. renderBlocks(bv, children);
  740. endVParea();
  741. currentIPPosition = saveIP;
  742. currentBPPosition = saveBP;
  743. currentBPPosition += bv.getAllocBPD();
  744. }
  745. viewportDimensionStack.pop();
  746. maybeEndLayer(bv, inNewLayer);
  747. }
  748. /** {@inheritDoc} */
  749. public void renderInlineViewport(InlineViewport viewport) {
  750. StructureTreeElement structElem
  751. = (StructureTreeElement) viewport.getTrait(Trait.STRUCTURE_TREE_ELEMENT);
  752. establishStructureTreeElement(structElem);
  753. pushID(viewport);
  754. Dimension dim = new Dimension(viewport.getIPD(), viewport.getBPD());
  755. viewportDimensionStack.push(dim);
  756. super.renderInlineViewport(viewport);
  757. viewportDimensionStack.pop();
  758. resetStructurePointer();
  759. popID(viewport);
  760. }
  761. /** {@inheritDoc} */
  762. protected void startVParea(CTM ctm, Rectangle clippingRect) {
  763. if (log.isTraceEnabled()) {
  764. log.trace("startVParea() ctm=" + ctm + ", clippingRect=" + clippingRect);
  765. }
  766. AffineTransform at = new AffineTransform(ctm.toArray());
  767. startViewport(at, clippingRect);
  768. if (log.isTraceEnabled()) {
  769. log.trace("startVPArea: " + at + " --> " + graphicContext.getTransform());
  770. }
  771. }
  772. private void startViewport(AffineTransform at, Rectangle clipRect) {
  773. saveGraphicsState();
  774. try {
  775. IFGraphicContext.Viewport viewport = new IFGraphicContext.Viewport(
  776. at, (Dimension)viewportDimensionStack.peek(), clipRect);
  777. graphicContext.pushGroup(viewport);
  778. viewport.start(painter);
  779. } catch (IFException e) {
  780. handleIFException(e);
  781. }
  782. }
  783. /** {@inheritDoc} */
  784. protected void endVParea() {
  785. log.trace("endVParea()");
  786. endViewport();
  787. if (log.isTraceEnabled()) {
  788. log.trace("endVPArea() --> " + graphicContext.getTransform());
  789. }
  790. }
  791. private void endViewport() {
  792. restoreGraphicsState();
  793. }
  794. /** {@inheritDoc} */
  795. protected void startLayer(String layer) {
  796. if (log.isTraceEnabled()) {
  797. log.trace("startLayer() layer=" + layer);
  798. }
  799. saveGraphicsState();
  800. pushGroup(new IFGraphicContext.Group(layer));
  801. }
  802. /** {@inheritDoc} */
  803. protected void endLayer() {
  804. if (log.isTraceEnabled()) {
  805. log.trace("endLayer()");
  806. }
  807. restoreGraphicsState();
  808. }
  809. /** {@inheritDoc} */
  810. protected void renderInlineArea(InlineArea inlineArea) {
  811. saveInlinePosIfTargetable(inlineArea);
  812. pushID(inlineArea);
  813. super.renderInlineArea(inlineArea);
  814. popID(inlineArea);
  815. }
  816. /** {@inheritDoc} */
  817. public void renderInlineParent(InlineParent ip) {
  818. // stuff we only need if a link must be created:
  819. Rectangle ipRect = null;
  820. AbstractAction action = null;
  821. // make sure the rect is determined *before* calling super!
  822. int ipp = currentIPPosition;
  823. int bpp = currentBPPosition + ip.getBlockProgressionOffset();
  824. ipRect = new Rectangle(ipp, bpp, ip.getIPD(), ip.getBPD());
  825. AffineTransform transform = graphicContext.getTransform();
  826. ipRect = transform.createTransformedShape(ipRect).getBounds();
  827. // render contents
  828. super.renderInlineParent(ip);
  829. boolean linkTraitFound = false;
  830. // try INTERNAL_LINK first
  831. Trait.InternalLink intLink = (Trait.InternalLink) ip.getTrait(Trait.INTERNAL_LINK);
  832. if (intLink != null) {
  833. linkTraitFound = true;
  834. String pvKey = intLink.getPVKey();
  835. String idRef = intLink.getIDRef();
  836. boolean pvKeyOK = pvKey != null && pvKey.length() > 0;
  837. boolean idRefOK = idRef != null && idRef.length() > 0;
  838. if (pvKeyOK && idRefOK) {
  839. Integer pageIndex = (Integer)pageIndices.get(pvKey);
  840. action = getGoToActionForID(idRef, (pageIndex != null ? pageIndex : -1));
  841. } else {
  842. //Warnings already issued by AreaTreeHandler
  843. }
  844. }
  845. // no INTERNAL_LINK, look for EXTERNAL_LINK
  846. if (!linkTraitFound) {
  847. Trait.ExternalLink extLink = (Trait.ExternalLink) ip.getTrait(Trait.EXTERNAL_LINK);
  848. if (extLink != null) {
  849. String extDest = extLink.getDestination();
  850. if (extDest != null && extDest.length() > 0) {
  851. linkTraitFound = true;
  852. action = new URIAction(extDest, extLink.newWindow());
  853. action = actionSet.put(action);
  854. }
  855. }
  856. }
  857. // warn if link trait found but not allowed, else create link
  858. if (linkTraitFound) {
  859. StructureTreeElement structElem
  860. = (StructureTreeElement) ip.getTrait(Trait.STRUCTURE_TREE_ELEMENT);
  861. action.setStructureTreeElement(structElem);
  862. Link link = new Link(action, ipRect);
  863. this.deferredLinks.add(link);
  864. }
  865. }
  866. /** {@inheritDoc} */
  867. protected void renderBlock(Block block) {
  868. if (log.isTraceEnabled()) {
  869. log.trace("renderBlock() " + block);
  870. }
  871. saveBlockPosIfTargetable(block);
  872. pushID(block);
  873. IFContext context = documentHandler.getContext();
  874. Locale oldLocale = context.getLanguage();
  875. context.setLanguage(block.getLocale());
  876. String oldLocation = context.getLocation();
  877. context.setLocation(block.getLocation());
  878. super.renderBlock(block);
  879. context.setLocation(oldLocation);
  880. context.setLanguage(oldLocale);
  881. popID(block);
  882. }
  883. private void pushID(Area area) {
  884. String prodID = (String) area.getTrait(Trait.PROD_ID);
  885. if (prodID != null) {
  886. ids.push(prodID);
  887. documentHandler.getContext().setID(prodID);
  888. }
  889. }
  890. private void popID(Area area) {
  891. String prodID = (String) area.getTrait(Trait.PROD_ID);
  892. if (prodID != null) {
  893. ids.pop();
  894. documentHandler.getContext().setID(ids.empty() ? "" : ids.peek());
  895. }
  896. }
  897. private Typeface getTypeface(String fontName) {
  898. Typeface tf = fontInfo.getFonts().get(fontName);
  899. if (tf instanceof LazyFont) {
  900. tf = ((LazyFont)tf).getRealFont();
  901. }
  902. return tf;
  903. }
  904. /** {@inheritDoc} */
  905. protected void renderText(TextArea text) {
  906. if (log.isTraceEnabled()) {
  907. log.trace("renderText() " + text);
  908. }
  909. renderInlineAreaBackAndBorders(text);
  910. Color ct = (Color) text.getTrait(Trait.COLOR);
  911. beginTextObject();
  912. String fontName = getInternalFontNameForArea(text);
  913. int size = (Integer) text.getTrait(Trait.FONT_SIZE);
  914. StructureTreeElement structElem
  915. = (StructureTreeElement) text.getTrait(Trait.STRUCTURE_TREE_ELEMENT);
  916. establishStructureTreeElement(structElem);
  917. // This assumes that *all* CIDFonts use a /ToUnicode mapping
  918. Typeface tf = getTypeface(fontName);
  919. FontTriplet triplet = (FontTriplet)text.getTrait(Trait.FONT);
  920. try {
  921. painter.setFont(triplet.getName(), triplet.getStyle(), triplet.getWeight(),
  922. "normal", size, ct);
  923. } catch (IFException e) {
  924. handleIFException(e);
  925. }
  926. int rx = currentIPPosition + text.getBorderAndPaddingWidthStart();
  927. int bl = currentBPPosition + text.getBlockProgressionOffset() + text.getBaselineOffset();
  928. textUtil.flush();
  929. textUtil.setStartPosition(rx, bl);
  930. textUtil.setSpacing(text.getTextLetterSpaceAdjust(), text.getTextWordSpaceAdjust());
  931. documentHandler.getContext().setHyphenated(text.isHyphenated());
  932. super.renderText(text);
  933. textUtil.flush();
  934. renderTextDecoration(tf, size, text, bl, rx);
  935. documentHandler.getContext().setHyphenated(false);
  936. resetStructurePointer();
  937. }
  938. /** {@inheritDoc} */
  939. protected void renderWord(WordArea word) {
  940. Font font = getFontFromArea(word.getParentArea());
  941. String s = word.getWord();
  942. int[][] dp = word.getGlyphPositionAdjustments();
  943. Area parentArea = word.getParentArea();
  944. assert (parentArea instanceof AbstractTextArea);
  945. if (dp == null) {
  946. renderTextWithAdjustments(s, word.getLetterAdjustArray(), word.isReversed(),
  947. font, (AbstractTextArea) parentArea);
  948. } else if (IFUtil.isDPOnlyDX(dp)) {
  949. renderTextWithAdjustments(s, IFUtil.convertDPToDX(dp), word.isReversed(),
  950. font, (AbstractTextArea) parentArea);
  951. } else {
  952. renderTextWithAdjustments(s, dp, word.isReversed(),
  953. font, (AbstractTextArea) parentArea);
  954. }
  955. super.renderWord(word);
  956. }
  957. /** {@inheritDoc} */
  958. protected void renderSpace(SpaceArea space) {
  959. Font font = getFontFromArea(space.getParentArea());
  960. String s = space.getSpace();
  961. Area parentArea = space.getParentArea();
  962. assert (parentArea instanceof AbstractTextArea);
  963. AbstractTextArea textArea = (AbstractTextArea) parentArea;
  964. renderTextWithAdjustments(s, (int[]) null, false, font, textArea);
  965. /* COMBINED is always false
  966. if (textUtil.COMBINED && space.isAdjustable()) {
  967. //Used for justified text, for example
  968. int tws = textArea.getTextWordSpaceAdjust()
  969. + 2 * textArea.getTextLetterSpaceAdjust();
  970. if (tws != 0) {
  971. textUtil.adjust(tws);
  972. }
  973. }
  974. */
  975. super.renderSpace(space);
  976. }
  977. /**
  978. * Does low-level rendering of text using DX only position adjustments.
  979. * @param s text to render
  980. * @param dx an array of widths for letter adjustment (may be null)
  981. * @param reversed if true then text has been reversed (from logical order)
  982. * @param font to font in use
  983. * @param parentArea the parent text area to retrieve certain traits from
  984. */
  985. private void renderTextWithAdjustments(String s,
  986. int[] dx, boolean reversed,
  987. Font font, AbstractTextArea parentArea) {
  988. int l = s.length();
  989. if (l == 0) {
  990. return;
  991. }
  992. for (int i = 0; i < l; i++) {
  993. char ch = s.charAt(i);
  994. textUtil.addChar(ch);
  995. int glyphAdjust = 0;
  996. /* COMBINED is always false
  997. if (textUtil.COMBINED && font.hasChar(ch)) {
  998. int tls = (i < l - 1 ? parentArea.getTextLetterSpaceAdjust() : 0);
  999. glyphAdjust += tls;
  1000. }
  1001. */
  1002. if (dx != null && i < l) {
  1003. glyphAdjust += dx[i];
  1004. }
  1005. textUtil.adjust(glyphAdjust);
  1006. }
  1007. }
  1008. /**
  1009. * Does low-level rendering of text using generalized position adjustments.
  1010. * @param s text to render
  1011. * @param dp an array of 4-tuples, expressing [X,Y] placment
  1012. * adjustments and [X,Y] advancement adjustments, in that order (may be null)
  1013. * @param reversed if true then text has been reversed (from logical order)
  1014. * @param font to font in use
  1015. * @param parentArea the parent text area to retrieve certain traits from
  1016. */
  1017. private void renderTextWithAdjustments(String s,
  1018. int[][] dp, boolean reversed,
  1019. Font font, AbstractTextArea parentArea) {
  1020. // assert !textUtil.COMBINED;
  1021. for (int i = 0, n = s.length(); i < n; i++) {
  1022. textUtil.addChar(s.charAt(i));
  1023. if (dp != null) {
  1024. textUtil.adjust(dp[i]);
  1025. }
  1026. }
  1027. }
  1028. private class TextUtil {
  1029. private static final int INITIAL_BUFFER_SIZE = 16;
  1030. private int[][] dp = new int[INITIAL_BUFFER_SIZE][];
  1031. private final StringBuffer text = new StringBuffer();
  1032. private int startx;
  1033. private int starty;
  1034. private int tls;
  1035. private int tws;
  1036. // private final static boolean COMBINED = false; // no longer referenced
  1037. void addChar(char ch) {
  1038. text.append(ch);
  1039. }
  1040. void adjust(int dx) {
  1041. if (dx != 0) {
  1042. adjust(new int[] {
  1043. dx, // xPlaAdjust
  1044. 0, // yPlaAdjust
  1045. dx, // xAdvAdjust
  1046. 0 // yAdvAdjust
  1047. });
  1048. }
  1049. }
  1050. void adjust(int[] pa) {
  1051. if (!IFUtil.isPAIdentity(pa)) {
  1052. int idx = text.length();
  1053. if (idx > dp.length - 1) {
  1054. int newSize = Math.max(dp.length, idx + 1) + INITIAL_BUFFER_SIZE;
  1055. int[][] newDP = new int[newSize][];
  1056. // reuse prior DP[0]...DP[dp.length-1]
  1057. System.arraycopy(dp, 0, newDP, 0, dp.length);
  1058. // switch to new DP, leaving DP[dp.length]...DP[newDP.length-1] unpopulated
  1059. dp = newDP;
  1060. }
  1061. if (dp[idx - 1] == null) {
  1062. dp[idx - 1] = new int[4];
  1063. }
  1064. IFUtil.adjustPA(dp[idx - 1], pa);
  1065. }
  1066. }
  1067. void reset() {
  1068. if (text.length() > 0) {
  1069. text.setLength(0);
  1070. for (int i = 0, n = dp.length; i < n; i++) {
  1071. dp[i] = null;
  1072. }
  1073. }
  1074. }
  1075. void setStartPosition(int x, int y) {
  1076. this.startx = x;
  1077. this.starty = y;
  1078. }
  1079. void setSpacing(int tls, int tws) {
  1080. this.tls = tls;
  1081. this.tws = tws;
  1082. }
  1083. void flush() {
  1084. if (text.length() > 0) {
  1085. try {
  1086. /* if (COMBINED) { // COMBINED is always false
  1087. painter.drawText(startx, starty, 0, 0,
  1088. trimAdjustments(dp, text.length()), text.toString());
  1089. } else { */
  1090. painter.drawText(startx, starty, tls, tws,
  1091. trimAdjustments(dp, text.length()), text.toString());
  1092. /* } */
  1093. } catch (IFException e) {
  1094. handleIFException(e);
  1095. }
  1096. reset();
  1097. }
  1098. }
  1099. /**
  1100. * Trim adjustments array <code>dp</code> to be no greater length than
  1101. * text length, and where trailing all-zero entries are removed.
  1102. * @param dp a position adjustments array (or null)
  1103. * @param textLength the length of the associated text
  1104. * @return either the original value of <code>dp</code> or a copy
  1105. * of its first N significant adjustment entries, such that N is
  1106. * no greater than text length, and the last entry has a non-zero
  1107. * adjustment.
  1108. */
  1109. private int[][] trimAdjustments(int[][] dp, int textLength) {
  1110. if (dp != null) {
  1111. int tl = textLength;
  1112. int pl = dp.length;
  1113. int i = (tl < pl) ? tl : pl;
  1114. while (i > 0) {
  1115. int[] pa = dp [ i - 1 ];
  1116. if ((pa != null) && !IFUtil.isPAIdentity(pa)) {
  1117. break;
  1118. } else {
  1119. i--;
  1120. }
  1121. }
  1122. if (i == 0) {
  1123. dp = null;
  1124. } else if (i < pl) {
  1125. dp = IFUtil.copyDP(dp, 0, i);
  1126. }
  1127. }
  1128. return dp;
  1129. }
  1130. }
  1131. /** {@inheritDoc} */
  1132. public void renderImage(Image image, Rectangle2D pos) {
  1133. drawImage(image.getURL(), pos, image.getForeignAttributes());
  1134. }
  1135. /** {@inheritDoc} */
  1136. protected void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) {
  1137. Rectangle posInt = new Rectangle(
  1138. currentIPPosition + (int)pos.getX(),
  1139. currentBPPosition + (int)pos.getY(),
  1140. (int)pos.getWidth(),
  1141. (int)pos.getHeight());
  1142. uri = URISpecification.getURL(uri);
  1143. try {
  1144. establishForeignAttributes(foreignAttributes);
  1145. painter.drawImage(uri, posInt);
  1146. resetForeignAttributes();
  1147. } catch (IFException ife) {
  1148. handleIFException(ife);
  1149. }
  1150. }
  1151. /** {@inheritDoc} */
  1152. public void renderForeignObject(ForeignObject fo, Rectangle2D pos) {
  1153. endTextObject();
  1154. Rectangle posInt = new Rectangle(
  1155. currentIPPosition + (int)pos.getX(),
  1156. currentBPPosition + (int)pos.getY(),
  1157. (int)pos.getWidth(),
  1158. (int)pos.getHeight());
  1159. Document doc = fo.getDocument();
  1160. try {
  1161. establishForeignAttributes(fo.getForeignAttributes());
  1162. painter.drawImage(doc, posInt);
  1163. resetForeignAttributes();
  1164. } catch (IFException ife) {
  1165. handleIFException(ife);
  1166. }
  1167. }
  1168. /** {@inheritDoc} */
  1169. public void renderLeader(Leader area) {
  1170. renderInlineAreaBackAndBorders(area);
  1171. int style = area.getRuleStyle();
  1172. int ruleThickness = area.getRuleThickness();
  1173. int startx = currentIPPosition + area.getBorderAndPaddingWidthStart();
  1174. int starty = currentBPPosition + area.getBlockProgressionOffset() + (ruleThickness / 2);
  1175. int endx = currentIPPosition
  1176. + area.getBorderAndPaddingWidthStart()
  1177. + area.getIPD();
  1178. Color col = (Color)area.getTrait(Trait.COLOR);
  1179. Point start = new Point(startx, starty);
  1180. Point end = new Point(endx, starty);
  1181. try {
  1182. painter.drawLine(start, end, ruleThickness, col, RuleStyle.valueOf(style));
  1183. } catch (IFException ife) {
  1184. handleIFException(ife);
  1185. }
  1186. super.renderLeader(area);
  1187. }
  1188. /** {@inheritDoc} */
  1189. protected void clip() {
  1190. throw new IllegalStateException("Not used");
  1191. }
  1192. /** {@inheritDoc} */
  1193. protected void clipRect(float x, float y, float width, float height) {
  1194. pushGroup(new IFGraphicContext.Group());
  1195. try {
  1196. painter.clipRect(toMillipointRectangle(x, y, width, height));
  1197. } catch (IFException ife) {
  1198. handleIFException(ife);
  1199. }
  1200. }
  1201. /** {@inheritDoc} */
  1202. protected void clipBackground(float startx, float starty,
  1203. float width, float height,
  1204. BorderProps bpsBefore, BorderProps bpsAfter,
  1205. BorderProps bpsStart, BorderProps bpsEnd) {
  1206. pushGroup(new IFGraphicContext.Group());
  1207. Rectangle rect = toMillipointRectangle(startx, starty, width, height);
  1208. try {
  1209. painter.clipBackground(rect,
  1210. bpsBefore, bpsAfter, bpsStart, bpsEnd);
  1211. } catch (IFException ife) {
  1212. handleIFException(ife);
  1213. }
  1214. }
  1215. /** {@inheritDoc} */
  1216. protected void closePath() {
  1217. throw new IllegalStateException("Not used");
  1218. }
  1219. /** {@inheritDoc} */
  1220. protected void drawBackground(float startx, float starty,
  1221. float width, float height,
  1222. Trait.Background back,
  1223. BorderProps bpsBefore, BorderProps bpsAfter,
  1224. BorderProps bpsStart, BorderProps bpsEnd) {
  1225. if (painter.isBackgroundRequired(bpsBefore, bpsAfter, bpsStart, bpsEnd)) {
  1226. super.drawBackground(startx, starty, width, height,
  1227. back, bpsBefore, bpsAfter,
  1228. bpsStart, bpsEnd);
  1229. }
  1230. }
  1231. /** {@inheritDoc} */
  1232. protected void drawBorders(float startx, float starty,
  1233. float width, float height,
  1234. BorderProps bpsBefore, BorderProps bpsAfter,
  1235. BorderProps bpsStart, BorderProps bpsEnd, int level, Color innerBackgroundColor) {
  1236. Rectangle rect = toMillipointRectangle(startx, starty, width, height);
  1237. try {
  1238. BorderProps bpsTop = bpsBefore;
  1239. BorderProps bpsBottom = bpsAfter;
  1240. BorderProps bpsLeft;
  1241. BorderProps bpsRight;
  1242. if ((level == -1) || ((level & 1) == 0)) {
  1243. bpsLeft = bpsStart;
  1244. bpsRight = bpsEnd;
  1245. } else {
  1246. bpsLeft = bpsEnd;
  1247. bpsRight = bpsStart;
  1248. }
  1249. painter.drawBorderRect(rect, bpsTop, bpsBottom, bpsLeft, bpsRight, innerBackgroundColor);
  1250. } catch (IFException ife) {
  1251. handleIFException(ife);
  1252. }
  1253. }
  1254. /** {@inheritDoc} */
  1255. protected void drawBorderLine(float x1, float y1, float x2, float y2, boolean horz,
  1256. boolean startOrBefore, int style, Color col) {
  1257. //Simplified implementation that is only used by renderTextDecoration()
  1258. //drawBorders() is overridden and uses the Painter's high-level method drawBorderRect()
  1259. updateColor(col, true);
  1260. fillRect(x1, y1, x2 - x1, y2 - y1);
  1261. }
  1262. private int toMillipoints(float coordinate) {
  1263. return Math.round(coordinate * 1000);
  1264. }
  1265. private Rectangle toMillipointRectangle(float x, float y, float width, float height) {
  1266. return new Rectangle(
  1267. toMillipoints(x),
  1268. toMillipoints(y),
  1269. toMillipoints(width),
  1270. toMillipoints(height));
  1271. }
  1272. /** {@inheritDoc} */
  1273. protected void fillRect(float x, float y, float width, float height) {
  1274. try {
  1275. painter.fillRect(
  1276. toMillipointRectangle(x, y, width, height),
  1277. this.graphicContext.getPaint());
  1278. } catch (IFException e) {
  1279. handleIFException(e);
  1280. }
  1281. }
  1282. /** {@inheritDoc} */
  1283. protected void moveTo(float x, float y) {
  1284. throw new IllegalStateException("Not used");
  1285. }
  1286. /** {@inheritDoc} */
  1287. protected void lineTo(float x, float y) {
  1288. throw new IllegalStateException("Not used");
  1289. }
  1290. /** {@inheritDoc} */
  1291. protected void updateColor(Color col, boolean fill) {
  1292. if (fill) {
  1293. this.graphicContext.setPaint(col);
  1294. } else {
  1295. this.graphicContext.setColor(col);
  1296. }
  1297. }
  1298. }