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.

AreaTreeParser.java 50KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  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.area;
  19. import java.awt.Color;
  20. import java.awt.geom.Rectangle2D;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Set;
  24. import java.util.Stack;
  25. import java.util.StringTokenizer;
  26. import javax.xml.transform.Source;
  27. import javax.xml.transform.Transformer;
  28. import javax.xml.transform.TransformerConfigurationException;
  29. import javax.xml.transform.TransformerException;
  30. import javax.xml.transform.dom.DOMResult;
  31. import javax.xml.transform.sax.SAXResult;
  32. import javax.xml.transform.sax.SAXTransformerFactory;
  33. import javax.xml.transform.sax.TransformerHandler;
  34. import org.w3c.dom.DOMImplementation;
  35. import org.w3c.dom.Document;
  36. import org.xml.sax.Attributes;
  37. import org.xml.sax.ContentHandler;
  38. import org.xml.sax.SAXException;
  39. import org.xml.sax.helpers.DefaultHandler;
  40. import org.apache.commons.logging.Log;
  41. import org.apache.commons.logging.LogFactory;
  42. import org.apache.xmlgraphics.image.loader.ImageInfo;
  43. import org.apache.xmlgraphics.image.loader.ImageManager;
  44. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  45. import org.apache.fop.apps.FOUserAgent;
  46. import org.apache.fop.area.Trait.Background;
  47. import org.apache.fop.area.Trait.InternalLink;
  48. import org.apache.fop.area.inline.AbstractTextArea;
  49. import org.apache.fop.area.inline.Character;
  50. import org.apache.fop.area.inline.ForeignObject;
  51. import org.apache.fop.area.inline.Image;
  52. import org.apache.fop.area.inline.InlineArea;
  53. import org.apache.fop.area.inline.InlineBlockParent;
  54. import org.apache.fop.area.inline.InlineParent;
  55. import org.apache.fop.area.inline.Leader;
  56. import org.apache.fop.area.inline.Space;
  57. import org.apache.fop.area.inline.SpaceArea;
  58. import org.apache.fop.area.inline.TextArea;
  59. import org.apache.fop.area.inline.Viewport;
  60. import org.apache.fop.area.inline.WordArea;
  61. import org.apache.fop.fo.Constants;
  62. import org.apache.fop.fo.ElementMappingRegistry;
  63. import org.apache.fop.fo.expr.PropertyException;
  64. import org.apache.fop.fo.extensions.ExtensionAttachment;
  65. import org.apache.fop.fonts.Font;
  66. import org.apache.fop.fonts.FontInfo;
  67. import org.apache.fop.traits.BorderProps;
  68. import org.apache.fop.util.ColorUtil;
  69. import org.apache.fop.util.ContentHandlerFactory;
  70. import org.apache.fop.util.ContentHandlerFactoryRegistry;
  71. import org.apache.fop.util.DefaultErrorListener;
  72. import org.apache.fop.util.QName;
  73. /**
  74. * This is a parser for the area tree XML (intermediate format) which is used to reread an area
  75. * tree (or part of it) into memory again for rendering to the final output format.
  76. */
  77. public class AreaTreeParser {
  78. /** Logger instance */
  79. protected static Log log = LogFactory.getLog(AreaTreeParser.class);
  80. private static SAXTransformerFactory tFactory
  81. = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
  82. /**
  83. * Parses an intermediate file (area tree XML) into an AreaTreeModel instance by adding
  84. * pages to it.
  85. * @param src the Source instance pointing to the intermediate file
  86. * @param treeModel the AreaTreeModel that the parsed pages are added to
  87. * @param userAgent the user agent
  88. * @throws TransformerException if an error occurs while parsing the area tree XML
  89. */
  90. public void parse(Source src, AreaTreeModel treeModel, FOUserAgent userAgent)
  91. throws TransformerException {
  92. Transformer transformer = tFactory.newTransformer();
  93. transformer.setErrorListener(new DefaultErrorListener(log));
  94. SAXResult res = new SAXResult(getContentHandler(treeModel, userAgent));
  95. transformer.transform(src, res);
  96. }
  97. /**
  98. * Creates a new ContentHandler instance that you can send the area tree XML to. The parsed
  99. * pages are added to the AreaTreeModel instance you pass in as a parameter.
  100. * @param treeModel the AreaTreeModel that the parsed pages are added to
  101. * @param userAgent the user agent
  102. * @return the ContentHandler instance to receive the SAX stream from the area tree XML
  103. */
  104. public ContentHandler getContentHandler(AreaTreeModel treeModel, FOUserAgent userAgent) {
  105. ElementMappingRegistry elementMappingRegistry
  106. = userAgent.getFactory().getElementMappingRegistry();
  107. return new Handler(treeModel, userAgent, elementMappingRegistry);
  108. }
  109. private static class Handler extends DefaultHandler {
  110. private Map makers = new java.util.HashMap();
  111. private AreaTreeModel treeModel;
  112. private FOUserAgent userAgent;
  113. private ElementMappingRegistry elementMappingRegistry;
  114. private Attributes lastAttributes;
  115. private StringBuffer content = new StringBuffer();
  116. private PageViewport currentPageViewport;
  117. private Map pageViewportsByKey = new java.util.HashMap();
  118. // set of "ID firsts" that have already been assigned to a PV:
  119. private Set idFirstsAssigned = new java.util.HashSet();
  120. private Stack areaStack = new Stack();
  121. private boolean firstFlow;
  122. private boolean pendingStartPageSequence;
  123. private Stack delegateStack = new Stack();
  124. private ContentHandler delegate;
  125. private DOMImplementation domImplementation;
  126. public Handler(AreaTreeModel treeModel, FOUserAgent userAgent,
  127. ElementMappingRegistry elementMappingRegistry) {
  128. this.treeModel = treeModel;
  129. this.userAgent = userAgent;
  130. this.elementMappingRegistry = elementMappingRegistry;
  131. makers.put("areaTree", new AreaTreeMaker());
  132. makers.put("page", new PageMaker());
  133. makers.put("pageSequence", new PageSequenceMaker());
  134. makers.put("title", new TitleMaker());
  135. makers.put("pageViewport", new PageViewportMaker());
  136. makers.put("regionViewport", new RegionViewportMaker());
  137. makers.put("regionBefore", new RegionBeforeMaker());
  138. makers.put("regionAfter", new RegionAfterMaker());
  139. makers.put("regionStart", new RegionStartMaker());
  140. makers.put("regionEnd", new RegionEndMaker());
  141. makers.put("regionBody", new RegionBodyMaker());
  142. makers.put("flow", new FlowMaker());
  143. makers.put("mainReference", new MainReferenceMaker());
  144. makers.put("span", new SpanMaker());
  145. makers.put("footnote", new FootnoteMaker());
  146. makers.put("beforeFloat", new BeforeFloatMaker());
  147. makers.put("block", new BlockMaker());
  148. makers.put("lineArea", new LineAreaMaker());
  149. makers.put("inline", new InlineMaker());
  150. makers.put("inlineparent", new InlineParentMaker());
  151. makers.put("inlineblockparent", new InlineBlockParentMaker());
  152. makers.put("text", new TextMaker());
  153. makers.put("word", new WordMaker());
  154. makers.put("space", new SpaceMaker());
  155. makers.put("char", new CharMaker());
  156. makers.put("leader", new LeaderMaker());
  157. makers.put("viewport", new ViewportMaker());
  158. makers.put("image", new ImageMaker());
  159. makers.put("foreignObject", new ForeignObjectMaker());
  160. makers.put("bookmarkTree", new BookmarkTreeMaker());
  161. makers.put("bookmark", new BookmarkMaker());
  162. makers.put("destination", new DestinationMaker());
  163. }
  164. private static Rectangle2D parseRect(String rect) {
  165. StringTokenizer tokenizer = new StringTokenizer(rect, " ");
  166. return new Rectangle2D.Double(
  167. Double.parseDouble(tokenizer.nextToken()),
  168. Double.parseDouble(tokenizer.nextToken()),
  169. Double.parseDouble(tokenizer.nextToken()),
  170. Double.parseDouble(tokenizer.nextToken()));
  171. }
  172. private Area findAreaType(Class clazz) {
  173. if (areaStack.size() > 0) {
  174. int pos = areaStack.size() - 1;
  175. Object obj = null;
  176. while (pos >= 0 && !(clazz.isInstance(obj = areaStack.get(pos)))) {
  177. pos--;
  178. }
  179. if (pos >= 0) {
  180. return (Area)obj;
  181. }
  182. }
  183. return null;
  184. }
  185. private RegionViewport getCurrentRegionViewport() {
  186. return (RegionViewport)findAreaType(RegionViewport.class);
  187. }
  188. private BodyRegion getCurrentBodyRegion() {
  189. return (BodyRegion)findAreaType(BodyRegion.class);
  190. }
  191. private BlockParent getCurrentBlockParent() {
  192. return (BlockParent)findAreaType(BlockParent.class);
  193. }
  194. private AbstractTextArea getCurrentText() {
  195. return (AbstractTextArea)findAreaType(AbstractTextArea.class);
  196. }
  197. private Viewport getCurrentViewport() {
  198. return (Viewport)findAreaType(Viewport.class);
  199. }
  200. /** {@inheritDoc} */
  201. public void startElement(String uri, String localName, String qName, Attributes attributes)
  202. throws SAXException {
  203. if (delegate != null) {
  204. delegateStack.push(qName);
  205. delegate.startElement(uri, localName, qName, attributes);
  206. } else if (domImplementation != null) {
  207. //domImplementation is set so we need to start a new DOM building sub-process
  208. TransformerHandler handler;
  209. try {
  210. handler = tFactory.newTransformerHandler();
  211. } catch (TransformerConfigurationException e) {
  212. throw new SAXException("Error creating a new TransformerHandler", e);
  213. }
  214. Document doc = domImplementation.createDocument(uri, qName, null);
  215. //It's easier to work with an empty document, so remove the root element
  216. doc.removeChild(doc.getDocumentElement());
  217. handler.setResult(new DOMResult(doc));
  218. Area parent = (Area)areaStack.peek();
  219. ((ForeignObject)parent).setDocument(doc);
  220. //activate delegate for nested foreign document
  221. domImplementation = null; //Not needed anymore now
  222. this.delegate = handler;
  223. delegateStack.push(qName);
  224. delegate.startDocument();
  225. delegate.startElement(uri, localName, qName, attributes);
  226. } else {
  227. lastAttributes = attributes;
  228. boolean handled = true;
  229. if ("".equals(uri)) {
  230. Maker maker = (Maker)makers.get(localName);
  231. if (maker != null) {
  232. maker.startElement(attributes);
  233. } else if ("extension-attachments".equals(localName)) {
  234. //TODO implement me
  235. } else {
  236. handled = false;
  237. }
  238. } else {
  239. ContentHandlerFactoryRegistry registry
  240. = userAgent.getFactory().getContentHandlerFactoryRegistry();
  241. ContentHandlerFactory factory = registry.getFactory(uri);
  242. if (factory != null) {
  243. delegate = factory.createContentHandler();
  244. delegateStack.push(qName);
  245. delegate.startDocument();
  246. delegate.startElement(uri, localName, qName, attributes);
  247. } else {
  248. handled = false;
  249. }
  250. }
  251. if (!handled) {
  252. if (uri == null || uri.length() == 0) {
  253. throw new SAXException("Unhandled element " + localName
  254. + " in namespace: " + uri);
  255. } else {
  256. log.warn("Unhandled element " + localName
  257. + " in namespace: " + uri);
  258. }
  259. }
  260. }
  261. }
  262. /** {@inheritDoc} */
  263. public void endElement(String uri, String localName, String qName) throws SAXException {
  264. if (delegate != null) {
  265. delegate.endElement(uri, localName, qName);
  266. delegateStack.pop();
  267. if (delegateStack.size() == 0) {
  268. delegate.endDocument();
  269. if (delegate instanceof ContentHandlerFactory.ObjectSource) {
  270. Object obj = ((ContentHandlerFactory.ObjectSource)delegate).getObject();
  271. handleExternallyGeneratedObject(obj);
  272. }
  273. delegate = null; //Sub-document is processed, return to normal processing
  274. }
  275. } else {
  276. if ("".equals(uri)) {
  277. Maker maker = (Maker)makers.get(localName);
  278. if (maker != null) {
  279. maker.endElement();
  280. }
  281. } else {
  282. //log.debug("Ignoring " + localName + " in namespace: " + uri);
  283. }
  284. content.setLength(0); //Reset text buffer (see characters())
  285. }
  286. }
  287. // ============== Maker classes for the area tree objects =============
  288. private static interface Maker {
  289. void startElement(Attributes attributes) throws SAXException;
  290. void endElement();
  291. }
  292. private abstract class AbstractMaker implements Maker {
  293. public void startElement(Attributes attributes) throws SAXException {
  294. //nop
  295. }
  296. public void endElement() {
  297. //nop
  298. }
  299. }
  300. private class AreaTreeMaker extends AbstractMaker {
  301. public void startElement(Attributes attributes) {
  302. // In case the Handler is reused:
  303. idFirstsAssigned.clear();
  304. }
  305. }
  306. private class PageSequenceMaker extends AbstractMaker {
  307. public void startElement(Attributes attributes) {
  308. pendingStartPageSequence = true;
  309. //treeModel.startPageSequence(null); Done after title or on the first viewport
  310. }
  311. }
  312. private class TitleMaker extends AbstractMaker {
  313. public void startElement(Attributes attributes) {
  314. LineArea line = new LineArea();
  315. transferForeignObjects(attributes, line);
  316. areaStack.push(line);
  317. }
  318. public void endElement() {
  319. LineArea line = (LineArea)areaStack.pop();
  320. treeModel.startPageSequence(line);
  321. pendingStartPageSequence = false;
  322. }
  323. }
  324. private class PageViewportMaker extends AbstractMaker {
  325. public void startElement(Attributes attributes) {
  326. if (pendingStartPageSequence) {
  327. treeModel.startPageSequence(null);
  328. pendingStartPageSequence = false;
  329. }
  330. if (currentPageViewport != null) {
  331. throw new IllegalStateException("currentPageViewport must be null");
  332. }
  333. Rectangle2D viewArea = parseRect(attributes.getValue("bounds"));
  334. int pageNumber = getAttributeAsInteger(attributes, "nr", -1);
  335. String key = attributes.getValue("key");
  336. String pageNumberString = attributes.getValue("formatted-nr");
  337. String pageMaster = attributes.getValue("simple-page-master-name");
  338. boolean blank = getAttributeAsBoolean(attributes, "blank", false);
  339. currentPageViewport = new PageViewport(viewArea,
  340. pageNumber, pageNumberString,
  341. pageMaster, blank);
  342. transferForeignObjects(attributes, currentPageViewport);
  343. currentPageViewport.setKey(key);
  344. pageViewportsByKey.put(key, currentPageViewport);
  345. }
  346. }
  347. private class PageMaker extends AbstractMaker {
  348. public void startElement(Attributes attributes) {
  349. Page p = new Page();
  350. currentPageViewport.setPage(p);
  351. }
  352. public void endElement() {
  353. treeModel.addPage(currentPageViewport);
  354. currentPageViewport = null;
  355. }
  356. }
  357. private class RegionViewportMaker extends AbstractMaker {
  358. public void startElement(Attributes attributes) {
  359. RegionViewport rv = getCurrentRegionViewport();
  360. if (rv != null) {
  361. throw new IllegalStateException("Current RegionViewport must be null");
  362. }
  363. Rectangle2D viewArea = parseRect(attributes.getValue("rect"));
  364. rv = new RegionViewport(viewArea);
  365. transferForeignObjects(attributes, rv);
  366. rv.setClip(getAttributeAsBoolean(attributes, "clipped", false));
  367. setAreaAttributes(attributes, rv);
  368. setTraits(attributes, rv, SUBSET_COMMON);
  369. setTraits(attributes, rv, SUBSET_BOX);
  370. setTraits(attributes, rv, SUBSET_COLOR);
  371. areaStack.push(rv);
  372. }
  373. public void endElement() {
  374. assertObjectOfClass(areaStack.pop(), RegionViewport.class);
  375. }
  376. }
  377. private class RegionBeforeMaker extends AbstractMaker {
  378. public void startElement(Attributes attributes) {
  379. pushNewRegionReference(attributes, Constants.FO_REGION_BEFORE);
  380. }
  381. public void endElement() {
  382. assertObjectOfClass(areaStack.pop(), RegionReference.class);
  383. }
  384. }
  385. private class RegionAfterMaker extends AbstractMaker {
  386. public void startElement(Attributes attributes) {
  387. pushNewRegionReference(attributes, Constants.FO_REGION_AFTER);
  388. }
  389. public void endElement() {
  390. assertObjectOfClass(areaStack.pop(), RegionReference.class);
  391. }
  392. }
  393. private class RegionStartMaker extends AbstractMaker {
  394. public void startElement(Attributes attributes) {
  395. pushNewRegionReference(attributes, Constants.FO_REGION_START);
  396. }
  397. public void endElement() {
  398. assertObjectOfClass(areaStack.pop(), RegionReference.class);
  399. }
  400. }
  401. private class RegionEndMaker extends AbstractMaker {
  402. public void startElement(Attributes attributes) {
  403. pushNewRegionReference(attributes, Constants.FO_REGION_END);
  404. }
  405. public void endElement() {
  406. assertObjectOfClass(areaStack.pop(), RegionReference.class);
  407. }
  408. }
  409. private class RegionBodyMaker extends AbstractMaker {
  410. public void startElement(Attributes attributes) {
  411. BodyRegion body = getCurrentBodyRegion();
  412. if (body != null) {
  413. throw new IllegalStateException("Current BodyRegion must be null");
  414. }
  415. String regionName = attributes.getValue("name");
  416. int columnCount = getAttributeAsInteger(attributes, "columnCount", 1);
  417. int columnGap = getAttributeAsInteger(attributes, "columnGap", 0);
  418. RegionViewport rv = getCurrentRegionViewport();
  419. body = new BodyRegion(Constants.FO_REGION_BODY,
  420. regionName, rv, columnCount, columnGap);
  421. transferForeignObjects(attributes, body);
  422. body.setCTM(getAttributeAsCTM(attributes, "ctm"));
  423. setAreaAttributes(attributes, body);
  424. rv.setRegionReference(body);
  425. currentPageViewport.getPage().setRegionViewport(
  426. Constants.FO_REGION_BODY, rv);
  427. areaStack.push(body);
  428. }
  429. public void endElement() {
  430. assertObjectOfClass(areaStack.pop(), BodyRegion.class);
  431. }
  432. }
  433. private class FlowMaker extends AbstractMaker {
  434. public void startElement(Attributes attributes) {
  435. BodyRegion body = getCurrentBodyRegion();
  436. if (!firstFlow) {
  437. body.getMainReference().getCurrentSpan().moveToNextFlow();
  438. } else {
  439. firstFlow = false;
  440. }
  441. NormalFlow flow = body.getMainReference().getCurrentSpan().getCurrentFlow();
  442. transferForeignObjects(attributes, flow);
  443. setAreaAttributes(attributes, flow);
  444. areaStack.push(flow);
  445. }
  446. public void endElement() {
  447. assertObjectOfClass(areaStack.pop(), NormalFlow.class);
  448. }
  449. }
  450. private class MainReferenceMaker extends AbstractMaker {
  451. public void startElement(Attributes attributes) {
  452. //mainReference is created by the BodyRegion
  453. MainReference mr = getCurrentBodyRegion().getMainReference();
  454. transferForeignObjects(attributes, mr);
  455. setAreaAttributes(attributes, mr);
  456. }
  457. }
  458. private class SpanMaker extends AbstractMaker {
  459. public void startElement(Attributes attributes) {
  460. int ipd = getAttributeAsInteger(attributes, "ipd", 0);
  461. int columnCount = getAttributeAsInteger(attributes, "columnCount", 1);
  462. BodyRegion body = getCurrentBodyRegion();
  463. Span span = new Span(columnCount,
  464. body.getColumnGap(), ipd);
  465. transferForeignObjects(attributes, span);
  466. setAreaAttributes(attributes, span);
  467. body.getMainReference().getSpans().add(span);
  468. firstFlow = true;
  469. }
  470. }
  471. private class FootnoteMaker extends AbstractMaker {
  472. public void startElement(Attributes attributes) {
  473. Footnote fn = getCurrentBodyRegion().getFootnote();
  474. transferForeignObjects(attributes, fn);
  475. areaStack.push(fn);
  476. }
  477. public void endElement() {
  478. assertObjectOfClass(areaStack.pop(), Footnote.class);
  479. }
  480. }
  481. private class BeforeFloatMaker extends AbstractMaker {
  482. public void startElement(Attributes attributes) {
  483. BeforeFloat bf = getCurrentBodyRegion().getBeforeFloat();
  484. transferForeignObjects(attributes, bf);
  485. areaStack.push(bf);
  486. }
  487. public void endElement() {
  488. assertObjectOfClass(areaStack.pop(), BeforeFloat.class);
  489. }
  490. }
  491. private class BlockMaker extends AbstractMaker {
  492. public void startElement(Attributes attributes) {
  493. boolean isViewport = getAttributeAsBoolean(attributes,
  494. "is-viewport-area", false);
  495. Block block;
  496. if (isViewport) {
  497. BlockViewport bv = new BlockViewport();
  498. bv.setClip(getAttributeAsBoolean(attributes, "clipped", false));
  499. bv.setCTM(getAttributeAsCTM(attributes, "ctm"));
  500. if (bv.getPositioning() != BlockViewport.RELATIVE) {
  501. bv.setXOffset(
  502. getAttributeAsInteger(attributes, "left-position", 0));
  503. bv.setYOffset(
  504. getAttributeAsInteger(attributes, "top-position", 0));
  505. }
  506. block = bv;
  507. } else {
  508. block = new Block();
  509. }
  510. String positioning = attributes.getValue("positioning");
  511. if ("absolute".equalsIgnoreCase(positioning)) {
  512. block.setPositioning(Block.ABSOLUTE);
  513. } else if ("fixed".equalsIgnoreCase(positioning)) {
  514. block.setPositioning(Block.FIXED);
  515. } else if ("relative".equalsIgnoreCase(positioning)) {
  516. block.setPositioning(Block.RELATIVE);
  517. } else {
  518. block.setPositioning(Block.STACK);
  519. }
  520. if (attributes.getValue("left-offset") != null) {
  521. block.setXOffset(getAttributeAsInteger(attributes, "left-offset", 0));
  522. }
  523. if (attributes.getValue("top-offset") != null) {
  524. block.setYOffset(getAttributeAsInteger(attributes, "top-offset", 0));
  525. }
  526. transferForeignObjects(attributes, block);
  527. setAreaAttributes(attributes, block);
  528. setTraits(attributes, block, SUBSET_COMMON);
  529. setTraits(attributes, block, SUBSET_BOX);
  530. setTraits(attributes, block, SUBSET_COLOR);
  531. Area parent = (Area)areaStack.peek();
  532. //BlockParent parent = getCurrentBlockParent();
  533. parent.addChildArea(block);
  534. areaStack.push(block);
  535. }
  536. public void endElement() {
  537. assertObjectOfClass(areaStack.pop(), Block.class);
  538. }
  539. }
  540. private class LineAreaMaker extends AbstractMaker {
  541. public void startElement(Attributes attributes) {
  542. LineArea line = new LineArea();
  543. setAreaAttributes(attributes, line);
  544. setTraits(attributes, line, SUBSET_COMMON);
  545. setTraits(attributes, line, SUBSET_BOX);
  546. setTraits(attributes, line, SUBSET_COLOR);
  547. BlockParent parent = getCurrentBlockParent();
  548. parent.addChildArea(line);
  549. areaStack.push(line);
  550. }
  551. public void endElement() {
  552. assertObjectOfClass(areaStack.pop(), LineArea.class);
  553. }
  554. }
  555. // Maker for "generic" inline areas
  556. private class InlineMaker extends AbstractMaker {
  557. public void startElement(Attributes attributes) {
  558. InlineArea inl = new InlineArea();
  559. transferForeignObjects(attributes, inl);
  560. inl.setOffset(getAttributeAsInteger(attributes, "offset", 0));
  561. setAreaAttributes(attributes, inl);
  562. setTraits(attributes, inl, SUBSET_COMMON);
  563. setTraits(attributes, inl, SUBSET_BOX);
  564. setTraits(attributes, inl, SUBSET_COLOR);
  565. Area parent = (Area)areaStack.peek();
  566. parent.addChildArea(inl);
  567. areaStack.push(inl);
  568. }
  569. public void endElement() {
  570. assertObjectOfClass(areaStack.pop(), InlineArea.class);
  571. }
  572. }
  573. private class InlineParentMaker extends AbstractMaker {
  574. public void startElement(Attributes attributes) {
  575. InlineParent ip = new InlineParent();
  576. transferForeignObjects(attributes, ip);
  577. ip.setOffset(getAttributeAsInteger(attributes, "offset", 0));
  578. setAreaAttributes(attributes, ip);
  579. setTraits(attributes, ip, SUBSET_COMMON);
  580. setTraits(attributes, ip, SUBSET_BOX);
  581. setTraits(attributes, ip, SUBSET_COLOR);
  582. setTraits(attributes, ip, SUBSET_LINK);
  583. Area parent = (Area)areaStack.peek();
  584. parent.addChildArea(ip);
  585. areaStack.push(ip);
  586. }
  587. public void endElement() {
  588. assertObjectOfClass(areaStack.pop(), InlineParent.class);
  589. }
  590. }
  591. private class InlineBlockParentMaker extends AbstractMaker {
  592. public void startElement(Attributes attributes) {
  593. InlineBlockParent ibp = new InlineBlockParent();
  594. transferForeignObjects(attributes, ibp);
  595. ibp.setOffset(getAttributeAsInteger(attributes, "offset", 0));
  596. setAreaAttributes(attributes, ibp);
  597. setTraits(attributes, ibp, SUBSET_COMMON);
  598. setTraits(attributes, ibp, SUBSET_BOX);
  599. setTraits(attributes, ibp, SUBSET_COLOR);
  600. Area parent = (Area)areaStack.peek();
  601. parent.addChildArea(ibp);
  602. areaStack.push(ibp);
  603. }
  604. public void endElement() {
  605. assertObjectOfClass(areaStack.pop(), InlineBlockParent.class);
  606. }
  607. }
  608. private class TextMaker extends AbstractMaker {
  609. public void startElement(Attributes attributes) {
  610. if (getCurrentText() != null) {
  611. throw new IllegalStateException("Current Text must be null");
  612. }
  613. TextArea text = new TextArea();
  614. setAreaAttributes(attributes, text);
  615. setTraits(attributes, text, SUBSET_COMMON);
  616. setTraits(attributes, text, SUBSET_BOX);
  617. setTraits(attributes, text, SUBSET_COLOR);
  618. setTraits(attributes, text, SUBSET_FONT);
  619. text.setBaselineOffset(getAttributeAsInteger(attributes, "baseline", 0));
  620. text.setOffset(getAttributeAsInteger(attributes, "offset", 0));
  621. text.setTextLetterSpaceAdjust(getAttributeAsInteger(attributes,
  622. "tlsadjust", 0));
  623. text.setTextWordSpaceAdjust(getAttributeAsInteger(attributes,
  624. "twsadjust", 0));
  625. Area parent = (Area)areaStack.peek();
  626. parent.addChildArea(text);
  627. areaStack.push(text);
  628. }
  629. public void endElement() {
  630. assertObjectOfClass(areaStack.pop(), TextArea.class);
  631. }
  632. }
  633. private class WordMaker extends AbstractMaker {
  634. private int[] toIntArray(String s) {
  635. if (s == null || s.length() == 0) {
  636. return null;
  637. }
  638. StringTokenizer tokenizer = new StringTokenizer(s, " ");
  639. List values = new java.util.ArrayList();
  640. while (tokenizer.hasMoreTokens()) {
  641. values.add(new Integer(tokenizer.nextToken()));
  642. }
  643. int[] res = new int[values.size()];
  644. for (int i = 0, c = res.length; i < c; i++) {
  645. res[i] = ((Integer)values.get(i)).intValue();
  646. }
  647. return res;
  648. }
  649. public void endElement() {
  650. int offset = getAttributeAsInteger(lastAttributes, "offset", 0);
  651. int[] letterAdjust = toIntArray(lastAttributes.getValue("letter-adjust"));
  652. String txt = content.toString();
  653. WordArea word = new WordArea(txt, offset, letterAdjust);
  654. AbstractTextArea text = getCurrentText();
  655. word.setParentArea(text);
  656. text.addChildArea(word);
  657. }
  658. }
  659. private class SpaceMaker extends AbstractMaker {
  660. public void endElement() {
  661. int offset = getAttributeAsInteger(lastAttributes, "offset", 0);
  662. String txt = content.toString();
  663. //TODO the isAdjustable parameter is currently not used/implemented
  664. if (txt.length() > 0) {
  665. boolean adjustable = getAttributeAsBoolean(lastAttributes, "adj", true);
  666. SpaceArea space = new SpaceArea(txt.charAt(0), offset, adjustable);
  667. AbstractTextArea text = getCurrentText();
  668. space.setParentArea(text);
  669. text.addChildArea(space);
  670. } else {
  671. Space space = new Space();
  672. setAreaAttributes(lastAttributes, space);
  673. setTraits(lastAttributes, space, SUBSET_COMMON);
  674. setTraits(lastAttributes, space, SUBSET_BOX);
  675. setTraits(lastAttributes, space, SUBSET_COLOR);
  676. space.setOffset(offset);
  677. Area parent = (Area)areaStack.peek();
  678. parent.addChildArea(space);
  679. }
  680. }
  681. }
  682. private class CharMaker extends AbstractMaker {
  683. public void endElement() {
  684. String txt = content.toString();
  685. Character ch = new Character(txt.charAt(0));
  686. transferForeignObjects(lastAttributes, ch);
  687. setAreaAttributes(lastAttributes, ch);
  688. setTraits(lastAttributes, ch, SUBSET_COMMON);
  689. setTraits(lastAttributes, ch, SUBSET_BOX);
  690. setTraits(lastAttributes, ch, SUBSET_COLOR);
  691. setTraits(lastAttributes, ch, SUBSET_FONT);
  692. ch.setOffset(getAttributeAsInteger(lastAttributes, "offset", 0));
  693. ch.setBaselineOffset(getAttributeAsInteger(lastAttributes, "baseline", 0));
  694. Area parent = (Area)areaStack.peek();
  695. parent.addChildArea(ch);
  696. }
  697. }
  698. private class LeaderMaker extends AbstractMaker {
  699. public void startElement(Attributes attributes) {
  700. Leader leader = new Leader();
  701. transferForeignObjects(attributes, leader);
  702. setAreaAttributes(attributes, leader);
  703. setTraits(attributes, leader, SUBSET_COMMON);
  704. setTraits(attributes, leader, SUBSET_BOX);
  705. setTraits(attributes, leader, SUBSET_COLOR);
  706. setTraits(attributes, leader, SUBSET_FONT);
  707. leader.setOffset(getAttributeAsInteger(attributes, "offset", 0));
  708. String ruleStyle = attributes.getValue("ruleStyle");
  709. if (ruleStyle != null) {
  710. leader.setRuleStyle(ruleStyle);
  711. }
  712. leader.setRuleThickness(
  713. getAttributeAsInteger(attributes, "ruleThickness", 0));
  714. Area parent = (Area)areaStack.peek();
  715. parent.addChildArea(leader);
  716. }
  717. public void endElement() {
  718. }
  719. }
  720. private class ViewportMaker extends AbstractMaker {
  721. public void startElement(Attributes attributes) {
  722. Viewport viewport = new Viewport(null);
  723. transferForeignObjects(attributes, viewport);
  724. setAreaAttributes(attributes, viewport);
  725. setTraits(attributes, viewport, SUBSET_COMMON);
  726. setTraits(attributes, viewport, SUBSET_BOX);
  727. setTraits(attributes, viewport, SUBSET_COLOR);
  728. viewport.setContentPosition(getAttributeAsRectangle2D(attributes, "pos"));
  729. viewport.setClip(getAttributeAsBoolean(attributes, "clip", false));
  730. viewport.setOffset(getAttributeAsInteger(attributes, "offset", 0));
  731. Area parent = (Area)areaStack.peek();
  732. parent.addChildArea(viewport);
  733. areaStack.push(viewport);
  734. }
  735. public void endElement() {
  736. assertObjectOfClass(areaStack.pop(), Viewport.class);
  737. }
  738. }
  739. private class ImageMaker extends AbstractMaker {
  740. public void startElement(Attributes attributes) {
  741. String url = attributes.getValue("url");
  742. Image image = new Image(url);
  743. transferForeignObjects(attributes, image);
  744. setAreaAttributes(attributes, image);
  745. setTraits(attributes, image, SUBSET_COMMON);
  746. getCurrentViewport().setContent(image);
  747. }
  748. }
  749. private class ForeignObjectMaker extends AbstractMaker {
  750. public void startElement(Attributes attributes) throws SAXException {
  751. String ns = attributes.getValue("ns");
  752. domImplementation
  753. = elementMappingRegistry.getDOMImplementationForNamespace(ns);
  754. if (domImplementation == null) {
  755. throw new SAXException("No DOMImplementation could be"
  756. + " identified to handle namespace: " + ns);
  757. }
  758. ForeignObject foreign = new ForeignObject(ns);
  759. transferForeignObjects(attributes, foreign);
  760. setAreaAttributes(attributes, foreign);
  761. setTraits(attributes, foreign, SUBSET_COMMON);
  762. getCurrentViewport().setContent(foreign);
  763. areaStack.push(foreign);
  764. }
  765. public void endElement() {
  766. assertObjectOfClass(areaStack.pop(), ForeignObject.class);
  767. }
  768. }
  769. private class BookmarkTreeMaker extends AbstractMaker {
  770. public void startElement(Attributes attributes) {
  771. BookmarkData bm = new BookmarkData();
  772. areaStack.push(bm);
  773. }
  774. public void endElement() {
  775. Object tos = areaStack.pop();
  776. assertObjectOfClass(tos, BookmarkData.class);
  777. treeModel.handleOffDocumentItem((BookmarkData) tos);
  778. // as long as the bookmark tree comes after the last PageViewport in the
  779. // area tree XML, we don't have to worry about resolved/unresolved. The
  780. // only resolution needed is the mapping of the pvKey to the PV instance.
  781. }
  782. }
  783. private class BookmarkMaker extends AbstractMaker {
  784. public void startElement(Attributes attributes) {
  785. String title = attributes.getValue("title");
  786. boolean showChildren = getAttributeAsBoolean(attributes, "show-children", false);
  787. String[] linkdata
  788. = InternalLink.parseXMLAttribute(attributes.getValue("internal-link"));
  789. PageViewport pv = (PageViewport) pageViewportsByKey.get(linkdata[0]);
  790. BookmarkData bm = new BookmarkData(title, showChildren, pv, linkdata[1]);
  791. Object tos = areaStack.peek();
  792. if (tos instanceof BookmarkData) {
  793. BookmarkData parent = (BookmarkData) tos;
  794. parent.addSubData(bm);
  795. }
  796. areaStack.push(bm);
  797. }
  798. public void endElement() {
  799. assertObjectOfClass(areaStack.pop(), BookmarkData.class);
  800. }
  801. }
  802. private class DestinationMaker extends AbstractMaker {
  803. public void startElement(Attributes attributes) {
  804. String[] linkdata
  805. = InternalLink.parseXMLAttribute(lastAttributes.getValue("internal-link"));
  806. PageViewport pv = (PageViewport) pageViewportsByKey.get(linkdata[0]);
  807. DestinationData dest = new DestinationData(linkdata[1]);
  808. List pages = new java.util.ArrayList();
  809. pages.add(pv);
  810. dest.resolveIDRef(linkdata[1], pages);
  811. areaStack.push(dest);
  812. }
  813. public void endElement() {
  814. Object tos = areaStack.pop();
  815. assertObjectOfClass(tos, DestinationData.class);
  816. treeModel.handleOffDocumentItem((DestinationData) tos);
  817. }
  818. }
  819. // ====================================================================
  820. private void pushNewRegionReference(Attributes attributes, int side) {
  821. String regionName = attributes.getValue("name");
  822. RegionViewport rv = getCurrentRegionViewport();
  823. RegionReference reg = new RegionReference(side,
  824. regionName, rv);
  825. transferForeignObjects(attributes, reg);
  826. reg.setCTM(getAttributeAsCTM(attributes, "ctm"));
  827. setAreaAttributes(attributes, reg);
  828. rv.setRegionReference(reg);
  829. currentPageViewport.getPage().setRegionViewport(
  830. side, rv);
  831. areaStack.push(reg);
  832. }
  833. private void assertObjectOfClass(Object obj, Class clazz) {
  834. if (!clazz.isInstance(obj)) {
  835. throw new IllegalStateException("Object is not an instance of "
  836. + clazz.getName() + " but of " + obj.getClass().getName());
  837. }
  838. }
  839. /**
  840. * Handles objects created by "sub-parsers" that implement the ObjectSource interface.
  841. * An example of object handled here are ExtensionAttachments.
  842. * @param obj the Object to be handled.
  843. */
  844. protected void handleExternallyGeneratedObject(Object obj) {
  845. if (areaStack.size() == 0 && obj instanceof ExtensionAttachment) {
  846. ExtensionAttachment attachment = (ExtensionAttachment)obj;
  847. if (this.currentPageViewport == null) {
  848. this.treeModel.handleOffDocumentItem(
  849. new OffDocumentExtensionAttachment(attachment));
  850. } else {
  851. this.currentPageViewport.addExtensionAttachment(attachment);
  852. }
  853. } else {
  854. log.warn("Don't know how to handle externally generated object: " + obj);
  855. }
  856. }
  857. private void setAreaAttributes(Attributes attributes, Area area) {
  858. area.setIPD(Integer.parseInt(attributes.getValue("ipd")));
  859. area.setBPD(Integer.parseInt(attributes.getValue("bpd")));
  860. }
  861. private static final Object[] SUBSET_COMMON = new Object[] {
  862. Trait.PROD_ID};
  863. private static final Object[] SUBSET_LINK = new Object[] {
  864. Trait.INTERNAL_LINK, Trait.EXTERNAL_LINK};
  865. private static final Object[] SUBSET_COLOR = new Object[] {
  866. Trait.BACKGROUND, Trait.COLOR};
  867. private static final Object[] SUBSET_FONT = new Object[] {
  868. Trait.FONT, Trait.FONT_SIZE, Trait.BLINK,
  869. Trait.OVERLINE, Trait.OVERLINE_COLOR,
  870. Trait.LINETHROUGH, Trait.LINETHROUGH_COLOR,
  871. Trait.UNDERLINE, Trait.UNDERLINE_COLOR};
  872. private static final Object[] SUBSET_BOX = new Object[] {
  873. Trait.BORDER_BEFORE, Trait.BORDER_AFTER, Trait.BORDER_START, Trait.BORDER_END,
  874. Trait.SPACE_BEFORE, Trait.SPACE_AFTER, Trait.SPACE_START, Trait.SPACE_END,
  875. Trait.PADDING_BEFORE, Trait.PADDING_AFTER, Trait.PADDING_START, Trait.PADDING_END,
  876. Trait.START_INDENT, Trait.END_INDENT,
  877. Trait.IS_REFERENCE_AREA, Trait.IS_VIEWPORT_AREA};
  878. private void setTraits(Attributes attributes, Area area, Object[] traitSubset) {
  879. for (int i = 0, c = traitSubset.length; i < c; i++) {
  880. Object trait = traitSubset[i];
  881. String traitName = Trait.getTraitName(trait);
  882. String value = attributes.getValue(traitName);
  883. if (value != null) {
  884. Class cl = Trait.getTraitClass(trait);
  885. if (cl == Integer.class) {
  886. area.addTrait(trait, new Integer(value));
  887. } else if (cl == Boolean.class) {
  888. area.addTrait(trait, Boolean.valueOf(value));
  889. } else if (cl == String.class) {
  890. area.addTrait(trait, value);
  891. if (trait == Trait.PROD_ID
  892. && !idFirstsAssigned.contains(value)
  893. && currentPageViewport != null) {
  894. currentPageViewport.setFirstWithID(value);
  895. idFirstsAssigned.add(value);
  896. }
  897. } else if (cl == Color.class) {
  898. try {
  899. area.addTrait(trait, ColorUtil.parseColorString(this.userAgent, value));
  900. } catch (PropertyException e) {
  901. throw new IllegalArgumentException(e.getMessage());
  902. }
  903. } else if (cl == InternalLink.class) {
  904. area.addTrait(trait, new InternalLink(value));
  905. } else if (cl == Background.class) {
  906. Background bkg = new Background();
  907. try {
  908. Color col = ColorUtil.parseColorString(
  909. this.userAgent, attributes.getValue("bkg-color"));
  910. bkg.setColor(col);
  911. } catch (PropertyException e) {
  912. throw new IllegalArgumentException(e.getMessage());
  913. }
  914. String uri = attributes.getValue("bkg-img");
  915. if (uri != null) {
  916. bkg.setURL(uri);
  917. try {
  918. ImageManager manager = userAgent.getFactory().getImageManager();
  919. ImageSessionContext sessionContext
  920. = userAgent.getImageSessionContext();
  921. ImageInfo info = manager.getImageInfo(uri, sessionContext);
  922. bkg.setImageInfo(info);
  923. } catch (Exception e) {
  924. log.error("Background image not available: " + uri, e);
  925. }
  926. String repeat = attributes.getValue("bkg-repeat");
  927. if (repeat != null) {
  928. bkg.setRepeat(repeat);
  929. }
  930. bkg.setHoriz(getAttributeAsInteger(attributes,
  931. "bkg-horz-offset", 0));
  932. bkg.setVertical(getAttributeAsInteger(attributes,
  933. "bkg-vert-offset", 0));
  934. }
  935. area.addTrait(trait, bkg);
  936. } else if (cl == BorderProps.class) {
  937. area.addTrait(trait, BorderProps.valueOf(this.userAgent, value));
  938. }
  939. } else {
  940. if (trait == Trait.FONT) {
  941. String fontName = attributes.getValue("font-name");
  942. if (fontName != null) {
  943. String fontStyle = attributes.getValue("font-style");
  944. int fontWeight = getAttributeAsInteger(
  945. attributes, "font-weight", Font.WEIGHT_NORMAL);
  946. area.addTrait(trait,
  947. FontInfo.createFontKey(fontName, fontStyle, fontWeight));
  948. }
  949. }
  950. }
  951. }
  952. }
  953. private boolean getAttributeAsBoolean(Attributes attributes, String name,
  954. boolean defaultValue) {
  955. String s = attributes.getValue(name);
  956. if (s == null) {
  957. return defaultValue;
  958. } else {
  959. return Boolean.valueOf(s).booleanValue();
  960. }
  961. }
  962. private int getAttributeAsInteger(Attributes attributes, String name,
  963. int defaultValue) {
  964. String s = attributes.getValue(name);
  965. if (s == null) {
  966. return defaultValue;
  967. } else {
  968. return Integer.parseInt(s);
  969. }
  970. }
  971. private CTM getAttributeAsCTM(Attributes attributes, String name) {
  972. String s = attributes.getValue(name).trim();
  973. if (s.startsWith("[") && s.endsWith("]")) {
  974. s = s.substring(1, s.length() - 1);
  975. StringTokenizer tokenizer = new StringTokenizer(s, " ");
  976. double[] values = new double[] {
  977. Double.parseDouble(tokenizer.nextToken()),
  978. Double.parseDouble(tokenizer.nextToken()),
  979. Double.parseDouble(tokenizer.nextToken()),
  980. Double.parseDouble(tokenizer.nextToken()),
  981. Double.parseDouble(tokenizer.nextToken()),
  982. Double.parseDouble(tokenizer.nextToken())};
  983. return new CTM(values[0], values[1], values[2], values[3], values[4], values[5]);
  984. } else {
  985. throw new IllegalArgumentException("CTM must be surrounded by square brackets");
  986. }
  987. }
  988. private Rectangle2D getAttributeAsRectangle2D(Attributes attributes, String name) {
  989. String s = attributes.getValue(name).trim();
  990. StringTokenizer tokenizer = new StringTokenizer(s, " ");
  991. double[] values = new double[] {
  992. Double.parseDouble(tokenizer.nextToken()),
  993. Double.parseDouble(tokenizer.nextToken()),
  994. Double.parseDouble(tokenizer.nextToken()),
  995. Double.parseDouble(tokenizer.nextToken())};
  996. return new Rectangle2D.Double(values[0], values[1], values[2], values[3]);
  997. }
  998. private void transferForeignObjects(Attributes atts, AreaTreeObject ato) {
  999. for (int i = 0, c = atts.getLength(); i < c; i++) {
  1000. String ns = atts.getURI(i);
  1001. if (ns.length() > 0) {
  1002. if ("http://www.w3.org/2000/xmlns/".equals(ns)) {
  1003. continue;
  1004. }
  1005. QName qname = new QName(ns, atts.getQName(i));
  1006. ato.setForeignAttribute(qname, atts.getValue(i));
  1007. }
  1008. }
  1009. }
  1010. /** {@inheritDoc} */
  1011. public void characters(char[] ch, int start, int length) throws SAXException {
  1012. if (delegate != null) {
  1013. delegate.characters(ch, start, length);
  1014. } else {
  1015. content.append(ch, start, length);
  1016. }
  1017. }
  1018. }
  1019. }