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

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