From e0edd215721150e6c04ac49706622d6189cb0b42 Mon Sep 17 00:00:00 2001
From: Tore Engvig
Date: Mon, 30 Jul 2001 20:29:35 +0000
Subject: [PATCH] Formatted code according to code standards. Changed license
to use short license.
git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@194380 13f79535-47bb-0310-9956-ffa450edef68
---
src/org/apache/fop/apps/AWTStarter.java | 47 +-
.../apache/fop/apps/CommandLineOptions.java | 498 +--
.../apache/fop/apps/CommandLineStarter.java | 54 +-
src/org/apache/fop/apps/Driver.java | 270 +-
src/org/apache/fop/apps/ErrorHandler.java | 59 +-
src/org/apache/fop/apps/FOInputHandler.java | 12 +-
src/org/apache/fop/apps/FOPException.java | 143 +-
src/org/apache/fop/apps/Fop.java | 14 +-
src/org/apache/fop/apps/InputHandler.java | 26 +-
src/org/apache/fop/apps/Options.java | 94 +-
src/org/apache/fop/apps/PDFOutputHandler.java | 354 +-
src/org/apache/fop/apps/PrintStarter.java | 29 +-
src/org/apache/fop/apps/Starter.java | 15 +-
src/org/apache/fop/apps/TraxInputHandler.java | 38 +-
src/org/apache/fop/apps/Version.java | 7 +-
src/org/apache/fop/apps/XSLTInputHandler.java | 39 +-
src/org/apache/fop/apps/XTDriver.java | 436 ++-
.../fop/configuration/Configuration.java | 360 +-
.../configuration/ConfigurationParser.java | 142 +-
.../configuration/ConfigurationReader.java | 83 +-
.../apache/fop/configuration/FontInfo.java | 10 +-
.../apache/fop/configuration/FontTriplet.java | 3 +-
src/org/apache/fop/datatypes/ColorSpace.java | 34 +-
src/org/apache/fop/datatypes/ColorType.java | 1161 +++---
.../fop/datatypes/CompoundDatatype.java | 61 +-
src/org/apache/fop/datatypes/CondLength.java | 109 +-
src/org/apache/fop/datatypes/IDNode.java | 195 +-
.../apache/fop/datatypes/IDReferences.java | 246 +-
src/org/apache/fop/datatypes/Keep.java | 11 +-
src/org/apache/fop/datatypes/KeepValue.java | 65 +-
src/org/apache/fop/datatypes/Length.java | 230 +-
src/org/apache/fop/datatypes/LengthBase.java | 60 +-
src/org/apache/fop/datatypes/LengthPair.java | 6 +-
src/org/apache/fop/datatypes/LengthRange.java | 103 +-
.../datatypes/LinearCombinationLength.java | 66 +-
src/org/apache/fop/datatypes/MixedLength.java | 99 +-
src/org/apache/fop/datatypes/PercentBase.java | 61 +-
.../apache/fop/datatypes/PercentLength.java | 114 +-
src/org/apache/fop/datatypes/Space.java | 16 +-
.../apache/fop/datatypes/TableColLength.java | 110 +-
.../apache/fop/datatypes/ToBeImplemented.java | 7 +-
.../datatypes/ToBeImplementedProperty.java | 9 +-
.../extensions/ExtensionElementMapping.java | 13 +-
.../apache/fop/extensions/ExtensionObj.java | 80 +-
src/org/apache/fop/extensions/Label.java | 86 +-
src/org/apache/fop/extensions/Outline.java | 188 +-
.../apache/fop/fo/BoxPropShorthandParser.java | 58 +-
src/org/apache/fop/fo/CharacterProperty.java | 88 +-
src/org/apache/fop/fo/ColorProfile.java | 12 +-
src/org/apache/fop/fo/ColorTypeProperty.java | 106 +-
src/org/apache/fop/fo/CondLengthProperty.java | 88 +-
src/org/apache/fop/fo/Declarations.java | 6 +-
src/org/apache/fop/fo/ElementMapping.java | 3 +-
src/org/apache/fop/fo/EnumProperty.java | 109 +-
src/org/apache/fop/fo/FONode.java | 290 +-
src/org/apache/fop/fo/FOText.java | 484 +--
src/org/apache/fop/fo/FOTreeBuilder.java | 65 +-
src/org/apache/fop/fo/FObj.java | 258 +-
src/org/apache/fop/fo/FObjMixed.java | 37 +-
.../apache/fop/fo/GenericShorthandParser.java | 92 +-
src/org/apache/fop/fo/KeepProperty.java | 80 +-
src/org/apache/fop/fo/LengthPairProperty.java | 28 +-
src/org/apache/fop/fo/LengthProperty.java | 176 +-
.../apache/fop/fo/LengthRangeProperty.java | 80 +-
src/org/apache/fop/fo/ListProperty.java | 54 +-
src/org/apache/fop/fo/NumberProperty.java | 146 +-
src/org/apache/fop/fo/Property.java | 704 ++--
src/org/apache/fop/fo/PropertyList.java | 633 ++--
.../apache/fop/fo/PropertyListBuilder.java | 443 ++-
src/org/apache/fop/fo/PropertyManager.java | 204 +-
src/org/apache/fop/fo/ShorthandParser.java | 12 +-
src/org/apache/fop/fo/SpaceProperty.java | 86 +-
.../apache/fop/fo/StandardElementMapping.java | 26 +-
src/org/apache/fop/fo/Status.java | 89 +-
src/org/apache/fop/fo/StringProperty.java | 131 +-
src/org/apache/fop/fo/Title.java | 6 +-
.../apache/fop/fo/ToBeImplementedElement.java | 16 +-
src/org/apache/fop/fo/TreeBuilder.java | 67 +-
src/org/apache/fop/fo/XTElementMapping.java | 55 +-
src/org/apache/fop/fo/XTFOTreeBuilder.java | 212 +-
src/org/apache/fop/fo/expr/AbsFunction.java | 77 +-
.../apache/fop/fo/expr/BodyStartFunction.java | 90 +-
.../apache/fop/fo/expr/CeilingFunction.java | 75 +-
src/org/apache/fop/fo/expr/FloorFunction.java | 75 +-
.../fop/fo/expr/FopPropValFunction.java | 78 +-
.../fop/fo/expr/FromParentFunction.java | 91 +-
.../fop/fo/expr/FromTableColumnFunction.java | 76 +-
src/org/apache/fop/fo/expr/Function.java | 63 +-
src/org/apache/fop/fo/expr/FunctionBase.java | 75 +-
.../fop/fo/expr/InheritedPropFunction.java | 76 +-
.../apache/fop/fo/expr/LabelEndFunction.java | 112 +-
src/org/apache/fop/fo/expr/MaxFunction.java | 80 +-
src/org/apache/fop/fo/expr/MinFunction.java | 79 +-
.../apache/fop/fo/expr/NCnameProperty.java | 89 +-
.../fop/fo/expr/NearestSpecPropFunction.java | 80 +-
src/org/apache/fop/fo/expr/Numeric.java | 665 ++--
.../apache/fop/fo/expr/NumericProperty.java | 95 +-
.../fop/fo/expr/PPColWidthFunction.java | 84 +-
.../apache/fop/fo/expr/PropertyException.java | 62 +-
src/org/apache/fop/fo/expr/PropertyInfo.java | 166 +-
.../apache/fop/fo/expr/PropertyParser.java | 858 +++--
.../apache/fop/fo/expr/PropertyTokenizer.java | 660 ++--
.../apache/fop/fo/expr/RGBColorFunction.java | 132 +-
src/org/apache/fop/fo/expr/RoundFunction.java | 83 +-
src/org/apache/fop/fo/flow/BasicLink.java | 178 +-
src/org/apache/fop/fo/flow/BidiOverride.java | 6 +-
src/org/apache/fop/fo/flow/Block.java | 538 +--
.../apache/fop/fo/flow/BlockContainer.java | 270 +-
src/org/apache/fop/fo/flow/Character.java | 126 +-
.../apache/fop/fo/flow/ExternalGraphic.java | 450 ++-
src/org/apache/fop/fo/flow/Float.java | 6 +-
src/org/apache/fop/fo/flow/Flow.java | 357 +-
src/org/apache/fop/fo/flow/Footnote.java | 134 +-
src/org/apache/fop/fo/flow/FootnoteBody.java | 107 +-
.../fop/fo/flow/InitialPropertySet.java | 8 +-
src/org/apache/fop/fo/flow/Inline.java | 83 +-
.../apache/fop/fo/flow/InlineContainer.java | 6 +-
.../fop/fo/flow/InstreamForeignObject.java | 80 +-
src/org/apache/fop/fo/flow/Leader.java | 333 +-
src/org/apache/fop/fo/flow/ListBlock.java | 262 +-
src/org/apache/fop/fo/flow/ListItem.java | 209 +-
src/org/apache/fop/fo/flow/ListItemBody.java | 73 +-
src/org/apache/fop/fo/flow/ListItemLabel.java | 63 +-
src/org/apache/fop/fo/flow/Marker.java | 135 +-
src/org/apache/fop/fo/flow/MultiCase.java | 6 +-
.../apache/fop/fo/flow/MultiProperties.java | 6 +-
.../apache/fop/fo/flow/MultiPropertySet.java | 8 +-
src/org/apache/fop/fo/flow/MultiSwitch.java | 6 +-
src/org/apache/fop/fo/flow/MultiToggle.java | 6 +-
src/org/apache/fop/fo/flow/PageNumber.java | 160 +-
.../fop/fo/flow/PageNumberCitation.java | 344 +-
.../apache/fop/fo/flow/RetrieveMarker.java | 272 +-
src/org/apache/fop/fo/flow/RowSpanMgr.java | 155 +-
src/org/apache/fop/fo/flow/StaticContent.java | 30 +-
src/org/apache/fop/fo/flow/Table.java | 704 ++--
.../apache/fop/fo/flow/TableAndCaption.java | 6 +-
src/org/apache/fop/fo/flow/TableBody.java | 92 +-
src/org/apache/fop/fo/flow/TableCaption.java | 6 +-
src/org/apache/fop/fo/flow/TableCell.java | 793 +++--
src/org/apache/fop/fo/flow/TableColumn.java | 239 +-
src/org/apache/fop/fo/flow/TableFooter.java | 77 +-
src/org/apache/fop/fo/flow/TableHeader.java | 71 +-
src/org/apache/fop/fo/flow/TableRow.java | 659 ++--
src/org/apache/fop/fo/flow/Wrapper.java | 38 +-
.../ConditionalPageMasterReference.java | 318 +-
.../fop/fo/pagination/LayoutMasterSet.java | 254 +-
.../fo/pagination/PageMasterReference.java | 152 +-
.../fo/pagination/PageNumberGenerator.java | 255 +-
.../fop/fo/pagination/PageSequence.java | 474 +--
.../fop/fo/pagination/PageSequenceMaster.java | 160 +-
src/org/apache/fop/fo/pagination/Region.java | 44 +-
.../apache/fop/fo/pagination/RegionAfter.java | 105 +-
.../fop/fo/pagination/RegionBefore.java | 105 +-
.../apache/fop/fo/pagination/RegionBody.java | 156 +-
.../apache/fop/fo/pagination/RegionEnd.java | 129 +-
.../apache/fop/fo/pagination/RegionStart.java | 124 +-
.../RepeatablePageMasterAlternatives.java | 242 +-
.../RepeatablePageMasterReference.java | 182 +-
src/org/apache/fop/fo/pagination/Root.java | 61 +-
.../fop/fo/pagination/SimplePageMaster.java | 287 +-
.../pagination/SinglePageMasterReference.java | 122 +-
.../fo/pagination/SubSequenceSpecifier.java | 67 +-
src/org/apache/fop/fonts/FontFileReader.java | 127 +-
src/org/apache/fop/fonts/Glyphs.java | 2419 +++----------
src/org/apache/fop/fonts/PFMFile.java | 266 +-
src/org/apache/fop/fonts/PFMInputStream.java | 80 +-
src/org/apache/fop/fonts/TTFCmapEntry.java | 19 +-
src/org/apache/fop/fonts/TTFDirTabEntry.java | 30 +-
src/org/apache/fop/fonts/TTFFile.java | 686 ++--
src/org/apache/fop/fonts/TTFMtxEntry.java | 20 +-
src/org/apache/fop/fonts/TTFSegEntry.java | 11 +-
src/org/apache/fop/fonts/TTFSubSetFile.java | 1354 +++----
src/org/apache/fop/fonts/apps/PFMReader.java | 149 +-
src/org/apache/fop/fonts/apps/TTFReader.java | 180 +-
.../apache/fop/image/AbstractFopImage.java | 489 +--
src/org/apache/fop/image/BmpImage.java | 402 +--
src/org/apache/fop/image/FopImage.java | 95 +-
.../apache/fop/image/FopImageConsumer.java | 286 +-
.../apache/fop/image/FopImageException.java | 8 +-
src/org/apache/fop/image/FopImageFactory.java | 115 +-
src/org/apache/fop/image/GifJpegImage.java | 243 +-
src/org/apache/fop/image/ImageArea.java | 172 +-
src/org/apache/fop/image/JAIImage.java | 240 +-
src/org/apache/fop/image/JimiImage.java | 262 +-
src/org/apache/fop/image/SVGImage.java | 13 +-
.../image/analyser/AbstractImageReader.java | 66 +-
.../apache/fop/image/analyser/BMPReader.java | 96 +-
.../apache/fop/image/analyser/GIFReader.java | 86 +-
.../fop/image/analyser/ImageReader.java | 70 +-
.../image/analyser/ImageReaderFactory.java | 80 +-
.../apache/fop/image/analyser/JPEGReader.java | 196 +-
.../apache/fop/image/analyser/PNGReader.java | 107 +-
.../apache/fop/image/analyser/SVGReader.java | 17 +-
.../apache/fop/image/analyser/TIFFReader.java | 152 +-
src/org/apache/fop/layout/Area.java | 296 +-
src/org/apache/fop/layout/AreaClass.java | 38 +-
src/org/apache/fop/layout/AreaContainer.java | 47 +-
src/org/apache/fop/layout/AreaTree.java | 126 +-
.../apache/fop/layout/BackgroundProps.java | 7 +-
src/org/apache/fop/layout/BlockArea.java | 41 +-
.../apache/fop/layout/BodyAreaContainer.java | 622 ++--
src/org/apache/fop/layout/BodyRegionArea.java | 56 +-
.../apache/fop/layout/BorderAndPadding.java | 224 +-
src/org/apache/fop/layout/Box.java | 3 +-
src/org/apache/fop/layout/ColumnArea.java | 59 +-
src/org/apache/fop/layout/DisplaySpace.java | 23 +-
src/org/apache/fop/layout/ExtensionArea.java | 32 +-
src/org/apache/fop/layout/FontDescriptor.java | 35 +-
src/org/apache/fop/layout/FontInfo.java | 30 +-
src/org/apache/fop/layout/FontMetric.java | 3 +-
src/org/apache/fop/layout/FontState.java | 119 +-
.../apache/fop/layout/HyphenationProps.java | 13 +-
src/org/apache/fop/layout/LineArea.java | 1125 +++---
src/org/apache/fop/layout/LinkSet.java | 52 +-
.../apache/fop/layout/LinkedRectangle.java | 66 +-
src/org/apache/fop/layout/MarginProps.java | 23 +-
src/org/apache/fop/layout/Page.java | 163 +-
src/org/apache/fop/layout/PageMaster.java | 64 +-
src/org/apache/fop/layout/RegionArea.java | 25 +-
src/org/apache/fop/layout/Space.java | 6 +-
src/org/apache/fop/layout/SpanArea.java | 193 +-
src/org/apache/fop/layout/TextState.java | 14 +-
.../fop/layout/hyphenation/ByteVector.java | 176 +-
.../fop/layout/hyphenation/CharVector.java | 196 +-
.../apache/fop/layout/hyphenation/Hyphen.java | 65 +-
.../fop/layout/hyphenation/Hyphenation.java | 32 +-
.../hyphenation/HyphenationException.java | 11 +-
.../layout/hyphenation/HyphenationTree.java | 851 ++---
.../fop/layout/hyphenation/Hyphenator.java | 139 +-
.../layout/hyphenation/PatternConsumer.java | 48 +-
.../fop/layout/hyphenation/PatternParser.java | 669 ++--
.../fop/layout/hyphenation/TernaryTree.java | 1133 +++---
.../fop/layout/inline/ForeignObjectArea.java | 252 +-
.../apache/fop/layout/inline/InlineArea.java | 15 +-
.../apache/fop/layout/inline/InlineSpace.java | 49 +-
.../apache/fop/layout/inline/LeaderArea.java | 13 +-
.../layout/inline/PageNumberInlineArea.java | 16 +-
.../apache/fop/layout/inline/WordArea.java | 7 +-
.../fop/messaging/DefaultMessageListener.java | 91 +-
.../apache/fop/messaging/MessageEvent.java | 129 +-
.../apache/fop/messaging/MessageHandler.java | 304 +-
.../apache/fop/messaging/MessageListener.java | 65 +-
src/org/apache/fop/mif/MIFDocument.java | 227 +-
src/org/apache/fop/pdf/ASCII85Filter.java | 315 +-
src/org/apache/fop/pdf/ASCIIHexFilter.java | 99 +-
src/org/apache/fop/pdf/FlateFilter.java | 247 +-
src/org/apache/fop/pdf/PDFAction.java | 72 +-
src/org/apache/fop/pdf/PDFAnnotList.java | 104 +-
src/org/apache/fop/pdf/PDFArray.java | 118 +-
src/org/apache/fop/pdf/PDFCIDFont.java | 388 +-
.../apache/fop/pdf/PDFCIDFontDescriptor.java | 89 +-
src/org/apache/fop/pdf/PDFCIDSystemInfo.java | 121 +-
src/org/apache/fop/pdf/PDFCMap.java | 419 ++-
src/org/apache/fop/pdf/PDFCharProcs.java | 102 +-
src/org/apache/fop/pdf/PDFColor.java | 639 ++--
src/org/apache/fop/pdf/PDFDocument.java | 1055 +++---
src/org/apache/fop/pdf/PDFEncoding.java | 201 +-
src/org/apache/fop/pdf/PDFFileSpec.java | 92 +-
src/org/apache/fop/pdf/PDFFilter.java | 130 +-
.../apache/fop/pdf/PDFFilterException.java | 8 +-
src/org/apache/fop/pdf/PDFFont.java | 196 +-
src/org/apache/fop/pdf/PDFFontDescriptor.java | 340 +-
src/org/apache/fop/pdf/PDFFontNonBase14.java | 196 +-
src/org/apache/fop/pdf/PDFFontTrueType.java | 88 +-
src/org/apache/fop/pdf/PDFFontType0.java | 178 +-
src/org/apache/fop/pdf/PDFFontType1.java | 88 +-
src/org/apache/fop/pdf/PDFFontType3.java | 278 +-
src/org/apache/fop/pdf/PDFFunction.java | 1344 ++++---
src/org/apache/fop/pdf/PDFGoTo.java | 128 +-
src/org/apache/fop/pdf/PDFGoToRemote.java | 103 +-
src/org/apache/fop/pdf/PDFInfo.java | 72 +-
src/org/apache/fop/pdf/PDFInternalLink.java | 75 +-
src/org/apache/fop/pdf/PDFLink.java | 122 +-
src/org/apache/fop/pdf/PDFNumber.java | 213 +-
src/org/apache/fop/pdf/PDFObject.java | 98 +-
src/org/apache/fop/pdf/PDFOutline.java | 310 +-
src/org/apache/fop/pdf/PDFPage.java | 149 +-
src/org/apache/fop/pdf/PDFPages.java | 97 +-
src/org/apache/fop/pdf/PDFPathPaint.java | 109 +-
src/org/apache/fop/pdf/PDFPattern.java | 567 ++-
src/org/apache/fop/pdf/PDFRectangle.java | 159 +-
src/org/apache/fop/pdf/PDFResources.java | 250 +-
src/org/apache/fop/pdf/PDFRoot.java | 96 +-
src/org/apache/fop/pdf/PDFShading.java | 1017 +++---
src/org/apache/fop/pdf/PDFStream.java | 502 ++-
src/org/apache/fop/pdf/PDFT1Stream.java | 229 +-
src/org/apache/fop/pdf/PDFTTFStream.java | 116 +-
src/org/apache/fop/pdf/PDFUri.java | 77 +-
src/org/apache/fop/pdf/PDFWArray.java | 235 +-
src/org/apache/fop/pdf/PDFXObject.java | 168 +-
src/org/apache/fop/render/PrintRenderer.java | 673 ++--
src/org/apache/fop/render/Renderer.java | 183 +-
.../apache/fop/render/awt/AWTFontMetrics.java | 162 +-
.../apache/fop/render/awt/AWTRenderer.java | 561 +--
.../fop/render/awt/FontMetricsMapper.java | 116 +-
src/org/apache/fop/render/awt/FontSetup.java | 105 +-
src/org/apache/fop/render/mif/Font.java | 3 +-
src/org/apache/fop/render/mif/FontSetup.java | 42 +-
.../apache/fop/render/mif/MIFRenderer.java | 253 +-
.../apache/fop/render/mif/fonts/Courier.java | 20 +-
.../fop/render/mif/fonts/CourierBold.java | 20 +-
.../render/mif/fonts/CourierBoldOblique.java | 20 +-
.../fop/render/mif/fonts/CourierOblique.java | 20 +-
.../fop/render/mif/fonts/Helvetica.java | 20 +-
.../fop/render/mif/fonts/HelveticaBold.java | 20 +-
.../mif/fonts/HelveticaBoldOblique.java | 20 +-
.../render/mif/fonts/HelveticaOblique.java | 20 +-
.../apache/fop/render/mif/fonts/Symbol.java | 20 +-
.../fop/render/mif/fonts/TimesBold.java | 20 +-
.../fop/render/mif/fonts/TimesBoldItalic.java | 20 +-
.../fop/render/mif/fonts/TimesItalic.java | 20 +-
.../fop/render/mif/fonts/TimesRoman.java | 20 +-
.../fop/render/mif/fonts/ZapfDingbats.java | 20 +-
.../apache/fop/render/pcl/PCLRenderer.java | 460 +--
src/org/apache/fop/render/pcl/PCLStream.java | 12 +-
src/org/apache/fop/render/pdf/CIDFont.java | 60 +-
src/org/apache/fop/render/pdf/CMap.java | 57 +-
src/org/apache/fop/render/pdf/Font.java | 84 +-
src/org/apache/fop/render/pdf/FontReader.java | 83 +-
src/org/apache/fop/render/pdf/FontSetup.java | 366 +-
.../apache/fop/render/pdf/PDFRenderer.java | 441 +--
.../apache/fop/render/pdf/fonts/BFEntry.java | 65 +-
.../fop/render/pdf/fonts/MultiByteFont.java | 77 +-
.../fop/render/pdf/fonts/SingleByteFont.java | 211 +-
.../fop/render/ps/ASCII85EncodeFilter.java | 58 +-
.../fop/render/ps/ASCIIHexEncodeFilter.java | 13 +-
src/org/apache/fop/render/ps/Filter.java | 6 +-
.../apache/fop/render/ps/FilterThread.java | 14 +-
.../fop/render/ps/FlateEncodeFilter.java | 9 +-
.../apache/fop/render/ps/PSGraphics2D.java | 473 +--
src/org/apache/fop/render/ps/PSRenderer.java | 446 +--
src/org/apache/fop/render/ps/PSStream.java | 3 +-
.../apache/fop/render/txt/TXTRenderer.java | 3109 ++++++++---------
.../apache/fop/render/xml/XMLRenderer.java | 231 +-
src/org/apache/fop/svg/PDFAElementBridge.java | 5 +-
src/org/apache/fop/svg/PDFANode.java | 3 +-
.../apache/fop/svg/PDFDocumentGraphics2D.java | 22 +-
src/org/apache/fop/svg/PDFGraphics2D.java | 479 +--
src/org/apache/fop/svg/PDFTextPainter.java | 113 +-
src/org/apache/fop/svg/PDFTranscoder.java | 99 +-
src/org/apache/fop/svg/SVGArea.java | 12 +-
src/org/apache/fop/svg/SVGElement.java | 43 +-
src/org/apache/fop/svg/SVGElementMapping.java | 14 +-
src/org/apache/fop/svg/SVGObj.java | 4 +-
src/org/apache/fop/svg/SVGStringProperty.java | 14 +-
src/org/apache/fop/svg/SVGUtilities.java | 45 +-
src/org/apache/fop/svg/XMLObj.java | 57 +-
src/org/apache/fop/system/BufferArray.java | 23 +-
src/org/apache/fop/system/BufferFile.java | 15 +-
src/org/apache/fop/system/BufferManager.java | 342 +-
.../apache/fop/tools/DocumentInputSource.java | 45 +-
src/org/apache/fop/tools/DocumentReader.java | 418 ++-
src/org/apache/fop/tools/TestConverter.java | 58 +-
.../apache/fop/tools/anttasks/Compare.java | 327 +-
.../fop/tools/anttasks/CompileXMLFiles.java | 462 ++-
src/org/apache/fop/tools/anttasks/Fop.java | 45 +-
.../apache/fop/tools/anttasks/Manifest.java | 370 +-
.../apache/fop/tools/anttasks/RunTest.java | 80 +-
.../tools/anttasks/SerializeHyphPattern.java | 166 +-
src/org/apache/fop/tools/anttasks/Xslt.java | 294 +-
.../apache/fop/tools/xslt/TraxTransform.java | 219 +-
.../apache/fop/tools/xslt/XSLTransform.java | 281 +-
.../fop/tools/xslt/Xalan1Transform.java | 210 +-
src/org/apache/fop/viewer/Command.java | 12 +-
src/org/apache/fop/viewer/GoToPageDialog.java | 162 +-
src/org/apache/fop/viewer/IconToolBar.java | 50 +-
.../apache/fop/viewer/LoadableProperties.java | 99 +-
.../apache/fop/viewer/MessageException.java | 86 +-
src/org/apache/fop/viewer/MessagesDialog.java | 405 ++-
src/org/apache/fop/viewer/PreviewDialog.java | 789 +++--
.../fop/viewer/PreviewDialogAboutBox.java | 155 +-
.../apache/fop/viewer/ProgressListener.java | 21 +-
.../fop/viewer/SecureResourceBundle.java | 146 +-
src/org/apache/fop/viewer/Translator.java | 44 +-
src/org/apache/fop/viewer/UserMessage.java | 664 ++--
375 files changed, 31579 insertions(+), 37470 deletions(-)
diff --git a/src/org/apache/fop/apps/AWTStarter.java b/src/org/apache/fop/apps/AWTStarter.java
index a38edf207..96dc271aa 100644
--- a/src/org/apache/fop/apps/AWTStarter.java
+++ b/src/org/apache/fop/apps/AWTStarter.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -6,11 +7,10 @@
package org.apache.fop.apps;
/*
- originally contributed by
- Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
- Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
- Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
-
+ * originally contributed by
+ * Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
+ * Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
+ * Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
*/
import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.viewer.*;
@@ -50,20 +50,20 @@ public class AWTStarter extends CommandLineStarter {
PreviewDialog frame;
AWTRenderer renderer;
- public static String TRANSLATION_PATH = "/org/apache/fop/viewer/resources/";
+ public static String TRANSLATION_PATH =
+ "/org/apache/fop/viewer/resources/";
private Translator resource;
- public AWTStarter (CommandLineOptions commandLineOptions)
- throws FOPException {
+ public AWTStarter(CommandLineOptions commandLineOptions)
+ throws FOPException {
super(commandLineOptions);
init();
}
- private void init () {
+ private void init() {
try {
- UIManager.setLookAndFeel(
- new javax.swing.plaf.metal.MetalLookAndFeel());
+ UIManager.setLookAndFeel(new javax.swing.plaf.metal.MetalLookAndFeel());
} catch (Exception e) {
e.printStackTrace();
}
@@ -73,12 +73,12 @@ public class AWTStarter extends CommandLineStarter {
if (language == null)
language = System.getProperty("user.language");
- resource = getResourceBundle(TRANSLATION_PATH + "resources." +
- language);
+ resource = getResourceBundle(TRANSLATION_PATH + "resources."
+ + language);
- UserMessage.setTranslator(
- getResourceBundle(TRANSLATION_PATH + "messages." +
- language));
+ UserMessage.setTranslator(getResourceBundle(TRANSLATION_PATH
+ + "messages."
+ + language));
resource.setMissingEmphasized(false);
renderer = new AWTRenderer(resource);
@@ -90,13 +90,13 @@ public class AWTStarter extends CommandLineStarter {
}
- public void run () throws FOPException {
+ public void run() throws FOPException {
Driver driver = new Driver();
if (errorDump) {
driver.setErrorDump(true);
}
- //init parser
+ // init parser
frame.progress(resource.getString("Init parser") + " ...");
XMLReader parser = inputHandler.getParser();
@@ -126,7 +126,7 @@ public class AWTStarter extends CommandLineStarter {
} catch (Exception e) {
if (e instanceof FOPException) {
- throw (FOPException) e;
+ throw (FOPException)e;
}
throw new FOPException(e);
}
@@ -134,7 +134,7 @@ public class AWTStarter extends CommandLineStarter {
}
protected PreviewDialog createPreviewDialog(AWTRenderer renderer,
- Translator res) {
+ Translator res) {
PreviewDialog frame = new PreviewDialog(renderer, res);
frame.validate();
@@ -160,11 +160,12 @@ public class AWTStarter extends CommandLineStarter {
URL url = getClass().getResource(path);
in = url.openStream();
} catch (Exception ex) {
- MessageHandler.logln("Can't find URL to: <" + path + "> " +
- ex.getMessage());
+ MessageHandler.logln("Can't find URL to: <" + path + "> "
+ + ex.getMessage());
}
return new SecureResourceBundle(in);
}
+
}
diff --git a/src/org/apache/fop/apps/CommandLineOptions.java b/src/org/apache/fop/apps/CommandLineOptions.java
index 61b78a4d0..c13e65518 100644
--- a/src/org/apache/fop/apps/CommandLineOptions.java
+++ b/src/org/apache/fop/apps/CommandLineOptions.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -6,7 +7,7 @@
package org.apache.fop.apps;
-//java
+// java
import java.util.Vector;
import java.io.File;
import java.io.FileNotFoundException;
@@ -17,29 +18,29 @@ import org.apache.fop.configuration.Configuration;
import org.apache.fop.apps.FOPException;
/**
- * Options parses the commandline arguments
+ * Options parses the commandline arguments
*/
public class CommandLineOptions {
/* input / output not set */
private static final int NOT_SET = 0;
- /* input: fo file */
+ /* input: fo file */
private static final int FO_INPUT = 1;
- /* input: xml+xsl file */
+ /* input: xml+xsl file */
private static final int XSLT_INPUT = 2;
- /* output: pdf file */
+ /* output: pdf file */
private static final int PDF_OUTPUT = 1;
- /* output: screen using swing */
+ /* output: screen using swing */
private static final int AWT_OUTPUT = 2;
- /* output: mif file */
+ /* output: mif file */
private static final int MIF_OUTPUT = 3;
- /* output: sent swing rendered file to printer */
+ /* output: sent swing rendered file to printer */
private static final int PRINT_OUTPUT = 4;
- /* output: pcl file */
+ /* output: pcl file */
private static final int PCL_OUTPUT = 5;
- /* output: postscript file */
+ /* output: postscript file */
private static final int PS_OUTPUT = 6;
- /* output: text file */
+ /* output: text file */
private static final int TXT_OUTPUT = 7;
/* System buffers */
@@ -48,29 +49,29 @@ public class CommandLineOptions {
/* System buffers */
private static final int AREA_OUTPUT = 9;
- /* use debug mode*/
+ /* use debug mode */
Boolean errorDump = new Boolean(false);
/* show configuration information */
Boolean dumpConfiguration = new Boolean(false);
- /*suppress any progress information */
+ /* suppress any progress information */
Boolean quiet = new Boolean(false);
/* for area tree XML output, only down to block area level */
Boolean suppressLowLevelAreas = new Boolean(false);
- /* name of user configuration file*/
+ /* name of user configuration file */
File userConfigFile = null;
- /* name of input fo file */
+ /* name of input fo file */
File fofile = null;
- /* name of xsltfile (xslt transformation as input)*/
+ /* name of xsltfile (xslt transformation as input) */
File xsltfile = null;
- /* name of xml file (xslt transformation as input)*/
+ /* name of xml file (xslt transformation as input) */
File xmlfile = null;
- /* name of output file */
+ /* name of output file */
File outfile = null;
/* name of buffer file */
File bufferFile = null;
/* input mode */
int inputmode = NOT_SET;
- /*output mode */
+ /* output mode */
int outputmode = NOT_SET;
/* buffer mode */
int buffermode = NOT_SET;
@@ -79,14 +80,14 @@ public class CommandLineOptions {
private java.util.Hashtable rendererOptions;
- public CommandLineOptions (String [] args) throws FOPException,
- FileNotFoundException {
+ public CommandLineOptions(String[] args)
+ throws FOPException, FileNotFoundException {
boolean optionsParsed = true;
rendererOptions = new java.util.Hashtable();
try {
optionsParsed = parseOptions(args);
if (optionsParsed) {
- checkSettings ();
+ checkSettings();
if (errorDump != null && errorDump.booleanValue()) {
debug();
}
@@ -94,8 +95,7 @@ public class CommandLineOptions {
} catch (FOPException e) {
printUsage();
throw e;
- }
- catch (java.io.FileNotFoundException e) {
+ } catch (java.io.FileNotFoundException e) {
printUsage();
throw e;
}
@@ -103,29 +103,30 @@ public class CommandLineOptions {
}
/**
- * parses the commandline arguments
+ * parses the commandline arguments
* @return true if parse was successful and procesing can continue, false if processing should stop
* @exception FOPException if there was an error in the format of the options
*/
- private boolean parseOptions (String args[]) throws FOPException {
+ private boolean parseOptions(String args[]) throws FOPException {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-d") || args[i].equals("--full-error-dump")) {
errorDump = new Boolean(true);
- } else if (args[i].equals("-x") || args[i].equals("--dump-config")) {
+ } else if (args[i].equals("-x")
+ || args[i].equals("--dump-config")) {
dumpConfiguration = new Boolean(true);
} else if (args[i].equals("-q") || args[i].equals("--quiet")) {
quiet = new Boolean(true);
} else if (args[i].equals("-c")) {
- if ((i + 1 == args.length) ||
- (args[i + 1].charAt(0) == '-')) {
+ if ((i + 1 == args.length)
+ || (args[i + 1].charAt(0) == '-')) {
throw new FOPException("if you use '-c', you must specify the name of the configuration file");
} else {
- userConfigFile = new File (args[i + 1]);
+ userConfigFile = new File(args[i + 1]);
i++;
}
} else if (args[i].equals("-l")) {
- if ((i + 1 == args.length) ||
- (args[i + 1].charAt(0) == '-')) {
+ if ((i + 1 == args.length)
+ || (args[i + 1].charAt(0) == '-')) {
throw new FOPException("if you use '-l', you must specify a language");
} else {
language = args[i + 1];
@@ -135,17 +136,17 @@ public class CommandLineOptions {
suppressLowLevelAreas = new Boolean(true);
} else if (args[i].equals("-fo")) {
inputmode = FO_INPUT;
- if ((i + 1 == args.length) ||
- (args[i + 1].charAt(0) == '-')) {
+ if ((i + 1 == args.length)
+ || (args[i + 1].charAt(0) == '-')) {
throw new FOPException("you must specify the fo file for the '-fo' option");
} else {
- fofile = new File (args[i + 1]);
+ fofile = new File(args[i + 1]);
i++;
}
} else if (args[i].equals("-xsl")) {
inputmode = XSLT_INPUT;
- if ((i + 1 == args.length) ||
- (args[i + 1].charAt(0) == '-')) {
+ if ((i + 1 == args.length)
+ || (args[i + 1].charAt(0) == '-')) {
throw new FOPException("you must specify the stylesheet file for the '-xsl' option");
} else {
xsltfile = new File(args[i + 1]);
@@ -153,8 +154,8 @@ public class CommandLineOptions {
}
} else if (args[i].equals("-xml")) {
inputmode = XSLT_INPUT;
- if ((i + 1 == args.length) ||
- (args[i + 1].charAt(0) == '-')) {
+ if ((i + 1 == args.length)
+ || (args[i + 1].charAt(0) == '-')) {
throw new FOPException("you must specify the input file for the '-xml' option");
} else {
xmlfile = new File(args[i + 1]);
@@ -164,17 +165,17 @@ public class CommandLineOptions {
setOutputMode(AWT_OUTPUT);
} else if (args[i].equals("-pdf")) {
setOutputMode(PDF_OUTPUT);
- if ((i + 1 == args.length) ||
- (args[i + 1].charAt(0) == '-')) {
+ if ((i + 1 == args.length)
+ || (args[i + 1].charAt(0) == '-')) {
throw new FOPException("you must specify the pdf output file");
} else {
- outfile = new File (args[i + 1]);
+ outfile = new File(args[i + 1]);
i++;
}
} else if (args[i].equals("-mif")) {
setOutputMode(MIF_OUTPUT);
- if ((i + 1 == args.length) ||
- (args[i + 1].charAt(0) == '-')) {
+ if ((i + 1 == args.length)
+ || (args[i + 1].charAt(0) == '-')) {
throw new FOPException("you must specify the mif output file");
} else {
outfile = new File(args[i + 1]);
@@ -182,7 +183,7 @@ public class CommandLineOptions {
}
} else if (args[i].equals("-print")) {
setOutputMode(PRINT_OUTPUT);
- //show print help
+ // show print help
if (i + 1 < args.length) {
if (args[i + 1].equals("help")) {
printUsagePrintOutput();
@@ -191,41 +192,41 @@ public class CommandLineOptions {
}
} else if (args[i].equals("-pcl")) {
setOutputMode(PCL_OUTPUT);
- if ((i + 1 == args.length) ||
- (args[i + 1].charAt(0) == '-')) {
+ if ((i + 1 == args.length)
+ || (args[i + 1].charAt(0) == '-')) {
throw new FOPException("you must specify the pdf output file");
} else {
- outfile = new File (args[i + 1]);
+ outfile = new File(args[i + 1]);
i++;
}
} else if (args[i].equals("-ps")) {
setOutputMode(PS_OUTPUT);
- if ((i + 1 == args.length) ||
- (args[i + 1].charAt(0) == '-')) {
+ if ((i + 1 == args.length)
+ || (args[i + 1].charAt(0) == '-')) {
throw new FOPException("you must specify the PostScript output file");
} else {
- outfile = new File (args[i + 1]);
+ outfile = new File(args[i + 1]);
i++;
}
} else if (args[i].equals("-txt")) {
setOutputMode(TXT_OUTPUT);
- if ((i + 1 == args.length) ||
- (args[i + 1].charAt(0) == '-')) {
+ if ((i + 1 == args.length)
+ || (args[i + 1].charAt(0) == '-')) {
throw new FOPException("you must specify the text output file");
} else {
- outfile = new File (args[i + 1]);
+ outfile = new File(args[i + 1]);
i++;
}
} else if (args[i].charAt(0) != '-') {
if (inputmode == NOT_SET) {
inputmode = FO_INPUT;
- fofile = new File (args[i]);
+ fofile = new File(args[i]);
} else if (outputmode == NOT_SET) {
outputmode = PDF_OUTPUT;
outfile = new File(args[i]);
} else {
- throw new FOPException(
- "Don't know what to do with " + args[i]);
+ throw new FOPException("Don't know what to do with "
+ + args[i]);
}
} else if (args[i].equals("-buf")) {
if (buffermode == NOT_SET) {
@@ -234,21 +235,21 @@ public class CommandLineOptions {
MessageHandler.errorln("ERROR: you can only set one buffer method");
printUsage();
}
- if ((i + 1 == args.length) ||
- (args[i + 1].charAt(0) == '-')) {
+ if ((i + 1 == args.length)
+ || (args[i + 1].charAt(0) == '-')) {
MessageHandler.errorln("ERROR: you must specify the buffer output file");
printUsage();
} else {
- bufferFile = new File (args[i + 1]);
+ bufferFile = new File(args[i + 1]);
i++;
}
} else if (args[i].equals("-at")) {
setOutputMode(AREA_OUTPUT);
- if ((i + 1 == args.length) ||
- (args[i + 1].charAt(0) == '-')) {
+ if ((i + 1 == args.length)
+ || (args[i + 1].charAt(0) == '-')) {
throw new FOPException("you must specify the area-tree output file");
} else {
- outfile = new File (args[i + 1]);
+ outfile = new File(args[i + 1]);
i++;
}
} else {
@@ -257,7 +258,7 @@ public class CommandLineOptions {
}
}
return true;
- } //end parseOptions
+ } // end parseOptions
private void setOutputMode(int mode) throws FOPException {
if (outputmode == NOT_SET) {
@@ -270,8 +271,7 @@ public class CommandLineOptions {
/**
* checks whether all necessary information has been given in a consistent way
*/
- private void checkSettings () throws FOPException,
- FileNotFoundException {
+ private void checkSettings() throws FOPException, FileNotFoundException {
if (inputmode == NOT_SET) {
throw new FOPException("No input file specified");
}
@@ -281,7 +281,7 @@ public class CommandLineOptions {
}
if (inputmode == XSLT_INPUT) {
- //check whether xml *and* xslt file have been set
+ // check whether xml *and* xslt file have been set
if (xmlfile == null) {
throw new FOPException("XML file must be specified for the tranform mode");
}
@@ -289,22 +289,25 @@ public class CommandLineOptions {
throw new FOPException("XSLT file must be specified for the tranform mode");
}
- //warning if fofile has been set in xslt mode
+ // warning if fofile has been set in xslt mode
if (fofile != null) {
- MessageHandler.errorln(
- "WARNING: Can't use fo file with transform mode! Ignoring.\n" +
- "Your input is "+ "\n xmlfile: " +
- xmlfile.getAbsolutePath() + "\nxsltfile: " +
- xsltfile.getAbsolutePath() + "\n fofile: " +
- fofile.getAbsolutePath());
+ MessageHandler.errorln("WARNING: Can't use fo file with transform mode! Ignoring.\n"
+ + "Your input is " + "\n xmlfile: "
+ + xmlfile.getAbsolutePath()
+ + "\nxsltfile: "
+ + xsltfile.getAbsolutePath()
+ + "\n fofile: "
+ + fofile.getAbsolutePath());
}
if (!xmlfile.exists()) {
- throw new FileNotFoundException("xml file " +
- xmlfile.getAbsolutePath() + " not found ");
+ throw new FileNotFoundException("xml file "
+ + xmlfile.getAbsolutePath()
+ + " not found ");
}
if (!xsltfile.exists()) {
- throw new FileNotFoundException("xsl file " +
- xsltfile.getAbsolutePath() + " not found ");
+ throw new FileNotFoundException("xsl file "
+ + xsltfile.getAbsolutePath()
+ + " not found ");
}
} else if (inputmode == FO_INPUT) {
@@ -314,53 +317,54 @@ public class CommandLineOptions {
MessageHandler.errorln("xslt file: " + xsltfile.toString());
}
if (!fofile.exists()) {
- throw new FileNotFoundException("fo file " +
- fofile.getAbsolutePath() + " not found ");
+ throw new FileNotFoundException("fo file "
+ + fofile.getAbsolutePath()
+ + " not found ");
}
}
- }// end checkSettings
+ } // end checkSettings
/**
- * returns the chosen renderer, throws FOPException
+ * returns the chosen renderer, throws FOPException
*/
- public int getRenderer () throws FOPException {
+ public int getRenderer() throws FOPException {
switch (outputmode) {
- case NOT_SET:
- throw new FOPException("Renderer has not been set!");
- case PDF_OUTPUT:
- return Driver.RENDER_PDF;
- case AWT_OUTPUT:
- return Driver.RENDER_AWT;
- case MIF_OUTPUT:
- return Driver.RENDER_MIF;
- case PRINT_OUTPUT:
- return Driver.RENDER_PRINT;
- case PCL_OUTPUT:
- return Driver.RENDER_PCL;
- case PS_OUTPUT:
- return Driver.RENDER_PS;
- case TXT_OUTPUT:
- return Driver.RENDER_TXT;
- case AREA_OUTPUT:
- rendererOptions.put("fineDetail", isCoarseAreaXml());
- return Driver.RENDER_XML;
- default:
- throw new FOPException("Invalid Renderer setting!");
+ case NOT_SET:
+ throw new FOPException("Renderer has not been set!");
+ case PDF_OUTPUT:
+ return Driver.RENDER_PDF;
+ case AWT_OUTPUT:
+ return Driver.RENDER_AWT;
+ case MIF_OUTPUT:
+ return Driver.RENDER_MIF;
+ case PRINT_OUTPUT:
+ return Driver.RENDER_PRINT;
+ case PCL_OUTPUT:
+ return Driver.RENDER_PCL;
+ case PS_OUTPUT:
+ return Driver.RENDER_PS;
+ case TXT_OUTPUT:
+ return Driver.RENDER_TXT;
+ case AREA_OUTPUT:
+ rendererOptions.put("fineDetail", isCoarseAreaXml());
+ return Driver.RENDER_XML;
+ default:
+ throw new FOPException("Invalid Renderer setting!");
}
}
/**
*
- **/
- public InputHandler getInputHandler () {
+ */
+ public InputHandler getInputHandler() {
switch (inputmode) {
- case FO_INPUT:
- return new FOInputHandler(fofile);
- case XSLT_INPUT:
- return new XSLTInputHandler(xmlfile, xsltfile);
- default:
- return new FOInputHandler(fofile);
+ case FO_INPUT:
+ return new FOInputHandler(fofile);
+ case XSLT_INPUT:
+ return new XSLTInputHandler(xmlfile, xsltfile);
+ default:
+ return new FOInputHandler(fofile);
}
}
@@ -370,35 +374,36 @@ public class CommandLineOptions {
public Starter getStarter() throws FOPException {
switch (outputmode) {
- case AWT_OUTPUT:
- try {
- return((Starter) Class.forName(
- "org.apache.fop.apps.AWTStarter").
- getConstructor(
- new Class[]{CommandLineOptions.class}).
- newInstance(new Object[]{this}));
- } catch (Exception e) {
- if (e instanceof FOPException) {
- throw (FOPException) e;
- }
- throw new FOPException("AWTStarter could not be loaded.",e);
+ case AWT_OUTPUT:
+ try {
+ return ((Starter)Class.forName("org.apache.fop.apps.AWTStarter").getConstructor(new Class[] {
+ CommandLineOptions.class
+ }).newInstance(new Object[] {
+ this
+ }));
+ } catch (Exception e) {
+ if (e instanceof FOPException) {
+ throw (FOPException)e;
}
- case PRINT_OUTPUT:
- try {
- return((Starter) Class.forName(
- "org.apache.fop.apps.PrintStarter").
- getConstructor(
- new Class[]{CommandLineOptions.class}).
- newInstance(new Object[]{this}));
- } catch (Exception e) {
- if (e instanceof FOPException) {
- throw (FOPException) e;
- }
- throw new FOPException("PrintStarter could not be loaded.",e);
+ throw new FOPException("AWTStarter could not be loaded.", e);
+ }
+ case PRINT_OUTPUT:
+ try {
+ return ((Starter)Class.forName("org.apache.fop.apps.PrintStarter").getConstructor(new Class[] {
+ CommandLineOptions.class
+ }).newInstance(new Object[] {
+ this
+ }));
+ } catch (Exception e) {
+ if (e instanceof FOPException) {
+ throw (FOPException)e;
}
+ throw new FOPException("PrintStarter could not be loaded.",
+ e);
+ }
- default:
- return new CommandLineStarter(this);
+ default:
+ return new CommandLineStarter(this);
}
}
@@ -426,7 +431,7 @@ public class CommandLineOptions {
return outfile;
}
- public File getUserConfigFile () {
+ public File getUserConfigFile() {
return userConfigFile;
}
@@ -459,132 +464,131 @@ public class CommandLineOptions {
*/
public File getInputFile() {
switch (inputmode) {
- case FO_INPUT:
- return fofile;
- case XSLT_INPUT:
- return xmlfile;
- default:
- return fofile;
+ case FO_INPUT:
+ return fofile;
+ case XSLT_INPUT:
+ return xmlfile;
+ default:
+ return fofile;
}
}
/**
- * shows the commandline syntax including a summary of all available options and some examples
+ * shows the commandline syntax including a summary of all available options and some examples
*/
public static void printUsage() {
- MessageHandler.errorln(
- "\nUSAGE\nFop [options] [-fo|-xml] infile [-xsl file] [-awt|-pdf|-mif|-pcl|-ps|-txt|-at|-print] \n" +
- " [OPTIONS] \n" + " -d debug mode \n" +
- " -x dump configuration settings \n" +
- " -q quiet mode \n" +
- " -c cfg.xml use additional configuration file cfg.xml\n" +
- " -l lang the language to use for user information \n" +
- " -s for area tree XML, down to block areas only\n\n" +
- " [INPUT] \n" +
- " infile xsl:fo input file (the same as the next) \n" +
- " -fo infile xsl:fo input file \n" +
- " -xml infile xml input file, must be used together with -xsl \n" +
- " -xsl stylesheet xslt stylesheet \n \n" +
- " [OUTPUT] \n" +
- " outfile input will be rendered as pdf file into outfile \n" +
- " -pdf outfile input will be rendered as pdf file (outfile req'd) \n" +
- " -awt input will be displayed on screen \n" +
- " -mif outfile input will be rendered as mif file (outfile req'd)\n" +
- " -pcl outfile input will be rendered as pcl file (outfile req'd) \n" +
- " -ps outfile input will be rendered as PostScript file (outfile req'd) \n" +
- " -txt outfile input will be rendered as text file (outfile req'd) \n" +
- " -at outfile representation of area tree as XML (outfile req'd) \n" +
- " -print input file will be rendered and sent to the printer \n" +
- " see options with \"-print help\" \n\n" +
- " [Examples]\n" + " Fop foo.fo foo.pdf \n" +
- " Fop -fo foo.fo -pdf foo.pdf (does the same as the previous line)\n" +
- " Fop -xsl foo.xsl -xml foo.xml -pdf foo.pdf\n" +
- " Fop foo.fo -mif foo.mif\n" +
- " Fop foo.fo -print or Fop -print foo.fo \n" + " Fop foo.fo -awt \n");
+ MessageHandler.errorln("\nUSAGE\nFop [options] [-fo|-xml] infile [-xsl file] [-awt|-pdf|-mif|-pcl|-ps|-txt|-at|-print] \n"
+ + " [OPTIONS] \n"
+ + " -d debug mode \n"
+ + " -x dump configuration settings \n"
+ + " -q quiet mode \n"
+ + " -c cfg.xml use additional configuration file cfg.xml\n"
+ + " -l lang the language to use for user information \n"
+ + " -s for area tree XML, down to block areas only\n\n"
+ + " [INPUT] \n"
+ + " infile xsl:fo input file (the same as the next) \n"
+ + " -fo infile xsl:fo input file \n"
+ + " -xml infile xml input file, must be used together with -xsl \n"
+ + " -xsl stylesheet xslt stylesheet \n \n"
+ + " [OUTPUT] \n"
+ + " outfile input will be rendered as pdf file into outfile \n"
+ + " -pdf outfile input will be rendered as pdf file (outfile req'd) \n"
+ + " -awt input will be displayed on screen \n"
+ + " -mif outfile input will be rendered as mif file (outfile req'd)\n"
+ + " -pcl outfile input will be rendered as pcl file (outfile req'd) \n"
+ + " -ps outfile input will be rendered as PostScript file (outfile req'd) \n"
+ + " -txt outfile input will be rendered as text file (outfile req'd) \n"
+ + " -at outfile representation of area tree as XML (outfile req'd) \n"
+ + " -print input file will be rendered and sent to the printer \n"
+ + " see options with \"-print help\" \n\n"
+ + " [Examples]\n" + " Fop foo.fo foo.pdf \n"
+ + " Fop -fo foo.fo -pdf foo.pdf (does the same as the previous line)\n"
+ + " Fop -xsl foo.xsl -xml foo.xml -pdf foo.pdf\n"
+ + " Fop foo.fo -mif foo.mif\n"
+ + " Fop foo.fo -print or Fop -print foo.fo \n"
+ + " Fop foo.fo -awt \n");
}
/**
- * shows the options for print output
+ * shows the options for print output
*/
public void printUsagePrintOutput() {
- MessageHandler.errorln(
- "USAGE: -print [-Dstart=i] [-Dend=i] [-Dcopies=i] [-Deven=true|false] " +
- " org.apache.fop.apps.Fop (..) -print \n" +
- "Example:\n" + "java -Dstart=1 -Dend=2 org.apache.Fop.apps.Fop infile.fo -print ");
+ MessageHandler.errorln("USAGE: -print [-Dstart=i] [-Dend=i] [-Dcopies=i] [-Deven=true|false] "
+ + " org.apache.fop.apps.Fop (..) -print \n"
+ + "Example:\n"
+ + "java -Dstart=1 -Dend=2 org.apache.Fop.apps.Fop infile.fo -print ");
}
/**
* debug mode. outputs all commandline settings
*/
- private void debug () {
+ private void debug() {
System.out.print("Input mode: ");
switch (inputmode) {
- case NOT_SET:
- MessageHandler.logln("not set");
- break;
- case FO_INPUT:
- MessageHandler.logln("FO ");
- MessageHandler.logln("fo input file: " + fofile.toString());
- break;
- case XSLT_INPUT:
- MessageHandler.logln("xslt transformation");
- MessageHandler.logln("xml input file: " +
- xmlfile.toString());
- MessageHandler.logln("xslt stylesheet: " +
- xsltfile.toString());
- break;
- default:
- MessageHandler.logln("unknown input type");
+ case NOT_SET:
+ MessageHandler.logln("not set");
+ break;
+ case FO_INPUT:
+ MessageHandler.logln("FO ");
+ MessageHandler.logln("fo input file: " + fofile.toString());
+ break;
+ case XSLT_INPUT:
+ MessageHandler.logln("xslt transformation");
+ MessageHandler.logln("xml input file: " + xmlfile.toString());
+ MessageHandler.logln("xslt stylesheet: " + xsltfile.toString());
+ break;
+ default:
+ MessageHandler.logln("unknown input type");
}
System.out.print("Output mode: ");
switch (outputmode) {
- case NOT_SET:
- MessageHandler.logln("not set");
- break;
- case PDF_OUTPUT:
- MessageHandler.logln("pdf");
- MessageHandler.logln("output file: " + outfile.toString());
- break;
- case AWT_OUTPUT:
- MessageHandler.logln("awt on screen");
- if (outfile != null) {
- MessageHandler.logln("ERROR: awt mode, but outfile is set:");
- MessageHandler.logln("out file: " + outfile.toString());
- }
- break;
- case MIF_OUTPUT:
- MessageHandler.logln("mif");
- MessageHandler.logln("output file: " + outfile.toString());
- break;
- case PRINT_OUTPUT:
- MessageHandler.logln("print directly");
- if (outfile != null) {
- MessageHandler.logln("ERROR: print mode, but outfile is set:");
- MessageHandler.logln("out file: " + outfile.toString());
- }
- break;
- case PCL_OUTPUT:
- MessageHandler.logln("pcl");
- MessageHandler.logln("output file: " + outfile.toString());
- break;
- case PS_OUTPUT:
- MessageHandler.logln("PostScript");
- MessageHandler.logln("output file: " + outfile.toString());
- break;
- case TXT_OUTPUT:
- MessageHandler.logln("txt");
- MessageHandler.logln("output file: " + outfile.toString());
- break;
- default:
- MessageHandler.logln("unknown input type");
+ case NOT_SET:
+ MessageHandler.logln("not set");
+ break;
+ case PDF_OUTPUT:
+ MessageHandler.logln("pdf");
+ MessageHandler.logln("output file: " + outfile.toString());
+ break;
+ case AWT_OUTPUT:
+ MessageHandler.logln("awt on screen");
+ if (outfile != null) {
+ MessageHandler.logln("ERROR: awt mode, but outfile is set:");
+ MessageHandler.logln("out file: " + outfile.toString());
+ }
+ break;
+ case MIF_OUTPUT:
+ MessageHandler.logln("mif");
+ MessageHandler.logln("output file: " + outfile.toString());
+ break;
+ case PRINT_OUTPUT:
+ MessageHandler.logln("print directly");
+ if (outfile != null) {
+ MessageHandler.logln("ERROR: print mode, but outfile is set:");
+ MessageHandler.logln("out file: " + outfile.toString());
+ }
+ break;
+ case PCL_OUTPUT:
+ MessageHandler.logln("pcl");
+ MessageHandler.logln("output file: " + outfile.toString());
+ break;
+ case PS_OUTPUT:
+ MessageHandler.logln("PostScript");
+ MessageHandler.logln("output file: " + outfile.toString());
+ break;
+ case TXT_OUTPUT:
+ MessageHandler.logln("txt");
+ MessageHandler.logln("output file: " + outfile.toString());
+ break;
+ default:
+ MessageHandler.logln("unknown input type");
}
MessageHandler.logln("OPTIONS");
if (userConfigFile != null) {
- MessageHandler.logln("user configuration file: " +
- userConfigFile.toString());
+ MessageHandler.logln("user configuration file: "
+ + userConfigFile.toString());
} else {
MessageHandler.logln("no user configuration file is used [default]");
}
@@ -606,19 +610,21 @@ public class CommandLineOptions {
}
- //debug: create class and output all settings
- public static void main (String args[]) {
+ // debug: create class and output all settings
+ public static void main(String args[]) {
/*
- for (int i = 0; i < args.length; i++) {
- MessageHandler.logln(">"+args[i]+"<");
- }*/
+ * for (int i = 0; i < args.length; i++) {
+ * MessageHandler.logln(">"+args[i]+"<");
+ * }
+ */
try {
- CommandLineOptions options = new CommandLineOptions (args);
+ CommandLineOptions options = new CommandLineOptions(args);
} catch (Exception e) {
e.printStackTrace();
}
- //options.debug();
+ // options.debug();
}
+
}
diff --git a/src/org/apache/fop/apps/CommandLineStarter.java b/src/org/apache/fop/apps/CommandLineStarter.java
index 7565df347..648365826 100644
--- a/src/org/apache/fop/apps/CommandLineStarter.java
+++ b/src/org/apache/fop/apps/CommandLineStarter.java
@@ -1,3 +1,10 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.apps;
// SAX
@@ -16,58 +23,55 @@ import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.configuration.Configuration;
/**
- * super class for all classes which start Fop from the commandline
+ * super class for all classes which start Fop from the commandline
*/
public class CommandLineStarter extends Starter {
-
+
CommandLineOptions commandLineOptions;
- boolean errorDump;
-
- public CommandLineStarter (CommandLineOptions commandLineOptions)
- throws FOPException
- {
+ boolean errorDump;
+
+ public CommandLineStarter(CommandLineOptions commandLineOptions)
+ throws FOPException {
this.commandLineOptions = commandLineOptions;
- options.setCommandLineOptions(commandLineOptions);
- errorDump = Configuration.getBooleanValue("debugMode").booleanValue();
- super.setInputHandler(commandLineOptions.getInputHandler());
+ options.setCommandLineOptions(commandLineOptions);
+ errorDump = Configuration.getBooleanValue("debugMode").booleanValue();
+ super.setInputHandler(commandLineOptions.getInputHandler());
}
-
+
/**
* Run the format.
* @exception FOPException if there is an error during processing
*/
- public void run()
- throws FOPException
- {
+ public void run() throws FOPException {
String version = Version.getVersion();
MessageHandler.logln(version);
XMLReader parser = inputHandler.getParser();
setParserFeatures(parser);
-
- Driver driver = new Driver();
- driver.setBufferFile(commandLineOptions.getBufferFile());
+
+ Driver driver = new Driver();
+ driver.setBufferFile(commandLineOptions.getBufferFile());
if (errorDump) {
driver.setErrorDump(true);
}
-
+
try {
driver.setRenderer(commandLineOptions.getRenderer());
- driver.getRenderer().setOptions(commandLineOptions.getRendererOptions());
+ driver.getRenderer().setOptions(commandLineOptions.getRendererOptions());
driver.buildFOTree(parser, inputHandler.getInputSource());
driver.format();
driver.setOutputStream(new FileOutputStream(commandLineOptions.getOutputFile()));
driver.render();
System.exit(0);
} catch (Exception e) {
- if (e instanceof FOPException) {
- throw (FOPException) e;
- }
- throw new FOPException(e);
- }
+ if (e instanceof FOPException) {
+ throw (FOPException)e;
+ }
+ throw new FOPException(e);
+ }
}
-
+
}
diff --git a/src/org/apache/fop/apps/Driver.java b/src/org/apache/fop/apps/Driver.java
index b263e2d99..60c250176 100644
--- a/src/org/apache/fop/apps/Driver.java
+++ b/src/org/apache/fop/apps/Driver.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -47,12 +48,11 @@ import java.util.*;
* Here is an example use of Driver which outputs PDF:
*
*
- * Driver driver = new Driver(new InputSource (args[0]),
- * new FileOutputStream(args[1]));
- * driver.setRenderer(RENDER_PDF);
- * driver.run();
+ * Driver driver = new Driver(new InputSource (args[0]),
+ * new FileOutputStream(args[1]));
+ * driver.setRenderer(RENDER_PDF);
+ * driver.run();
*
-
* If neccessary, calling classes can call into the lower level
* methods to setup and
* render. Methods can be called to set the
@@ -78,76 +78,109 @@ import java.util.*;
* Here is an example use of Driver which outputs to AWT:
*
*
- * Driver driver = new Driver();
- * driver.setRenderer(new org.apache.fop.render.awt.AWTRenderer(translator));
- * driver.buildFOTree(parser, fileInputSource(args[0]));
- * driver.format();
- * driver.render();
+ * Driver driver = new Driver();
+ * driver.setRenderer(new org.apache.fop.render.awt.AWTRenderer(translator));
+ * driver.buildFOTree(parser, fileInputSource(args[0]));
+ * driver.format();
+ * driver.render();
*
*/
public class Driver {
- /** Render to PDF. OutputStream must be set */
+ /**
+ * Render to PDF. OutputStream must be set
+ */
public static final int RENDER_PDF = 1;
- /** Render to a GUI window. No OutputStream neccessary */
+ /**
+ * Render to a GUI window. No OutputStream neccessary
+ */
public static final int RENDER_AWT = 2;
- /** Render to MIF. OutputStream must be set */
+ /**
+ * Render to MIF. OutputStream must be set
+ */
public static final int RENDER_MIF = 3;
- /** Render to XML. OutputStream must be set */
+ /**
+ * Render to XML. OutputStream must be set
+ */
public static final int RENDER_XML = 4;
- /** Render to PRINT. No OutputStream neccessary */
+ /**
+ * Render to PRINT. No OutputStream neccessary
+ */
public static final int RENDER_PRINT = 5;
- /** Render to PCL. OutputStream must be set */
+ /**
+ * Render to PCL. OutputStream must be set
+ */
public static final int RENDER_PCL = 6;
- /** Render to Postscript. OutputStream must be set */
+ /**
+ * Render to Postscript. OutputStream must be set
+ */
public static final int RENDER_PS = 7;
- /** Render to Text. OutputStream must be set */
+ /**
+ * Render to Text. OutputStream must be set
+ */
public static final int RENDER_TXT = 8;
- /** the FO tree builder */
+ /**
+ * the FO tree builder
+ */
private FOTreeBuilder _treeBuilder;
- /** the area tree that is the result of formatting the FO tree */
+ /**
+ * the area tree that is the result of formatting the FO tree
+ */
private AreaTree _areaTree;
- /** the renderer to use to output the area tree */
+ /**
+ * the renderer to use to output the area tree
+ */
private Renderer _renderer;
- /** the source of the FO file */
+ /**
+ * the source of the FO file
+ */
private InputSource _source;
- /** the stream to use to output the results of the renderer */
+ /**
+ * the stream to use to output the results of the renderer
+ */
private OutputStream _stream;
- /** The XML parser to use when building the FO tree */
+ /**
+ * The XML parser to use when building the FO tree
+ */
private XMLReader _reader;
- /** If true, full error stacks are reported */
+ /**
+ * If true, full error stacks are reported
+ */
private boolean _errorDump = false;
- /** the system resources that FOP will use */
+ /**
+ * the system resources that FOP will use
+ */
private BufferManager _bufferManager;
public static final String getParserClassName() {
String parserClassName = null;
try {
parserClassName = System.getProperty("org.xml.sax.parser");
- } catch(SecurityException se) {
- }
+ } catch (SecurityException se) {}
if (parserClassName == null) {
parserClassName = "org.apache.xerces.parsers.SAXParser";
}
return parserClassName;
}
- /** create a new Driver */
+ /**
+ * create a new Driver
+ */
public Driver() {
_stream = null;
_bufferManager = new BufferManager();
@@ -173,7 +206,7 @@ public class Driver {
}
public boolean hasData() {
- return(_treeBuilder.hasData());
+ return (_treeBuilder.hasData());
}
/**
@@ -221,14 +254,14 @@ public class Driver {
addElementMapping("org.apache.fop.extensions.ExtensionElementMapping");
// add mappings from available services
- Enumeration providers = Service.providers(org.apache.fop.fo.ElementMapping.class);
+ Enumeration providers =
+ Service.providers(org.apache.fop.fo.ElementMapping.class);
if (providers != null) {
- while(providers.hasMoreElements()) {
+ while (providers.hasMoreElements()) {
String str = (String)providers.nextElement();
try {
addElementMapping(str);
- } catch (IllegalArgumentException e) {
- }
+ } catch (IllegalArgumentException e) {}
}
}
}
@@ -236,42 +269,42 @@ public class Driver {
/**
* Set the rendering type to use. Must be one of
*
- * - RENDER_PDF
- *
- RENDER_AWT
- *
- RENDER_MIF
- *
- RENDER_XML
- *
- RENDER_PCL
- *
- RENDER_PS
- *
- RENDER_TXT
+ *
- RENDER_PDF
+ *
- RENDER_AWT
+ *
- RENDER_MIF
+ *
- RENDER_XML
+ *
- RENDER_PCL
+ *
- RENDER_PS
+ *
- RENDER_TXT
*
* @param renderer the type of renderer to use
*/
public void setRenderer(int renderer) throws IllegalArgumentException {
switch (renderer) {
- case RENDER_PDF:
- setRenderer(new org.apache.fop.render.pdf.PDFRenderer());
- break;
- case RENDER_AWT:
- throw new IllegalArgumentException("Use renderer form of setRenderer() for AWT");
- case RENDER_PRINT:
- throw new IllegalArgumentException("Use renderer form of setRenderer() for PRINT");
- case RENDER_PCL:
- setRenderer(new org.apache.fop.render.pcl.PCLRenderer());
- break;
- case RENDER_PS:
- setRenderer(new org.apache.fop.render.ps.PSRenderer());
- break;
- case RENDER_TXT:
- setRenderer(new org.apache.fop.render.txt.TXTRenderer());
- break;
- case RENDER_MIF:
- setRenderer(new org.apache.fop.render.mif.MIFRenderer());
- break;
- case RENDER_XML:
- setRenderer(new org.apache.fop.render.xml.XMLRenderer());
- break;
- default:
- throw new IllegalArgumentException("Unknown renderer type");
+ case RENDER_PDF:
+ setRenderer(new org.apache.fop.render.pdf.PDFRenderer());
+ break;
+ case RENDER_AWT:
+ throw new IllegalArgumentException("Use renderer form of setRenderer() for AWT");
+ case RENDER_PRINT:
+ throw new IllegalArgumentException("Use renderer form of setRenderer() for PRINT");
+ case RENDER_PCL:
+ setRenderer(new org.apache.fop.render.pcl.PCLRenderer());
+ break;
+ case RENDER_PS:
+ setRenderer(new org.apache.fop.render.ps.PSRenderer());
+ break;
+ case RENDER_TXT:
+ setRenderer(new org.apache.fop.render.txt.TXTRenderer());
+ break;
+ case RENDER_MIF:
+ setRenderer(new org.apache.fop.render.mif.MIFRenderer());
+ break;
+ case RENDER_XML:
+ setRenderer(new org.apache.fop.render.xml.XMLRenderer());
+ break;
+ default:
+ throw new IllegalArgumentException("Unknown renderer type");
}
}
@@ -306,25 +339,23 @@ public class Driver {
* @see #setRenderer(int)
*/
public void setRenderer(String rendererClassName)
- throws IllegalArgumentException {
+ throws IllegalArgumentException {
try {
- _renderer = (Renderer) Class.forName(
- rendererClassName).newInstance();
+ _renderer =
+ (Renderer)Class.forName(rendererClassName).newInstance();
_renderer.setProducer(Version.getVersion());
} catch (ClassNotFoundException e) {
- throw new IllegalArgumentException("Could not find " +
- rendererClassName);
- }
- catch (InstantiationException e) {
- throw new IllegalArgumentException(
- "Could not instantiate " + rendererClassName);
- }
- catch (IllegalAccessException e) {
- throw new IllegalArgumentException("Could not access " +
- rendererClassName);
- }
- catch (ClassCastException e) {
- throw new IllegalArgumentException(rendererClassName + " is not a renderer");
+ throw new IllegalArgumentException("Could not find "
+ + rendererClassName);
+ } catch (InstantiationException e) {
+ throw new IllegalArgumentException("Could not instantiate "
+ + rendererClassName);
+ } catch (IllegalAccessException e) {
+ throw new IllegalArgumentException("Could not access "
+ + rendererClassName);
+ } catch (ClassCastException e) {
+ throw new IllegalArgumentException(rendererClassName
+ + " is not a renderer");
}
}
@@ -342,25 +373,23 @@ public class Driver {
* add the element mapping with the given class name
*/
public void addElementMapping(String mappingClassName)
- throws IllegalArgumentException {
+ throws IllegalArgumentException {
try {
- ElementMapping mapping = (ElementMapping) Class.forName(
- mappingClassName).newInstance();
+ ElementMapping mapping =
+ (ElementMapping)Class.forName(mappingClassName).newInstance();
addElementMapping(mapping);
} catch (ClassNotFoundException e) {
- throw new IllegalArgumentException("Could not find " +
- mappingClassName);
- }
- catch (InstantiationException e) {
- throw new IllegalArgumentException(
- "Could not instantiate " + mappingClassName);
- }
- catch (IllegalAccessException e) {
- throw new IllegalArgumentException("Could not access " +
- mappingClassName);
- }
- catch (ClassCastException e) {
- throw new IllegalArgumentException(mappingClassName + " is not an ElementMapping");
+ throw new IllegalArgumentException("Could not find "
+ + mappingClassName);
+ } catch (InstantiationException e) {
+ throw new IllegalArgumentException("Could not instantiate "
+ + mappingClassName);
+ } catch (IllegalAccessException e) {
+ throw new IllegalArgumentException("Could not access "
+ + mappingClassName);
+ } catch (ClassCastException e) {
+ throw new IllegalArgumentException(mappingClassName
+ + " is not an ElementMapping");
}
}
@@ -379,21 +408,19 @@ public class Driver {
* Build the formatting object tree using the given SAX Parser and
* SAX InputSource
*/
- public synchronized void buildFOTree(XMLReader parser,
- InputSource source)
- throws FOPException {
+ public synchronized void buildFOTree(XMLReader parser, InputSource source)
+ throws FOPException {
parser.setContentHandler(_treeBuilder);
try {
parser.parse(source);
} catch (SAXException e) {
if (e.getException() instanceof FOPException) {
- throw (FOPException) e.getException();
+ throw (FOPException)e.getException();
} else {
throw new FOPException(e);
}
- }
- catch (IOException e) {
+ } catch (IOException e) {
throw new FOPException(e);
}
}
@@ -402,7 +429,7 @@ public class Driver {
* Build the formatting object tree using the given DOM Document
*/
public synchronized void buildFOTree(Document document)
- throws FOPException {
+ throws FOPException {
try {
DocumentInputSource source = new DocumentInputSource(document);
DocumentReader reader = new DocumentReader();
@@ -410,8 +437,7 @@ public class Driver {
reader.parse(source);
} catch (SAXException e) {
throw new FOPException(e);
- }
- catch (IOException e) {
+ } catch (IOException e) {
throw new FOPException(e);
}
@@ -424,13 +450,13 @@ public class Driver {
if (_errorDump) {
if (e instanceof SAXException) {
e.printStackTrace();
- if (((SAXException) e).getException() != null) {
- ((SAXException) e).getException().printStackTrace();
+ if (((SAXException)e).getException() != null) {
+ ((SAXException)e).getException().printStackTrace();
}
} else if (e instanceof FOPException) {
e.printStackTrace();
- if (((FOPException) e).getException() != null) {
- ((FOPException) e).getException().printStackTrace();
+ if (((FOPException)e).getException() != null) {
+ ((FOPException)e).getException().printStackTrace();
}
} else {
e.printStackTrace();
@@ -447,8 +473,7 @@ public class Driver {
/**
* format the formatting object tree into an area tree
*/
- public synchronized void format()
- throws FOPException {
+ public synchronized void format() throws FOPException {
FontInfo fontInfo = new FontInfo();
_renderer.setupFontInfo(fontInfo);
@@ -461,8 +486,7 @@ public class Driver {
/**
* render the area tree to the output form
*/
- public synchronized void render()
- throws IOException, FOPException {
+ public synchronized void render() throws IOException, FOPException {
_renderer.render(_areaTree, _stream);
}
@@ -470,8 +494,7 @@ public class Driver {
* Runs the formatting and renderering process using the previously set
* inputsource and outputstream
*/
- public synchronized void run()
- throws IOException, FOPException {
+ public synchronized void run() throws IOException, FOPException {
if (_renderer == null) {
setRenderer(RENDER_PDF);
}
@@ -491,11 +514,13 @@ public class Driver {
format();
render();
}
+
}
// code stolen from org.apache.batik.util and modified slightly
// does what sun.misc.Service probably does, but it cannot be relied on.
// hopefully will be part of standard jdk sometime.
+
/**
* This class loads services present in the class path.
*/
@@ -505,7 +530,7 @@ class Service {
public static synchronized Enumeration providers(Class cls) {
ClassLoader cl = cls.getClassLoader();
- String serviceFile = "META-INF/services/"+cls.getName();
+ String serviceFile = "META-INF/services/" + cls.getName();
// System.out.println("File: " + serviceFile);
@@ -528,8 +553,8 @@ class Service {
java.net.URL u = (java.net.URL)e.nextElement();
// System.out.println("URL: " + u);
- InputStream is = u.openStream();
- Reader r = new InputStreamReader(is, "UTF-8");
+ InputStream is = u.openStream();
+ Reader r = new InputStreamReader(is, "UTF-8");
BufferedReader br = new BufferedReader(r);
String line = br.readLine();
@@ -540,7 +565,7 @@ class Service {
if (idx != -1)
line = line.substring(0, idx);
- // Trim whitespace.
+ // Trim whitespace.
line = line.trim();
// If nothing left then loop around...
@@ -551,7 +576,7 @@ class Service {
// System.out.println("Line: " + line);
// Try and load the class
- //Object obj = cl.loadClass(line).newInstance();
+ // Object obj = cl.loadClass(line).newInstance();
// stick it into our vector...
v.add(line);
} catch (Exception ex) {
@@ -565,5 +590,6 @@ class Service {
}
return v.elements();
}
+
}
diff --git a/src/org/apache/fop/apps/ErrorHandler.java b/src/org/apache/fop/apps/ErrorHandler.java
index 79c889897..d559c9357 100644
--- a/src/org/apache/fop/apps/ErrorHandler.java
+++ b/src/org/apache/fop/apps/ErrorHandler.java
@@ -1,54 +1,13 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.apps;
-/** not implemented yet */
+/**
+ * not implemented yet
+ */
public interface ErrorHandler {}
diff --git a/src/org/apache/fop/apps/FOInputHandler.java b/src/org/apache/fop/apps/FOInputHandler.java
index 5fd055a4c..f2828dd20 100644
--- a/src/org/apache/fop/apps/FOInputHandler.java
+++ b/src/org/apache/fop/apps/FOInputHandler.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -10,10 +11,10 @@ package org.apache.fop.apps;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
-//fop
+// fop
import org.apache.fop.messaging.MessageHandler;
-//java
+// java
import java.io.File;
/**
@@ -22,16 +23,17 @@ import java.io.File;
public class FOInputHandler extends InputHandler {
File fofile;
- public FOInputHandler (File fofile) {
+ public FOInputHandler(File fofile) {
this.fofile = fofile;
}
- public InputSource getInputSource () {
+ public InputSource getInputSource() {
return super.fileInputSource(fofile);
}
public XMLReader getParser() throws FOPException {
return super.createParser();
}
+
}
diff --git a/src/org/apache/fop/apps/FOPException.java b/src/org/apache/fop/apps/FOPException.java
index 765d9eede..f6391ce6c 100644
--- a/src/org/apache/fop/apps/FOPException.java
+++ b/src/org/apache/fop/apps/FOPException.java
@@ -1,6 +1,7 @@
-/*
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
+ * For details on use and redistribution please refer to the
* LICENSE file included with these sources."
*/
@@ -15,9 +16,9 @@ import org.xml.sax.SAXException;
public class FOPException extends Exception {
private static final String EXCEPTION_SEPARATOR = "\n---------\n";
-
+
private Throwable _exception;
-
+
/**
* create a new FOP Exception
*
@@ -26,86 +27,82 @@ public class FOPException extends Exception {
public FOPException(String message) {
super(message);
}
+
public FOPException(Throwable e) {
super(e.getMessage());
- setException(e);
+ setException(e);
}
-
+
public FOPException(String message, Throwable e) {
super(message);
- setException(e);
+ setException(e);
}
-
- protected void setException(Throwable t)
- {
- _exception = t;
+
+ protected void setException(Throwable t) {
+ _exception = t;
}
-
- public Throwable getException()
- {
- return _exception;
+
+ public Throwable getException() {
+ return _exception;
}
- protected Throwable getRootException()
- {
- Throwable result = _exception;
-
- if (result instanceof SAXException) {
- result = ((SAXException)result).getException();
- }
- if (result instanceof java.lang.reflect.InvocationTargetException) {
- result = ((java.lang.reflect.InvocationTargetException)result).getTargetException();
- }
- if (result != _exception) {
- return result;
- }
- return null;
+ protected Throwable getRootException() {
+ Throwable result = _exception;
+
+ if (result instanceof SAXException) {
+ result = ((SAXException)result).getException();
+ }
+ if (result instanceof java.lang.reflect.InvocationTargetException) {
+ result =
+ ((java.lang.reflect.InvocationTargetException)result).getTargetException();
+ }
+ if (result != _exception) {
+ return result;
+ }
+ return null;
}
-
-
- public void printStackTrace()
- {
- synchronized (System.err) {
- super.printStackTrace();
- if (_exception != null) {
- System.err.println(EXCEPTION_SEPARATOR);
- _exception.printStackTrace();
- }
- if (getRootException() != null) {
- System.err.println(EXCEPTION_SEPARATOR);
- getRootException().printStackTrace();
- }
- }
+
+
+ public void printStackTrace() {
+ synchronized (System.err) {
+ super.printStackTrace();
+ if (_exception != null) {
+ System.err.println(EXCEPTION_SEPARATOR);
+ _exception.printStackTrace();
+ }
+ if (getRootException() != null) {
+ System.err.println(EXCEPTION_SEPARATOR);
+ getRootException().printStackTrace();
+ }
+ }
}
-
- public void printStackTrace(java.io.PrintStream stream)
- {
- synchronized (stream) {
- super.printStackTrace(stream);
- if (_exception != null) {
- stream.println(EXCEPTION_SEPARATOR);
- _exception.printStackTrace(stream);
- }
- if (getRootException() != null) {
- System.err.println(EXCEPTION_SEPARATOR);
- getRootException().printStackTrace(stream);
- }
- }
+
+ public void printStackTrace(java.io.PrintStream stream) {
+ synchronized (stream) {
+ super.printStackTrace(stream);
+ if (_exception != null) {
+ stream.println(EXCEPTION_SEPARATOR);
+ _exception.printStackTrace(stream);
+ }
+ if (getRootException() != null) {
+ System.err.println(EXCEPTION_SEPARATOR);
+ getRootException().printStackTrace(stream);
+ }
+ }
}
-
- public void printStackTrace(java.io.PrintWriter writer)
- {
- synchronized (writer) {
- super.printStackTrace(writer);
- if (_exception != null) {
- writer.println(EXCEPTION_SEPARATOR);
- _exception.printStackTrace(writer);
- }
- if (getRootException() != null) {
- System.err.println(EXCEPTION_SEPARATOR);
- getRootException().printStackTrace(writer);
- }
- }
+
+ public void printStackTrace(java.io.PrintWriter writer) {
+ synchronized (writer) {
+ super.printStackTrace(writer);
+ if (_exception != null) {
+ writer.println(EXCEPTION_SEPARATOR);
+ _exception.printStackTrace(writer);
+ }
+ if (getRootException() != null) {
+ System.err.println(EXCEPTION_SEPARATOR);
+ getRootException().printStackTrace(writer);
+ }
+ }
}
-
+
}
diff --git a/src/org/apache/fop/apps/Fop.java b/src/org/apache/fop/apps/Fop.java
index 801bf8a81..b4ae7d708 100644
--- a/src/org/apache/fop/apps/Fop.java
+++ b/src/org/apache/fop/apps/Fop.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -9,21 +10,20 @@ package org.apache.fop.apps;
import org.apache.fop.messaging.MessageHandler;
public class Fop {
- public static void main (String [] args) {
+ public static void main(String[] args) {
CommandLineOptions options = null;
try {
- options = new CommandLineOptions (args);
+ options = new CommandLineOptions(args);
Starter starter = options.getStarter();
starter.run();
} catch (FOPException e) {
- MessageHandler.errorln("ERROR: "+e.getMessage());
+ MessageHandler.errorln("ERROR: " + e.getMessage());
if (options != null && options.isDebugMode().booleanValue()) {
e.printStackTrace();
}
- }
- catch (java.io.FileNotFoundException e) {
- MessageHandler.errorln("ERROR: "+e.getMessage());
+ } catch (java.io.FileNotFoundException e) {
+ MessageHandler.errorln("ERROR: " + e.getMessage());
if (options != null && options.isDebugMode().booleanValue()) {
e.printStackTrace();
}
diff --git a/src/org/apache/fop/apps/InputHandler.java b/src/org/apache/fop/apps/InputHandler.java
index 731e375e9..fe2d7cd7a 100644
--- a/src/org/apache/fop/apps/InputHandler.java
+++ b/src/org/apache/fop/apps/InputHandler.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -61,22 +62,19 @@ abstract public class InputHandler {
MessageHandler.logln("using SAX parser " + parserClassName);
try {
- return (XMLReader) Class.forName(
- parserClassName).newInstance();
+ return (XMLReader)Class.forName(parserClassName).newInstance();
} catch (ClassNotFoundException e) {
throw new FOPException(e);
- }
- catch (InstantiationException e) {
- throw new FOPException("Could not instantiate " +
- parserClassName, e);
- }
- catch (IllegalAccessException e) {
- throw new FOPException("Could not access " +
- parserClassName, e);
- }
- catch (ClassCastException e) {
- throw new FOPException(parserClassName + " is not a SAX driver",e);
+ } catch (InstantiationException e) {
+ throw new FOPException("Could not instantiate "
+ + parserClassName, e);
+ } catch (IllegalAccessException e) {
+ throw new FOPException("Could not access " + parserClassName, e);
+ } catch (ClassCastException e) {
+ throw new FOPException(parserClassName + " is not a SAX driver",
+ e);
}
}
+
}
diff --git a/src/org/apache/fop/apps/Options.java b/src/org/apache/fop/apps/Options.java
index 9f65b4c78..a6e16f31b 100644
--- a/src/org/apache/fop/apps/Options.java
+++ b/src/org/apache/fop/apps/Options.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -6,100 +7,95 @@
package org.apache.fop.apps;
-//sax
+// sax
import org.xml.sax.InputSource;
-//java
+// java
import java.io.File;
import java.io.InputStream;
-//fop
+// fop
import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.configuration.Configuration;
import org.apache.fop.configuration.ConfigurationReader;
/**
- * Options handles loading of configuration files and
- * additional setting of commandline options
+ * Options handles loading of configuration files and
+ * additional setting of commandline options
*/
public class Options {
boolean errorDump = false;
- public Options () throws FOPException {
+ public Options() throws FOPException {
this.loadStandardConfiguration();
- initOptions ();
+ initOptions();
}
- public Options (File userConfigFile) throws FOPException {
+ public Options(File userConfigFile) throws FOPException {
this();
this.loadUserconfiguration(userConfigFile);
}
- public Options (CommandLineOptions clOptions) throws FOPException
- {
+ public Options(CommandLineOptions clOptions) throws FOPException {
this();
this.setCommandLineOptions(clOptions);
}
- //initializing option settings
- void initOptions () {
+ // initializing option settings
+ void initOptions() {
if (Configuration.getBooleanValue("quiet").booleanValue()) {
MessageHandler.setQuiet(true);
}
if (Configuration.getBooleanValue("debugMode").booleanValue()) {
errorDump = true;
}
- if (Configuration.getBooleanValue(
- "dumpConfiguration").booleanValue()) {
- Configuration.put("dumpConfiguration","true");
+ if (Configuration.getBooleanValue("dumpConfiguration").booleanValue()) {
+ Configuration.put("dumpConfiguration", "true");
Configuration.dumpConfiguration();
}
}
- //setting clOptions
+ // setting clOptions
void setCommandLineOptions(CommandLineOptions clOptions) {
- //load user configuration file,if there is one
+ // load user configuration file,if there is one
File userConfigFile = clOptions.getUserConfigFile();
if (userConfigFile != null) {
this.loadUserconfiguration(userConfigFile);
}
- //debug mode
+ // debug mode
if (clOptions.isDebugMode() != null) {
errorDump = clOptions.isDebugMode().booleanValue();
- Configuration.put("debugMode",new Boolean(errorDump));
+ Configuration.put("debugMode", new Boolean(errorDump));
}
- //show configuration settings
+ // show configuration settings
boolean dumpConfiguration;
if (clOptions.dumpConfiguration() != null) {
- dumpConfiguration =
- clOptions.dumpConfiguration().booleanValue();
+ dumpConfiguration = clOptions.dumpConfiguration().booleanValue();
} else {
- dumpConfiguration = Configuration.getBooleanValue(
- "dumpConfiguration").booleanValue();
+ dumpConfiguration =
+ Configuration.getBooleanValue("dumpConfiguration").booleanValue();
}
if (dumpConfiguration) {
- Configuration.put("dumpConfiguration","true");
+ Configuration.put("dumpConfiguration", "true");
Configuration.dumpConfiguration();
System.exit(0);
}
- //quiet mode
+ // quiet mode
if (clOptions.isQuiet() != null) {
MessageHandler.setQuiet(clOptions.isQuiet().booleanValue());
}
- //set base directory
+ // set base directory
String baseDir = Configuration.getStringValue("baseDir");
if (baseDir == null) {
try {
- baseDir = new File(
- clOptions.getInputFile().getAbsolutePath()).
- getParentFile().toURL().toExternalForm();
+ baseDir =
+ new File(clOptions.getInputFile().getAbsolutePath()).getParentFile().toURL().toExternalForm();
Configuration.put("baseDir", baseDir);
- } catch (Exception e) {
- }
+ } catch (Exception e) {}
}
if (errorDump) {
MessageHandler.logln("base directory: " + baseDir);
@@ -107,7 +103,7 @@ public class Options {
}
/**
- * loads standard configuration file and a user file, if it has been specified
+ * loads standard configuration file and a user file, if it has been specified
*/
public void loadStandardConfiguration() throws FOPException {
String file = "config.xml";
@@ -116,23 +112,21 @@ public class Options {
// Try to use Context Class Loader to load the properties file.
try {
java.lang.reflect.Method getCCL =
- Thread.class.getMethod("getContextClassLoader",
- new Class[0]);
+ Thread.class.getMethod("getContextClassLoader", new Class[0]);
if (getCCL != null) {
ClassLoader contextClassLoader =
- (ClassLoader) getCCL.invoke(
- Thread.currentThread(), new Object[0]);
- configfile =
- contextClassLoader.getResourceAsStream("conf/" +
- file);
+ (ClassLoader)getCCL.invoke(Thread.currentThread(),
+ new Object[0]);
+ configfile = contextClassLoader.getResourceAsStream("conf/"
+ + file);
}
} catch (Exception e) {}
// the entry /conf/config.xml refers to a directory conf which is a sibling of org
if (configfile == null)
configfile =
- ConfigurationReader.class.getResourceAsStream("/conf/"+
- file);
+ ConfigurationReader.class.getResourceAsStream("/conf/"
+ + file);
if (configfile == null) {
throw new FOPException("can't find default configuration file");
}
@@ -140,7 +134,7 @@ public class Options {
MessageHandler.logln("reading default configuration file");
}
ConfigurationReader reader =
- new ConfigurationReader (new InputSource(configfile));
+ new ConfigurationReader(new InputSource(configfile));
if (errorDump) {
reader.setDumpError(true);
}
@@ -153,20 +147,19 @@ public class Options {
}
public void loadUserconfiguration(File userConfigFile) {
- //read user configuration file
+ // read user configuration file
if (userConfigFile != null) {
MessageHandler.logln("reading user configuration file");
- ConfigurationReader reader = new ConfigurationReader (
- InputHandler.fileInputSource(userConfigFile));
+ ConfigurationReader reader =
+ new ConfigurationReader(InputHandler.fileInputSource(userConfigFile));
if (errorDump) {
reader.setDumpError(true);
}
try {
reader.start();
} catch (org.apache.fop.apps.FOPException error) {
- MessageHandler.errorln(
- "Can't find user configuration file " +
- userConfigFile);
+ MessageHandler.errorln("Can't find user configuration file "
+ + userConfigFile);
MessageHandler.errorln("using default values");
if (errorDump) {
reader.dumpError(error);
@@ -174,6 +167,7 @@ public class Options {
}
}
}
+
}
diff --git a/src/org/apache/fop/apps/PDFOutputHandler.java b/src/org/apache/fop/apps/PDFOutputHandler.java
index aadba4b2f..0b39c67c8 100644
--- a/src/org/apache/fop/apps/PDFOutputHandler.java
+++ b/src/org/apache/fop/apps/PDFOutputHandler.java
@@ -1,3 +1,10 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.apps;
import org.xml.sax.*;
@@ -6,182 +13,201 @@ import java.io.*;
// FOP
import org.apache.fop.fo.XTFOTreeBuilder;
-import org.apache.fop.fo.XTElementMapping;
+import org.apache.fop.fo.XTElementMapping;
import org.apache.fop.layout.AreaTree;
import org.apache.fop.layout.FontInfo;
import org.apache.fop.render.Renderer;
import org.apache.fop.messaging.MessageHandler;
-//////////////////////////////////////////////////////////////////////////////////////
+// ////////////////////////////////////////////////////////////////////////////////////
+
/**
* A DocumentHandler that writes a PDF representation to an OutputStream.
- *
+ *
* Use with James Clark's XT. Just put FOP on your class path and add
- *
+ *
* to your stylesheet. Now XT will automatically call FOP.
- *
+ *
*/
-public class PDFOutputHandler extends XTFOTreeBuilder implements OutputDocumentHandler {
-
- /** the area tree that is the result of formatting the FO tree */
- protected AreaTree areaTree;
-
- /** the renderer to use to output the area tree */
- protected Renderer renderer;
-
- /** the PrintWriter to use to output the results of the renderer */
- protected PrintWriter writer;
-
- /** the stream to use to output the results of the renderer */
- protected OutputStream stream;
-
- private boolean keepOpen;
-
- //////////////////////////////////////////////////////////////////////////////////////
- /**
- */
- public PDFOutputHandler() {
- }
-
- //////////////////////////////////////////////////////////////////////////////////////
- /**
- */
- public PDFOutputHandler(OutputStream out) {
- this();
- this.stream = out;
- }
-
- //////////////////////////////////////////////////////////////////////////////////////
- /**
- */
- public DocumentHandler init(Destination dest, AttributeList atts) throws IOException {
- this.stream = dest.getOutputStream("application/pdf", null);
- this.keepOpen = dest.keepOpen();
-
- String version = org.apache.fop.apps.Version.getVersion();
- setRenderer("org.apache.fop.render.pdf.PDFRenderer", version);
- addElementMapping("org.apache.fop.fo.StandardElementMapping");
- addElementMapping("org.apache.fop.svg.SVGElementMapping");
- return this;
- }
-
- //////////////////////////////////////////////////////////////////////////////////////
- /**
- * set the class name of the Renderer to use as well as the
- * producer string for those renderers that can make use of it
- */
- public void setRenderer(String rendererClassName, String producer) {
- this.renderer = createRenderer(rendererClassName);
- this.renderer.setProducer(producer);
- }
-
- //////////////////////////////////////////////////////////////////////////////////////
- /**
- * SAX passthrough, finish rendering the document
- */
- public void endDocument() throws SAXException {
- super.endDocument();
-
- try {
- doFormat();
- doRender();
- } catch (IOException io) {
- throw new SAXException(io);
- } catch (FOPException fop) {
- throw new SAXException(fop);
+public class PDFOutputHandler extends XTFOTreeBuilder
+ implements OutputDocumentHandler {
+
+ /**
+ * the area tree that is the result of formatting the FO tree
+ */
+ protected AreaTree areaTree;
+
+ /**
+ * the renderer to use to output the area tree
+ */
+ protected Renderer renderer;
+
+ /**
+ * the PrintWriter to use to output the results of the renderer
+ */
+ protected PrintWriter writer;
+
+ /**
+ * the stream to use to output the results of the renderer
+ */
+ protected OutputStream stream;
+
+ private boolean keepOpen;
+
+ // ////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ */
+ public PDFOutputHandler() {}
+
+ // ////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ */
+ public PDFOutputHandler(OutputStream out) {
+ this();
+ this.stream = out;
+ }
+
+ // ////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ */
+ public DocumentHandler init(Destination dest,
+ AttributeList atts) throws IOException {
+ this.stream = dest.getOutputStream("application/pdf", null);
+ this.keepOpen = dest.keepOpen();
+
+ String version = org.apache.fop.apps.Version.getVersion();
+ setRenderer("org.apache.fop.render.pdf.PDFRenderer", version);
+ addElementMapping("org.apache.fop.fo.StandardElementMapping");
+ addElementMapping("org.apache.fop.svg.SVGElementMapping");
+ return this;
+ }
+
+ // ////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * set the class name of the Renderer to use as well as the
+ * producer string for those renderers that can make use of it
+ */
+ public void setRenderer(String rendererClassName, String producer) {
+ this.renderer = createRenderer(rendererClassName);
+ this.renderer.setProducer(producer);
}
- writer.flush();
- }
-
- //////////////////////////////////////////////////////////////////////////////////////
- /**
- * format the formatting object tree into an area tree
- */
- public void doFormat()
- throws FOPException {
- FontInfo fontInfo = new FontInfo();
- this.renderer.setupFontInfo(fontInfo);
-
- this.areaTree = new AreaTree();
- this.areaTree.setFontInfo(fontInfo);
-
- format(areaTree);
- }
-
- //////////////////////////////////////////////////////////////////////////////////////
- /**
- * render the area tree to the output form
- */
- public void doRender()
- throws IOException,FOPException {
- this.renderer.render(areaTree, this.stream);
- }
-
- //////////////////////////////////////////////////////////////////////////////////////
- /**
- * add the given element mapping.
- *
- * an element mapping maps element names to Java classes
- */
- public void addElementMapping(XTElementMapping mapping) {
- mapping.addToBuilder(this);
- }
-
- //////////////////////////////////////////////////////////////////////////////////////
- /**
- * add the element mapping with the given class name
- */
- public void addElementMapping(String mappingClassName) {
- createElementMapping(mappingClassName).addToBuilder(this);
- }
-
- //////////////////////////////////////////////////////////////////////////////////////
- /**
- * protected method used by addElementMapping(String) to
- * instantiate element mapping class
- */
- protected XTElementMapping createElementMapping(String mappingClassName) {
- MessageHandler.logln("using element mapping " + mappingClassName);
-
- try {
- return (XTElementMapping)
- Class.forName(mappingClassName).newInstance();
- } catch (ClassNotFoundException e) {
- MessageHandler.errorln("Could not find " + mappingClassName);
- } catch (InstantiationException e) {
- MessageHandler.errorln("Could not instantiate "
- + mappingClassName);
- } catch (IllegalAccessException e) {
- MessageHandler.errorln("Could not access " + mappingClassName);
- } catch (ClassCastException e) {
- MessageHandler.errorln(mappingClassName + " is not an element mapping");
+
+ // ////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * SAX passthrough, finish rendering the document
+ */
+ public void endDocument() throws SAXException {
+ super.endDocument();
+
+ try {
+ doFormat();
+ doRender();
+ } catch (IOException io) {
+ throw new SAXException(io);
+ } catch (FOPException fop) {
+ throw new SAXException(fop);
+ }
+ writer.flush();
+ }
+
+ // ////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * format the formatting object tree into an area tree
+ */
+ public void doFormat() throws FOPException {
+ FontInfo fontInfo = new FontInfo();
+ this.renderer.setupFontInfo(fontInfo);
+
+ this.areaTree = new AreaTree();
+ this.areaTree.setFontInfo(fontInfo);
+
+ format(areaTree);
}
- return null;
- }
-
- //////////////////////////////////////////////////////////////////////////////////////
- /**
- * protected method used by setRenderer(String, String) to
- * instantiate the Renderer class
- */
- protected Renderer createRenderer(String rendererClassName) {
- MessageHandler.logln("using renderer " + rendererClassName);
-
- try {
- return (Renderer)
- Class.forName(rendererClassName).newInstance();
- } catch (ClassNotFoundException e) {
- MessageHandler.errorln("Could not find " + rendererClassName);
- } catch (InstantiationException e) {
- MessageHandler.errorln("Could not instantiate "
- + rendererClassName);
- } catch (IllegalAccessException e) {
- MessageHandler.errorln("Could not access " + rendererClassName);
- } catch (ClassCastException e) {
- MessageHandler.errorln(rendererClassName + " is not a renderer");
+
+ // ////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * render the area tree to the output form
+ */
+ public void doRender() throws IOException, FOPException {
+ this.renderer.render(areaTree, this.stream);
}
- return null;
- }
+
+ // ////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * add the given element mapping.
+ *
+ * an element mapping maps element names to Java classes
+ */
+ public void addElementMapping(XTElementMapping mapping) {
+ mapping.addToBuilder(this);
+ }
+
+ // ////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * add the element mapping with the given class name
+ */
+ public void addElementMapping(String mappingClassName) {
+ createElementMapping(mappingClassName).addToBuilder(this);
+ }
+
+ // ////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * protected method used by addElementMapping(String) to
+ * instantiate element mapping class
+ */
+ protected XTElementMapping createElementMapping(String mappingClassName) {
+ MessageHandler.logln("using element mapping " + mappingClassName);
+
+ try {
+ return (XTElementMapping)Class.forName(mappingClassName).newInstance();
+ } catch (ClassNotFoundException e) {
+ MessageHandler.errorln("Could not find " + mappingClassName);
+ } catch (InstantiationException e) {
+ MessageHandler.errorln("Could not instantiate "
+ + mappingClassName);
+ } catch (IllegalAccessException e) {
+ MessageHandler.errorln("Could not access " + mappingClassName);
+ } catch (ClassCastException e) {
+ MessageHandler.errorln(mappingClassName
+ + " is not an element mapping");
+ }
+ return null;
+ }
+
+ // ////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * protected method used by setRenderer(String, String) to
+ * instantiate the Renderer class
+ */
+ protected Renderer createRenderer(String rendererClassName) {
+ MessageHandler.logln("using renderer " + rendererClassName);
+
+ try {
+ return (Renderer)Class.forName(rendererClassName).newInstance();
+ } catch (ClassNotFoundException e) {
+ MessageHandler.errorln("Could not find " + rendererClassName);
+ } catch (InstantiationException e) {
+ MessageHandler.errorln("Could not instantiate "
+ + rendererClassName);
+ } catch (IllegalAccessException e) {
+ MessageHandler.errorln("Could not access " + rendererClassName);
+ } catch (ClassCastException e) {
+ MessageHandler.errorln(rendererClassName + " is not a renderer");
+ }
+ return null;
+ }
+
}
diff --git a/src/org/apache/fop/apps/PrintStarter.java b/src/org/apache/fop/apps/PrintStarter.java
index 3d2c52a0d..c50172c4d 100644
--- a/src/org/apache/fop/apps/PrintStarter.java
+++ b/src/org/apache/fop/apps/PrintStarter.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -7,9 +8,9 @@
package org.apache.fop.apps;
/*
- originally contributed by
- Stanislav Gorkhover: stanislav.gorkhover@jcatalog.com
- jCatalog Software AG
+ * originally contributed by
+ * Stanislav Gorkhover: stanislav.gorkhover@jcatalog.com
+ * jCatalog Software AG
*/
@@ -43,11 +44,11 @@ import org.apache.fop.messaging.MessageHandler;
*/
public class PrintStarter extends CommandLineStarter {
- public PrintStarter (CommandLineOptions options) throws FOPException {
+ public PrintStarter(CommandLineOptions options) throws FOPException {
super(options);
}
- public void run () throws FOPException {
+ public void run() throws FOPException {
Driver driver = new Driver();
if (errorDump) {
driver.setErrorDump(true);
@@ -69,7 +70,7 @@ public class PrintStarter extends CommandLineStarter {
driver.render();
} catch (Exception e) {
if (e instanceof FOPException) {
- throw (FOPException) e;
+ throw (FOPException)e;
}
throw new FOPException(e);
}
@@ -111,8 +112,7 @@ public class PrintStarter extends CommandLineStarter {
if (str != null) {
try {
mode = Boolean.valueOf(str).booleanValue() ? EVEN : ODD;
- } catch (Exception e) {
- }
+ } catch (Exception e) {}
}
}
@@ -140,14 +140,13 @@ public class PrintStarter extends CommandLineStarter {
Vector numbers = getInvalidPageNumbers();
for (int i = numbers.size() - 1; i > -1; i--)
- tree.getPages().removeElementAt(
- Integer.parseInt((String) numbers.elementAt(i)));
+ tree.getPages().removeElementAt(Integer.parseInt((String)numbers.elementAt(i)));
}
public void renderPage(Page page) {
- pageWidth = (int)((float) page.getWidth() / 1000f);
- pageHeight = (int)((float) page.getHeight() / 1000f);
+ pageWidth = (int)((float)page.getWidth() / 1000f);
+ pageHeight = (int)((float)page.getHeight() / 1000f);
super.renderPage(page);
}
@@ -184,8 +183,8 @@ public class PrintStarter extends CommandLineStarter {
}
- } // class PrintRenderer
-} // class PrintCommandLine
+ } // class PrintRenderer
+} // class PrintCommandLine
diff --git a/src/org/apache/fop/apps/Starter.java b/src/org/apache/fop/apps/Starter.java
index 130e2f1ac..c0882e93f 100644
--- a/src/org/apache/fop/apps/Starter.java
+++ b/src/org/apache/fop/apps/Starter.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -28,7 +29,7 @@ public abstract class Starter {
InputHandler inputHandler;
public Starter() throws FOPException {
- options = new Options ();
+ options = new Options();
}
public void setInputHandler(InputHandler inputHandler) {
@@ -37,15 +38,15 @@ public abstract class Starter {
abstract public void run() throws FOPException;
- // setting the parser features
- public void setParserFeatures (XMLReader parser) throws FOPException {
+ // setting the parser features
+ public void setParserFeatures(XMLReader parser) throws FOPException {
try {
parser.setFeature("http://xml.org/sax/features/namespace-prefixes",
true);
} catch (SAXException e) {
- throw new FOPException(
- "Error in setting up parser feature namespace-prefixes\n" +
- "You need a parser which supports SAX version 2",e);
+ throw new FOPException("Error in setting up parser feature namespace-prefixes\n"
+ + "You need a parser which supports SAX version 2", e);
}
}
+
}
diff --git a/src/org/apache/fop/apps/TraxInputHandler.java b/src/org/apache/fop/apps/TraxInputHandler.java
index 0b1e10f43..4cebd7521 100644
--- a/src/org/apache/fop/apps/TraxInputHandler.java
+++ b/src/org/apache/fop/apps/TraxInputHandler.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -39,21 +40,21 @@ public class TraxInputHandler extends InputHandler {
File xmlfile, xsltfile;
- public TraxInputHandler (File xmlfile, File xsltfile) {
+ public TraxInputHandler(File xmlfile, File xsltfile) {
this.xmlfile = xmlfile;
this.xsltfile = xsltfile;
}
/**
- * overwrites the method of the super class to return the xmlfile
+ * overwrites the method of the super class to return the xmlfile
*/
- public InputSource getInputSource () {
+ public InputSource getInputSource() {
return fileInputSource(xmlfile);
}
/**
- * overwrites this method of the super class and returns an XMLFilter instead of a
- * simple XMLReader which allows chaining of transformations
+ * overwrites this method of the super class and returns an XMLFilter instead of a
+ * simple XMLReader which allows chaining of transformations
*
*/
public XMLReader getParser() throws FOPException {
@@ -69,21 +70,21 @@ public class TraxInputHandler extends InputHandler {
* @param xsltfile An xslt stylesheet
* @return XMLFilter an XMLFilter which can be chained together with other XMLReaders or XMLFilters
*/
- public static XMLFilter getXMLFilter (File xmlfile,
- File xsltfile) throws FOPException {
+ public static XMLFilter getXMLFilter(File xmlfile,
+ File xsltfile) throws FOPException {
try {
// Instantiate a TransformerFactory.
TransformerFactory tFactory = TransformerFactory.newInstance();
// Determine whether the TransformerFactory supports The use uf SAXSource
// and SAXResult
- if (tFactory.getFeature(SAXSource.FEATURE) &&
- tFactory.getFeature(SAXResult.FEATURE)) {
+ if (tFactory.getFeature(SAXSource.FEATURE)
+ && tFactory.getFeature(SAXResult.FEATURE)) {
// Cast the TransformerFactory to SAXTransformerFactory.
SAXTransformerFactory saxTFactory =
- ((SAXTransformerFactory) tFactory);
+ ((SAXTransformerFactory)tFactory);
// Create an XMLFilter for each stylesheet.
- XMLFilter xmlfilter = saxTFactory.newXMLFilter(
- new StreamSource(xsltfile));
+ XMLFilter xmlfilter =
+ saxTFactory.newXMLFilter(new StreamSource(xsltfile));
// Create an XMLReader.
XMLReader parser = createParser();
@@ -95,17 +96,16 @@ public class TraxInputHandler extends InputHandler {
xmlfilter.setParent(parser);
return xmlfilter;
} else {
- throw new FOPException(
- "Your parser doesn't support the features SAXSource and SAXResult." +
- "\nMake sure you are using a xsl parser which supports TrAX");
+ throw new FOPException("Your parser doesn't support the features SAXSource and SAXResult."
+ + "\nMake sure you are using a xsl parser which supports TrAX");
}
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
if (ex instanceof FOPException) {
- throw (FOPException) ex;
+ throw (FOPException)ex;
}
throw new FOPException(ex);
}
}
+
}
diff --git a/src/org/apache/fop/apps/Version.java b/src/org/apache/fop/apps/Version.java
index cb4e86572..a7d64534b 100644
--- a/src/org/apache/fop/apps/Version.java
+++ b/src/org/apache/fop/apps/Version.java
@@ -1,12 +1,14 @@
-/*
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
+ * For details on use and redistribution please refer to the
* LICENSE file included with these sources."
*/
package org.apache.fop.apps;
import org.apache.fop.configuration.Configuration;
+
/**
* class representing the version of FOP.
*/
@@ -20,4 +22,5 @@ public class Version {
public static String getVersion() {
return Configuration.getStringValue("version");
}
+
}
diff --git a/src/org/apache/fop/apps/XSLTInputHandler.java b/src/org/apache/fop/apps/XSLTInputHandler.java
index 1169e5870..3b035838a 100644
--- a/src/org/apache/fop/apps/XSLTInputHandler.java
+++ b/src/org/apache/fop/apps/XSLTInputHandler.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -30,15 +31,15 @@ public class XSLTInputHandler extends InputHandler {
File xmlfile, xsltfile;
boolean useOldTransform = false;
- public XSLTInputHandler (File xmlfile, File xsltfile) {
+ public XSLTInputHandler(File xmlfile, File xsltfile) {
this.xmlfile = xmlfile;
this.xsltfile = xsltfile;
}
/**
- * overwrites the method of the super class to return the xmlfile
+ * overwrites the method of the super class to return the xmlfile
*/
- public InputSource getInputSource () {
+ public InputSource getInputSource() {
if (useOldTransform) {
try {
java.io.Writer writer;
@@ -87,26 +88,29 @@ public class XSLTInputHandler extends InputHandler {
XMLReader result = null;
try {
// try trax first
- Class transformer = Class.forName("javax.xml.transform.Transformer");
- transformer = Class.forName("org.apache.fop.apps.TraxInputHandler");
- Class[] argTypes = { File.class, File.class };
- Method getFilterMethod =
- transformer.getMethod("getXMLFilter",argTypes);
- File[] args = {xmlfile, xsltfile};
+ Class transformer =
+ Class.forName("javax.xml.transform.Transformer");
+ transformer =
+ Class.forName("org.apache.fop.apps.TraxInputHandler");
+ Class[] argTypes = {
+ File.class, File.class
+ };
+ Method getFilterMethod = transformer.getMethod("getXMLFilter",
+ argTypes);
+ File[] args = {
+ xmlfile, xsltfile
+ };
Object obj = getFilterMethod.invoke(null, args);
if (obj instanceof XMLReader) {
- result = (XMLReader) obj;
+ result = (XMLReader)obj;
}
} catch (ClassNotFoundException ex) {
throw new FOPException(ex);
- }
- catch (InvocationTargetException ex) {
+ } catch (InvocationTargetException ex) {
throw new FOPException(ex);
- }
- catch (IllegalAccessException ex) {
+ } catch (IllegalAccessException ex) {
throw new FOPException(ex);
- }
- catch (NoSuchMethodException ex) {
+ } catch (NoSuchMethodException ex) {
throw new FOPException(ex);
}
// otherwise, use DOM documents via our XSLTransform tool class old style
@@ -117,5 +121,6 @@ public class XSLTInputHandler extends InputHandler {
return result;
}
+
}
diff --git a/src/org/apache/fop/apps/XTDriver.java b/src/org/apache/fop/apps/XTDriver.java
index b069bbabc..0fd8094d2 100644
--- a/src/org/apache/fop/apps/XTDriver.java
+++ b/src/org/apache/fop/apps/XTDriver.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.apps;
@@ -102,41 +58,55 @@ import java.io.*;
* Here is an example use of Driver from CommandLine.java:
*
*
- * Driver driver = new Driver();
- * driver.setRenderer("org.apache.fop.render.pdf.PDFRenderer", version);
- * driver.addElementMapping("org.apache.fop.fo.StandardElementMapping");
- * driver.addElementMapping("org.apache.fop.svg.SVGElementMapping");
- * driver.setWriter(new PrintWriter(new FileWriter(args[1])));
- * driver.buildFOTree(parser, fileInputSource(args[0]));
- * driver.format();
- * driver.render();
+ * Driver driver = new Driver();
+ * driver.setRenderer("org.apache.fop.render.pdf.PDFRenderer", version);
+ * driver.addElementMapping("org.apache.fop.fo.StandardElementMapping");
+ * driver.addElementMapping("org.apache.fop.svg.SVGElementMapping");
+ * driver.setWriter(new PrintWriter(new FileWriter(args[1])));
+ * driver.buildFOTree(parser, fileInputSource(args[0]));
+ * driver.format();
+ * driver.render();
*
*/
public class XTDriver {
- /** the FO tree builder */
+ /**
+ * the FO tree builder
+ */
protected XTFOTreeBuilder treeBuilder;
- /** the area tree that is the result of formatting the FO tree */
+ /**
+ * the area tree that is the result of formatting the FO tree
+ */
protected AreaTree areaTree;
- /** the renderer to use to output the area tree */
+ /**
+ * the renderer to use to output the area tree
+ */
protected Renderer renderer;
- /** the PrintWriter to use to output the results of the renderer */
+ /**
+ * the PrintWriter to use to output the results of the renderer
+ */
protected PrintWriter writer;
- /** the stream to use to output the results of the renderer */
+ /**
+ * the stream to use to output the results of the renderer
+ */
protected OutputStream stream;
- /** create a new Driver */
+ /**
+ * create a new Driver
+ */
public XTDriver() {
- this.treeBuilder = new XTFOTreeBuilder();
+ this.treeBuilder = new XTFOTreeBuilder();
}
-
- /** set the Renderer to use */
+
+ /**
+ * set the Renderer to use
+ */
public void setRenderer(Renderer renderer) {
- this.renderer = renderer;
+ this.renderer = renderer;
}
/**
@@ -144,8 +114,8 @@ public class XTDriver {
* producer string for those renderers that can make use of it
*/
public void setRenderer(String rendererClassName, String producer) {
- this.renderer = createRenderer(rendererClassName);
- this.renderer.setProducer(producer);
+ this.renderer = createRenderer(rendererClassName);
+ this.renderer.setProducer(producer);
}
/**
@@ -153,38 +123,37 @@ public class XTDriver {
* instantiate the Renderer class
*/
protected Renderer createRenderer(String rendererClassName) {
- MessageHandler.logln("using renderer " + rendererClassName);
-
- try {
- return (Renderer)
- Class.forName(rendererClassName).newInstance();
- } catch (ClassNotFoundException e) {
- MessageHandler.errorln("Could not find " + rendererClassName);
- } catch (InstantiationException e) {
- MessageHandler.errorln("Could not instantiate "
- + rendererClassName);
- } catch (IllegalAccessException e) {
- MessageHandler.errorln("Could not access " + rendererClassName);
- } catch (ClassCastException e) {
- MessageHandler.errorln(rendererClassName + " is not a renderer");
- }
- return null;
+ MessageHandler.logln("using renderer " + rendererClassName);
+
+ try {
+ return (Renderer)Class.forName(rendererClassName).newInstance();
+ } catch (ClassNotFoundException e) {
+ MessageHandler.errorln("Could not find " + rendererClassName);
+ } catch (InstantiationException e) {
+ MessageHandler.errorln("Could not instantiate "
+ + rendererClassName);
+ } catch (IllegalAccessException e) {
+ MessageHandler.errorln("Could not access " + rendererClassName);
+ } catch (ClassCastException e) {
+ MessageHandler.errorln(rendererClassName + " is not a renderer");
+ }
+ return null;
}
-
+
/**
* add the given element mapping.
*
* an element mapping maps element names to Java classes
*/
public void addElementMapping(ElementMapping mapping) {
- mapping.addToBuilder(this.treeBuilder);
+ mapping.addToBuilder(this.treeBuilder);
}
-
+
/**
* add the element mapping with the given class name
*/
public void addElementMapping(String mappingClassName) {
- createElementMapping(mappingClassName).addToBuilder(this.treeBuilder);
+ createElementMapping(mappingClassName).addToBuilder(this.treeBuilder);
}
/**
@@ -192,29 +161,29 @@ public class XTDriver {
* instantiate element mapping class
*/
protected ElementMapping createElementMapping(String mappingClassName) {
- MessageHandler.logln("using element mapping " + mappingClassName);
-
- try {
- return (ElementMapping)
- Class.forName(mappingClassName).newInstance();
- } catch (ClassNotFoundException e) {
- MessageHandler.errorln("Could not find " + mappingClassName);
- } catch (InstantiationException e) {
- MessageHandler.errorln("Could not instantiate "
- + mappingClassName);
- } catch (IllegalAccessException e) {
- MessageHandler.errorln("Could not access " + mappingClassName);
- } catch (ClassCastException e) {
- MessageHandler.errorln(mappingClassName + " is not an element mapping");
- }
- return null;
+ MessageHandler.logln("using element mapping " + mappingClassName);
+
+ try {
+ return (ElementMapping)Class.forName(mappingClassName).newInstance();
+ } catch (ClassNotFoundException e) {
+ MessageHandler.errorln("Could not find " + mappingClassName);
+ } catch (InstantiationException e) {
+ MessageHandler.errorln("Could not instantiate "
+ + mappingClassName);
+ } catch (IllegalAccessException e) {
+ MessageHandler.errorln("Could not access " + mappingClassName);
+ } catch (ClassCastException e) {
+ MessageHandler.errorln(mappingClassName
+ + " is not an element mapping");
+ }
+ return null;
}
/**
* add the element mapping with the given class name
*/
public void addPropertyList(String listClassName) {
- createPropertyList(listClassName).addToBuilder(this.treeBuilder);
+ createPropertyList(listClassName).addToBuilder(this.treeBuilder);
}
/**
@@ -222,22 +191,21 @@ public class XTDriver {
* instantiate list mapping class
*/
protected PropertyListMapping createPropertyList(String listClassName) {
- MessageHandler.logln("using property list mapping " + listClassName);
-
- try {
- return (PropertyListMapping)
- Class.forName(listClassName).newInstance();
- } catch (ClassNotFoundException e) {
- MessageHandler.errorln("Could not find " + listClassName);
- } catch (InstantiationException e) {
- MessageHandler.errorln("Could not instantiate "
- + listClassName);
- } catch (IllegalAccessException e) {
- MessageHandler.errorln("Could not access " + listClassName);
- } catch (ClassCastException e) {
- MessageHandler.errorln(listClassName + " is not an property list");
- }
- return null;
+ MessageHandler.logln("using property list mapping " + listClassName);
+
+ try {
+ return (PropertyListMapping)Class.forName(listClassName).newInstance();
+ } catch (ClassNotFoundException e) {
+ MessageHandler.errorln("Could not find " + listClassName);
+ } catch (InstantiationException e) {
+ MessageHandler.errorln("Could not instantiate " + listClassName);
+ } catch (IllegalAccessException e) {
+ MessageHandler.errorln("Could not access " + listClassName);
+ } catch (ClassCastException e) {
+ MessageHandler.errorln(listClassName
+ + " is not an property list");
+ }
+ return null;
}
/**
@@ -248,116 +216,115 @@ public class XTDriver {
* events but isn't a SAX Parser itself.
*/
public DocumentHandler getDocumentHandler() {
- return this.treeBuilder;
+ return this.treeBuilder;
}
/**
* build the formatting object tree using the given SAX Parser and
* SAX InputSource
*/
- public void buildFOTree(Parser parser, InputSource source)
- throws FOPException {
-
- parser.setDocumentHandler(this.treeBuilder);
- try {
- parser.parse(source);
- } catch (SAXException e) {
- if (e.getException() instanceof FOPException)
- throw (FOPException) e.getException();
- else
- throw new FOPException(e.getMessage());
- } catch (IOException e) {
- throw new FOPException(e.getMessage());
- }
+ public void buildFOTree(Parser parser,
+ InputSource source) throws FOPException {
+
+ parser.setDocumentHandler(this.treeBuilder);
+ try {
+ parser.parse(source);
+ } catch (SAXException e) {
+ if (e.getException() instanceof FOPException)
+ throw (FOPException)e.getException();
+ else
+ throw new FOPException(e.getMessage());
+ } catch (IOException e) {
+ throw new FOPException(e.getMessage());
+ }
}
/**
* build the formatting object tree using the given DOM Document
*/
- public void buildFOTree(Document document)
- throws FOPException {
-
- /* most of this code is modified from John Cowan's */
-
- Node currentNode;
- AttributesImpl currentAtts;
-
- /* temporary array for making Strings into character arrays */
- char[] array = null;
-
- currentAtts = new AttributesImpl();
-
- /* start at the document element */
- currentNode = document;
-
- try {
- while (currentNode != null) {
- switch (currentNode.getNodeType()) {
- case Node.DOCUMENT_NODE:
- this.treeBuilder.startDocument();
- break;
- case Node.CDATA_SECTION_NODE:
- case Node.TEXT_NODE:
- String data = currentNode.getNodeValue();
- int datalen = data.length();
- if (array == null || array.length < datalen) {
- /* if the array isn't big enough, make a new
- one */
- array = new char[datalen];
- }
- data.getChars(0, datalen, array, 0);
- this.treeBuilder.characters(array, 0, datalen);
- break;
- case Node.PROCESSING_INSTRUCTION_NODE:
- this.treeBuilder.processingInstruction(
- currentNode.getNodeName(),
- currentNode.getNodeValue());
- break;
- case Node.ELEMENT_NODE:
- NamedNodeMap map = currentNode.getAttributes();
- currentAtts.clear();
- for (int i = map.getLength() - 1; i >= 0; i--) {
- Attr att = (Attr)map.item(i);
- currentAtts.addAttribute("",
- att.getName(),
- "",
- "CDATA",
- att.getValue());
- }
- this.treeBuilder.startElement(
- "", currentNode.getNodeName(), "", currentAtts);
- break;
- }
-
- Node nextNode = currentNode.getFirstChild();
- if (nextNode != null) {
- currentNode = nextNode;
- continue;
- }
-
- while (currentNode != null) {
- switch (currentNode.getNodeType()) {
- case Node.DOCUMENT_NODE:
- this.treeBuilder.endDocument();
- break;
- case Node.ELEMENT_NODE:
- this.treeBuilder.endElement(
- "", currentNode.getNodeName(), "" );
- break;
- }
-
- nextNode = currentNode.getNextSibling();
- if (nextNode != null) {
- currentNode = nextNode;
- break;
- }
-
- currentNode = currentNode.getParentNode();
- }
- }
- } catch (SAXException e) {
- throw new FOPException(e.getMessage());
- }
+ public void buildFOTree(Document document) throws FOPException {
+
+ /* most of this code is modified from John Cowan's */
+
+ Node currentNode;
+ AttributesImpl currentAtts;
+
+ /* temporary array for making Strings into character arrays */
+ char[] array = null;
+
+ currentAtts = new AttributesImpl();
+
+ /* start at the document element */
+ currentNode = document;
+
+ try {
+ while (currentNode != null) {
+ switch (currentNode.getNodeType()) {
+ case Node.DOCUMENT_NODE:
+ this.treeBuilder.startDocument();
+ break;
+ case Node.CDATA_SECTION_NODE:
+ case Node.TEXT_NODE:
+ String data = currentNode.getNodeValue();
+ int datalen = data.length();
+ if (array == null || array.length < datalen) {
+ /*
+ * if the array isn't big enough, make a new
+ * one
+ */
+ array = new char[datalen];
+ }
+ data.getChars(0, datalen, array, 0);
+ this.treeBuilder.characters(array, 0, datalen);
+ break;
+ case Node.PROCESSING_INSTRUCTION_NODE:
+ this.treeBuilder.processingInstruction(currentNode.getNodeName(),
+ currentNode.getNodeValue());
+ break;
+ case Node.ELEMENT_NODE:
+ NamedNodeMap map = currentNode.getAttributes();
+ currentAtts.clear();
+ for (int i = map.getLength() - 1; i >= 0; i--) {
+ Attr att = (Attr)map.item(i);
+ currentAtts.addAttribute("", att.getName(), "",
+ "CDATA", att.getValue());
+ }
+ this.treeBuilder.startElement("",
+ currentNode.getNodeName(),
+ "", currentAtts);
+ break;
+ }
+
+ Node nextNode = currentNode.getFirstChild();
+ if (nextNode != null) {
+ currentNode = nextNode;
+ continue;
+ }
+
+ while (currentNode != null) {
+ switch (currentNode.getNodeType()) {
+ case Node.DOCUMENT_NODE:
+ this.treeBuilder.endDocument();
+ break;
+ case Node.ELEMENT_NODE:
+ this.treeBuilder.endElement("",
+ currentNode.getNodeName(),
+ "");
+ break;
+ }
+
+ nextNode = currentNode.getNextSibling();
+ if (nextNode != null) {
+ currentNode = nextNode;
+ break;
+ }
+
+ currentNode = currentNode.getParentNode();
+ }
+ }
+ } catch (SAXException e) {
+ throw new FOPException(e.getMessage());
+ }
}
/**
@@ -365,13 +332,13 @@ public class XTDriver {
* (if applicable)
*/
public void setWriter(PrintWriter writer) {
- this.writer = writer;
+ this.writer = writer;
}
/**
- * set the OutputStream to use to output the result of the Renderer
- * (if applicable)
- */
+ * set the OutputStream to use to output the result of the Renderer
+ * (if applicable)
+ */
public void setOutputStream(OutputStream stream) {
this.stream = stream;
}
@@ -379,22 +346,21 @@ public class XTDriver {
/**
* format the formatting object tree into an area tree
*/
- public void format()
- throws FOPException {
- FontInfo fontInfo = new FontInfo();
- this.renderer.setupFontInfo(fontInfo);
+ public void format() throws FOPException {
+ FontInfo fontInfo = new FontInfo();
+ this.renderer.setupFontInfo(fontInfo);
- this.areaTree = new AreaTree();
- this.areaTree.setFontInfo(fontInfo);
+ this.areaTree = new AreaTree();
+ this.areaTree.setFontInfo(fontInfo);
- this.treeBuilder.format(areaTree);
+ this.treeBuilder.format(areaTree);
}
/**
* render the area tree to the output form
*/
- public void render()
- throws IOException, FOPException {
- this.renderer.render(areaTree, this.stream);
+ public void render() throws IOException, FOPException {
+ this.renderer.render(areaTree, this.stream);
}
+
}
diff --git a/src/org/apache/fop/configuration/Configuration.java b/src/org/apache/fop/configuration/Configuration.java
index ec860c8e9..ad9deedae 100644
--- a/src/org/apache/fop/configuration/Configuration.java
+++ b/src/org/apache/fop/configuration/Configuration.java
@@ -1,6 +1,7 @@
-/*
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
+ * For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
@@ -12,32 +13,41 @@ import java.util.Enumeration;
import org.apache.fop.messaging.MessageHandler;
/**
- * a configuration class for all general configuration aspects except those
- * related to specific renderers. All configuration is stored
- * in key / value pairs. The value can be a String, a list of Strings
- * or a map, containing a list of key / value pairs.
+ * a configuration class for all general configuration aspects except those
+ * related to specific renderers. All configuration is stored
+ * in key / value pairs. The value can be a String, a list of Strings
+ * or a map, containing a list of key / value pairs.
*
*/
public class Configuration {
- /** defines role types */
+ /**
+ * defines role types
+ */
public final static int STANDARD = 0;
public final static int PDF = 1;
public final static int AWT = 2;
- /** stores the configuration information */
- private static Hashtable standardConfiguration = new Hashtable(30);;
- private static Hashtable pdfConfiguration = new Hashtable(20);
- private static Hashtable awtConfiguration = new Hashtable(20);
+ /**
+ * stores the configuration information
+ */
+ private static Hashtable standardConfiguration = new Hashtable(30);
+ ;
+ private static Hashtable pdfConfiguration = new Hashtable(20);
+ private static Hashtable awtConfiguration = new Hashtable(20);
- /** contains a Hashtable of existing Hashtables */
+ /**
+ * contains a Hashtable of existing Hashtables
+ */
private static Hashtable configuration = new Hashtable(3);
- /** loads the configuration types into the configuration Hashtable */
+ /**
+ * loads the configuration types into the configuration Hashtable
+ */
static {
- configuration.put("standard",standardConfiguration);
- configuration.put("pdf",pdfConfiguration);
- configuration.put("awt",awtConfiguration);
+ configuration.put("standard", standardConfiguration);
+ configuration.put("pdf", pdfConfiguration);
+ configuration.put("awt", awtConfiguration);
}
public static Hashtable getConfiguration() {
@@ -48,105 +58,117 @@ public class Configuration {
* general access method
*
* @param key a string containing the key value for the configuration value
- * role detemines the configuration target
+ * role detemines the configuration target
* @return Object containing the value; normally you would use one of the
- * convenience methods, which return the correct form.
- * null if the key is not defined.
+ * convenience methods, which return the correct form.
+ * null if the key is not defined.
*/
- public static Object getValue (String key, int role) {
+ public static Object getValue(String key, int role) {
switch (role) {
- case Configuration.STANDARD:
- return standardConfiguration.get(key);
- case Configuration.PDF:
- return pdfConfiguration.get(key);
- case Configuration.AWT:
- return awtConfiguration.get(key);
- default:
- return standardConfiguration.get(key);
+ case Configuration.STANDARD:
+ return standardConfiguration.get(key);
+ case Configuration.PDF:
+ return pdfConfiguration.get(key);
+ case Configuration.AWT:
+ return awtConfiguration.get(key);
+ default:
+ return standardConfiguration.get(key);
}
- };
+ }
+
+ ;
/**
- * convenience methods to access strings values in the configuration
- * @param key a string containing the key value for the configuration value
- * role detemines the configuration target
- * @return String a string containing the value
- * null if the key is not defined.
+ * convenience methods to access strings values in the configuration
+ * @param key a string containing the key value for the configuration value
+ * role detemines the configuration target
+ * @return String a string containing the value
+ * null if the key is not defined.
*/
public static String getStringValue(String key, int role) {
- Object obj = Configuration.getValue (key, role);
+ Object obj = Configuration.getValue(key, role);
if (obj instanceof String) {
- return (String) obj;
+ return (String)obj;
} else {
return null;
}
- };
+ }
+
+ ;
/**
- * convenience methods to access int values in the configuration
- * @param key a string containing the key value for the configuration value
- * role detemines the configuration target
- * @return int a int containing the value
- * -1 if the key is not defined.
+ * convenience methods to access int values in the configuration
+ * @param key a string containing the key value for the configuration value
+ * role detemines the configuration target
+ * @return int a int containing the value
+ * -1 if the key is not defined.
*/
public static int getIntValue(String key, int role) {
- Object obj = Configuration.getValue (key, role);
+ Object obj = Configuration.getValue(key, role);
if (obj instanceof String) {
- return Integer.parseInt((String) obj);
+ return Integer.parseInt((String)obj);
} else {
return -1;
}
- };
+ }
+
+ ;
/**
- * convenience methods to access boolean values in the configuration
- * @param key a string containing the key value for the configuration value
- * role detemines the configuration target
- * @return Boolean true or false as value
- * null if the key is not defined.
+ * convenience methods to access boolean values in the configuration
+ * @param key a string containing the key value for the configuration value
+ * role detemines the configuration target
+ * @return Boolean true or false as value
+ * null if the key is not defined.
*/
public static Boolean getBooleanValue(String key, int role) {
- Object obj = Configuration.getValue (key, role);
- if (obj instanceof String) {
- return new Boolean((String)obj);
- } else if (obj instanceof Boolean) {
- return (Boolean) obj;
- } else {
- return null;
- }
- };
+ Object obj = Configuration.getValue(key, role);
+ if (obj instanceof String) {
+ return new Boolean((String)obj);
+ } else if (obj instanceof Boolean) {
+ return (Boolean)obj;
+ } else {
+ return null;
+ }
+ }
+
+ ;
/**
- * convenience methods to access list values in the configuration
- * @param key a string containing the key value for the configuration value
- * role detemines the configuration target
- * @return Vector a Vector containing the values
- * null if the key is not defined.
+ * convenience methods to access list values in the configuration
+ * @param key a string containing the key value for the configuration value
+ * role detemines the configuration target
+ * @return Vector a Vector containing the values
+ * null if the key is not defined.
*/
public static Vector getListValue(String key, int role) {
- Object obj = Configuration.getValue (key, role);
+ Object obj = Configuration.getValue(key, role);
if (obj instanceof Vector) {
- return (Vector) obj;
+ return (Vector)obj;
} else {
return null;
}
- };
+ }
+
+ ;
/**
- * convenience methods to access map/hashtable values in the configuration
- * @param key a string containing the key value for the configuration value
- * role detemines the configuration target
- * @return Hashtable a Hashtable containing the values
- * null if the key is not defined.
+ * convenience methods to access map/hashtable values in the configuration
+ * @param key a string containing the key value for the configuration value
+ * role detemines the configuration target
+ * @return Hashtable a Hashtable containing the values
+ * null if the key is not defined.
*/
public static Hashtable getHashtableValue(String key, int role) {
- Object obj = Configuration.getValue (key, role);
+ Object obj = Configuration.getValue(key, role);
if (obj instanceof Hashtable) {
- return (Hashtable) obj;
+ return (Hashtable)obj;
} else {
return null;
}
- };
+ }
+
+ ;
/**
@@ -155,132 +177,135 @@ public class Configuration {
*
* @param key a string containing the key value for the configuration value
* @return Object containing the value; normally you would use one of the
- * convenience methods, which return the correct form.
- * null if the key is not defined.
+ * convenience methods, which return the correct form.
+ * null if the key is not defined.
*/
- public static Object getValue (String key) {
+ public static Object getValue(String key) {
return Configuration.getValue(key, Configuration.STANDARD);
}
/**
- * convenience methods to access strings values in the standard configuration
- *
- * @param key a string containing the key value for the configuration value
- * @return String a string containing the value
- * null if the key is not defined.
- */
+ * convenience methods to access strings values in the standard configuration
+ *
+ * @param key a string containing the key value for the configuration value
+ * @return String a string containing the value
+ * null if the key is not defined.
+ */
public static String getStringValue(String key) {
return Configuration.getStringValue(key, Configuration.STANDARD);
}
/**
- * convenience methods to access int values in the standard configuration
- *
- * @param key a string containing the key value for the configuration value
- * @return int a int containing the value
- * -1 if the key is not defined.
- */
+ * convenience methods to access int values in the standard configuration
+ *
+ * @param key a string containing the key value for the configuration value
+ * @return int a int containing the value
+ * -1 if the key is not defined.
+ */
public static int getIntValue(String key) {
return Configuration.getIntValue(key, Configuration.STANDARD);
}
/**
- * convenience methods to access boolean values in the configuration
- *
- * @param key a string containing the key value for the configuration value
- * @return boolean true or false as value
- * null if the key is not defined.
- */
+ * convenience methods to access boolean values in the configuration
+ *
+ * @param key a string containing the key value for the configuration value
+ * @return boolean true or false as value
+ * null if the key is not defined.
+ */
public static Boolean getBooleanValue(String key) {
return Configuration.getBooleanValue(key, Configuration.STANDARD);
}
/**
- * convenience methods to access list values in the standard configuration
- *
- * @param key a string containing the key value for the configuration value
- * @return Vector a Vector containing the values
- * null if the key is not defined.
- */
+ * convenience methods to access list values in the standard configuration
+ *
+ * @param key a string containing the key value for the configuration value
+ * @return Vector a Vector containing the values
+ * null if the key is not defined.
+ */
public static Vector getListValue(String key) {
return Configuration.getListValue(key, Configuration.STANDARD);
}
/**
- * convenience methods to access map/hashtable values in the standard configuration
- *
- * @param key a string containing the key value for the configuration value
- * @return Hashtable a Hashtable containing the values
- * null if the key is not defined.
- */
+ * convenience methods to access map/hashtable values in the standard configuration
+ *
+ * @param key a string containing the key value for the configuration value
+ * @return Hashtable a Hashtable containing the values
+ * null if the key is not defined.
+ */
public static Hashtable getHashtableValue(String key) {
return Configuration.getHashtableValue(key, Configuration.STANDARD);
}
/**
- * method to access fonts values in the standard configuration
- *
- * @param key a string containing the key value for the configuration value
- * @return Hashtable a Hashtable containing the values
- * null if the key is not defined.
- */
- public static Vector getFonts() {
- return (Vector) Configuration.getValue("fonts", Configuration.STANDARD);
- }
-
+ * method to access fonts values in the standard configuration
+ *
+ * @param key a string containing the key value for the configuration value
+ * @return Hashtable a Hashtable containing the values
+ * null if the key is not defined.
+ */
+ public static Vector getFonts() {
+ return (Vector)Configuration.getValue("fonts",
+ Configuration.STANDARD);
+ }
+
/**
- * initializes this configuration
- * @param config contains the configuration information
- */
+ * initializes this configuration
+ * @param config contains the configuration information
+ */
public static void setup(int role, Hashtable config) {
switch (role) {
- case Configuration.STANDARD:
- standardConfiguration = config;
- break;
- case Configuration.PDF:
- pdfConfiguration = config;
- break;
- case Configuration.AWT:
- awtConfiguration = config;
- break;
- default:
- MessageHandler.errorln("Can't setup configuration. Unknown configuration role/target");
+ case Configuration.STANDARD:
+ standardConfiguration = config;
+ break;
+ case Configuration.PDF:
+ pdfConfiguration = config;
+ break;
+ case Configuration.AWT:
+ awtConfiguration = config;
+ break;
+ default:
+ MessageHandler.errorln("Can't setup configuration. Unknown configuration role/target");
}
}
/**
- * adds information to the configuration map/hashtable in key,value form
- * @param key a string containing the key value for the configuration value
- * value the configuration information
- * role detemines the configuration target
- * @param value an Object containing the value; can be a String, a Vector or a Hashtable
- */
+ * adds information to the configuration map/hashtable in key,value form
+ * @param key a string containing the key value for the configuration value
+ * value the configuration information
+ * role detemines the configuration target
+ * @param value an Object containing the value; can be a String, a Vector or a Hashtable
+ */
public static void put(String key, Object value, int role) {
switch (role) {
- case Configuration.STANDARD:
- standardConfiguration.put(key, value);
- break;
- case Configuration.PDF:
- pdfConfiguration.put(key, value);
- break;
- case Configuration.AWT:
- awtConfiguration.put(key, value);
- break;
- default:
- standardConfiguration.put(key, value);
- MessageHandler.errorln(
- "Unknown role for new configuration entry. " +
- "Putting key:" + key + " - value:" + value + " into standard configuration.");
+ case Configuration.STANDARD:
+ standardConfiguration.put(key, value);
+ break;
+ case Configuration.PDF:
+ pdfConfiguration.put(key, value);
+ break;
+ case Configuration.AWT:
+ awtConfiguration.put(key, value);
+ break;
+ default:
+ standardConfiguration.put(key, value);
+ MessageHandler.errorln("Unknown role for new configuration entry. "
+ + "Putting key:" + key + " - value:"
+ + value + " into standard configuration.");
}
- };
+ }
+
+ ;
/**
- * adds information to the standard configuration map/hashtable in key,value form
- * @param key a string containing the key value for the configuration value
- * value the configuration information
- * role detemines the configuration target
- * @param value an Object containing the value; can be a String, a Vector or a Hashtable
+ * adds information to the standard configuration map/hashtable in key,value form
+ * @param key a string containing the key value for the configuration value
+ * value the configuration information
+ * role detemines the configuration target
+ * @param value an Object containing the value; can be a String, a Vector or a Hashtable
*/
public static void put(String key, Object value) {
@@ -288,8 +313,8 @@ public class Configuration {
}
/**
- * debug methods, which writes out all information in this configuration
- */
+ * debug methods, which writes out all information in this configuration
+ */
public static void dumpConfiguration() {
String key;
Object value;
@@ -298,20 +323,21 @@ public class Configuration {
Enumeration enum;
String tmp;
System.out.println("Dumping configuration: ");
- Hashtable [] configs = {standardConfiguration,
- pdfConfiguration, awtConfiguration};
- for (int i = 0; i < configs.length ; i++) {
+ Hashtable[] configs = {
+ standardConfiguration, pdfConfiguration, awtConfiguration
+ };
+ for (int i = 0; i < configs.length; i++) {
MessageHandler.logln("----------------------");
configuration = configs[i];
Enumeration enumeration = configuration.keys();
while (enumeration.hasMoreElements()) {
- key = (String) enumeration.nextElement();
+ key = (String)enumeration.nextElement();
MessageHandler.logln("key: " + key);
value = configuration.get(key);
if (value instanceof String) {
MessageHandler.logln(" value: " + value);
} else if (value instanceof Vector) {
- list = (Vector) value;
+ list = (Vector)value;
enum = list.elements();
MessageHandler.log(" values: ");
while (enum.hasMoreElements()) {
@@ -319,11 +345,11 @@ public class Configuration {
}
MessageHandler.logln("");
} else if (value instanceof Hashtable) {
- map = (Hashtable) value;
+ map = (Hashtable)value;
enum = map.keys();
MessageHandler.log(" values: ");
while (enum.hasMoreElements()) {
- tmp = (String) enum.nextElement();
+ tmp = (String)enum.nextElement();
MessageHandler.log(" " + tmp + ":" + map.get(tmp));
}
MessageHandler.logln("");
diff --git a/src/org/apache/fop/configuration/ConfigurationParser.java b/src/org/apache/fop/configuration/ConfigurationParser.java
index e06b99f43..3cce731aa 100644
--- a/src/org/apache/fop/configuration/ConfigurationParser.java
+++ b/src/org/apache/fop/configuration/ConfigurationParser.java
@@ -1,4 +1,5 @@
/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -7,16 +8,16 @@
package org.apache.fop.configuration;
-//sax
+// sax
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
-//java
+// java
import java.util.Hashtable;
import java.util.Vector;
-//fop
+// fop
import org.apache.fop.messaging.MessageHandler;
@@ -39,58 +40,64 @@ public class ConfigurationParser extends DefaultHandler {
private final int LIST = 1;
private final int MAP = 2;
- //state of parser
+ // state of parser
private int status = OUT;
private int datatype = -1;
- //store the result configuration
+ // store the result configuration
private static Hashtable configuration;
private static Hashtable activeConfiguration;
- //stores key for new config entry
+ // stores key for new config entry
private String key = "";
private Vector keyStack = new Vector();
- //stores string value
+ // stores string value
private String value = "";
- //stores key for new config entry
+ // stores key for new config entry
private String subkey = "";
- //stores list value
- private Vector list = new Vector (15);
+ // stores list value
+ private Vector list = new Vector(15);
- //stores hashtable value
+ // stores hashtable value
private Hashtable map = new Hashtable(15);
- /** locator for line number information */
+ /**
+ * locator for line number information
+ */
private Locator locator;
- /** determines role / target of configuration information, default is standard */
+ /**
+ * determines role / target of configuration information, default is standard
+ */
private String role = "standard";
- //stores fonts
+ // stores fonts
private Vector fontList = null;
- //stores information on one font
+ // stores information on one font
private FontInfo fontInfo = null;
- //stores information on a font triplet
+ // stores information on a font triplet
private FontTriplet fontTriplet = null;
- //information on a font
+ // information on a font
private String fontName, metricsFile, embedFile, kerningAsString;
private boolean kerning;
private Vector fontTriplets;
- //information on a font triplet
+ // information on a font triplet
private String fontTripletName, weight, style;
public void startDocument() {
configuration = Configuration.getConfiguration();
}
- /** get locator for position information */
+ /**
+ * get locator for position information
+ */
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
@@ -98,8 +105,8 @@ public class ConfigurationParser extends DefaultHandler {
/**
* extracts the element and attribute name and sets the fitting status and datatype values
*/
- public void startElement(String uri, String localName,
- String qName, Attributes attributes) {
+ public void startElement(String uri, String localName, String qName,
+ Attributes attributes) {
if (localName.equals("key")) {
status += IN_KEY;
} else if (localName.equals("value")) {
@@ -109,16 +116,16 @@ public class ConfigurationParser extends DefaultHandler {
} else if (localName.equals("subentry")) {
status += IN_SUBENTRY;
} else if (localName.equals("entry")) {
- //role=standard as default
+ // role=standard as default
if (attributes.getLength() == 0) {
role = "standard";
- //retrieve attribute value for "role" which determines configuration target
+ // retrieve attribute value for "role" which determines configuration target
} else {
role = attributes.getValue("role");
}
- } else if (localName.equals("configuration")) {
- } else if (localName.equals("fonts")) { //list of fonts starts
- fontList = new Vector (10);
+ } else if (localName.equals("configuration")) {}
+ else if (localName.equals("fonts")) { // list of fonts starts
+ fontList = new Vector(10);
} else if (localName.equals("font")) {
kerningAsString = attributes.getValue("kerning");
if (kerningAsString.equalsIgnoreCase("yes")) {
@@ -137,11 +144,11 @@ public class ConfigurationParser extends DefaultHandler {
fontTriplet = new FontTriplet(fontTripletName, weight, style);
fontTriplets.addElement(fontTriplet);
} else {
- //to make sure that user knows about false tag
- MessageHandler.errorln(
- "Unknown tag in configuration file: " + localName);
+ // to make sure that user knows about false tag
+ MessageHandler.errorln("Unknown tag in configuration file: "
+ + localName);
}
- } //end startElement
+ } // end startElement
/**
* stores subentries or entries into their hashes (map for subentries, configuration for entry)
@@ -149,14 +156,14 @@ public class ConfigurationParser extends DefaultHandler {
public void endElement(String uri, String localName, String qName) {
if (localName.equals("entry")) {
switch (datatype) {
- case STRING:
- this.store(role, key, value);
- break;
- case LIST:
- this.store(role, key, list);
- break;
- case MAP:
- this.store(role, key, map);
+ case STRING:
+ this.store(role, key, value);
+ break;
+ case LIST:
+ this.store(role, key, list);
+ break;
+ case MAP:
+ this.store(role, key, map);
}
status = OUT;
role = "standard";
@@ -164,7 +171,7 @@ public class ConfigurationParser extends DefaultHandler {
keyStack.removeElementAt(keyStack.size() - 1);
}
if (keyStack.size() > 0) {
- key = (String) keyStack.elementAt(keyStack.size() - 1);
+ key = (String)keyStack.elementAt(keyStack.size() - 1);
} else {
key = "";
}
@@ -176,7 +183,7 @@ public class ConfigurationParser extends DefaultHandler {
keyStack.removeElementAt(keyStack.size() - 1);
}
if (keyStack.size() > 0) {
- key = (String) keyStack.elementAt(keyStack.size() - 1);
+ key = (String)keyStack.elementAt(keyStack.size() - 1);
} else {
key = "";
}
@@ -200,8 +207,7 @@ public class ConfigurationParser extends DefaultHandler {
embedFile = null;
fontName = null;
kerningAsString = "";
- } else if (localName.equals("font-triplet")) {
- }
+ } else if (localName.equals("font-triplet")) {}
}
/**
@@ -209,30 +215,30 @@ public class ConfigurationParser extends DefaultHandler {
* variables
*/
public void characters(char[] ch, int start, int length) {
- char characters [] = new char [length];
+ char characters[] = new char[length];
System.arraycopy(ch, start, characters, 0, length);
String text = new String(characters);
switch (status) {
- case IN_KEY:
- key = text;
- break;
- case IN_LIST + IN_SUBENTRY + IN_KEY:
- subkey = text;
- break;
- case IN_VALUE:
- value = text;
- datatype = STRING;
- break;
- case IN_LIST + IN_VALUE:
- list.addElement(text);
- datatype = LIST;
- break;
- case IN_LIST + IN_SUBENTRY + IN_VALUE:
- value = text;
- datatype = MAP;
- break;
+ case IN_KEY:
+ key = text;
+ break;
+ case IN_LIST + IN_SUBENTRY + IN_KEY:
+ subkey = text;
+ break;
+ case IN_VALUE:
+ value = text;
+ datatype = STRING;
+ break;
+ case IN_LIST + IN_VALUE:
+ list.addElement(text);
+ datatype = LIST;
+ break;
+ case IN_LIST + IN_SUBENTRY + IN_VALUE:
+ value = text;
+ datatype = MAP;
+ break;
}
- } //end characters
+ } // end characters
/**
* stores configuration entry into configuration hashtable according to the role
@@ -241,14 +247,16 @@ public class ConfigurationParser extends DefaultHandler {
* @param key a string containing the key value for the configuration
* @param value a string containing the value for the configuration
*/
- private void store (String role, String key, Object value) {
- activeConfiguration = (Hashtable) configuration.get(role);
+ private void store(String role, String key, Object value) {
+ activeConfiguration = (Hashtable)configuration.get(role);
if (activeConfiguration != null) {
activeConfiguration.put(key, value);
} else {
- MessageHandler.errorln("Unknown role >" + role +
- "< for new configuration entry. \n" +
- "Putting configuration with key:" + key + " into standard configuration.");
+ MessageHandler.errorln("Unknown role >" + role
+ + "< for new configuration entry. \n"
+ + "Putting configuration with key:" + key
+ + " into standard configuration.");
}
}
+
}
diff --git a/src/org/apache/fop/configuration/ConfigurationReader.java b/src/org/apache/fop/configuration/ConfigurationReader.java
index 1d92f3afb..3f982407f 100644
--- a/src/org/apache/fop/configuration/ConfigurationReader.java
+++ b/src/org/apache/fop/configuration/ConfigurationReader.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -6,38 +7,43 @@
package org.apache.fop.configuration;
-//sax
+// sax
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.XMLReader;
import org.xml.sax.SAXException;
import java.io.IOException;
import org.xml.sax.InputSource;
-//fop
+// fop
import org.apache.fop.apps.Driver;
import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.apps.FOPException;
import org.apache.fop.configuration.Configuration;
/**
- * entry class for reading configuration from file and creating a configuration
- * class. typical use looks like that:
+ * entry class for reading configuration from file and creating a configuration
+ * class. typical use looks like that:
*
- * ConfigurationReader reader = new ConfigurationReader ("config.xml","standard");
- * try {
- * reader.start();
- * } catch (org.apache.fop.apps.FOPException error) {
- * reader.dumpError(error);
- * }
- *
- * Once the configuration has been setup, the information can be accessed with
- * the methods of StandardConfiguration.
+ * ConfigurationReader reader = new ConfigurationReader ("config.xml","standard");
+ * try {
+ * reader.start();
+ * } catch (org.apache.fop.apps.FOPException error) {
+ * reader.dumpError(error);
+ * }
+ *
+ * Once the configuration has been setup, the information can be accessed with
+ * the methods of StandardConfiguration.
*/
public class ConfigurationReader {
- /** show a full dump on error */
+
+ /**
+ * show a full dump on error
+ */
private static boolean errorDump = false;
- /** inputsource for configuration file */
+ /**
+ * inputsource for configuration file
+ */
private InputSource filename;
@@ -45,14 +51,14 @@ public class ConfigurationReader {
* creates a configuration reader
* @param filename the file which contains the configuration information
*/
- public ConfigurationReader (InputSource filename) {
+ public ConfigurationReader(InputSource filename) {
this.filename = filename;
}
/**
* intantiates parser and starts parsing of config file
*/
- public void start () throws FOPException {
+ public void start() throws FOPException {
XMLReader parser = createParser();
// setting the parser features
@@ -60,7 +66,8 @@ public class ConfigurationReader {
parser.setFeature("http://xml.org/sax/features/namespace-prefixes",
false);
} catch (SAXException e) {
- throw new FOPException("You need a parser which supports SAX version 2",e);
+ throw new FOPException("You need a parser which supports SAX version 2",
+ e);
}
ConfigurationParser configurationParser = new ConfigurationParser();
parser.setContentHandler(configurationParser);
@@ -69,12 +76,11 @@ public class ConfigurationReader {
parser.parse(filename);
} catch (SAXException e) {
if (e.getException() instanceof FOPException) {
- throw (FOPException) e.getException();
+ throw (FOPException)e.getException();
} else {
throw new FOPException(e);
}
- }
- catch (IOException e) {
+ } catch (IOException e) {
throw new FOPException(e);
}
}
@@ -88,26 +94,22 @@ public class ConfigurationReader {
public static XMLReader createParser() throws FOPException {
String parserClassName = Driver.getParserClassName();
if (errorDump) {
- MessageHandler.logln( "configuration reader using SAX parser " +
- parserClassName);
+ MessageHandler.logln("configuration reader using SAX parser "
+ + parserClassName);
}
try {
- return (XMLReader) Class.forName(
- parserClassName).newInstance();
+ return (XMLReader)Class.forName(parserClassName).newInstance();
} catch (ClassNotFoundException e) {
throw new FOPException("Could not find " + parserClassName, e);
- }
- catch (InstantiationException e) {
- throw new FOPException("Could not instantiate " +
- parserClassName, e);
- }
- catch (IllegalAccessException e) {
- throw new FOPException("Could not access " +
- parserClassName, e);
- }
- catch (ClassCastException e) {
- throw new FOPException(parserClassName + " is not a SAX driver",e);
+ } catch (InstantiationException e) {
+ throw new FOPException("Could not instantiate "
+ + parserClassName, e);
+ } catch (IllegalAccessException e) {
+ throw new FOPException("Could not access " + parserClassName, e);
+ } catch (ClassCastException e) {
+ throw new FOPException(parserClassName + " is not a SAX driver",
+ e);
}
}
@@ -118,8 +120,8 @@ public class ConfigurationReader {
if (errorDump) {
if (e instanceof SAXException) {
e.printStackTrace();
- if (((SAXException) e).getException() != null) {
- ((SAXException) e).getException().printStackTrace();
+ if (((SAXException)e).getException() != null) {
+ ((SAXException)e).getException().printStackTrace();
}
} else {
e.printStackTrace();
@@ -128,10 +130,11 @@ public class ConfigurationReader {
}
/**
- * long or short error messages
+ * long or short error messages
*
*/
public void setDumpError(boolean dumpError) {
errorDump = dumpError;
}
+
}
diff --git a/src/org/apache/fop/configuration/FontInfo.java b/src/org/apache/fop/configuration/FontInfo.java
index 07af6b12b..e552e0cd4 100644
--- a/src/org/apache/fop/configuration/FontInfo.java
+++ b/src/org/apache/fop/configuration/FontInfo.java
@@ -1,7 +1,8 @@
/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
@@ -18,8 +19,8 @@ public class FontInfo {
private boolean kerning;
private Vector fontTriplets;
- public FontInfo (String name, String metricsFile, boolean kerning,
- Vector fontTriplets, String embedFile) {
+ public FontInfo(String name, String metricsFile, boolean kerning,
+ Vector fontTriplets, String embedFile) {
this.name = name;
this.metricsFile = metricsFile;
this.embedFile = embedFile;
@@ -30,12 +31,15 @@ public class FontInfo {
public String getMetricsFile() {
return metricsFile;
}
+
public String getEmbedFile() {
return embedFile;
}
+
public boolean getKerning() {
return kerning;
}
+
public Vector getFontTriplets() {
return fontTriplets;
}
diff --git a/src/org/apache/fop/configuration/FontTriplet.java b/src/org/apache/fop/configuration/FontTriplet.java
index d5e927d6f..b39ab3edf 100644
--- a/src/org/apache/fop/configuration/FontTriplet.java
+++ b/src/org/apache/fop/configuration/FontTriplet.java
@@ -1,7 +1,8 @@
/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
diff --git a/src/org/apache/fop/datatypes/ColorSpace.java b/src/org/apache/fop/datatypes/ColorSpace.java
index 546d756bc..9b289369f 100644
--- a/src/org/apache/fop/datatypes/ColorSpace.java
+++ b/src/org/apache/fop/datatypes/ColorSpace.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -7,44 +8,47 @@
package org.apache.fop.datatypes;
public class ColorSpace {
- //Ok... so I had some grand purpose for this, but I can't recall.
- //I'm just writing it
+ // Ok... so I had some grand purpose for this, but I can't recall.
+ // I'm just writing it
public static int DEVICE_UNKNOWN = -1;
public static int DEVICE_GRAY = 1;
- //what's the *official* spelling?
- //public static int DEVICE_GREY = 1;
+ // what's the *official* spelling?
+ // public static int DEVICE_GREY = 1;
public static int DEVICE_RGB = 2;
public static int DEVICE_CMYK = 3;
- //Are there any others?
+ // Are there any others?
protected int currentColorSpace = -1;
- public ColorSpace (int theColorSpace) {
+ public ColorSpace(int theColorSpace) {
this.currentColorSpace = theColorSpace;
}
+
public int getColorSpace() {
return (this.currentColorSpace);
}
+
public void setColorSpace(int theColorSpace) {
this.currentColorSpace = theColorSpace;
}
- public String getColorSpacePDFString() {//this is for PDF Output. Does anyone else need a string representation?
+ public String getColorSpacePDFString() { // this is for PDF Output. Does anyone else need a string representation?
- //shouldn't this be a select-case? I can never remember
- //the syntax for that.
+ // shouldn't this be a select-case? I can never remember
+ // the syntax for that.
if (this.currentColorSpace == this.DEVICE_RGB) {
- return("DeviceRGB");
+ return ("DeviceRGB");
} else if (this.currentColorSpace == this.DEVICE_CMYK) {
- return("DeviceCMYK");
+ return ("DeviceCMYK");
} else if (this.currentColorSpace == this.DEVICE_GRAY) {
- return("DeviceGray");
- } else {//unknown... Error. Tell them it's RGB and hope they don't notice.
- return("DeviceRGB");
+ return ("DeviceGray");
+ } else { // unknown... Error. Tell them it's RGB and hope they don't notice.
+ return ("DeviceRGB");
}
}
+
}
diff --git a/src/org/apache/fop/datatypes/ColorType.java b/src/org/apache/fop/datatypes/ColorType.java
index 76e9fc723..3964343c3 100644
--- a/src/org/apache/fop/datatypes/ColorType.java
+++ b/src/org/apache/fop/datatypes/ColorType.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -14,583 +15,635 @@ import org.apache.fop.messaging.MessageHandler;
*/
public class ColorType {
- /** the red component */
+ /**
+ * the red component
+ */
protected float red;
- /** the green component */
+ /**
+ * the green component
+ */
protected float green;
- /** the blue component */
+ /**
+ * the blue component
+ */
protected float blue;
- /** the alpha component */
+ /**
+ * the alpha component
+ */
protected float alpha = 0;
- public ColorType (float red, float green, float blue) {
- this.red = red;
- this.green = green;
- this.blue = blue;
+ public ColorType(float red, float green, float blue) {
+ this.red = red;
+ this.green = green;
+ this.blue = blue;
}
/**
* set the colour given a particular String specifying either a
- * colour name or #RGB or #RRGGBB
+ * colour name or #RGB or #RRGGBB
*/
- public ColorType (String value) {
- if (value.startsWith("#")) {
- try {
- if (value.length()==4) {
- // note: divide by 15 so F = FF = 1 and so on
- this.red = Integer.parseInt(value.substring(1,2),16)/15f;
- this.green = Integer.parseInt(value.substring(2,3),16)/15f;
- this.blue = Integer.parseInt(value.substring(3),16)/15f;
- } else if (value.length()==7) {
- // note: divide by 255 so FF = 1
- this.red = Integer.parseInt(value.substring(1,3),16)/255f;
- this.green = Integer.parseInt(value.substring(3,5),16)/255f;
- this.blue = Integer.parseInt(value.substring(5),16)/255f;
- } else {
- this.red = 0;
- this.green = 0;
- this.blue = 0;
- MessageHandler.errorln("ERROR: unknown colour format. Must be #RGB or #RRGGBB");
- }
- } catch (Exception e) {
- this.red = 0;
- this.green = 0;
- this.blue = 0;
- MessageHandler.errorln("ERROR: unknown colour format. Must be #RGB or #RRGGBB");
- }
- } else if (value.startsWith("rgb(")) {
- int poss = value.indexOf("(");
- int pose = value.indexOf(")");
- if(poss != -1 && pose != -1) {
- value = value.substring(poss + 1, pose);
- StringTokenizer st = new StringTokenizer(value, ",");
- try {
- if(st.hasMoreTokens()) {
- String str = st.nextToken().trim();
- if(str.endsWith("%")) {
- this.red = Integer.parseInt(str.substring(0, str.length() - 1)) * 2.55f;
- } else {
- this.red = Integer.parseInt(str)/255f;
- }
- }
- if(st.hasMoreTokens()) {
- String str = st.nextToken().trim();
- if(str.endsWith("%")) {
- this.green = Integer.parseInt(str.substring(0, str.length() - 1)) * 2.55f;
- } else {
- this.green = Integer.parseInt(str)/255f;
- }
- }
- if(st.hasMoreTokens()) {
- String str = st.nextToken().trim();
- if(str.endsWith("%")) {
- this.blue = Integer.parseInt(str.substring(0, str.length() - 1)) * 2.55f;
- } else {
- this.blue = Integer.parseInt(str)/255f;
- }
- }
- } catch (Exception e) {
- this.red = 0;
- this.green = 0;
- this.blue = 0;
- MessageHandler.errorln("ERROR: unknown colour format. Must be #RGB or #RRGGBB");
- }
- }
- } else if (value.startsWith("url(")) {
- // refers to a gradient
- } else {
- if (value.toLowerCase().equals("transparent")) {
- this.red = 0;
- this.green = 0;
- this.blue = 0;
- this.alpha = 1;
- } else {
- boolean found = false;
- for(int count = 0; count < names.length; count++) {
- if (value.toLowerCase().equals(names[count])) {
- this.red = vals[count][0] / 255f;
- this.green = vals[count][1] / 255f;
- this.blue = vals[count][2] / 255f;
- found = true;
- break;
- }
- }
- if(!found) {
- this.red = 0;
- this.green = 0;
- this.blue = 0;
- MessageHandler.errorln("ERROR: unknown colour name: " + value);
- }
- }
- }
+ public ColorType(String value) {
+ if (value.startsWith("#")) {
+ try {
+ if (value.length() == 4) {
+ // note: divide by 15 so F = FF = 1 and so on
+ this.red = Integer.parseInt(value.substring(1, 2), 16)
+ / 15f;
+ this.green = Integer.parseInt(value.substring(2, 3), 16)
+ / 15f;
+ this.blue = Integer.parseInt(value.substring(3), 16)
+ / 15f;
+ } else if (value.length() == 7) {
+ // note: divide by 255 so FF = 1
+ this.red = Integer.parseInt(value.substring(1, 3), 16)
+ / 255f;
+ this.green = Integer.parseInt(value.substring(3, 5), 16)
+ / 255f;
+ this.blue = Integer.parseInt(value.substring(5), 16)
+ / 255f;
+ } else {
+ this.red = 0;
+ this.green = 0;
+ this.blue = 0;
+ MessageHandler.errorln("ERROR: unknown colour format. Must be #RGB or #RRGGBB");
+ }
+ } catch (Exception e) {
+ this.red = 0;
+ this.green = 0;
+ this.blue = 0;
+ MessageHandler.errorln("ERROR: unknown colour format. Must be #RGB or #RRGGBB");
+ }
+ } else if (value.startsWith("rgb(")) {
+ int poss = value.indexOf("(");
+ int pose = value.indexOf(")");
+ if (poss != -1 && pose != -1) {
+ value = value.substring(poss + 1, pose);
+ StringTokenizer st = new StringTokenizer(value, ",");
+ try {
+ if (st.hasMoreTokens()) {
+ String str = st.nextToken().trim();
+ if (str.endsWith("%")) {
+ this.red =
+ Integer.parseInt(str.substring(0, str.length() - 1))
+ * 2.55f;
+ } else {
+ this.red = Integer.parseInt(str) / 255f;
+ }
+ }
+ if (st.hasMoreTokens()) {
+ String str = st.nextToken().trim();
+ if (str.endsWith("%")) {
+ this.green =
+ Integer.parseInt(str.substring(0, str.length() - 1))
+ * 2.55f;
+ } else {
+ this.green = Integer.parseInt(str) / 255f;
+ }
+ }
+ if (st.hasMoreTokens()) {
+ String str = st.nextToken().trim();
+ if (str.endsWith("%")) {
+ this.blue =
+ Integer.parseInt(str.substring(0, str.length() - 1))
+ * 2.55f;
+ } else {
+ this.blue = Integer.parseInt(str) / 255f;
+ }
+ }
+ } catch (Exception e) {
+ this.red = 0;
+ this.green = 0;
+ this.blue = 0;
+ MessageHandler.errorln("ERROR: unknown colour format. Must be #RGB or #RRGGBB");
+ }
+ }
+ } else if (value.startsWith("url(")) {
+ // refers to a gradient
+ } else {
+ if (value.toLowerCase().equals("transparent")) {
+ this.red = 0;
+ this.green = 0;
+ this.blue = 0;
+ this.alpha = 1;
+ } else {
+ boolean found = false;
+ for (int count = 0; count < names.length; count++) {
+ if (value.toLowerCase().equals(names[count])) {
+ this.red = vals[count][0] / 255f;
+ this.green = vals[count][1] / 255f;
+ this.blue = vals[count][2] / 255f;
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ this.red = 0;
+ this.green = 0;
+ this.blue = 0;
+ MessageHandler.errorln("ERROR: unknown colour name: "
+ + value);
+ }
+ }
+ }
}
-
+
public float blue() {
- return this.blue;
+ return this.blue;
}
-
+
public float green() {
- return this.green;
+ return this.green;
}
-
+
public float red() {
- return this.red;
+ return this.red;
}
public float alpha() {
- return this.alpha;
+ return this.alpha;
}
- final static String[] names = {
- "aliceblue",
- "antiquewhite",
- "aqua",
- "aquamarine",
- "azure",
- "beige",
- "bisque",
- "black",
- "blanchedalmond",
- "blue",
- "blueviolet",
- "brown",
- "burlywood",
- "cadetblue",
- "chartreuse",
- "chocolate",
- "coral",
- "cornflowerblue",
- "cornsilk",
- "crimson",
- "cyan",
- "darkblue",
- "darkcyan",
- "darkgoldenrod",
- "darkgray",
- "darkgreen",
- "darkgrey",
- "darkkhaki",
- "darkmagenta",
- "darkolivegreen",
- "darkorange",
- "darkorchid",
- "darkred",
- "darksalmon",
- "darkseagreen",
- "darkslateblue",
- "darkslategray",
- "darkslategrey",
- "darkturquoise",
- "darkviolet",
- "deeppink",
- "deepskyblue",
- "dimgray",
- "dimgrey",
- "dodgerblue",
- "firebrick",
- "floralwhite",
- "forestgreen",
- "fuchsia",
- "gainsboro",
- "lightpink",
- "lightsalmon",
- "lightseagreen",
- "lightskyblue",
- "lightslategray",
- "lightslategrey",
- "lightsteelblue",
- "lightyellow",
- "lime",
- "limegreen",
- "linen",
- "magenta",
- "maroon",
- "mediumaquamarine",
- "mediumblue",
- "mediumorchid",
- "mediumpurple",
- "mediumseagreen",
- "mediumslateblue",
- "mediumspringgreen",
- "mediumturquoise",
- "mediumvioletred",
- "midnightblue",
- "mintcream",
- "mistyrose",
- "moccasin",
- "navajowhite",
- "navy",
- "oldlace",
- "olive",
- "olivedrab",
- "orange",
- "orangered",
- "orchid",
- "palegoldenrod",
- "palegreen",
- "paleturquoise",
- "palevioletred",
- "papayawhip",
- "peachpuff",
- "peru",
- "pink",
- "plum",
- "powderblue",
- "purple",
- "red",
- "rosybrown",
- "royalblue",
- "saddlebrown",
- "salmon",
- "ghostwhite",
- "gold",
- "goldenrod",
- "gray",
- "grey",
- "green",
- "greenyellow",
- "honeydew",
- "hotpink",
- "indianred",
- "indigo",
- "ivory",
- "khaki",
- "lavender",
- "lavenderblush",
- "lawngreen",
- "lemonchiffon",
- "lightblue",
- "lightcoral",
- "lightcyan",
- "lightgoldenrodyellow",
- "lightgray",
- "lightgreen",
- "lightgrey",
- "sandybrown",
- "seagreen",
- "seashell",
- "sienna",
- "silver",
- "skyblue",
- "slateblue",
- "slategray",
- "slategrey",
- "snow",
- "springgreen",
- "steelblue",
- "tan",
- "teal",
- "thistle",
- "tomato",
- "turquoise",
- "violet",
- "wheat",
- "white",
- "whitesmoke",
- "yellow",
- "yellowgreen"
- };
+ final static String[] names = {
+ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
+ "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
+ "burlywood", "cadetblue", "chartreuse", "chocolate", "coral",
+ "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue",
+ "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkgrey",
+ "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange",
+ "darkorchid", "darkred", "darksalmon", "darkseagreen",
+ "darkslateblue", "darkslategray", "darkslategrey", "darkturquoise",
+ "darkviolet", "deeppink", "deepskyblue", "dimgray", "dimgrey",
+ "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia",
+ "gainsboro", "lightpink", "lightsalmon", "lightseagreen",
+ "lightskyblue", "lightslategray", "lightslategrey", "lightsteelblue",
+ "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon",
+ "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
+ "mediumseagreen", "mediumslateblue", "mediumspringgreen",
+ "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream",
+ "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive",
+ "olivedrab", "orange", "orangered", "orchid", "palegoldenrod",
+ "palegreen", "paleturquoise", "palevioletred", "papayawhip",
+ "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red",
+ "rosybrown", "royalblue", "saddlebrown", "salmon", "ghostwhite",
+ "gold", "goldenrod", "gray", "grey", "green", "greenyellow",
+ "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki",
+ "lavender", "lavenderblush", "lawngreen", "lemonchiffon",
+ "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow",
+ "lightgray", "lightgreen", "lightgrey", "sandybrown", "seagreen",
+ "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray",
+ "slategrey", "snow", "springgreen", "steelblue", "tan", "teal",
+ "thistle", "tomato", "turquoise", "violet", "wheat", "white",
+ "whitesmoke", "yellow", "yellowgreen"
+ };
- final static int[][] vals = {
- {240, 248, 255},
- {250, 235, 215},
- {0, 255, 255},
- {127, 255, 212},
- {240, 255, 255},
- {245, 245, 220},
- {255, 228, 196},
- {0, 0, 0},
- {255, 235, 205},
- {0, 0, 255},
- {138, 43, 226},
- {165, 42, 42},
- {222, 184, 135},
- {95, 158, 160},
- {127, 255, 0},
- {210, 105, 30},
- {255, 127, 80},
- {100, 149, 237},
- {255, 248, 220},
- {220, 20, 60},
- {0, 255, 255},
- {0, 0, 139},
- {0, 139, 139},
- {184, 134, 11},
- {169, 169, 169},
- {0, 100, 0},
- {169, 169, 169},
- {189, 183, 107},
- {139, 0, 139},
- {85, 107, 47},
- {255, 140, 0},
- {153, 50, 204},
- {139, 0, 0},
- {233, 150, 122},
- {143, 188, 143},
- {72, 61, 139},
- {47, 79, 79},
- {47, 79, 79},
- {0, 206, 209},
- {148, 0, 211},
- {255, 20, 147},
- {0, 191, 255},
- {105, 105, 105},
- {105, 105, 105},
- {30, 144, 255},
- {178, 34, 34},
- {255, 250, 240},
- {34, 139, 34},
- {255, 0, 255},
- {220, 220, 220},
- {255, 182, 193},
- {255, 160, 122},
- {32, 178, 170},
- {135, 206, 250},
- {119, 136, 153},
- {119, 136, 153},
- {176, 196, 222},
- {255, 255, 224},
- {0, 255, 0},
- {50, 205, 50},
- {250, 240, 230},
- {255, 0, 255},
- {128, 0, 0},
- {102, 205, 170},
- {0, 0, 205},
- {186, 85, 211},
- {147, 112, 219},
- {60, 179, 113},
- {123, 104, 238},
- {0, 250, 154},
- {72, 209, 204},
- {199, 21, 133},
- {25, 25, 112},
- {245, 255, 250},
- {255, 228, 225},
- {255, 228, 181},
- {255, 222, 173},
- {0, 0, 128},
- {253, 245, 230},
- {128, 128, 0},
- {107, 142, 35},
- {255, 165, 0},
- {255, 69, 0},
- {218, 112, 214},
- {238, 232, 170},
- {152, 251, 152},
- {175, 238, 238},
- {219, 112, 147},
- {255, 239, 213},
- {255, 218, 185},
- {205, 133, 63},
- {255, 192, 203},
- {221, 160, 221},
- {176, 224, 230},
- {128, 0, 128},
- {255, 0, 0},
- {188, 143, 143},
- {65, 105, 225},
- {139, 69, 19},
- {250, 128, 114},
- {248, 248, 255},
- {255, 215, 0},
- {218, 165, 32},
- {128, 128, 128},
- {128, 128, 128},
- {0, 128, 0},
- {173, 255, 47},
- {240, 255, 240},
- {255, 105, 180},
- {205, 92, 92},
- {75, 0, 130},
- {255, 255, 240},
- {240, 230, 140},
- {230, 230, 250},
- {255, 240, 245},
- {124, 252, 0},
- {255, 250, 205},
- {173, 216, 230},
- {240, 128, 128},
- {224, 255, 255},
- {250, 250, 210},
- {211, 211, 211},
- {144, 238, 144},
- {211, 211, 211},
- {244, 164, 96},
- {46, 139, 87},
- {255, 245, 238},
- {160, 82, 45},
- {192, 192, 192},
- {135, 206, 235},
- {106, 90, 205},
- {112, 128, 144},
- {112, 128, 144},
- {255, 250, 250},
- {0, 255, 127},
- {70, 130, 180},
- {210, 180, 140},
- {0, 128, 128},
- {216, 191, 216},
- {255, 99, 71},
- {64, 224, 208},
- {238, 130, 238},
- {245, 222, 179},
- {255, 255, 255},
- {245, 245, 245},
- {255, 255, 0},
- {154, 205, 50}
- };
+ final static int[][] vals = {
+ {
+ 240, 248, 255
+ }, {
+ 250, 235, 215
+ }, {
+ 0, 255, 255
+ }, {
+ 127, 255, 212
+ }, {
+ 240, 255, 255
+ }, {
+ 245, 245, 220
+ }, {
+ 255, 228, 196
+ }, {
+ 0, 0, 0
+ }, {
+ 255, 235, 205
+ }, {
+ 0, 0, 255
+ }, {
+ 138, 43, 226
+ }, {
+ 165, 42, 42
+ }, {
+ 222, 184, 135
+ }, {
+ 95, 158, 160
+ }, {
+ 127, 255, 0
+ }, {
+ 210, 105, 30
+ }, {
+ 255, 127, 80
+ }, {
+ 100, 149, 237
+ }, {
+ 255, 248, 220
+ }, {
+ 220, 20, 60
+ }, {
+ 0, 255, 255
+ }, {
+ 0, 0, 139
+ }, {
+ 0, 139, 139
+ }, {
+ 184, 134, 11
+ }, {
+ 169, 169, 169
+ }, {
+ 0, 100, 0
+ }, {
+ 169, 169, 169
+ }, {
+ 189, 183, 107
+ }, {
+ 139, 0, 139
+ }, {
+ 85, 107, 47
+ }, {
+ 255, 140, 0
+ }, {
+ 153, 50, 204
+ }, {
+ 139, 0, 0
+ }, {
+ 233, 150, 122
+ }, {
+ 143, 188, 143
+ }, {
+ 72, 61, 139
+ }, {
+ 47, 79, 79
+ }, {
+ 47, 79, 79
+ }, {
+ 0, 206, 209
+ }, {
+ 148, 0, 211
+ }, {
+ 255, 20, 147
+ }, {
+ 0, 191, 255
+ }, {
+ 105, 105, 105
+ }, {
+ 105, 105, 105
+ }, {
+ 30, 144, 255
+ }, {
+ 178, 34, 34
+ }, {
+ 255, 250, 240
+ }, {
+ 34, 139, 34
+ }, {
+ 255, 0, 255
+ }, {
+ 220, 220, 220
+ }, {
+ 255, 182, 193
+ }, {
+ 255, 160, 122
+ }, {
+ 32, 178, 170
+ }, {
+ 135, 206, 250
+ }, {
+ 119, 136, 153
+ }, {
+ 119, 136, 153
+ }, {
+ 176, 196, 222
+ }, {
+ 255, 255, 224
+ }, {
+ 0, 255, 0
+ }, {
+ 50, 205, 50
+ }, {
+ 250, 240, 230
+ }, {
+ 255, 0, 255
+ }, {
+ 128, 0, 0
+ }, {
+ 102, 205, 170
+ }, {
+ 0, 0, 205
+ }, {
+ 186, 85, 211
+ }, {
+ 147, 112, 219
+ }, {
+ 60, 179, 113
+ }, {
+ 123, 104, 238
+ }, {
+ 0, 250, 154
+ }, {
+ 72, 209, 204
+ }, {
+ 199, 21, 133
+ }, {
+ 25, 25, 112
+ }, {
+ 245, 255, 250
+ }, {
+ 255, 228, 225
+ }, {
+ 255, 228, 181
+ }, {
+ 255, 222, 173
+ }, {
+ 0, 0, 128
+ }, {
+ 253, 245, 230
+ }, {
+ 128, 128, 0
+ }, {
+ 107, 142, 35
+ }, {
+ 255, 165, 0
+ }, {
+ 255, 69, 0
+ }, {
+ 218, 112, 214
+ }, {
+ 238, 232, 170
+ }, {
+ 152, 251, 152
+ }, {
+ 175, 238, 238
+ }, {
+ 219, 112, 147
+ }, {
+ 255, 239, 213
+ }, {
+ 255, 218, 185
+ }, {
+ 205, 133, 63
+ }, {
+ 255, 192, 203
+ }, {
+ 221, 160, 221
+ }, {
+ 176, 224, 230
+ }, {
+ 128, 0, 128
+ }, {
+ 255, 0, 0
+ }, {
+ 188, 143, 143
+ }, {
+ 65, 105, 225
+ }, {
+ 139, 69, 19
+ }, {
+ 250, 128, 114
+ }, {
+ 248, 248, 255
+ }, {
+ 255, 215, 0
+ }, {
+ 218, 165, 32
+ }, {
+ 128, 128, 128
+ }, {
+ 128, 128, 128
+ }, {
+ 0, 128, 0
+ }, {
+ 173, 255, 47
+ }, {
+ 240, 255, 240
+ }, {
+ 255, 105, 180
+ }, {
+ 205, 92, 92
+ }, {
+ 75, 0, 130
+ }, {
+ 255, 255, 240
+ }, {
+ 240, 230, 140
+ }, {
+ 230, 230, 250
+ }, {
+ 255, 240, 245
+ }, {
+ 124, 252, 0
+ }, {
+ 255, 250, 205
+ }, {
+ 173, 216, 230
+ }, {
+ 240, 128, 128
+ }, {
+ 224, 255, 255
+ }, {
+ 250, 250, 210
+ }, {
+ 211, 211, 211
+ }, {
+ 144, 238, 144
+ }, {
+ 211, 211, 211
+ }, {
+ 244, 164, 96
+ }, {
+ 46, 139, 87
+ }, {
+ 255, 245, 238
+ }, {
+ 160, 82, 45
+ }, {
+ 192, 192, 192
+ }, {
+ 135, 206, 235
+ }, {
+ 106, 90, 205
+ }, {
+ 112, 128, 144
+ }, {
+ 112, 128, 144
+ }, {
+ 255, 250, 250
+ }, {
+ 0, 255, 127
+ }, {
+ 70, 130, 180
+ }, {
+ 210, 180, 140
+ }, {
+ 0, 128, 128
+ }, {
+ 216, 191, 216
+ }, {
+ 255, 99, 71
+ }, {
+ 64, 224, 208
+ }, {
+ 238, 130, 238
+ }, {
+ 245, 222, 179
+ }, {
+ 255, 255, 255
+ }, {
+ 245, 245, 245
+ }, {
+ 255, 255, 0
+ }, {
+ 154, 205, 50
+ }
+ };
}
-/*
-aliceblue rgb(240, 248, 255)
-antiquewhite rgb(250, 235, 215)
-aqua rgb( 0, 255, 255)
-aquamarine rgb(127, 255, 212)
-azure rgb(240, 255, 255)
-beige rgb(245, 245, 220)
-bisque rgb(255, 228, 196)
-black rgb( 0, 0, 0)
-blanchedalmond rgb(255, 235, 205)
-blue rgb( 0, 0, 255)
-blueviolet rgb(138, 43, 226)
-brown rgb(165, 42, 42)
-burlywood rgb(222, 184, 135)
-cadetblue rgb( 95, 158, 160)
-chartreuse rgb(127, 255, 0)
-chocolate rgb(210, 105, 30)
-coral rgb(255, 127, 80)
-cornflowerblue rgb(100, 149, 237)
-cornsilk rgb(255, 248, 220)
-crimson rgb(220, 20, 60)
-cyan rgb( 0, 255, 255)
-darkblue rgb( 0, 0, 139)
-darkcyan rgb( 0, 139, 139)
-darkgoldenrod rgb(184, 134, 11)
-darkgray rgb(169, 169, 169)
-darkgreen rgb( 0, 100, 0)
-darkgrey rgb(169, 169, 169)
-darkkhaki rgb(189, 183, 107)
-darkmagenta rgb(139, 0, 139)
-darkolivegreen rgb( 85, 107, 47)
-darkorange rgb(255, 140, 0)
-darkorchid rgb(153, 50, 204)
-darkred rgb(139, 0, 0)
-darksalmon rgb(233, 150, 122)
-darkseagreen rgb(143, 188, 143)
-darkslateblue rgb( 72, 61, 139)
-darkslategray rgb( 47, 79, 79)
-darkslategrey rgb( 47, 79, 79)
-darkturquoise rgb( 0, 206, 209)
-darkviolet rgb(148, 0, 211)
-deeppink rgb(255, 20, 147)
-deepskyblue rgb( 0, 191, 255)
-dimgray rgb(105, 105, 105)
-dimgrey rgb(105, 105, 105)
-dodgerblue rgb( 30, 144, 255)
-firebrick rgb(178, 34, 34)
-floralwhite rgb(255, 250, 240)
-forestgreen rgb( 34, 139, 34)
-fuchsia rgb(255, 0, 255)
-gainsboro rgb(220, 220, 220)
-lightpink rgb(255, 182, 193)
-lightsalmon rgb(255, 160, 122)
-lightseagreen rgb( 32, 178, 170)
-lightskyblue rgb(135, 206, 250)
-lightslategray rgb(119, 136, 153)
-lightslategrey rgb(119, 136, 153)
-lightsteelblue rgb(176, 196, 222)
-lightyellow rgb(255, 255, 224)
-lime rgb( 0, 255, 0)
-limegreen rgb( 50, 205, 50)
-linen rgb(250, 240, 230)
-magenta rgb(255, 0, 255)
-maroon rgb(128, 0, 0)
-mediumaquamarine rgb(102, 205, 170)
-mediumblue rgb( 0, 0, 205)
-mediumorchid rgb(186, 85, 211)
-mediumpurple rgb(147, 112, 219)
-mediumseagreen rgb( 60, 179, 113)
-mediumslateblue rgb(123, 104, 238)
-mediumspringgreen rgb( 0, 250, 154)
-mediumturquoise rgb( 72, 209, 204)
-mediumvioletred rgb(199, 21, 133)
-midnightblue rgb( 25, 25, 112)
-mintcream rgb(245, 255, 250)
-mistyrose rgb(255, 228, 225)
-moccasin rgb(255, 228, 181)
-navajowhite rgb(255, 222, 173)
-navy rgb( 0, 0, 128)
-oldlace rgb(253, 245, 230)
-olive rgb(128, 128, 0)
-olivedrab rgb(107, 142, 35)
-orange rgb(255, 165, 0)
-orangered rgb(255, 69, 0)
-orchid rgb(218, 112, 214)
-palegoldenrod rgb(238, 232, 170)
-palegreen rgb(152, 251, 152)
-paleturquoise rgb(175, 238, 238)
-palevioletred rgb(219, 112, 147)
-papayawhip rgb(255, 239, 213)
-peachpuff rgb(255, 218, 185)
-peru rgb(205, 133, 63)
-pink rgb(255, 192, 203)
-plum rgb(221, 160, 221)
-powderblue rgb(176, 224, 230)
-purple rgb(128, 0, 128)
-red rgb(255, 0, 0)
-rosybrown rgb(188, 143, 143)
-royalblue rgb( 65, 105, 225)
-saddlebrown rgb(139, 69, 19)
-salmon rgb(250, 128, 114)
-ghostwhite rgb(248, 248, 255)
-gold rgb(255, 215, 0)
-goldenrod rgb(218, 165, 32)
-gray rgb(128, 128, 128)
-grey rgb(128, 128, 128)
-green rgb( 0, 128, 0)
-greenyellow rgb(173, 255, 47)
-honeydew rgb(240, 255, 240)
-hotpink rgb(255, 105, 180)
-indianred rgb(205, 92, 92)
-indigo rgb( 75, 0, 130)
-ivory rgb(255, 255, 240)
-khaki rgb(240, 230, 140)
-lavender rgb(230, 230, 250)
-lavenderblush rgb(255, 240, 245)
-lawngreen rgb(124, 252, 0)
-lemonchiffon rgb(255, 250, 205)
-lightblue rgb(173, 216, 230)
-lightcoral rgb(240, 128, 128)
-lightcyan rgb(224, 255, 255)
-lightgoldenrodyellow rgb(250, 250, 210)
-lightgray rgb(211, 211, 211)
-lightgreen rgb(144, 238, 144)
-lightgrey rgb(211, 211, 211)
-sandybrown rgb(244, 164, 96)
-seagreen rgb( 46, 139, 87)
-seashell rgb(255, 245, 238)
-sienna rgb(160, 82, 45)
-silver rgb(192, 192, 192)
-skyblue rgb(135, 206, 235)
-slateblue rgb(106, 90, 205)
-slategray rgb(112, 128, 144)
-slategrey rgb(112, 128, 144)
-snow rgb(255, 250, 250)
-springgreen rgb( 0, 255, 127)
-steelblue rgb( 70, 130, 180)
-tan rgb(210, 180, 140)
-teal rgb( 0, 128, 128)
-thistle rgb(216, 191, 216)
-tomato rgb(255, 99, 71)
-turquoise rgb( 64, 224, 208)
-violet rgb(238, 130, 238)
-wheat rgb(245, 222, 179)
-white rgb(255, 255, 255)
-whitesmoke rgb(245, 245, 245)
-yellow rgb(255, 255, 0)
-yellowgreen rgb(154, 205, 50)
-*/
+/*
+ * aliceblue rgb(240, 248, 255)
+ * antiquewhite rgb(250, 235, 215)
+ * aqua rgb( 0, 255, 255)
+ * aquamarine rgb(127, 255, 212)
+ * azure rgb(240, 255, 255)
+ * beige rgb(245, 245, 220)
+ * bisque rgb(255, 228, 196)
+ * black rgb( 0, 0, 0)
+ * blanchedalmond rgb(255, 235, 205)
+ * blue rgb( 0, 0, 255)
+ * blueviolet rgb(138, 43, 226)
+ * brown rgb(165, 42, 42)
+ * burlywood rgb(222, 184, 135)
+ * cadetblue rgb( 95, 158, 160)
+ * chartreuse rgb(127, 255, 0)
+ * chocolate rgb(210, 105, 30)
+ * coral rgb(255, 127, 80)
+ * cornflowerblue rgb(100, 149, 237)
+ * cornsilk rgb(255, 248, 220)
+ * crimson rgb(220, 20, 60)
+ * cyan rgb( 0, 255, 255)
+ * darkblue rgb( 0, 0, 139)
+ * darkcyan rgb( 0, 139, 139)
+ * darkgoldenrod rgb(184, 134, 11)
+ * darkgray rgb(169, 169, 169)
+ * darkgreen rgb( 0, 100, 0)
+ * darkgrey rgb(169, 169, 169)
+ * darkkhaki rgb(189, 183, 107)
+ * darkmagenta rgb(139, 0, 139)
+ * darkolivegreen rgb( 85, 107, 47)
+ * darkorange rgb(255, 140, 0)
+ * darkorchid rgb(153, 50, 204)
+ * darkred rgb(139, 0, 0)
+ * darksalmon rgb(233, 150, 122)
+ * darkseagreen rgb(143, 188, 143)
+ * darkslateblue rgb( 72, 61, 139)
+ * darkslategray rgb( 47, 79, 79)
+ * darkslategrey rgb( 47, 79, 79)
+ * darkturquoise rgb( 0, 206, 209)
+ * darkviolet rgb(148, 0, 211)
+ * deeppink rgb(255, 20, 147)
+ * deepskyblue rgb( 0, 191, 255)
+ * dimgray rgb(105, 105, 105)
+ * dimgrey rgb(105, 105, 105)
+ * dodgerblue rgb( 30, 144, 255)
+ * firebrick rgb(178, 34, 34)
+ * floralwhite rgb(255, 250, 240)
+ * forestgreen rgb( 34, 139, 34)
+ * fuchsia rgb(255, 0, 255)
+ * gainsboro rgb(220, 220, 220)
+ * lightpink rgb(255, 182, 193)
+ * lightsalmon rgb(255, 160, 122)
+ * lightseagreen rgb( 32, 178, 170)
+ * lightskyblue rgb(135, 206, 250)
+ * lightslategray rgb(119, 136, 153)
+ * lightslategrey rgb(119, 136, 153)
+ * lightsteelblue rgb(176, 196, 222)
+ * lightyellow rgb(255, 255, 224)
+ * lime rgb( 0, 255, 0)
+ * limegreen rgb( 50, 205, 50)
+ * linen rgb(250, 240, 230)
+ * magenta rgb(255, 0, 255)
+ * maroon rgb(128, 0, 0)
+ * mediumaquamarine rgb(102, 205, 170)
+ * mediumblue rgb( 0, 0, 205)
+ * mediumorchid rgb(186, 85, 211)
+ * mediumpurple rgb(147, 112, 219)
+ * mediumseagreen rgb( 60, 179, 113)
+ * mediumslateblue rgb(123, 104, 238)
+ * mediumspringgreen rgb( 0, 250, 154)
+ * mediumturquoise rgb( 72, 209, 204)
+ * mediumvioletred rgb(199, 21, 133)
+ * midnightblue rgb( 25, 25, 112)
+ * mintcream rgb(245, 255, 250)
+ * mistyrose rgb(255, 228, 225)
+ * moccasin rgb(255, 228, 181)
+ * navajowhite rgb(255, 222, 173)
+ * navy rgb( 0, 0, 128)
+ * oldlace rgb(253, 245, 230)
+ * olive rgb(128, 128, 0)
+ * olivedrab rgb(107, 142, 35)
+ * orange rgb(255, 165, 0)
+ * orangered rgb(255, 69, 0)
+ * orchid rgb(218, 112, 214)
+ * palegoldenrod rgb(238, 232, 170)
+ * palegreen rgb(152, 251, 152)
+ * paleturquoise rgb(175, 238, 238)
+ * palevioletred rgb(219, 112, 147)
+ * papayawhip rgb(255, 239, 213)
+ * peachpuff rgb(255, 218, 185)
+ * peru rgb(205, 133, 63)
+ * pink rgb(255, 192, 203)
+ * plum rgb(221, 160, 221)
+ * powderblue rgb(176, 224, 230)
+ * purple rgb(128, 0, 128)
+ * red rgb(255, 0, 0)
+ * rosybrown rgb(188, 143, 143)
+ * royalblue rgb( 65, 105, 225)
+ * saddlebrown rgb(139, 69, 19)
+ * salmon rgb(250, 128, 114)
+ * ghostwhite rgb(248, 248, 255)
+ * gold rgb(255, 215, 0)
+ * goldenrod rgb(218, 165, 32)
+ * gray rgb(128, 128, 128)
+ * grey rgb(128, 128, 128)
+ * green rgb( 0, 128, 0)
+ * greenyellow rgb(173, 255, 47)
+ * honeydew rgb(240, 255, 240)
+ * hotpink rgb(255, 105, 180)
+ * indianred rgb(205, 92, 92)
+ * indigo rgb( 75, 0, 130)
+ * ivory rgb(255, 255, 240)
+ * khaki rgb(240, 230, 140)
+ * lavender rgb(230, 230, 250)
+ * lavenderblush rgb(255, 240, 245)
+ * lawngreen rgb(124, 252, 0)
+ * lemonchiffon rgb(255, 250, 205)
+ * lightblue rgb(173, 216, 230)
+ * lightcoral rgb(240, 128, 128)
+ * lightcyan rgb(224, 255, 255)
+ * lightgoldenrodyellow rgb(250, 250, 210)
+ * lightgray rgb(211, 211, 211)
+ * lightgreen rgb(144, 238, 144)
+ * lightgrey rgb(211, 211, 211)
+ * sandybrown rgb(244, 164, 96)
+ * seagreen rgb( 46, 139, 87)
+ * seashell rgb(255, 245, 238)
+ * sienna rgb(160, 82, 45)
+ * silver rgb(192, 192, 192)
+ * skyblue rgb(135, 206, 235)
+ * slateblue rgb(106, 90, 205)
+ * slategray rgb(112, 128, 144)
+ * slategrey rgb(112, 128, 144)
+ * snow rgb(255, 250, 250)
+ * springgreen rgb( 0, 255, 127)
+ * steelblue rgb( 70, 130, 180)
+ * tan rgb(210, 180, 140)
+ * teal rgb( 0, 128, 128)
+ * thistle rgb(216, 191, 216)
+ * tomato rgb(255, 99, 71)
+ * turquoise rgb( 64, 224, 208)
+ * violet rgb(238, 130, 238)
+ * wheat rgb(245, 222, 179)
+ * white rgb(255, 255, 255)
+ * whitesmoke rgb(245, 245, 245)
+ * yellow rgb(255, 255, 0)
+ * yellowgreen rgb(154, 205, 50)
+ */
diff --git a/src/org/apache/fop/datatypes/CompoundDatatype.java b/src/org/apache/fop/datatypes/CompoundDatatype.java
index 820eab327..3e2f6bc6e 100644
--- a/src/org/apache/fop/datatypes/CompoundDatatype.java
+++ b/src/org/apache/fop/datatypes/CompoundDatatype.java
@@ -1,59 +1,16 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.datatypes;
import org.apache.fop.fo.Property;
public interface CompoundDatatype {
- public void setComponent(String sCmpnName, Property cmpnValue,
- boolean bIsDefault);
+ public void setComponent(String sCmpnName, Property cmpnValue,
+ boolean bIsDefault);
- public Property getComponent(String sCmpnName);
+ public Property getComponent(String sCmpnName);
}
diff --git a/src/org/apache/fop/datatypes/CondLength.java b/src/org/apache/fop/datatypes/CondLength.java
index a338f7586..1e2f1999c 100644
--- a/src/org/apache/fop/datatypes/CondLength.java
+++ b/src/org/apache/fop/datatypes/CondLength.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.datatypes;
import org.apache.fop.fo.Property;
@@ -58,39 +15,41 @@ import org.apache.fop.fo.properties.Constants;
*/
public class CondLength implements CompoundDatatype {
- private Property length;
- private Property conditionality;
+ private Property length;
+ private Property conditionality;
- // From CompoundDatatype
+ // From CompoundDatatype
public void setComponent(String sCmpnName, Property cmpnValue,
- boolean bIsDefault) {
- if (sCmpnName.equals("length"))
- length = cmpnValue;
- else if (sCmpnName.equals("conditionality"))
- conditionality = cmpnValue;
- }
+ boolean bIsDefault) {
+ if (sCmpnName.equals("length"))
+ length = cmpnValue;
+ else if (sCmpnName.equals("conditionality"))
+ conditionality = cmpnValue;
+ }
- public Property getComponent(String sCmpnName) {
- if (sCmpnName.equals("length"))
- return length;
- else if (sCmpnName.equals("conditionality"))
- return conditionality ;
- else return null;
- }
+ public Property getComponent(String sCmpnName) {
+ if (sCmpnName.equals("length"))
+ return length;
+ else if (sCmpnName.equals("conditionality"))
+ return conditionality;
+ else
+ return null;
+ }
- public Property getConditionality() {
- return this.conditionality ;
+ public Property getConditionality() {
+ return this.conditionality;
}
- public Property getLength() {
- return this.length;
- }
+ public Property getLength() {
+ return this.length;
+ }
+
+ public boolean isDiscard() {
+ return this.conditionality.getEnum() == Constants.DISCARD;
+ }
- public boolean isDiscard() {
- return this.conditionality.getEnum() == Constants.DISCARD ;
+ public int mvalue() {
+ return this.length.getLength().mvalue();
}
- public int mvalue() {
- return this.length.getLength().mvalue();
- }
}
diff --git a/src/org/apache/fop/datatypes/IDNode.java b/src/org/apache/fop/datatypes/IDNode.java
index 0ef57e895..4fd5a72ac 100644
--- a/src/org/apache/fop/datatypes/IDNode.java
+++ b/src/org/apache/fop/datatypes/IDNode.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.datatypes;
@@ -54,96 +10,81 @@ package org.apache.fop.datatypes;
import org.apache.fop.pdf.PDFGoTo;
-public class IDNode
-{
- private String
- idValue,
- internalLinkGoToPageReference;
+public class IDNode {
+ private String idValue, internalLinkGoToPageReference;
- private PDFGoTo
- internalLinkGoTo;
+ private PDFGoTo internalLinkGoTo;
- private int
- pageNumber = -1,
- xPosition = 0, // x position on page
- yPosition = 0; // y position on page
+ private int pageNumber = -1, xPosition = 0, // x position on page
+ yPosition = 0; // y position on page
/**
* Constructor for IDNode
- *
+ *
* @param idValue The value of the id for this node
*/
- protected IDNode(String idValue)
- {
- this.idValue = idValue;
+ protected IDNode(String idValue) {
+ this.idValue = idValue;
}
/**
* Sets the page number for this node
- *
+ *
* @param number page number of node
*/
- protected void setPageNumber(int number)
- {
- pageNumber=number;
+ protected void setPageNumber(int number) {
+ pageNumber = number;
}
/**
* Returns the page number of this node
- *
+ *
* @return page number of this node
*/
- public String getPageNumber()
- {
- return(pageNumber != -1)?new Integer(pageNumber).toString():null;
+ public String getPageNumber() {
+ return (pageNumber != -1) ? new Integer(pageNumber).toString() : null;
}
/**
* creates a new GoTo object for an internal link
- *
+ *
* @param objectNumber
- * the number to be assigned to the new object
+ * the number to be assigned to the new object
*/
- protected void createInternalLinkGoTo(int objectNumber)
- {
- if ( internalLinkGoToPageReference==null )
- {
- internalLinkGoTo = new PDFGoTo(objectNumber,null);
- }
- else
- {
- internalLinkGoTo = new PDFGoTo(objectNumber,internalLinkGoToPageReference);
+ protected void createInternalLinkGoTo(int objectNumber) {
+ if (internalLinkGoToPageReference == null) {
+ internalLinkGoTo = new PDFGoTo(objectNumber, null);
+ } else {
+ internalLinkGoTo = new PDFGoTo(objectNumber,
+ internalLinkGoToPageReference);
}
- if ( xPosition!=0 ) // if the position is known (if x is known, then y is known)
- {
+ if (xPosition
+ != 0) // if the position is known (if x is known, then y is known)
+ {
internalLinkGoTo.setXPosition(xPosition);
internalLinkGoTo.setYPosition(yPosition);
}
-
- }
+
+ }
/**
* sets the page reference for the internal link's GoTo. The GoTo will jump to this page reference.
- *
+ *
* @param pageReference
- * the page reference to which the internal link GoTo should jump
- * ex. 23 0 R
+ * the page reference to which the internal link GoTo should jump
+ * ex. 23 0 R
*/
- protected void setInternalLinkGoToPageReference(String pageReference)
- {
- if ( internalLinkGoTo !=null )
- {
- internalLinkGoTo.setPageReference(pageReference);
- }
- else
- {
+ protected void setInternalLinkGoToPageReference(String pageReference) {
+ if (internalLinkGoTo != null) {
+ internalLinkGoTo.setPageReference(pageReference);
+ } else {
internalLinkGoToPageReference = pageReference;
}
@@ -153,11 +94,10 @@ public class IDNode
/**
* Returns the reference to the Internal Link's GoTo object
- *
+ *
* @return GoTo object reference
*/
- protected String getInternalLinkGoToReference()
- {
+ protected String getInternalLinkGoToReference() {
return internalLinkGoTo.referencePDF();
}
@@ -165,11 +105,10 @@ public class IDNode
/**
* Returns the id value of this node
- *
+ *
* @return this node's id value
*/
- protected String getIDValue()
- {
+ protected String getIDValue() {
return idValue;
}
@@ -177,44 +116,38 @@ public class IDNode
/**
* Returns the PDFGoTo object associated with the internal link
- *
+ *
* @return PDFGoTo object
*/
- protected PDFGoTo getInternalLinkGoTo()
- {
+ protected PDFGoTo getInternalLinkGoTo() {
return internalLinkGoTo;
}
- /**
- * Determines whether there is an internal link GoTo for this node
- *
- * @return true if internal link GoTo for this node is set, false otherwise
- */
- protected boolean isThereInternalLinkGoTo()
- {
- return internalLinkGoTo!=null;
- }
+ /**
+ * Determines whether there is an internal link GoTo for this node
+ *
+ * @return true if internal link GoTo for this node is set, false otherwise
+ */
+ protected boolean isThereInternalLinkGoTo() {
+ return internalLinkGoTo != null;
+ }
- /**
+ /**
* Sets the position of this node
- *
- * @param x the x position
+ *
+ * @param x the x position
* @param y the y position
- */
- protected void setPosition(int x, int y)
- {
- if ( internalLinkGoTo !=null )
- {
+ */
+ protected void setPosition(int x, int y) {
+ if (internalLinkGoTo != null) {
internalLinkGoTo.setXPosition(x);
internalLinkGoTo.setYPosition(y);
+ } else {
+ xPosition = x;
+ yPosition = y;
}
- else
- {
- xPosition=x;
- yPosition=y;
- }
- }
-
+ }
+
}
diff --git a/src/org/apache/fop/datatypes/IDReferences.java b/src/org/apache/fop/datatypes/IDReferences.java
index 7dcc02b70..11b1b19b6 100644
--- a/src/org/apache/fop/datatypes/IDReferences.java
+++ b/src/org/apache/fop/datatypes/IDReferences.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.datatypes;
@@ -65,158 +21,148 @@ import org.apache.fop.apps.FOPException;
public class IDReferences {
- private Hashtable
- idReferences,
- idValidation;
+ private Hashtable idReferences, idValidation;
- final static int ID_PADDING = 5000; // space to add before id y position
+ final static int ID_PADDING = 5000; // space to add before id y position
/**
* Constructor for IDReferences
*/
- public IDReferences()
- {
+ public IDReferences() {
idReferences = new Hashtable();
idValidation = new Hashtable();
}
/**
- * Creates and configures the specified id.
- *
+ * Creates and configures the specified id.
+ *
* @param id The id to initialize
* @param area The area where this id was encountered
* @exception FOPException
*/
- public void initializeID(String id, Area area) throws FOPException
- {
+ public void initializeID(String id, Area area) throws FOPException {
createID(id);
- configureID(id,area);
+ configureID(id, area);
}
/**
* Creates id entry
- *
+ *
* @param id The id to create
* @param area The area where this id was encountered
* @exception FOPException
*/
- public void createID(String id) throws FOPException
- {
- if ( id!=null && !id.equals("") ) {
- if ( doesIDExist(id) ) {
- throw new FOPException("The id \""+id+"\" already exists in this document");
- }
- else {
+ public void createID(String id) throws FOPException {
+ if (id != null &&!id.equals("")) {
+ if (doesIDExist(id)) {
+ throw new FOPException("The id \"" + id
+ + "\" already exists in this document");
+ } else {
createNewId(id);
- removeFromIdValidationList(id);
+ removeFromIdValidationList(id);
}
-
+
}
}
/**
* Configures this id
- *
+ *
* @param id The id to configure
* @param area The area where the id was encountered
*/
- public void configureID(String id, Area area)
- {
- if ( id!=null && !id.equals("") ) {
- setPosition(id,area.getPage().getBody().getXPosition()+area.getTableCellXOffset()-ID_PADDING,area.getPage().getBody().getYPosition() - area.getAbsoluteHeight()+ID_PADDING);
- setPageNumber(id,area.getPage().getNumber());
- area.getPage().addToIDList(id);
- }
+ public void configureID(String id, Area area) {
+ if (id != null &&!id.equals("")) {
+ setPosition(id,
+ area.getPage().getBody().getXPosition()
+ + area.getTableCellXOffset() - ID_PADDING,
+ area.getPage().getBody().getYPosition()
+ - area.getAbsoluteHeight() + ID_PADDING);
+ setPageNumber(id, area.getPage().getNumber());
+ area.getPage().addToIDList(id);
}
+ }
/**
* Adds id to validation list to be validated . This should be used if it is unsure whether the id is valid
- *
+ *
* @param id id to be added
*/
- public void addToIdValidationList(String id)
- {
- idValidation.put(id,"");
+ public void addToIdValidationList(String id) {
+ idValidation.put(id, "");
}
/**
* Removes id from validation list. This should be used if the id has been determined to be valid
- *
+ *
* @param id the id to remove
*/
- public void removeFromIdValidationList(String id)
- {
- idValidation.remove(id);
+ public void removeFromIdValidationList(String id) {
+ idValidation.remove(id);
}
/**
* Removes id from IDReferences
- *
+ *
* @param id The id to remove
* @exception FOPException
*/
- public void removeID(String id)
- {
- idReferences.remove(id);
+ public void removeID(String id) {
+ idReferences.remove(id);
}
/**
* Determines whether all id's are valid
- *
+ *
* @return true if all id's are valid, false otherwise
*/
- public boolean isEveryIdValid()
- {
- return(idValidation.size()==0);
+ public boolean isEveryIdValid() {
+ return (idValidation.size() == 0);
}
/**
* Returns all invalid id's still remaining in the validation list
- *
+ *
* @return invalid ids from validation list
*/
- public String getInvalidIds()
- {
- StringBuffer list=new StringBuffer();
- Enumeration enum=idValidation.keys();
- while(enum.hasMoreElements())
- {
- list.append("\n\"").append(enum.nextElement().toString()).append("\" ") ;
+ public String getInvalidIds() {
+ StringBuffer list = new StringBuffer();
+ Enumeration enum = idValidation.keys();
+ while (enum.hasMoreElements()) {
+ list.append("\n\"").append(enum.nextElement().toString()).append("\" ");
}
- return list.toString();
+ return list.toString();
}
/**
* Determines whether specified id already exists in IDReferences
- *
+ *
* @param id the id to search for
* @return true if ID was found, false otherwise
*/
- public boolean doesIDExist(String id)
- {
+ public boolean doesIDExist(String id) {
return idReferences.containsKey(id);
}
/**
* Determines whether the GoTo reference for the specified id is defined
- *
+ *
* @param id the id to search for
* @return true if GoTo reference is defined, false otherwise
*/
- public boolean doesGoToReferenceExist(String id)
- {
- IDNode node = (IDNode)idReferences.get(id);
+ public boolean doesGoToReferenceExist(String id) {
+ IDNode node = (IDNode)idReferences.get(id);
return node.isThereInternalLinkGoTo();
}
@@ -225,70 +171,66 @@ public class IDReferences {
/**
* Returns the reference to the GoTo object used for the internal link
- *
+ *
* @param id the id whose reference to use
* @return reference to GoTo object
*/
- public String getInternalLinkGoToReference(String id)
- {
+ public String getInternalLinkGoToReference(String id) {
IDNode node = (IDNode)idReferences.get(id);
return node.getInternalLinkGoToReference();
}
-
+
/**
* creates an Internal Link GoTo object for this id
- *
+ *
* @param id The id for which to set the Internal Link Go To
* @param objectNumber
- * The object number to use for the GoTo object
+ * The object number to use for the GoTo object
* @return the object reference of the new GoTo object
*/
- public String createInternalLinkGoTo(String id, int objectNumber)
- {
- IDNode node = (IDNode)idReferences.get(id); // retrieve id node
- node.createInternalLinkGoTo(objectNumber); // create Internal Link GoTo object
- return node.getInternalLinkGoToReference(); //return Internal Link Go To object reference
+ public String createInternalLinkGoTo(String id, int objectNumber) {
+ IDNode node = (IDNode)idReferences.get(id); // retrieve id node
+ node.createInternalLinkGoTo(objectNumber); // create Internal Link GoTo object
+ return node.getInternalLinkGoToReference(); // return Internal Link Go To object reference
}
/**
* Adds an id to IDReferences
- *
+ *
* @param id the id to add
*/
- public void createNewId(String id)
- {
- IDNode node=new IDNode(id);
- idReferences.put(id,node);
+ public void createNewId(String id) {
+ IDNode node = new IDNode(id);
+ idReferences.put(id, node);
}
/**
* Returns the PDFGoTo object for the specified id
- *
+ *
* @param id the id for which the PDFGoTo to be retrieved is associated
* @return the PDFGoTo object associated with the specified id
*/
- public PDFGoTo getPDFGoTo(String id)
- {
- IDNode node=(IDNode)idReferences.get(id);
+ public PDFGoTo getPDFGoTo(String id) {
+ IDNode node = (IDNode)idReferences.get(id);
return node.getInternalLinkGoTo();
}
/**
* sets the page reference for the internal link's GoTo. The GoTo will jump to this page reference.
- *
+ *
* @param pageReference
- * the page reference to which the internal link GoTo should jump
- * ex. 23 0 R
+ * the page reference to which the internal link GoTo should jump
+ * ex. 23 0 R
*/
- public void setInternalGoToPageReference(String id, String pageReference)
- {
- IDNode node=(IDNode)idReferences.get(id);
+ public void setInternalGoToPageReference(String id,
+ String pageReference) {
+ IDNode node = (IDNode)idReferences.get(id);
if (node != null) {
node.setInternalLinkGoToPageReference(pageReference);
}
@@ -297,30 +239,27 @@ public class IDReferences {
/**
* Sets the page number for the specified id
- *
+ *
* @param id The id whose page number is being set
* @param pageNumber The page number of the specified id
*/
- public void setPageNumber(String id, int pageNumber)
- {
- IDNode node=(IDNode)idReferences.get(id);
- node.setPageNumber(pageNumber);
+ public void setPageNumber(String id, int pageNumber) {
+ IDNode node = (IDNode)idReferences.get(id);
+ node.setPageNumber(pageNumber);
}
/**
* Returns the page number where the specified id is found
- *
+ *
* @param id The id whose page number to return
* @return the page number of the id, or null if the id does not exist
*/
- public String getPageNumber(String id)
- {
- if ( doesIDExist(id) ) {
- IDNode node=(IDNode)idReferences.get(id);
- return node.getPageNumber();
- }
- else {
+ public String getPageNumber(String id) {
+ if (doesIDExist(id)) {
+ IDNode node = (IDNode)idReferences.get(id);
+ return node.getPageNumber();
+ } else {
addToIdValidationList(id);
return null;
}
@@ -329,15 +268,14 @@ public class IDReferences {
/**
* Sets the x and y position of specified id
- *
+ *
* @param id the id whose position is to be set
* @param x x position of id
* @param y y position of id
*/
- public void setPosition(String id, int x, int y)
- {
- IDNode node=(IDNode)idReferences.get(id);
- node.setPosition(x,y);
+ public void setPosition(String id, int x, int y) {
+ IDNode node = (IDNode)idReferences.get(id);
+ node.setPosition(x, y);
}
}
diff --git a/src/org/apache/fop/datatypes/Keep.java b/src/org/apache/fop/datatypes/Keep.java
index 467cdcc1b..8d16c25b9 100644
--- a/src/org/apache/fop/datatypes/Keep.java
+++ b/src/org/apache/fop/datatypes/Keep.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -16,8 +17,7 @@ public class Keep implements CompoundDatatype {
private Property withinColumn;
private Property withinPage;
- public Keep () {
- }
+ public Keep() {}
// From CompoundDatatype
public void setComponent(String sCmpnName, Property cmpnValue,
@@ -67,8 +67,11 @@ public class Keep implements CompoundDatatype {
return this.withinPage;
}
- /** What to do here?? There isn't really a meaningful single value. */
+ /**
+ * What to do here?? There isn't really a meaningful single value.
+ */
public String toString() {
return "Keep";
}
+
}
diff --git a/src/org/apache/fop/datatypes/KeepValue.java b/src/org/apache/fop/datatypes/KeepValue.java
index e8bb43452..4cc37f30d 100644
--- a/src/org/apache/fop/datatypes/KeepValue.java
+++ b/src/org/apache/fop/datatypes/KeepValue.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.datatypes;
/**
@@ -66,18 +23,16 @@ public class KeepValue {
this.value = val;
}
- public int getValue()
- {
+ public int getValue() {
return value;
}
- public String getType()
- {
+ public String getType() {
return type;
}
- public String toString()
- {
+ public String toString() {
return type;
}
+
}
diff --git a/src/org/apache/fop/datatypes/Length.java b/src/org/apache/fop/datatypes/Length.java
index 5870dc19e..58da8c924 100644
--- a/src/org/apache/fop/datatypes/Length.java
+++ b/src/org/apache/fop/datatypes/Length.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.datatypes;
import org.apache.fop.fo.Property;
@@ -57,115 +14,118 @@ import org.apache.fop.messaging.MessageHandler;
* a length quantity in XSL
*/
public class Length {
- public static final Length AUTO = new Length(0);
-
- static {
- AUTO.bAuto = true;
- }
-
- protected int millipoints = 0;
- protected boolean bIsComputed = false;
- private boolean bAuto = false;
-
- /**
- * Set the length given a number of relative units and the current
- * font size in base units.
- */
- public Length (double numRelUnits, int iCurFontSize) {
- millipoints = (int)(numRelUnits * (double)iCurFontSize);
- setIsComputed(true);
+ public static final Length AUTO = new Length(0);
+
+ static {
+ AUTO.bAuto = true;
}
- /**
- * Set the length given a number of units and a unit name.
- */
- public Length (double numUnits, String units) {
- convert(numUnits, units);
+ protected int millipoints = 0;
+ protected boolean bIsComputed = false;
+ private boolean bAuto = false;
+
+ /**
+ * Set the length given a number of relative units and the current
+ * font size in base units.
+ */
+ public Length(double numRelUnits, int iCurFontSize) {
+ millipoints = (int)(numRelUnits * (double)iCurFontSize);
+ setIsComputed(true);
+ }
+
+ /**
+ * Set the length given a number of units and a unit name.
+ */
+ public Length(double numUnits, String units) {
+ convert(numUnits, units);
}
/**
* set the length as a number of base units
*/
- public Length (int baseUnits) {
- millipoints = baseUnits;
- setIsComputed(true);
+ public Length(int baseUnits) {
+ millipoints = baseUnits;
+ setIsComputed(true);
}
- /**
- * Convert the given length to a dimensionless integer representing
- * a whole number of base units (milli-points).
- */
- protected void convert(double dvalue, String unit) {
-
- int assumed_resolution = 1; // points/pixel
-
- if (unit.equals("in"))
- dvalue = dvalue * 72;
- else if (unit.equals("cm"))
- dvalue = dvalue * 28.35;
- else if (unit.equals("mm"))
- dvalue = dvalue * 2.84;
- else if (unit.equals("pt"))
- dvalue = dvalue;
- else if (unit.equals("pc"))
- dvalue = dvalue * 12;
- /* else if (unit.equals("em"))
- dvalue = dvalue * fontsize; */
- else if (unit.equals("px"))
- dvalue = dvalue * assumed_resolution;
- else {
- dvalue = 0;
- MessageHandler.errorln("ERROR: unknown length unit '" + unit + "'");
+ /**
+ * Convert the given length to a dimensionless integer representing
+ * a whole number of base units (milli-points).
+ */
+ protected void convert(double dvalue, String unit) {
+
+ int assumed_resolution = 1; // points/pixel
+
+ if (unit.equals("in"))
+ dvalue = dvalue * 72;
+ else if (unit.equals("cm"))
+ dvalue = dvalue * 28.35;
+ else if (unit.equals("mm"))
+ dvalue = dvalue * 2.84;
+ else if (unit.equals("pt"))
+ dvalue = dvalue;
+ else if (unit.equals("pc"))
+ dvalue = dvalue * 12;
+ /*
+ * else if (unit.equals("em"))
+ * dvalue = dvalue * fontsize;
+ */
+ else if (unit.equals("px"))
+ dvalue = dvalue * assumed_resolution;
+ else {
+ dvalue = 0;
+ MessageHandler.errorln("ERROR: unknown length unit '" + unit
+ + "'");
+ }
+ this.millipoints = (int)(dvalue * 1000);
+ setIsComputed(true);
}
- this.millipoints = (int) (dvalue * 1000);
- setIsComputed(true);
- }
- protected void setIsComputed(boolean bIsComputed) {
- this.bIsComputed = bIsComputed;
- }
+ protected void setIsComputed(boolean bIsComputed) {
+ this.bIsComputed = bIsComputed;
+ }
/**
* return the length in 1/1000ths of a point
*/
public int mvalue() {
- if (!bIsComputed)
- millipoints = computeValue();
- return millipoints;
+ if (!bIsComputed)
+ millipoints = computeValue();
+ return millipoints;
}
- protected int computeValue() {
- return millipoints;
- }
+ protected int computeValue() {
+ return millipoints;
+ }
- protected void setValue(int millipoints) {
- this.millipoints = millipoints;
- setIsComputed(true);
- }
+ protected void setValue(int millipoints) {
+ this.millipoints = millipoints;
+ setIsComputed(true);
+ }
- public boolean isAuto()
- {
- return bAuto;
+ public boolean isAuto() {
+ return bAuto;
}
- /**
- * Return the number of table units which are included in this
- * length specification.
- * This will always be 0 unless the property specification used
- * the proportional-column-width() function (only only table
- * column FOs).
- * If this value is not 0, the actual value of the Length cannot
- * be known without looking at all of the columns in the table to
- * determine the value of a "table-unit".
- * @return The number of table units which are included in this
- * length specification.
- */
- public double getTableUnits() {
- return 0.0;
- }
+ /**
+ * Return the number of table units which are included in this
+ * length specification.
+ * This will always be 0 unless the property specification used
+ * the proportional-column-width() function (only only table
+ * column FOs).
+ *
If this value is not 0, the actual value of the Length cannot
+ * be known without looking at all of the columns in the table to
+ * determine the value of a "table-unit".
+ * @return The number of table units which are included in this
+ * length specification.
+ */
+ public double getTableUnits() {
+ return 0.0;
+ }
public String toString() {
- String s = millipoints + "mpt";
- return s;
+ String s = millipoints + "mpt";
+ return s;
}
+
}
diff --git a/src/org/apache/fop/datatypes/LengthBase.java b/src/org/apache/fop/datatypes/LengthBase.java
index eef01459b..539467e95 100644
--- a/src/org/apache/fop/datatypes/LengthBase.java
+++ b/src/org/apache/fop/datatypes/LengthBase.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -22,11 +23,15 @@ public class LengthBase implements PercentBase {
* FO parent of the FO for which this property is to be calculated.
*/
protected /* final */ FObj parentFO;
+
/**
* PropertyList for the FO where this property is calculated.
*/
private /* final */ PropertyList propertyList;
- /** One of the defined types of LengthBase */
+
+ /**
+ * One of the defined types of LengthBase
+ */
private /* final */ int iBaseType;
public LengthBase(FObj parentFO, PropertyList plist, int iBaseType) {
@@ -35,14 +40,16 @@ public class LengthBase implements PercentBase {
this.iBaseType = iBaseType;
}
- /** Accessor for parentFO object from subclasses which define
+ /**
+ * Accessor for parentFO object from subclasses which define
* custom kinds of LengthBase calculations.
*/
protected FObj getParentFO() {
return parentFO;
}
- /** Accessor for propertyList object from subclasses which define
+ /**
+ * Accessor for propertyList object from subclasses which define
* custom kinds of LengthBase calculations.
*/
protected PropertyList getPropertyList() {
@@ -52,36 +59,35 @@ public class LengthBase implements PercentBase {
public int getDimension() {
return 1;
}
+
public double getBaseValue() {
return 1.0;
}
public int getBaseLength() {
switch (iBaseType) {
- case FONTSIZE:
- return propertyList.get("font-size").getLength().mvalue();
- case INH_FONTSIZE:
- return propertyList.getInherited(
- "font-size").getLength().mvalue();
- case CONTAINING_BOX:
- // depends on property?? inline-progression vs block-progression
- return parentFO.getContentWidth();
- case CONTAINING_REFAREA: // example: start-indent, end-indent
- {
- FObj fo;
- for (fo = parentFO; fo != null &&
- !fo.generatesReferenceAreas();
- fo = fo.getParent())
- ;
- return (fo != null ? fo.getContentWidth() : 0);
- }
- case CUSTOM_BASE:
- MessageHandler.errorln("!!! LengthBase.getBaseLength() called on CUSTOM_BASE type !!!");
- return 0;
- default:
- MessageHandler.errorln("Unknown base type for LengthBase.");
- return 0;
+ case FONTSIZE:
+ return propertyList.get("font-size").getLength().mvalue();
+ case INH_FONTSIZE:
+ return propertyList.getInherited("font-size").getLength().mvalue();
+ case CONTAINING_BOX:
+ // depends on property?? inline-progression vs block-progression
+ return parentFO.getContentWidth();
+ case CONTAINING_REFAREA: // example: start-indent, end-indent
+ {
+ FObj fo;
+ for (fo = parentFO; fo != null &&!fo.generatesReferenceAreas();
+ fo = fo.getParent());
+ return (fo != null ? fo.getContentWidth() : 0);
+ }
+ case CUSTOM_BASE:
+ MessageHandler.errorln("!!! LengthBase.getBaseLength() called on CUSTOM_BASE type !!!");
+ return 0;
+ default:
+ MessageHandler.errorln("Unknown base type for LengthBase.");
+ return 0;
}
}
+
}
diff --git a/src/org/apache/fop/datatypes/LengthPair.java b/src/org/apache/fop/datatypes/LengthPair.java
index 6f763d310..2144a0366 100644
--- a/src/org/apache/fop/datatypes/LengthPair.java
+++ b/src/org/apache/fop/datatypes/LengthPair.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -35,7 +36,7 @@ public class LengthPair implements CompoundDatatype {
else if (sCmpnName.equals("inline-progression-direction"))
return getIPD();
else
- return null; // SHOULDN'T HAPPEN
+ return null; // SHOULDN'T HAPPEN
}
public Property getIPD() {
@@ -45,4 +46,5 @@ public class LengthPair implements CompoundDatatype {
public Property getBPD() {
return this.bpd;
}
+
}
diff --git a/src/org/apache/fop/datatypes/LengthRange.java b/src/org/apache/fop/datatypes/LengthRange.java
index 8beeb189a..92d365b49 100644
--- a/src/org/apache/fop/datatypes/LengthRange.java
+++ b/src/org/apache/fop/datatypes/LengthRange.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -22,7 +23,7 @@ public class LengthRange implements CompoundDatatype {
private static final int MINSET = 1;
private static final int OPTSET = 2;
private static final int MAXSET = 4;
- private int bfSet = 0; // bit field
+ private int bfSet = 0; // bit field
private boolean bChecked = false;
// From CompoundDatatype
@@ -45,7 +46,7 @@ public class LengthRange implements CompoundDatatype {
else if (sCmpnName.equals("maximum"))
return getMaximum();
else
- return null; // SHOULDN'T HAPPEN
+ return null; // SHOULDN'T HAPPEN
}
/**
@@ -91,52 +92,55 @@ public class LengthRange implements CompoundDatatype {
private void checkConsistency() {
if (bChecked)
return;
- // Make sure max >= min
- // Must also control if have any allowed enum values!
- /*********************
- if (minimum.mvalue() > maximum.mvalue()) {
- if ((bfSet&MINSET)!=0) {
- // if minimum is explicit, force max to min
- if ((bfSet&MAXSET)!=0) {
- // Warning: min>max, resetting max to min
- MessageHandler.errorln("WARNING: forcing max to min in LengthRange");
- }
- maximum = minimum ;
- }
- else {
- minimum = maximum; // minimum was default value
- }
- }
- // Now make sure opt <= max and opt >= min
- if (optimum.mvalue() > maximum.mvalue()) {
- if ((bfSet&OPTSET)!=0) {
- if ((bfSet&MAXSET)!=0) {
- // Warning: opt > max, resetting opt to max
- MessageHandler.errorln("WARNING: forcing opt to max in LengthRange");
- optimum = maximum ;
- }
- else {
- maximum = optimum; // maximum was default value
- }
- }
- else {
- // opt is default and max is explicit or default
- optimum = maximum ;
- }
- }
- else if (optimum.mvalue() < minimum.mvalue()) {
- if ((bfSet&MINSET)!=0) {
- // if minimum is explicit, force opt to min
- if ((bfSet&OPTSET)!=0) {
- MessageHandler.errorln("WARNING: forcing opt to min in LengthRange");
- }
- optimum = minimum ;
- }
- else {
- minimum = optimum; // minimum was default value
- }
- }
- ********$*********/
+ // Make sure max >= min
+ // Must also control if have any allowed enum values!
+
+ /**
+ * *******************
+ * if (minimum.mvalue() > maximum.mvalue()) {
+ * if ((bfSet&MINSET)!=0) {
+ * // if minimum is explicit, force max to min
+ * if ((bfSet&MAXSET)!=0) {
+ * // Warning: min>max, resetting max to min
+ * MessageHandler.errorln("WARNING: forcing max to min in LengthRange");
+ * }
+ * maximum = minimum ;
+ * }
+ * else {
+ * minimum = maximum; // minimum was default value
+ * }
+ * }
+ * // Now make sure opt <= max and opt >= min
+ * if (optimum.mvalue() > maximum.mvalue()) {
+ * if ((bfSet&OPTSET)!=0) {
+ * if ((bfSet&MAXSET)!=0) {
+ * // Warning: opt > max, resetting opt to max
+ * MessageHandler.errorln("WARNING: forcing opt to max in LengthRange");
+ * optimum = maximum ;
+ * }
+ * else {
+ * maximum = optimum; // maximum was default value
+ * }
+ * }
+ * else {
+ * // opt is default and max is explicit or default
+ * optimum = maximum ;
+ * }
+ * }
+ * else if (optimum.mvalue() < minimum.mvalue()) {
+ * if ((bfSet&MINSET)!=0) {
+ * // if minimum is explicit, force opt to min
+ * if ((bfSet&OPTSET)!=0) {
+ * MessageHandler.errorln("WARNING: forcing opt to min in LengthRange");
+ * }
+ * optimum = minimum ;
+ * }
+ * else {
+ * minimum = optimum; // minimum was default value
+ * }
+ * }
+ * *******$*******
+ */
bChecked = true;
}
@@ -154,4 +158,5 @@ public class LengthRange implements CompoundDatatype {
checkConsistency();
return this.optimum;
}
+
}
diff --git a/src/org/apache/fop/datatypes/LinearCombinationLength.java b/src/org/apache/fop/datatypes/LinearCombinationLength.java
index 71126cfea..776d6f7d9 100644
--- a/src/org/apache/fop/datatypes/LinearCombinationLength.java
+++ b/src/org/apache/fop/datatypes/LinearCombinationLength.java
@@ -1,61 +1,14 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.datatypes;
import java.util.Vector;
-import org.apache.fop.messaging.MessageHandler;
-/**
- * a percent specified length quantity in XSL
- */
public class LinearCombinationLength extends Length {
protected Vector factors;
@@ -79,9 +32,10 @@ public class LinearCombinationLength extends Length {
protected int computeValue() {
int result = 0;
int numFactors = factors.size();
- for(int i = 0; i < numFactors; ++i) {
- result += (int)(((Double)factors.elementAt(i)).doubleValue()
- * (double)((Length)lengths.elementAt(i)).mvalue());
+ for (int i = 0; i < numFactors; ++i) {
+ result +=
+ (int)(((Double)factors.elementAt(i)).doubleValue()
+ * (double)((Length)lengths.elementAt(i)).mvalue());
}
return result;
}
diff --git a/src/org/apache/fop/datatypes/MixedLength.java b/src/org/apache/fop/datatypes/MixedLength.java
index e97af90cf..53216399e 100644
--- a/src/org/apache/fop/datatypes/MixedLength.java
+++ b/src/org/apache/fop/datatypes/MixedLength.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.datatypes;
import org.apache.fop.messaging.MessageHandler;
@@ -59,36 +16,36 @@ import org.apache.fop.messaging.MessageHandler;
*/
public class MixedLength extends Length {
- private PercentLength pcPart;
+ private PercentLength pcPart;
/**
* construct an object based on a factor (the percent, as a
* a factor) and an object which has a method to return the
* Length which provides the "base" for this calculation.
*/
- public MixedLength (int absPart, PercentLength pcPart) {
- super(absPart);
- this.pcPart = pcPart;
- super.setIsComputed(false);
- }
+ public MixedLength(int absPart, PercentLength pcPart) {
+ super(absPart);
+ this.pcPart = pcPart;
+ super.setIsComputed(false);
+ }
- protected int computeValue() {
- int rslt = super.computeValue(); // absolute part
- if (pcPart != null) {
- rslt += pcPart.computeValue();
+ protected int computeValue() {
+ int rslt = super.computeValue(); // absolute part
+ if (pcPart != null) {
+ rslt += pcPart.computeValue();
+ }
+ return rslt;
}
- return rslt;
- }
- public String toString() {
- // return the factor as a percent
- // What about the base value?
- StringBuffer rslt = new StringBuffer(super.toString());
-
- if (pcPart != null) {
- rslt.append("+" + pcPart.toString());
+ public String toString() {
+ // return the factor as a percent
+ // What about the base value?
+ StringBuffer rslt = new StringBuffer(super.toString());
+
+ if (pcPart != null) {
+ rslt.append("+" + pcPart.toString());
+ }
+ return rslt.toString();
}
- return rslt.toString();
- }
-
+
}
diff --git a/src/org/apache/fop/datatypes/PercentBase.java b/src/org/apache/fop/datatypes/PercentBase.java
index 75f5b4beb..f19ac425e 100644
--- a/src/org/apache/fop/datatypes/PercentBase.java
+++ b/src/org/apache/fop/datatypes/PercentBase.java
@@ -1,57 +1,14 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.datatypes;
public interface PercentBase {
- public int getDimension();
- public double getBaseValue();
- public int getBaseLength();
+ public int getDimension();
+ public double getBaseValue();
+ public int getBaseLength();
}
diff --git a/src/org/apache/fop/datatypes/PercentLength.java b/src/org/apache/fop/datatypes/PercentLength.java
index f85b96931..28848eef9 100644
--- a/src/org/apache/fop/datatypes/PercentLength.java
+++ b/src/org/apache/fop/datatypes/PercentLength.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.datatypes;
import org.apache.fop.messaging.MessageHandler;
@@ -57,46 +14,49 @@ import org.apache.fop.messaging.MessageHandler;
*/
public class PercentLength extends Length {
- private double factor;
- private PercentBase lbase=null;
+ private double factor;
+ private PercentBase lbase = null;
/**
* construct an object based on a factor (the percent, as a
* a factor) and an object which has a method to return the
* Length which provides the "base" for this calculation.
*/
- public PercentLength (double factor) {
- this(factor, null);
- }
+ public PercentLength(double factor) {
+ this(factor, null);
+ }
- public PercentLength (double factor, PercentBase lbase) {
- super(0);
- this.factor = factor;
- this.lbase = lbase;
- super.setIsComputed(false);
- }
+ public PercentLength(double factor, PercentBase lbase) {
+ super(0);
+ this.factor = factor;
+ this.lbase = lbase;
+ super.setIsComputed(false);
+ }
- public void setBaseLength(PercentBase lbase) {
- this.lbase = lbase;
- }
+ public void setBaseLength(PercentBase lbase) {
+ this.lbase = lbase;
+ }
- public PercentBase getBaseLength() {
- return this.lbase ;
- }
+ public PercentBase getBaseLength() {
+ return this.lbase;
+ }
- /**
- * Return the computed value in millipoints. This assumes that the
- * base length has been resolved to an absolute length value.
- */
- protected int computeValue() {
- return (int)(factor * (double)lbase.getBaseLength());
- }
+ /**
+ * Return the computed value in millipoints. This assumes that the
+ * base length has been resolved to an absolute length value.
+ */
+ protected int computeValue() {
+ return (int)(factor * (double)lbase.getBaseLength());
+ }
- public double value() { return factor; }
+ public double value() {
+ return factor;
+ }
public String toString() {
- // return the factor as a percent
- // What about the base value?
- return (new Double(factor*100.0).toString()) + "%";
+ // return the factor as a percent
+ // What about the base value?
+ return (new Double(factor * 100.0).toString()) + "%";
}
+
}
diff --git a/src/org/apache/fop/datatypes/Space.java b/src/org/apache/fop/datatypes/Space.java
index 71ce6e15c..036c17774 100644
--- a/src/org/apache/fop/datatypes/Space.java
+++ b/src/org/apache/fop/datatypes/Space.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -14,7 +15,7 @@ import org.apache.fop.fo.Property;
public class Space extends LengthRange {
private Property precedence;
- private Property conditionality ;
+ private Property conditionality;
// From CompoundDatatype
public void setComponent(String sCmpnName, Property cmpnValue,
@@ -47,16 +48,17 @@ public class Space extends LengthRange {
}
public Property getPrecedence() {
- return this.precedence ;
+ return this.precedence;
}
/*
- public boolean isDiscard() {
- return (this.conditionality == DISCARD);
- }
+ * public boolean isDiscard() {
+ * return (this.conditionality == DISCARD);
+ * }
*/
public Property getConditionality() {
- return this.conditionality ;
+ return this.conditionality;
}
+
}
diff --git a/src/org/apache/fop/datatypes/TableColLength.java b/src/org/apache/fop/datatypes/TableColLength.java
index e395e4f27..0a4df466a 100644
--- a/src/org/apache/fop/datatypes/TableColLength.java
+++ b/src/org/apache/fop/datatypes/TableColLength.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.datatypes;
import org.apache.fop.messaging.MessageHandler;
@@ -65,36 +22,39 @@ import org.apache.fop.messaging.MessageHandler;
*/
public class TableColLength extends MixedLength {
- /** Number of table-column proportional units */
- double tcolUnits;
-
- /**
- * Construct an object with tcolUnits of proportional measure.
- */
- public TableColLength (double tcolUnits) {
- super(0, null);
- this.tcolUnits = tcolUnits;
- }
+ /**
+ * Number of table-column proportional units
+ */
+ double tcolUnits;
+
+ /**
+ * Construct an object with tcolUnits of proportional measure.
+ */
+ public TableColLength(double tcolUnits) {
+ super(0, null);
+ this.tcolUnits = tcolUnits;
+ }
- public TableColLength (int absUnits,
- PercentLength pcUnits, double tcolUnits) {
- super(absUnits, pcUnits);
- this.tcolUnits = tcolUnits;
+ public TableColLength(int absUnits, PercentLength pcUnits,
+ double tcolUnits) {
+ super(absUnits, pcUnits);
+ this.tcolUnits = tcolUnits;
}
-
- /**
- * Override the method in Length to return the number of specified
- * proportional table-column units.
- */
- public double getTableUnits() {
- return tcolUnits;
- }
- // Set tcolUnits too when resolved?
+ /**
+ * Override the method in Length to return the number of specified
+ * proportional table-column units.
+ */
+ public double getTableUnits() {
+ return tcolUnits;
+ }
+
+ // Set tcolUnits too when resolved?
- public String toString() {
- return (super.toString() + "+" +
- (new Double(tcolUnits).toString()) + "table-column-units");
+ public String toString() {
+ return (super.toString() + "+" + (new Double(tcolUnits).toString())
+ + "table-column-units");
}
+
}
diff --git a/src/org/apache/fop/datatypes/ToBeImplemented.java b/src/org/apache/fop/datatypes/ToBeImplemented.java
index c05660945..2e8b908aa 100644
--- a/src/org/apache/fop/datatypes/ToBeImplemented.java
+++ b/src/org/apache/fop/datatypes/ToBeImplemented.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -11,7 +12,7 @@ package org.apache.fop.datatypes;
*/
public class ToBeImplemented {
- public ToBeImplemented(String value) {
- }
+ public ToBeImplemented(String value) {}
+
}
diff --git a/src/org/apache/fop/datatypes/ToBeImplementedProperty.java b/src/org/apache/fop/datatypes/ToBeImplementedProperty.java
index bba221191..b58ec5116 100644
--- a/src/org/apache/fop/datatypes/ToBeImplementedProperty.java
+++ b/src/org/apache/fop/datatypes/ToBeImplementedProperty.java
@@ -1,4 +1,5 @@
-/* $Id$ --
+/*
+ * $Id$ --
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -22,13 +23,15 @@ public class ToBeImplementedProperty extends Property {
if (p instanceof ToBeImplementedProperty)
return p;
ToBeImplementedProperty val =
- new ToBeImplementedProperty(getPropName());
+ new ToBeImplementedProperty(getPropName());
return val;
}
+
}
public ToBeImplementedProperty(String propName) {
- MessageHandler.errorln("Warning: property - \"" + propName + "\" is not implemented yet.");
+ MessageHandler.errorln("Warning: property - \"" + propName
+ + "\" is not implemented yet.");
}
}
diff --git a/src/org/apache/fop/extensions/ExtensionElementMapping.java b/src/org/apache/fop/extensions/ExtensionElementMapping.java
index 5105694c5..02e5c4275 100644
--- a/src/org/apache/fop/extensions/ExtensionElementMapping.java
+++ b/src/org/apache/fop/extensions/ExtensionElementMapping.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -26,11 +27,11 @@ public class ExtensionElementMapping implements ElementMapping {
ExtensionPropertyMapping.getGenericMappings());
/* Add any element mappings */
for (Enumeration e = ExtensionPropertyMapping.getElementMappings();
- e.hasMoreElements();) {
- String elem = (String) e.nextElement();
- builder.addElementPropertyList(ExtensionElementMapping.URI,
- elem, ExtensionPropertyMapping.getElementMapping(
- elem));
+ e.hasMoreElements(); ) {
+ String elem = (String)e.nextElement();
+ builder.addElementPropertyList(ExtensionElementMapping.URI, elem,
+ ExtensionPropertyMapping.getElementMapping(elem));
}
}
+
}
diff --git a/src/org/apache/fop/extensions/ExtensionObj.java b/src/org/apache/fop/extensions/ExtensionObj.java
index b508cf64b..9cfc091ef 100644
--- a/src/org/apache/fop/extensions/ExtensionObj.java
+++ b/src/org/apache/fop/extensions/ExtensionObj.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.extensions;
@@ -55,31 +11,31 @@ import org.apache.fop.fo.*;
import org.apache.fop.layout.*;
import org.apache.fop.apps.FOPException;
-/**
+/**
* base class for extension objects
*/
-public abstract class ExtensionObj extends FObj
-{
+public abstract class ExtensionObj extends FObj {
+
/**
*
* @param parent the parent formatting object
* @param propertyList the explicit properties of this object
*/
public ExtensionObj(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
+ super(parent, propertyList);
}
/**
* Called for extensions within a page sequence or flow. These extensions
* are allowed to generate visible areas within the layout.
*
- *
- * @param area
+ *
+ * @param area
*/
public Status layout(Area area) throws FOPException {
- ExtensionArea extArea = new ExtensionArea(this);
- area.addChild(extArea);
- return new Status(Status.OK);
+ ExtensionArea extArea = new ExtensionArea(this);
+ area.addChild(extArea);
+ return new Status(Status.OK);
}
@@ -87,12 +43,12 @@ public abstract class ExtensionObj extends FObj
* Called for root extensions. Root extensions aren't allowed to generate
* any visible areas. They are used for extra items that don't show up in
* the page layout itself. For example: pdf outlines
- *
- * @param areaTree
+ *
+ * @param areaTree
*/
public void format(AreaTree areaTree) throws FOPException {
- ExtensionArea extArea = new ExtensionArea(this);
- areaTree.addExtension(this);
+ ExtensionArea extArea = new ExtensionArea(this);
+ areaTree.addExtension(this);
}
}
diff --git a/src/org/apache/fop/extensions/Label.java b/src/org/apache/fop/extensions/Label.java
index 9849193a1..aa6bf1c31 100644
--- a/src/org/apache/fop/extensions/Label.java
+++ b/src/org/apache/fop/extensions/Label.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.extensions;
@@ -54,33 +10,31 @@ package org.apache.fop.extensions;
import org.apache.fop.fo.*;
-public class Label extends ExtensionObj
-{
+public class Label extends ExtensionObj {
private String _label = "";
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- {
- return new Label(parent, propertyList);
- }
+ public FObj make(FObj parent, PropertyList propertyList) {
+ return new Label(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new Label.Maker();
+ return new Label.Maker();
}
-
+
public Label(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
+ super(parent, propertyList);
}
- protected void addCharacters(char data[], int start, int end) {
- _label += new String(data, start, end-start);
+ protected void addCharacters(char data[], int start, int end) {
+ _label += new String(data, start, end - start);
}
-
- public String toString()
- {
- return _label;
+
+ public String toString() {
+ return _label;
}
-
-
+
+
}
diff --git a/src/org/apache/fop/extensions/Outline.java b/src/org/apache/fop/extensions/Outline.java
index b785919cd..136bc2155 100644
--- a/src/org/apache/fop/extensions/Outline.java
+++ b/src/org/apache/fop/extensions/Outline.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.extensions;
@@ -60,97 +16,95 @@ import org.apache.fop.messaging.MessageHandler;
import java.util.*;
-public class Outline extends ExtensionObj
-{
+public class Outline extends ExtensionObj {
private Label _label;
private Vector _outlines = new Vector();
-
+
private String _internalDestination;
private String _externalDestination;
-
- /** The parent outline object if it exists */
+
+ /**
+ * The parent outline object if it exists
+ */
private Outline _parentOutline;
-
- /** an opaque renderer context object, e.g. PDFOutline for PDFRenderer */
+
+ /**
+ * an opaque renderer context object, e.g. PDFOutline for PDFRenderer
+ */
private Object _rendererObject;
-
-
+
+
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- {
- return new Outline(parent, propertyList);
- }
+ public FObj make(FObj parent, PropertyList propertyList) {
+ return new Outline(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new Outline.Maker();
+ return new Outline.Maker();
}
-
+
public Outline(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
-
- _internalDestination = this.properties.get("internal-destination").getString();
- _externalDestination = this.properties.get("external-destination").getString();
- if (_externalDestination != null && !_externalDestination.equals("")) {
- MessageHandler.errorln("WARNING: fox:outline external-destination not supported currently.");
- }
-
- if (_internalDestination == null || _internalDestination.equals("")) {
- MessageHandler.errorln("WARNING: fox:outline requires an internal-destination.");
- }
-
- for (FONode node = getParent(); node != null; node = node.getParent()) {
- if (node instanceof Outline) {
- _parentOutline = (Outline)node;
- break;
- }
- }
-
+ super(parent, propertyList);
+
+ _internalDestination =
+ this.properties.get("internal-destination").getString();
+ _externalDestination =
+ this.properties.get("external-destination").getString();
+ if (_externalDestination != null &&!_externalDestination.equals("")) {
+ MessageHandler.errorln("WARNING: fox:outline external-destination not supported currently.");
+ }
+
+ if (_internalDestination == null || _internalDestination.equals("")) {
+ MessageHandler.errorln("WARNING: fox:outline requires an internal-destination.");
+ }
+
+ for (FONode node = getParent(); node != null;
+ node = node.getParent()) {
+ if (node instanceof Outline) {
+ _parentOutline = (Outline)node;
+ break;
+ }
+ }
+
}
- protected void addChild(FONode obj)
- {
- if (obj instanceof Label) {
- _label = (Label)obj;
- }
- else if (obj instanceof Outline) {
- _outlines.addElement(obj);
- }
- super.addChild(obj);
+ protected void addChild(FONode obj) {
+ if (obj instanceof Label) {
+ _label = (Label)obj;
+ } else if (obj instanceof Outline) {
+ _outlines.addElement(obj);
+ }
+ super.addChild(obj);
}
-
- public void setRendererObject(Object o)
- {
- _rendererObject = o;
+
+ public void setRendererObject(Object o) {
+ _rendererObject = o;
}
- public Object getRendererObject()
- {
- return _rendererObject;
+ public Object getRendererObject() {
+ return _rendererObject;
}
-
- public Outline getParentOutline()
- {
- return _parentOutline;
+
+ public Outline getParentOutline() {
+ return _parentOutline;
}
-
- public Label getLabel()
- {
- return _label == null?new Label(this,this.properties):_label;
+
+ public Label getLabel() {
+ return _label == null ? new Label(this, this.properties) : _label;
}
-
- public Vector getOutlines()
- {
- return _outlines;
+
+ public Vector getOutlines() {
+ return _outlines;
}
-
- public String getInternalDestination()
- {
- return _internalDestination;
+
+ public String getInternalDestination() {
+ return _internalDestination;
}
-
-
+
+
}
diff --git a/src/org/apache/fop/fo/BoxPropShorthandParser.java b/src/org/apache/fop/fo/BoxPropShorthandParser.java
index 362d4e04c..0e3f4debc 100644
--- a/src/org/apache/fop/fo/BoxPropShorthandParser.java
+++ b/src/org/apache/fop/fo/BoxPropShorthandParser.java
@@ -1,35 +1,41 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.fo;
import org.apache.fop.apps.FOPException;
public class BoxPropShorthandParser extends GenericShorthandParser {
- public BoxPropShorthandParser(ListProperty listprop) {
- super(listprop);
- }
-
- // Stores 1 to 4 values of same type
- // Set the given property based on the number of values set
- // Example: padding, border-width, border-color, border-style, margin
- protected Property convertValueForProperty(String propName,
- Property.Maker maker, PropertyList propertyList) {
- Property p = null;
- if (propName.indexOf("-top") >= 0) {
- p = getElement(0);
- }
- else if (propName.indexOf("-right") >= 0) {
- p = getElement(count()>1? 1:0);
- }
- else if (propName.indexOf("-bottom") >= 0) {
- p = getElement(count()>2? 2:0);
+ public BoxPropShorthandParser(ListProperty listprop) {
+ super(listprop);
}
- else if (propName.indexOf("-left") >= 0) {
- p = getElement(count()>3? 3: (count()>1?1:0));
- }
- // if p not null, try to convert it to a value of the correct type
- if (p != null) {
- return maker.convertShorthandProperty(propertyList, p, null);
+
+ // Stores 1 to 4 values of same type
+ // Set the given property based on the number of values set
+ // Example: padding, border-width, border-color, border-style, margin
+ protected Property convertValueForProperty(String propName,
+ Property.Maker maker,
+ PropertyList propertyList) {
+ Property p = null;
+ if (propName.indexOf("-top") >= 0) {
+ p = getElement(0);
+ } else if (propName.indexOf("-right") >= 0) {
+ p = getElement(count() > 1 ? 1 : 0);
+ } else if (propName.indexOf("-bottom") >= 0) {
+ p = getElement(count() > 2 ? 2 : 0);
+ } else if (propName.indexOf("-left") >= 0) {
+ p = getElement(count() > 3 ? 3 : (count() > 1 ? 1 : 0));
+ }
+ // if p not null, try to convert it to a value of the correct type
+ if (p != null) {
+ return maker.convertShorthandProperty(propertyList, p, null);
+ }
+ return p;
}
- return p;
- }
+
}
diff --git a/src/org/apache/fop/fo/CharacterProperty.java b/src/org/apache/fop/fo/CharacterProperty.java
index 78cc1ee8e..a638d883e 100644
--- a/src/org/apache/fop/fo/CharacterProperty.java
+++ b/src/org/apache/fop/fo/CharacterProperty.java
@@ -1,76 +1,44 @@
/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
+package org.apache.fop.fo;
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
+public class CharacterProperty extends Property {
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ public static class Maker extends Property.Maker {
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
+ public Maker(String propName) {
+ super(propName);
+ }
- */
-package org.apache.fop.fo;
+ public Property make(PropertyList propertyList, String value,
+ FObj fo) {
+ char c = value.charAt(0);
+ return new CharacterProperty(c);
+ }
-public class CharacterProperty extends Property {
+ } // end Charakter.Maker
- public static class Maker extends Property.Maker {
+ private char character;
- public Maker(String propName) {
- super(propName);
+ public CharacterProperty(char character) {
+ this.character = character;
}
- public Property make(PropertyList propertyList, String value, FObj fo) {
- char c = value.charAt(0);
- return new CharacterProperty(c);
+ public Object getObject() {
+ return new Character(character);
}
- } // end Charakter.Maker
- private char character ;
+ public char getCharacter() {
+ return this.character;
+ }
- public CharacterProperty(char character) {
- this.character = character;
- }
+ public String getString() {
+ return new Character(character).toString();
+ }
- public Object getObject() { return new Character(character); }
- public char getCharacter() { return this.character; }
- public String getString() { return new Character(character).toString(); }
}
diff --git a/src/org/apache/fop/fo/ColorProfile.java b/src/org/apache/fop/fo/ColorProfile.java
index 16494c96c..14cdc0c2b 100644
--- a/src/org/apache/fop/fo/ColorProfile.java
+++ b/src/org/apache/fop/fo/ColorProfile.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -25,6 +26,7 @@ public class ColorProfile extends ToBeImplementedElement {
PropertyList propertyList) throws FOPException {
return new ColorProfile(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -32,13 +34,13 @@ public class ColorProfile extends ToBeImplementedElement {
}
protected ColorProfile(FObj parent,
- PropertyList propertyList) throws FOPException {
+ PropertyList propertyList) throws FOPException {
super(parent, propertyList);
this.name = "fo:color-profile";
- //this.properties.get("src");
- //this.properties.get("color-profile-name");
- //this.properties.get("rendering-intent");
+ // this.properties.get("src");
+ // this.properties.get("color-profile-name");
+ // this.properties.get("rendering-intent");
}
}
diff --git a/src/org/apache/fop/fo/ColorTypeProperty.java b/src/org/apache/fop/fo/ColorTypeProperty.java
index 3aeed8240..17ea1e911 100644
--- a/src/org/apache/fop/fo/ColorTypeProperty.java
+++ b/src/org/apache/fop/fo/ColorTypeProperty.java
@@ -1,87 +1,47 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo;
import org.apache.fop.datatypes.ColorType;
public class ColorTypeProperty extends Property {
- public static class Maker extends Property.Maker {
-
- public Maker(String propName) {
- super(propName);
- }
+ public static class Maker extends Property.Maker {
+
+ public Maker(String propName) {
+ super(propName);
+ }
+
+ public Property convertProperty(Property p,
+ PropertyList propertyList, FObj fo) {
+ if (p instanceof ColorTypeProperty)
+ return p;
+ ColorType val = p.getColorType();
+ if (val != null)
+ return new ColorTypeProperty(val);
+ return convertPropertyDatatype(p, propertyList, fo);
+ }
- public Property convertProperty(Property p, PropertyList propertyList,
- FObj fo) {
- if (p instanceof ColorTypeProperty)
- return p;
- ColorType val = p.getColorType();
- if (val != null)
- return new ColorTypeProperty(val);
- return convertPropertyDatatype(p, propertyList, fo);
}
- }
- private ColorType colorType;
+ private ColorType colorType;
- public ColorTypeProperty(ColorType colorType) {
- this.colorType = colorType;
- }
+ public ColorTypeProperty(ColorType colorType) {
+ this.colorType = colorType;
+ }
+
+ // Can't convert to any other types
+ public ColorType getColorType() {
+ return this.colorType;
+ }
- // Can't convert to any other types
- public ColorType getColorType() {
- return this.colorType;
- }
+ public Object getObject() {
+ return this.colorType;
+ }
- public Object getObject() { return this.colorType; }
-
}
diff --git a/src/org/apache/fop/fo/CondLengthProperty.java b/src/org/apache/fop/fo/CondLengthProperty.java
index 6b6a27b29..9355e42c0 100644
--- a/src/org/apache/fop/fo/CondLengthProperty.java
+++ b/src/org/apache/fop/fo/CondLengthProperty.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo;
import org.apache.fop.datatypes.Length;
@@ -55,26 +12,31 @@ import org.apache.fop.datatypes.CondLength;
public class CondLengthProperty extends Property {
- public static class Maker extends Property.Maker {
+ public static class Maker extends Property.Maker {
+
+ public Maker(String name) {
+ super(name);
+ }
- public Maker(String name) {
- super(name);
}
- }
- private CondLength condLength= null;
+ private CondLength condLength = null;
- public CondLengthProperty(CondLength condLength) {
- this.condLength = condLength;
- }
+ public CondLengthProperty(CondLength condLength) {
+ this.condLength = condLength;
+ }
- public CondLength getCondLength() {
- return this.condLength;
- }
+ public CondLength getCondLength() {
+ return this.condLength;
+ }
- /* Question, should we allow this? */
- public Length getLength() { return this.condLength.getLength().getLength(); }
+ /* Question, should we allow this? */
+ public Length getLength() {
+ return this.condLength.getLength().getLength();
+ }
- public Object getObject() { return this.condLength; }
+ public Object getObject() {
+ return this.condLength;
+ }
}
diff --git a/src/org/apache/fop/fo/Declarations.java b/src/org/apache/fop/fo/Declarations.java
index fa35e3ed5..fe9ba9349 100644
--- a/src/org/apache/fop/fo/Declarations.java
+++ b/src/org/apache/fop/fo/Declarations.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -23,6 +24,7 @@ public class Declarations extends ToBeImplementedElement {
PropertyList propertyList) throws FOPException {
return new Declarations(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -30,7 +32,7 @@ public class Declarations extends ToBeImplementedElement {
}
protected Declarations(FObj parent,
- PropertyList propertyList) throws FOPException {
+ PropertyList propertyList) throws FOPException {
super(parent, propertyList);
this.name = "fo:declarations";
}
diff --git a/src/org/apache/fop/fo/ElementMapping.java b/src/org/apache/fop/fo/ElementMapping.java
index baa238033..25137f0f8 100644
--- a/src/org/apache/fop/fo/ElementMapping.java
+++ b/src/org/apache/fop/fo/ElementMapping.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
diff --git a/src/org/apache/fop/fo/EnumProperty.java b/src/org/apache/fop/fo/EnumProperty.java
index 41a519491..a5804420e 100644
--- a/src/org/apache/fop/fo/EnumProperty.java
+++ b/src/org/apache/fop/fo/EnumProperty.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo;
import org.apache.fop.apps.FOPException;
@@ -55,47 +12,51 @@ import org.apache.fop.messaging.MessageHandler;
public class EnumProperty extends Property {
- public static class Maker extends Property.Maker {
+ public static class Maker extends Property.Maker {
- protected Maker(String propName) {
- super(propName);
- }
+ protected Maker(String propName) {
+ super(propName);
+ }
- /**
- * Called by subclass if no match found.
- */
- public Property checkEnumValues(String value) {
- MessageHandler.errorln("WARNING: Unknown enumerated value for property '" +
- getPropName() + "': " + value);
- return null;
- }
+ /**
+ * Called by subclass if no match found.
+ */
+ public Property checkEnumValues(String value) {
+ MessageHandler.errorln("WARNING: Unknown enumerated value for property '"
+ + getPropName() + "': " + value);
+ return null;
+ }
- protected Property findConstant(String value) {
- return null;
- }
+ protected Property findConstant(String value) {
+ return null;
+ }
+
+ public Property convertProperty(Property p,
+ PropertyList propertyList,
+ FObj fo) throws FOPException {
+ if (p instanceof EnumProperty)
+ return p;
+ else
+ return null;
+ }
- public Property convertProperty(Property p,
- PropertyList propertyList, FObj fo) throws FOPException {
- if (p instanceof EnumProperty) return p;
- else return null;
}
- }
private int value;
public EnumProperty(int explicitValue) {
- this.value = explicitValue;
+ this.value = explicitValue;
}
public int getEnum() {
- return this.value;
+ return this.value;
}
public Object getObject() {
- // FIXME: return String value: property must reference maker
- // return maker.getEnumValue(this.value);
- return new Integer(this.value);
+ // FIXME: return String value: property must reference maker
+ // return maker.getEnumValue(this.value);
+ return new Integer(this.value);
}
}
diff --git a/src/org/apache/fop/fo/FONode.java b/src/org/apache/fop/fo/FONode.java
index 34d13623f..6c0213efe 100644
--- a/src/org/apache/fop/fo/FONode.java
+++ b/src/org/apache/fop/fo/FONode.java
@@ -1,7 +1,8 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
@@ -27,21 +28,26 @@ abstract public class FONode {
protected FObj parent;
protected String areaClass = AreaClass.UNASSIGNED;
-
- public BufferManager bufferManager;
-
- public Vector children = new Vector(); // made public for searching for id's
- /** value of marker before layout begins */
+ public BufferManager bufferManager;
+
+ public Vector children =
+ new Vector(); // made public for searching for id's
+
+ /**
+ * value of marker before layout begins
+ */
public final static int START = -1000;
- /** value of marker after break-after */
+ /**
+ * value of marker after break-after
+ */
public final static int BREAK_AFTER = -1001;
- /**
+ /**
* where the layout was up to.
- * for FObjs it is the child number
- * for FOText it is the character number
+ * for FObjs it is the child number
+ * for FOText it is the character number
*/
protected int marker = START;
@@ -57,183 +63,175 @@ abstract public class FONode {
// count of areas generated-by/returned-by
public int areasGenerated = 0;
-
+
// markers
protected Hashtable markers;
protected FONode(FObj parent) {
- this.parent = parent;
- if (parent != null) {
- this.bufferManager = parent.bufferManager;
- }
-
- markers = new Hashtable();
-
- if (null != parent)
- this.areaClass = parent.areaClass;
+ this.parent = parent;
+ if (parent != null) {
+ this.bufferManager = parent.bufferManager;
+ }
+
+ markers = new Hashtable();
+
+ if (null != parent)
+ this.areaClass = parent.areaClass;
}
public void setIsInTableCell() {
- this.isInTableCell = true;
- // made recursive by Eric Schaeffer
- for (int i = 0; i < this.children.size(); i++) {
- FONode child = (FONode) this.children.elementAt(i);
- child.setIsInTableCell();
- }
+ this.isInTableCell = true;
+ // made recursive by Eric Schaeffer
+ for (int i = 0; i < this.children.size(); i++) {
+ FONode child = (FONode)this.children.elementAt(i);
+ child.setIsInTableCell();
+ }
}
public void forceStartOffset(int offset) {
- this.forcedStartOffset = offset;
- // made recursive by Eric Schaeffer
- for (int i = 0; i < this.children.size(); i++) {
- FONode child = (FONode) this.children.elementAt(i);
- child.forceStartOffset(offset);
- }
+ this.forcedStartOffset = offset;
+ // made recursive by Eric Schaeffer
+ for (int i = 0; i < this.children.size(); i++) {
+ FONode child = (FONode)this.children.elementAt(i);
+ child.forceStartOffset(offset);
+ }
}
public void forceWidth(int width) {
- this.forcedWidth = width;
- // made recursive by Eric Schaeffer
- for (int i = 0; i < this.children.size(); i++) {
- FONode child = (FONode) this.children.elementAt(i);
- child.forceWidth(width);
- }
+ this.forcedWidth = width;
+ // made recursive by Eric Schaeffer
+ for (int i = 0; i < this.children.size(); i++) {
+ FONode child = (FONode)this.children.elementAt(i);
+ child.forceWidth(width);
+ }
}
public void resetMarker() {
- this.marker = START;
- int numChildren = this.children.size();
- for (int i = 0; i < numChildren; i++) {
- ((FONode) children.elementAt(i)).resetMarker();
- }
+ this.marker = START;
+ int numChildren = this.children.size();
+ for (int i = 0; i < numChildren; i++) {
+ ((FONode)children.elementAt(i)).resetMarker();
+ }
}
- public void setWidows(int wid)
- {
+ public void setWidows(int wid) {
widows = wid;
}
- public void setOrphans(int orph)
- {
+ public void setOrphans(int orph) {
orphans = orph;
}
public void removeAreas() {
- // still to do
+ // still to do
}
protected void addChild(FONode child) {
- children.addElement(child);
+ children.addElement(child);
}
public FObj getParent() {
- return this.parent;
+ return this.parent;
}
public void setBufferManager(BufferManager bufferManager) {
- this.bufferManager = bufferManager;
+ this.bufferManager = bufferManager;
}
-
+
public BufferManager getBufferManager() {
- return this.bufferManager;
+ return this.bufferManager;
}
-
+
public void setLinkSet(LinkSet linkSet) {
- this.linkSet = linkSet;
- for (int i = 0; i < this.children.size(); i++) {
- FONode child = (FONode) this.children.elementAt(i);
- child.setLinkSet(linkSet);
+ this.linkSet = linkSet;
+ for (int i = 0; i < this.children.size(); i++) {
+ FONode child = (FONode)this.children.elementAt(i);
+ child.setLinkSet(linkSet);
}
}
public LinkSet getLinkSet() {
- return this.linkSet;
+ return this.linkSet;
+ }
+
+ abstract public Status layout(Area area) throws FOPException;
+
+ /**
+ * lets outside sources access the property list
+ * first used by PageNumberCitation to find the "id" property
+ * returns null by default, overide this function when there is a property list
+ * @param name - the name of the desired property to obtain
+ * @returns the property
+ */
+ public Property getProperty(String name) {
+ return (null);
+ }
+
+ /**
+ * At the start of a new span area layout may be partway through a
+ * nested FO, and balancing requires rollback to this known point.
+ * The snapshot records exactly where layout is at.
+ * @param snapshot a Vector of markers (Integer)
+ * @returns the updated Vector of markers (Integers)
+ */
+ public Vector getMarkerSnapshot(Vector snapshot) {
+ snapshot.addElement(new Integer(this.marker));
+
+ // terminate if no kids or child not yet accessed
+ if (this.marker < 0)
+ return snapshot;
+ else if (children.isEmpty())
+ return snapshot;
+ else
+ return ((FONode)children.elementAt(this.marker)).getMarkerSnapshot(snapshot);
}
- abstract public Status layout(Area area)
- throws FOPException;
-
/**
- * lets outside sources access the property list
- * first used by PageNumberCitation to find the "id" property
- * returns null by default, overide this function when there is a property list
- *@param name - the name of the desired property to obtain
- * @returns the property
- */
- public Property getProperty(String name)
- {
- return(null);
- }
-
- /**
- * At the start of a new span area layout may be partway through a
- * nested FO, and balancing requires rollback to this known point.
- * The snapshot records exactly where layout is at.
- * @param snapshot a Vector of markers (Integer)
- * @returns the updated Vector of markers (Integers)
- */
- public Vector getMarkerSnapshot(Vector snapshot)
- {
- snapshot.addElement(new Integer(this.marker));
-
- // terminate if no kids or child not yet accessed
- if (this.marker < 0)
- return snapshot;
- else if (children.isEmpty())
- return snapshot;
- else
- return ((FONode) children.elementAt(this.marker)).getMarkerSnapshot(snapshot);
- }
-
- /**
- * When balancing occurs, the flow layout() method restarts at the
- * point specified by the current marker snapshot, which is retrieved
- * and restored using this method.
- * @param snapshot the Vector of saved markers (Integers)
- */
- public void rollback(Vector snapshot)
- {
- this.marker = ((Integer)snapshot.elementAt(0)).intValue();
- snapshot.removeElementAt(0);
-
- if (this.marker == START)
- {
- // make sure all the children of this FO are also reset
- resetMarker();
- return;
- }
- else if ((this.marker == -1) || children.isEmpty())
- return;
-
- int numChildren = this.children.size();
-
- if (this.marker <= START)
- {
- return;
- }
-
- for (int i = this.marker + 1; i < numChildren; i++) {
- FONode fo = (FONode) children.elementAt(i);
- fo.resetMarker();
- }
- ((FONode) children.elementAt(this.marker)).rollback(snapshot);
- }
-
-
- public void addMarker(Marker marker) throws FOPException {
- String mcname = marker.getMarkerClassName();
- if (!markers.containsKey(mcname) && children.isEmpty())
- markers.put(mcname, marker);
- else
- throw new FOPException("fo:marker must be an initial child," +
- "and 'marker-class-name' must be unique for same parent");
- }
-
- public boolean hasMarkers() {
- return !markers.isEmpty();
- }
-
- public Vector getMarkers() {
- return new Vector(markers.values());
- }
+ * When balancing occurs, the flow layout() method restarts at the
+ * point specified by the current marker snapshot, which is retrieved
+ * and restored using this method.
+ * @param snapshot the Vector of saved markers (Integers)
+ */
+ public void rollback(Vector snapshot) {
+ this.marker = ((Integer)snapshot.elementAt(0)).intValue();
+ snapshot.removeElementAt(0);
+
+ if (this.marker == START) {
+ // make sure all the children of this FO are also reset
+ resetMarker();
+ return;
+ } else if ((this.marker == -1) || children.isEmpty())
+ return;
+
+ int numChildren = this.children.size();
+
+ if (this.marker <= START) {
+ return;
+ }
+
+ for (int i = this.marker + 1; i < numChildren; i++) {
+ FONode fo = (FONode)children.elementAt(i);
+ fo.resetMarker();
+ }
+ ((FONode)children.elementAt(this.marker)).rollback(snapshot);
+ }
+
+
+ public void addMarker(Marker marker) throws FOPException {
+ String mcname = marker.getMarkerClassName();
+ if (!markers.containsKey(mcname) && children.isEmpty())
+ markers.put(mcname, marker);
+ else
+ throw new FOPException("fo:marker must be an initial child,"
+ + "and 'marker-class-name' must be unique for same parent");
+ }
+
+ public boolean hasMarkers() {
+ return !markers.isEmpty();
+ }
+
+ public Vector getMarkers() {
+ return new Vector(markers.values());
+ }
+
}
diff --git a/src/org/apache/fop/fo/FOText.java b/src/org/apache/fop/fo/FOText.java
index ae4971c71..20095d988 100644
--- a/src/org/apache/fop/fo/FOText.java
+++ b/src/org/apache/fop/fo/FOText.java
@@ -1,6 +1,7 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
+ * For details on use and redistribution please refer to the
* LICENSE file included with these sources."
*/
@@ -22,46 +23,45 @@ import org.apache.fop.system.BufferManager;
*/
public class FOText extends FONode {
- // protected char[] ca;
- protected int start;
- protected int length;
-
- FontState fs;
- float red;
- float green;
- float blue;
- int wrapOption;
- int whiteSpaceCollapse;
- int verticalAlign;
-
- // Textdecoration
- protected boolean underlined = false;
- protected boolean overlined = false;
- protected boolean lineThrough = false;
-
- TextState ts;
-
-
- public FOText(char[] chars, int s, int e, FObj parent) {
- super(parent);
- this.start = 0;
- char ca[] = new char[e - s];
- for (int i = s; i < e; i++)
- ca[i - s] = chars[i];
- this.length = e - s;
- this.bufferManager = parent.bufferManager;
- if (this.bufferManager != null) {
- bufferManager.writeBuffer((Object) this, ca);
- }
- else {
- System.out.println("abnormal exit");
- System.exit(0);
- }
- }
-
- public void setUnderlined(boolean ul) {
- this.underlined = ul;
- }
+ // protected char[] ca;
+ protected int start;
+ protected int length;
+
+ FontState fs;
+ float red;
+ float green;
+ float blue;
+ int wrapOption;
+ int whiteSpaceCollapse;
+ int verticalAlign;
+
+ // Textdecoration
+ protected boolean underlined = false;
+ protected boolean overlined = false;
+ protected boolean lineThrough = false;
+
+ TextState ts;
+
+
+ public FOText(char[] chars, int s, int e, FObj parent) {
+ super(parent);
+ this.start = 0;
+ char ca[] = new char[e - s];
+ for (int i = s; i < e; i++)
+ ca[i - s] = chars[i];
+ this.length = e - s;
+ this.bufferManager = parent.bufferManager;
+ if (this.bufferManager != null) {
+ bufferManager.writeBuffer((Object)this, ca);
+ } else {
+ System.out.println("abnormal exit");
+ System.exit(0);
+ }
+ }
+
+ public void setUnderlined(boolean ul) {
+ this.underlined = ul;
+ }
public void setOverlined(boolean ol) {
this.overlined = ol;
@@ -72,200 +72,212 @@ public class FOText extends FONode {
}
- public boolean willCreateArea()
- {
- char ca[] = this.bufferManager.readBuffer((Object) this);
- this.whiteSpaceCollapse = this.parent.properties.get(
- "white-space-collapse").getEnum();
- if(this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE && length > 0) {
- return true;
- }
-
- for (int i = start; i < start + length; i++) {
- char ch = ca[i];
- if (!((ch == ' ') || (ch == '\n') || (ch == '\r') ||
- (ch == '\t'))) { // whitespace
- return true;
- }
- }
- return false;
- }
-
- public Status layout(Area area) throws FOPException {
- char ca[] = this.bufferManager.readBuffer((Object) this);
- if (!(area instanceof BlockArea)) {
- MessageHandler.errorln("WARNING: text outside block area" +
- new String(ca, start, length));
- return new Status(Status.OK);
- }
- if (this.marker == START) {
- String fontFamily =
- this.parent.properties.get("font-family").getString();
- String fontStyle =
- this.parent.properties.get("font-style").getString();
- String fontWeight =
- this.parent.properties.get("font-weight").getString();
- int fontSize = this.parent.properties.get(
- "font-size").getLength().mvalue();
- // font-variant support
- // added by Eric SCHAEFFER
- int fontVariant = this.parent.properties.get("font-variant").getEnum();
-
- this.fs = new FontState(area.getFontInfo(), fontFamily,
- fontStyle, fontWeight, fontSize, fontVariant);
-
- ColorType c =
- this.parent.properties.get("color").getColorType();
- this.red = c.red();
- this.green = c.green();
- this.blue = c.blue();
-
- this.verticalAlign = this.parent.properties.get("vertical-align").getEnum();
-
- this.wrapOption =
- this.parent.properties.get("wrap-option").getEnum();
- this.whiteSpaceCollapse = this.parent.properties.get(
- "white-space-collapse").getEnum();
- this.ts = new TextState();
- ts.setUnderlined(underlined);
- ts.setOverlined(overlined);
- ts.setLineThrough(lineThrough);
-
- this.marker = this.start;
- }
- int orig_start = this.marker;
- this.marker = addText((BlockArea)area, fs, red, green, blue,
- wrapOption, this.getLinkSet(), whiteSpaceCollapse, ca,
- this.marker, length, ts, verticalAlign);
- if (this.marker == -1) {
-
-
- // commented out by Hani Elabed, 11/28/2000
- // if this object has been laid out
- // successfully, leave it alone....
- // Now, to prevent the array index out of
- // bound of LineArea.addText(), I have added
- // the following test at the beginning of that method.
- // if( start == -1 ) return -1;
- // see LineArea.addText()
-
- //this.marker = 0;
- return new Status(Status.OK);
- } else if (this.marker != orig_start) {
- return new Status(Status.AREA_FULL_SOME);
- } else {
- return new Status(Status.AREA_FULL_NONE);
- }
- }
-
- // font-variant support : addText is a wrapper for addRealText
- // added by Eric SCHAEFFER
- public static int addText(BlockArea ba, FontState fontState, float red, float green,
- float blue, int wrapOption, LinkSet ls,
- int whiteSpaceCollapse, char data[], int start, int end,
- TextState textState, int vAlign) {
- if (fontState.getFontVariant() == FontVariant.SMALL_CAPS) {
- FontState smallCapsFontState;
- try {
- int smallCapsFontHeight = (int) (((double) fontState.getFontSize()) * 0.8d);
- smallCapsFontState = new FontState(
- fontState.getFontInfo(),
- fontState.getFontFamily(),
- fontState.getFontStyle(),
- fontState.getFontWeight(),
- smallCapsFontHeight,
- FontVariant.NORMAL);
- } catch (FOPException ex) {
- smallCapsFontState = fontState;
- MessageHandler.errorln("Error creating small-caps FontState: " + ex.getMessage());
- }
-
- // parse text for upper/lower case and call addRealText
- char c;
- boolean isLowerCase;
- int caseStart;
- FontState fontStateToUse;
- for (int i = start; i < end; ) {
- caseStart = i;
- c = data[i];
- isLowerCase = (java.lang.Character.isLetter(c) && java.lang.Character.isLowerCase(c));
- while (isLowerCase == (java.lang.Character.isLetter(c) && java.lang.Character.isLowerCase(c))) {
- if (isLowerCase) {
- data[i] = java.lang.Character.toUpperCase(c);
- }
- i++;
- if (i == end)
- break;
- c = data[i];
- }
- if (isLowerCase) {
- fontStateToUse = smallCapsFontState;
- } else {
- fontStateToUse = fontState;
- }
- int index = addRealText(ba, fontStateToUse, red, green, blue, wrapOption, ls,
- whiteSpaceCollapse, data, caseStart, i, textState, vAlign);
- if (index != -1) {
- return index;
- }
- }
-
- return -1;
- }
-
- // font-variant normal
- return addRealText(ba, fontState, red, green, blue, wrapOption, ls,
- whiteSpaceCollapse, data, start, end, textState, vAlign);
- }
-
- protected static int addRealText(BlockArea ba, FontState fontState, float red, float green,
- float blue, int wrapOption, LinkSet ls,
- int whiteSpaceCollapse, char data[], int start, int end,
- TextState textState, int vAlign) {
- int ts, te;
- char[] ca;
-
- ts = start;
- te = end;
- ca = data;
-
- LineArea la = ba.getCurrentLineArea();
- if (la == null) {
- return start;
- }
-
- la.changeFont(fontState);
- la.changeColor(red, green, blue);
- la.changeWrapOption(wrapOption);
- la.changeWhiteSpaceCollapse(whiteSpaceCollapse);
- la.changeVerticalAlign(vAlign);
-// la.changeHyphenation(language, country, hyphenate,
-// hyphenationChar, hyphenationPushCharacterCount,
-// hyphenationRemainCharacterCount);
- ba.setupLinkSet(ls);
-
- ts = la.addText(ca, ts, te, ls, textState);
-// this.hasLines = true;
-
- while (ts != -1) {
- la = ba.createNextLineArea();
- if (la == null) {
- return ts;
- }
- la.changeFont(fontState);
- la.changeColor(red, green, blue);
- la.changeWrapOption(wrapOption);
- la.changeWhiteSpaceCollapse(
- whiteSpaceCollapse);
-// la.changeHyphenation(language, country, hyphenate,
-// hyphenationChar, hyphenationPushCharacterCount,
-// hyphenationRemainCharacterCount);
- ba.setupLinkSet(ls);
-
- ts = la.addText(ca, ts, te, ls, textState);
- }
- return -1;
- }
+ public boolean willCreateArea() {
+ char ca[] = this.bufferManager.readBuffer((Object)this);
+ this.whiteSpaceCollapse =
+ this.parent.properties.get("white-space-collapse").getEnum();
+ if (this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE
+ && length > 0) {
+ return true;
+ }
+
+ for (int i = start; i < start + length; i++) {
+ char ch = ca[i];
+ if (!((ch == ' ') || (ch == '\n') || (ch == '\r')
+ || (ch == '\t'))) { // whitespace
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public Status layout(Area area) throws FOPException {
+ char ca[] = this.bufferManager.readBuffer((Object)this);
+ if (!(area instanceof BlockArea)) {
+ MessageHandler.errorln("WARNING: text outside block area"
+ + new String(ca, start, length));
+ return new Status(Status.OK);
+ }
+ if (this.marker == START) {
+ String fontFamily =
+ this.parent.properties.get("font-family").getString();
+ String fontStyle =
+ this.parent.properties.get("font-style").getString();
+ String fontWeight =
+ this.parent.properties.get("font-weight").getString();
+ int fontSize =
+ this.parent.properties.get("font-size").getLength().mvalue();
+ // font-variant support
+ // added by Eric SCHAEFFER
+ int fontVariant =
+ this.parent.properties.get("font-variant").getEnum();
+
+ this.fs = new FontState(area.getFontInfo(), fontFamily,
+ fontStyle, fontWeight, fontSize,
+ fontVariant);
+
+ ColorType c = this.parent.properties.get("color").getColorType();
+ this.red = c.red();
+ this.green = c.green();
+ this.blue = c.blue();
+
+ this.verticalAlign =
+ this.parent.properties.get("vertical-align").getEnum();
+
+ this.wrapOption =
+ this.parent.properties.get("wrap-option").getEnum();
+ this.whiteSpaceCollapse =
+ this.parent.properties.get("white-space-collapse").getEnum();
+ this.ts = new TextState();
+ ts.setUnderlined(underlined);
+ ts.setOverlined(overlined);
+ ts.setLineThrough(lineThrough);
+
+ this.marker = this.start;
+ }
+ int orig_start = this.marker;
+ this.marker = addText((BlockArea)area, fs, red, green, blue,
+ wrapOption, this.getLinkSet(),
+ whiteSpaceCollapse, ca, this.marker, length,
+ ts, verticalAlign);
+ if (this.marker == -1) {
+
+
+ // commented out by Hani Elabed, 11/28/2000
+ // if this object has been laid out
+ // successfully, leave it alone....
+ // Now, to prevent the array index out of
+ // bound of LineArea.addText(), I have added
+ // the following test at the beginning of that method.
+ // if( start == -1 ) return -1;
+ // see LineArea.addText()
+
+ // this.marker = 0;
+ return new Status(Status.OK);
+ } else if (this.marker != orig_start) {
+ return new Status(Status.AREA_FULL_SOME);
+ } else {
+ return new Status(Status.AREA_FULL_NONE);
+ }
+ }
+
+ // font-variant support : addText is a wrapper for addRealText
+ // added by Eric SCHAEFFER
+ public static int addText(BlockArea ba, FontState fontState, float red,
+ float green, float blue, int wrapOption,
+ LinkSet ls, int whiteSpaceCollapse,
+ char data[], int start, int end,
+ TextState textState, int vAlign) {
+ if (fontState.getFontVariant() == FontVariant.SMALL_CAPS) {
+ FontState smallCapsFontState;
+ try {
+ int smallCapsFontHeight =
+ (int)(((double)fontState.getFontSize()) * 0.8d);
+ smallCapsFontState = new FontState(fontState.getFontInfo(),
+ fontState.getFontFamily(),
+ fontState.getFontStyle(),
+ fontState.getFontWeight(),
+ smallCapsFontHeight,
+ FontVariant.NORMAL);
+ } catch (FOPException ex) {
+ smallCapsFontState = fontState;
+ MessageHandler.errorln("Error creating small-caps FontState: "
+ + ex.getMessage());
+ }
+
+ // parse text for upper/lower case and call addRealText
+ char c;
+ boolean isLowerCase;
+ int caseStart;
+ FontState fontStateToUse;
+ for (int i = start; i < end; ) {
+ caseStart = i;
+ c = data[i];
+ isLowerCase = (java.lang.Character.isLetter(c)
+ && java.lang.Character.isLowerCase(c));
+ while (isLowerCase
+ == (java.lang.Character.isLetter(c)
+ && java.lang.Character.isLowerCase(c))) {
+ if (isLowerCase) {
+ data[i] = java.lang.Character.toUpperCase(c);
+ }
+ i++;
+ if (i == end)
+ break;
+ c = data[i];
+ }
+ if (isLowerCase) {
+ fontStateToUse = smallCapsFontState;
+ } else {
+ fontStateToUse = fontState;
+ }
+ int index = addRealText(ba, fontStateToUse, red, green, blue,
+ wrapOption, ls, whiteSpaceCollapse,
+ data, caseStart, i, textState,
+ vAlign);
+ if (index != -1) {
+ return index;
+ }
+ }
+
+ return -1;
+ }
+
+ // font-variant normal
+ return addRealText(ba, fontState, red, green, blue, wrapOption, ls,
+ whiteSpaceCollapse, data, start, end, textState,
+ vAlign);
+ }
+
+ protected static int addRealText(BlockArea ba, FontState fontState,
+ float red, float green, float blue,
+ int wrapOption, LinkSet ls,
+ int whiteSpaceCollapse, char data[],
+ int start, int end, TextState textState,
+ int vAlign) {
+ int ts, te;
+ char[] ca;
+
+ ts = start;
+ te = end;
+ ca = data;
+
+ LineArea la = ba.getCurrentLineArea();
+ if (la == null) {
+ return start;
+ }
+
+ la.changeFont(fontState);
+ la.changeColor(red, green, blue);
+ la.changeWrapOption(wrapOption);
+ la.changeWhiteSpaceCollapse(whiteSpaceCollapse);
+ la.changeVerticalAlign(vAlign);
+ // la.changeHyphenation(language, country, hyphenate,
+ // hyphenationChar, hyphenationPushCharacterCount,
+ // hyphenationRemainCharacterCount);
+ ba.setupLinkSet(ls);
+
+ ts = la.addText(ca, ts, te, ls, textState);
+ // this.hasLines = true;
+
+ while (ts != -1) {
+ la = ba.createNextLineArea();
+ if (la == null) {
+ return ts;
+ }
+ la.changeFont(fontState);
+ la.changeColor(red, green, blue);
+ la.changeWrapOption(wrapOption);
+ la.changeWhiteSpaceCollapse(whiteSpaceCollapse);
+ // la.changeHyphenation(language, country, hyphenate,
+ // hyphenationChar, hyphenationPushCharacterCount,
+ // hyphenationRemainCharacterCount);
+ ba.setupLinkSet(ls);
+
+ ts = la.addText(ca, ts, te, ls, textState);
+ }
+ return -1;
+ }
}
diff --git a/src/org/apache/fop/fo/FOTreeBuilder.java b/src/org/apache/fop/fo/FOTreeBuilder.java
index cf0b1dfe2..c719a2b35 100644
--- a/src/org/apache/fop/fo/FOTreeBuilder.java
+++ b/src/org/apache/fop/fo/FOTreeBuilder.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -79,8 +80,7 @@ public class FOTreeBuilder extends DefaultHandler implements TreeBuilder {
*/
public void addPropertyList(String namespaceURI, Hashtable list) {
PropertyListBuilder plb;
- plb = (PropertyListBuilder) this.propertylistTable.get(
- namespaceURI);
+ plb = (PropertyListBuilder)this.propertylistTable.get(namespaceURI);
if (plb == null) {
plb = new PropertyListBuilder();
plb.addList(list);
@@ -97,11 +97,10 @@ public class FOTreeBuilder extends DefaultHandler implements TreeBuilder {
* @param localName local name of formatting object element
* @param maker Maker for class representing formatting object
*/
- public void addElementPropertyList(String namespaceURI,
- String localName, Hashtable list) {
+ public void addElementPropertyList(String namespaceURI, String localName,
+ Hashtable list) {
PropertyListBuilder plb;
- plb = (PropertyListBuilder) this.propertylistTable.get(
- namespaceURI);
+ plb = (PropertyListBuilder)this.propertylistTable.get(namespaceURI);
if (plb == null) {
plb = new PropertyListBuilder();
plb.addElementList(localName, list);
@@ -111,53 +110,62 @@ public class FOTreeBuilder extends DefaultHandler implements TreeBuilder {
}
}
- /** SAX Handler for characters */
+ /**
+ * SAX Handler for characters
+ */
public void characters(char data[], int start, int length) {
currentFObj.addCharacters(data, start, start + length);
}
- /** SAX Handler for the end of an element */
+ /**
+ * SAX Handler for the end of an element
+ */
public void endElement(String uri, String localName, String rawName) {
currentFObj.end();
- currentFObj = (FObj) currentFObj.getParent();
+ currentFObj = (FObj)currentFObj.getParent();
}
- /** SAX Handler for the start of the document */
+ /**
+ * SAX Handler for the start of the document
+ */
public void startDocument() {
- rootFObj = null; // allows FOTreeBuilder to be reused
+ rootFObj = null; // allows FOTreeBuilder to be reused
MessageHandler.logln("building formatting object tree");
}
- /** SAX Handler for the start of an element */
- public void startElement(String uri, String localName,
- String rawName, Attributes attlist) throws SAXException {
+ /**
+ * SAX Handler for the start of an element
+ */
+ public void startElement(String uri, String localName, String rawName,
+ Attributes attlist) throws SAXException {
/* the formatting object started */
FObj fobj;
/* the maker for the formatting object started */
FObj.Maker fobjMaker;
- //String fullName = mapName(rawName);
+ // String fullName = mapName(rawName);
String fullName = uri + "^" + localName;
- fobjMaker = (FObj.Maker) fobjTable.get(fullName);
+ fobjMaker = (FObj.Maker)fobjTable.get(fullName);
PropertyListBuilder currentListBuilder =
- (PropertyListBuilder) this.propertylistTable.get(uri);
+ (PropertyListBuilder)this.propertylistTable.get(uri);
if (fobjMaker == null) {
if (!this.unknownFOs.containsKey(fullName)) {
this.unknownFOs.put(fullName, "");
- MessageHandler.errorln(
- "WARNING: Unknown formatting object " + fullName);
+ MessageHandler.errorln("WARNING: Unknown formatting object "
+ + fullName);
}
- fobjMaker = new FObjMixed.Maker(); // fall back
+ fobjMaker = new FObjMixed.Maker(); // fall back
}
try {
PropertyList list = null;
if (currentListBuilder != null) {
- list = currentListBuilder.makeList(fullName, attlist,
- (currentFObj == null) ? null :
- currentFObj.properties, currentFObj);
+ list =
+ currentListBuilder.makeList(fullName, attlist,
+ (currentFObj == null) ? null
+ : currentFObj.properties, currentFObj);
} else {
list = currentFObj.properties;
}
@@ -170,9 +178,9 @@ public class FOTreeBuilder extends DefaultHandler implements TreeBuilder {
rootFObj = fobj;
rootFObj.setBufferManager(this.bufferManager);
if (!fobj.getName().equals("fo:root")) {
- throw new SAXException(
- new FOPException("Root element must" +
- " be root, not " + fobj.getName()));
+ throw new SAXException(new FOPException("Root element must"
+ + " be root, not "
+ + fobj.getName()));
}
} else {
currentFObj.addChild(fobj);
@@ -189,7 +197,7 @@ public class FOTreeBuilder extends DefaultHandler implements TreeBuilder {
public void format(AreaTree areaTree) throws FOPException {
MessageHandler.logln("formatting FOs into areas");
this.bufferManager.readComplete();
- ((Root) this.rootFObj).format(areaTree);
+ ((Root)this.rootFObj).format(areaTree);
}
public void reset() {
@@ -204,4 +212,5 @@ public class FOTreeBuilder extends DefaultHandler implements TreeBuilder {
public void setBufferManager(BufferManager bufferManager) {
this.bufferManager = bufferManager;
}
+
}
diff --git a/src/org/apache/fop/fo/FObj.java b/src/org/apache/fop/fo/FObj.java
index f1256d56a..ad10bbc77 100644
--- a/src/org/apache/fop/fo/FObj.java
+++ b/src/org/apache/fop/fo/FObj.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -20,129 +21,127 @@ import java.util.Enumeration;
*/
public class FObj extends FONode {
- public static class Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new FObj(parent, propertyList);
+ public static class Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new FObj(parent, propertyList);
+ }
+
+ }
+
+ public static Maker maker() {
+ return new Maker();
+ }
+
+ // protected PropertyList properties;
+ public PropertyList properties;
+ protected PropertyManager propMgr;
+
+ protected String name;
+
+ protected FObj(FObj parent, PropertyList propertyList) {
+ super(parent);
+ this.properties = propertyList; // TO BE REMOVED!!!
+ propertyList.setFObj(this);
+ this.propMgr = makePropertyManager(propertyList);
+ this.name = "default FO";
+ setWritingMode();
+ }
+
+ protected PropertyManager makePropertyManager(PropertyList propertyList) {
+ return new PropertyManager(propertyList);
+ }
+
+ /**
+ * adds characters (does nothing here)
+ * @param data text
+ * @param start start position
+ * @param length length of the text
+ */
+ protected void addCharacters(char data[], int start, int length) {
+ // ignore
+ }
+
+ /**
+ * generates the area or areas for this formatting object
+ * and adds these to the area. This method should always be
+ * overridden by all sub classes
+ *
+ * @param area
+ */
+ public Status layout(Area area) throws FOPException {
+ // should always be overridden
+ return new Status(Status.OK);
+ }
+
+ /**
+ * returns the name of the formatting object
+ * @return the name of this formatting objects
+ */
+ public String getName() {
+ return this.name;
+ }
+
+ /**
+ *
+ */
+ protected void start() {
+ // do nothing by default
+ }
+
+ /**
+ *
+ */
+ protected void end() {
+ // do nothing by default
+ }
+
+ /**
+ * lets outside sources access the property list
+ * first used by PageNumberCitation to find the "id" property
+ * @param name - the name of the desired property to obtain
+ * @return the property
+ */
+ public Property getProperty(String name) {
+ return (properties.get(name));
}
- }
-
- public static Maker maker() {
- return new Maker();
- }
-
-// protected PropertyList properties;
- public PropertyList properties;
- protected PropertyManager propMgr;
-
- protected String name;
-
- protected FObj(FObj parent, PropertyList propertyList) {
- super(parent);
- this.properties = propertyList; // TO BE REMOVED!!!
- propertyList.setFObj(this);
- this.propMgr = makePropertyManager(propertyList);
- this.name = "default FO";
- setWritingMode();
- }
-
- protected PropertyManager makePropertyManager(PropertyList propertyList) {
- return new PropertyManager(propertyList);
- }
-
- /**
- * adds characters (does nothing here)
- * @param data text
- * @param start start position
- * @param length length of the text
- */
- protected void addCharacters(char data[], int start, int length) {
- // ignore
- }
-
- /**
- * generates the area or areas for this formatting object
- * and adds these to the area. This method should always be
- * overridden by all sub classes
- *
- * @param area
- */
- public Status layout(Area area) throws FOPException {
- // should always be overridden
- return new Status(Status.OK);
- }
-
- /**
- * returns the name of the formatting object
- * @return the name of this formatting objects
- */
- public String getName() {
- return this.name;
- }
-
- /**
- *
- */
- protected void start() {
- // do nothing by default
- }
-
- /**
- *
- */
- protected void end() {
- // do nothing by default
- }
-
- /**
- * lets outside sources access the property list
- * first used by PageNumberCitation to find the "id" property
- * @param name - the name of the desired property to obtain
- * @return the property
- */
- public Property getProperty(String name)
- {
- return(properties.get(name));
- }
-
-
- /**
- * Return the "content width" of the areas generated by this FO.
- * This is used by percent-based properties to get the dimension of
- * the containing block.
- * If an FO has a property with a percentage value, that value
- * is usually calculated on the basis of the corresponding dimension
- * of the area which contains areas generated by the FO.
- * NOTE: subclasses of FObj should implement this to return a reasonable
- * value!
- */
- public int getContentWidth() {
- return 0;
- }
-
- /**
- * removes property id
- * @param idReferences the id to remove
- */
- public void removeID(IDReferences idReferences)
- {
- if(((FObj)this).properties.get("id") == null || ((FObj)this).properties.get("id").getString() == null)
- return;
- idReferences.removeID( ((FObj)this).properties.get("id").getString());
- int numChildren = this.children.size();
- for (int i = 0; i < numChildren; i++)
- {
- FONode child= (FONode)children.elementAt(i);
- if ((child instanceof FObj))
- {
- ((FObj)child).removeID(idReferences);
- }
+
+
+ /**
+ * Return the "content width" of the areas generated by this FO.
+ * This is used by percent-based properties to get the dimension of
+ * the containing block.
+ * If an FO has a property with a percentage value, that value
+ * is usually calculated on the basis of the corresponding dimension
+ * of the area which contains areas generated by the FO.
+ * NOTE: subclasses of FObj should implement this to return a reasonable
+ * value!
+ */
+ public int getContentWidth() {
+ return 0;
}
- }
- public boolean generatesReferenceAreas() {
- return false;
- }
+ /**
+ * removes property id
+ * @param idReferences the id to remove
+ */
+ public void removeID(IDReferences idReferences) {
+ if (((FObj)this).properties.get("id") == null
+ || ((FObj)this).properties.get("id").getString() == null)
+ return;
+ idReferences.removeID(((FObj)this).properties.get("id").getString());
+ int numChildren = this.children.size();
+ for (int i = 0; i < numChildren; i++) {
+ FONode child = (FONode)children.elementAt(i);
+ if ((child instanceof FObj)) {
+ ((FObj)child).removeID(idReferences);
+ }
+ }
+ }
+
+ public boolean generatesReferenceAreas() {
+ return false;
+ }
/**
* Set writing mode for this FO.
@@ -150,13 +149,14 @@ public class FObj extends FONode {
* reference areas and use the value of its writing-mode property.
* If no such ancestor is found, use the value on the root FO.
*/
- private void setWritingMode() {
- FObj p ;
- FObj parent;
- for (p=this;
- !p.generatesReferenceAreas() && (parent = p.getParent()) != null;
- p=parent);
- this.properties.setWritingMode(p.getProperty("writing-mode").getEnum());
- }
+ private void setWritingMode() {
+ FObj p;
+ FObj parent;
+ for (p = this;
+ !p.generatesReferenceAreas() && (parent = p.getParent()) != null;
+ p = parent);
+ this.properties.setWritingMode(p.getProperty("writing-mode").getEnum());
+ }
+
}
diff --git a/src/org/apache/fop/fo/FObjMixed.java b/src/org/apache/fop/fo/FObjMixed.java
index 3b40d1310..d69c68179 100644
--- a/src/org/apache/fop/fo/FObjMixed.java
+++ b/src/org/apache/fop/fo/FObjMixed.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -11,15 +12,16 @@ import org.apache.fop.apps.FOPException;
/**
* base class for representation of mixed content formatting objects
- * and their processing
+ * and their processing
*/
public class FObjMixed extends FObj {
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
return new FObjMixed(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -30,40 +32,41 @@ public class FObjMixed extends FObj {
super(parent, propertyList);
}
- protected void addCharacters(char data[], int start, int length) {
- children.addElement(new FOText(data,start,length,this));
+ protected void addCharacters(char data[], int start, int length) {
+ children.addElement(new FOText(data, start, length, this));
}
public Status layout(Area area) throws FOPException {
- if(this.properties != null) {
+ if (this.properties != null) {
Property prop = this.properties.get("id");
- if(prop != null) {
+ if (prop != null) {
String id = prop.getString();
- if ( this.marker == START ) {
- if(area.getIDReferences() != null)
- area.getIDReferences().createID(id);
+ if (this.marker == START) {
+ if (area.getIDReferences() != null)
+ area.getIDReferences().createID(id);
this.marker = 0;
}
- if ( this.marker == 0 ) {
- if(area.getIDReferences() != null)
- area.getIDReferences().configureID(id,area);
+ if (this.marker == 0) {
+ if (area.getIDReferences() != null)
+ area.getIDReferences().configureID(id, area);
}
}
}
int numChildren = this.children.size();
- for ( int i = this.marker; i < numChildren; i++ ) {
- FONode fo = (FONode) children.elementAt(i);
+ for (int i = this.marker; i < numChildren; i++) {
+ FONode fo = (FONode)children.elementAt(i);
Status status;
- if ( (status = fo.layout(area)).isIncomplete() ) {
+ if ((status = fo.layout(area)).isIncomplete()) {
this.marker = i;
return status;
}
}
return new Status(Status.OK);
}
+
}
diff --git a/src/org/apache/fop/fo/GenericShorthandParser.java b/src/org/apache/fop/fo/GenericShorthandParser.java
index 90f2b725d..4237beb0f 100644
--- a/src/org/apache/fop/fo/GenericShorthandParser.java
+++ b/src/org/apache/fop/fo/GenericShorthandParser.java
@@ -1,3 +1,10 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.fo;
import java.util.Vector;
@@ -5,46 +12,51 @@ import java.util.Enumeration;
public class GenericShorthandParser implements ShorthandParser {
- protected Vector list; // Vector of Property objects
-
- public GenericShorthandParser(ListProperty listprop) {
- this.list=listprop.getList();
- }
-
- protected Property getElement(int index) {
- if (list.size() > index) return (Property)list.elementAt(index);
- else return null;
- }
-
- protected int count() {
- return list.size();
- }
-
- // Stores 1 to 3 values for border width, style, color
- // Used for: border, border-top, border-right etc
- public Property getValueForProperty(String propName, Property.Maker maker,
- PropertyList propertyList) {
- Property prop = null;
- // Check for keyword "inherit"
- if (count() == 1) {
- String sval = ((Property)list.elementAt(0)).getString();
- if (sval != null && sval.equals("inherit")) {
- return propertyList.getFromParent(propName);
- }
+ protected Vector list; // Vector of Property objects
+
+ public GenericShorthandParser(ListProperty listprop) {
+ this.list = listprop.getList();
+ }
+
+ protected Property getElement(int index) {
+ if (list.size() > index)
+ return (Property)list.elementAt(index);
+ else
+ return null;
}
- return convertValueForProperty(propName, maker, propertyList);
- }
-
-
- protected Property convertValueForProperty(String propName, Property.Maker maker,
- PropertyList propertyList) {
- Property prop = null;
- // Try each of the stored values in turn
- Enumeration eprop = list.elements();
- while (eprop.hasMoreElements() && prop == null) {
- Property p = (Property)eprop.nextElement();
- prop = maker.convertShorthandProperty(propertyList, p, null);
+
+ protected int count() {
+ return list.size();
}
- return prop;
- }
+
+ // Stores 1 to 3 values for border width, style, color
+ // Used for: border, border-top, border-right etc
+ public Property getValueForProperty(String propName,
+ Property.Maker maker,
+ PropertyList propertyList) {
+ Property prop = null;
+ // Check for keyword "inherit"
+ if (count() == 1) {
+ String sval = ((Property)list.elementAt(0)).getString();
+ if (sval != null && sval.equals("inherit")) {
+ return propertyList.getFromParent(propName);
+ }
+ }
+ return convertValueForProperty(propName, maker, propertyList);
+ }
+
+
+ protected Property convertValueForProperty(String propName,
+ Property.Maker maker,
+ PropertyList propertyList) {
+ Property prop = null;
+ // Try each of the stored values in turn
+ Enumeration eprop = list.elements();
+ while (eprop.hasMoreElements() && prop == null) {
+ Property p = (Property)eprop.nextElement();
+ prop = maker.convertShorthandProperty(propertyList, p, null);
+ }
+ return prop;
+ }
+
}
diff --git a/src/org/apache/fop/fo/KeepProperty.java b/src/org/apache/fop/fo/KeepProperty.java
index 64f28af67..341180c13 100644
--- a/src/org/apache/fop/fo/KeepProperty.java
+++ b/src/org/apache/fop/fo/KeepProperty.java
@@ -1,74 +1,36 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo;
import org.apache.fop.datatypes.Keep;
public class KeepProperty extends Property {
- public static class Maker extends Property.Maker {
+ public static class Maker extends Property.Maker {
+
+ protected Maker(String name) {
+ super(name);
+ }
- protected Maker(String name) {
- super(name);
}
- }
- private Keep keep ;
+ private Keep keep;
- public KeepProperty(Keep keep) {
- this.keep = keep;
- }
+ public KeepProperty(Keep keep) {
+ this.keep = keep;
+ }
- public Keep getKeep() { return this.keep; }
+ public Keep getKeep() {
+ return this.keep;
+ }
- public Object getObject() { return this.keep; }
+ public Object getObject() {
+ return this.keep;
+ }
}
diff --git a/src/org/apache/fop/fo/LengthPairProperty.java b/src/org/apache/fop/fo/LengthPairProperty.java
index 9420a2215..2cc7b465b 100644
--- a/src/org/apache/fop/fo/LengthPairProperty.java
+++ b/src/org/apache/fop/fo/LengthPairProperty.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -11,21 +12,26 @@ import org.apache.fop.datatypes.LengthPair;
public class LengthPairProperty extends Property {
- public static class Maker extends LengthProperty.Maker {
+ public static class Maker extends LengthProperty.Maker {
+
+ protected Maker(String name) {
+ super(name);
+ }
- protected Maker(String name) {
- super(name);
}
- }
- private LengthPair lengthPair ;
+ private LengthPair lengthPair;
- public LengthPairProperty(LengthPair lengthPair) {
- this.lengthPair = lengthPair;
- }
+ public LengthPairProperty(LengthPair lengthPair) {
+ this.lengthPair = lengthPair;
+ }
- public LengthPair getLengthPair() { return this.lengthPair; }
+ public LengthPair getLengthPair() {
+ return this.lengthPair;
+ }
- public Object getObject() { return this.lengthPair ; }
+ public Object getObject() {
+ return this.lengthPair;
+ }
}
diff --git a/src/org/apache/fop/fo/LengthProperty.java b/src/org/apache/fop/fo/LengthProperty.java
index 365eb811d..ed1abfa06 100644
--- a/src/org/apache/fop/fo/LengthProperty.java
+++ b/src/org/apache/fop/fo/LengthProperty.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo;
import org.apache.fop.datatypes.Length;
@@ -58,71 +15,78 @@ import org.apache.fop.apps.FOPException;
public class LengthProperty extends Property {
- public static class Maker extends Property.Maker {
+ public static class Maker extends Property.Maker {
+
+ public /* protected */ Maker(String name) {
+ super(name);
+ }
+
+ /**
+ * protected Property checkPropertyKeywords(String value) {
+ * if (isAutoLengthAllowed() && value.equals("auto")) {
+ * return new LengthProperty(Length.AUTO);
+ * }
+ * return null;
+ * }
+ */
+
+ protected boolean isAutoLengthAllowed() {
+ return false;
+ }
+
+ public Property convertProperty(Property p,
+ PropertyList propertyList,
+ FObj fo) throws FOPException {
+ if (isAutoLengthAllowed()) {
+ String pval = p.getString();
+ if (pval != null && pval.equals("auto"))
+ return new LengthProperty(Length.AUTO);
+ }
+ if (p instanceof LengthProperty)
+ return p;
+ Length val = p.getLength();
+ if (val != null)
+ return new LengthProperty(val);
+ return convertPropertyDatatype(p, propertyList, fo);
+ }
- public /* protected*/ Maker(String name) {
- super(name);
}
+ /*
+ * public static Property.Maker maker(String prop) {
+ * return new Maker(prop);
+ * }
+ */
+
/**
- protected Property checkPropertyKeywords(String value) {
- if (isAutoLengthAllowed() && value.equals("auto")) {
- return new LengthProperty(Length.AUTO);
- }
- return null;
+ * This object may be also be a subclass of Length, such
+ * as PercentLength, TableColLength.
+ */
+ private Length length;
+
+ public LengthProperty(Length length) {
+ this.length = length;
+ // System.err.println("Set LengthProperty: " + length.toString());
+ }
+
+ public Numeric getNumeric() {
+ // Can't just do new Numeric(length) because it always uses
+ // the constructor for Length!
+ // Otherwise, must make each class know about Numeric...
+ // ie, return length.asNumeric(): cleaner
+ if (length instanceof PercentLength)
+ return new Numeric((PercentLength)length);
+ if (length instanceof TableColLength)
+ return new Numeric((TableColLength)length);
+ return new Numeric(length);
}
- **/
- protected boolean isAutoLengthAllowed() {
- return false;
+ public Length getLength() {
+ return this.length;
}
- public Property convertProperty(Property p, PropertyList propertyList,
- FObj fo) throws FOPException {
- if (isAutoLengthAllowed()) {
- String pval = p.getString();
- if (pval != null && pval.equals("auto"))
- return new LengthProperty(Length.AUTO);
- }
- if (p instanceof LengthProperty)
- return p;
- Length val = p.getLength();
- if (val != null)
- return new LengthProperty(val);
- return convertPropertyDatatype(p, propertyList, fo);
+ public Object getObject() {
+ return this.length;
}
- }
-
- /*
- public static Property.Maker maker(String prop) {
- return new Maker(prop);
- }
- */
-
- /** This object may be also be a subclass of Length, such
- * as PercentLength, TableColLength.
- */
- private Length length ;
-
- public LengthProperty(Length length) {
- this.length = length;
- //System.err.println("Set LengthProperty: " + length.toString());
- }
-
- public Numeric getNumeric() {
- // Can't just do new Numeric(length) because it always uses
- // the constructor for Length!
- // Otherwise, must make each class know about Numeric...
- // ie, return length.asNumeric(): cleaner
- if (length instanceof PercentLength)
- return new Numeric((PercentLength)length);
- if (length instanceof TableColLength)
- return new Numeric((TableColLength)length);
- return new Numeric(length);
- }
-
- public Length getLength() { return this.length; }
-
- public Object getObject() { return this.length; }
}
diff --git a/src/org/apache/fop/fo/LengthRangeProperty.java b/src/org/apache/fop/fo/LengthRangeProperty.java
index 20968d77f..438f8ee23 100644
--- a/src/org/apache/fop/fo/LengthRangeProperty.java
+++ b/src/org/apache/fop/fo/LengthRangeProperty.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo;
import org.apache.fop.datatypes.Length;
@@ -55,21 +12,26 @@ import org.apache.fop.datatypes.LengthRange;
public class LengthRangeProperty extends Property {
- public static class Maker extends LengthProperty.Maker {
+ public static class Maker extends LengthProperty.Maker {
+
+ protected Maker(String name) {
+ super(name);
+ }
- protected Maker(String name) {
- super(name);
}
- }
- private LengthRange lengthRange ;
+ private LengthRange lengthRange;
- public LengthRangeProperty(LengthRange lengthRange) {
- this.lengthRange = lengthRange;
- }
+ public LengthRangeProperty(LengthRange lengthRange) {
+ this.lengthRange = lengthRange;
+ }
- public LengthRange getLengthRange() { return this.lengthRange; }
+ public LengthRange getLengthRange() {
+ return this.lengthRange;
+ }
- public Object getObject() { return this.lengthRange ; }
+ public Object getObject() {
+ return this.lengthRange;
+ }
}
diff --git a/src/org/apache/fop/fo/ListProperty.java b/src/org/apache/fop/fo/ListProperty.java
index 6c76a1ef7..9253283e3 100644
--- a/src/org/apache/fop/fo/ListProperty.java
+++ b/src/org/apache/fop/fo/ListProperty.java
@@ -1,35 +1,49 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.fo;
import java.util.Vector;
public class ListProperty extends Property {
- public static class Maker extends Property.Maker {
+ public static class Maker extends Property.Maker {
- public Maker(String name) {
- super(name);
- }
+ public Maker(String name) {
+ super(name);
+ }
+
+ public Property convertProperty(Property p,
+ PropertyList propertyList, FObj fo) {
+ if (p instanceof ListProperty)
+ return p;
+ else
+ return new ListProperty(p);
+ }
- public Property convertProperty(Property p, PropertyList propertyList,
- FObj fo) {
- if (p instanceof ListProperty)
- return p;
- else return new ListProperty(p);
}
- }
- protected Vector list;
+ protected Vector list;
+
+ public ListProperty(Property prop) {
+ list = new Vector();
+ list.addElement(prop);
+ }
- public ListProperty(Property prop) {
- list = new Vector();
- list.addElement(prop);
- }
+ public void addProperty(Property prop) {
+ list.addElement(prop);
+ }
- public void addProperty(Property prop) {
- list.addElement(prop);
- }
+ public Vector getList() {
+ return list;
+ }
- public Vector getList() { return list; }
- public Object getObject() { return list; }
+ public Object getObject() {
+ return list;
+ }
}
diff --git a/src/org/apache/fop/fo/NumberProperty.java b/src/org/apache/fop/fo/NumberProperty.java
index bc117cdaa..eec77dc3c 100644
--- a/src/org/apache/fop/fo/NumberProperty.java
+++ b/src/org/apache/fop/fo/NumberProperty.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo;
@@ -55,61 +11,63 @@ import org.apache.fop.fo.expr.Numeric;
public class NumberProperty extends Property {
- public static class Maker extends Property.Maker {
-
- public Maker(String propName) {
- super(propName);
- }
+ public static class Maker extends Property.Maker {
- public Property convertProperty(Property p, PropertyList propertyList,
- FObj fo) {
- if (p instanceof NumberProperty)
- return p;
- Number val = p.getNumber();
- if (val != null)
- return new NumberProperty(val);
- return convertPropertyDatatype(p, propertyList, fo);
- }
- }
+ public Maker(String propName) {
+ super(propName);
+ }
- private Number number;
+ public Property convertProperty(Property p,
+ PropertyList propertyList, FObj fo) {
+ if (p instanceof NumberProperty)
+ return p;
+ Number val = p.getNumber();
+ if (val != null)
+ return new NumberProperty(val);
+ return convertPropertyDatatype(p, propertyList, fo);
+ }
- public NumberProperty(Number num) {
- this.number = num;
- }
+ }
- public NumberProperty(double num) {
- this.number = new Double(num);
- }
+ private Number number;
- public NumberProperty(int num) {
- this.number = new Integer(num);
- }
+ public NumberProperty(Number num) {
+ this.number = num;
+ }
- public Number getNumber() {
- return this.number;
- }
+ public NumberProperty(double num) {
+ this.number = new Double(num);
+ }
- /**
- public Double getDouble() {
- return new Double(this.number.doubleValue());
- }
+ public NumberProperty(int num) {
+ this.number = new Integer(num);
+ }
- public Integer getInteger() {
- return new Integer(this.number.intValue());
- }
- **/
+ public Number getNumber() {
+ return this.number;
+ }
- public Object getObject() { return this.number; }
+ /**
+ * public Double getDouble() {
+ * return new Double(this.number.doubleValue());
+ * }
+ * public Integer getInteger() {
+ * return new Integer(this.number.intValue());
+ * }
+ */
+
+ public Object getObject() {
+ return this.number;
+ }
- public Numeric getNumeric() {
- return new Numeric(this.number);
- }
+ public Numeric getNumeric() {
+ return new Numeric(this.number);
+ }
- public ColorType getColorType() {
- // Convert numeric value to color ???
- // Convert to hexadecimal and then try to make it into a color?
- return new ColorType((float)0.0, (float)0.0, (float)0.0);
- }
+ public ColorType getColorType() {
+ // Convert numeric value to color ???
+ // Convert to hexadecimal and then try to make it into a color?
+ return new ColorType((float)0.0, (float)0.0, (float)0.0);
+ }
}
diff --git a/src/org/apache/fop/fo/Property.java b/src/org/apache/fop/fo/Property.java
index ecc4b20c4..d56d67ceb 100644
--- a/src/org/apache/fop/fo/Property.java
+++ b/src/org/apache/fop/fo/Property.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -17,369 +18,426 @@ import java.util.Vector;
public class Property {
- public static class Maker {
- private static final String UNKNOWN = "UNKNOWN";
- private String propName;
+ public static class Maker {
+ private static final String UNKNOWN = "UNKNOWN";
+ private String propName;
+
+ /**
+ * Return the name of the property whose value is being set.
+ */
+ protected String getPropName() {
+ return propName;
+ }
+
+ /**
+ * Construct an instance of a Property.Maker for the given property.
+ * @param propName The name of the property to be made.
+ */
+ protected Maker(String propName) {
+ this.propName = propName;
+ }
+
+ /**
+ * Construct an instance of a Property.Maker.
+ * Note: the property name is set to "UNKNOWN".
+ */
+ protected Maker() {
+ this.propName = UNKNOWN;
+ }
+
+
+ /**
+ * Default implementation of isInherited.
+ * @return A boolean indicating whether this property is inherited.
+ */
+ public boolean isInherited() {
+ return false;
+ }
+
+ /**
+ * Return a boolean indicating whether this property inherits the
+ * "specified" value rather than the "computed" value. The default is
+ * to inherit the "computed" value.
+ * @return If true, property inherits the value specified.
+ */
+ public boolean inheritsSpecified() {
+ return false;
+ }
+
+
+ /**
+ * Return an object implementing the PercentBase interface.
+ * This is used to handle properties specified as a percentage of
+ * some "base length", such as the content width of their containing
+ * box.
+ * Overridden by subclasses which allow percent specifications. See
+ * the documentation on properties.xsl for details.
+ */
+ public PercentBase getPercentBase(FObj fo, PropertyList pl) {
+ return null;
+ }
+
+ /**
+ * Return a Maker object which is used to set the values on components
+ * of compound property types, such as "space".
+ * Overridden by property maker subclasses which handle
+ * compound properties.
+ * @param subprop The name of the component for which a Maker is to
+ * returned, for example "optimum", if the FO attribute is
+ * space.optimum='10pt'.
+ */
+ protected Maker getSubpropMaker(String subprop) {
+ return null;
+ }
+
+ /**
+ * Return a property value for the given component of a compound
+ * property.
+ * @param p A property value for a compound property type such as
+ * SpaceProperty.
+ * @param subprop The name of the component whose value is to be
+ * returned.
+ * NOTE: this is only to ease porting when calls are made to
+ * PropertyList.get() using a component name of a compound property,
+ * such as get("space.optimum"). The recommended technique is:
+ * get("space").getOptimum().
+ * Overridden by property maker subclasses which handle
+ * compound properties.
+ */
+ public Property getSubpropValue(Property p, String subprop) {
+ return null;
+ }
+
+ /**
+ * Return a property value for a compound property. If the property
+ * value is already partially initialized, this method will modify it.
+ * @param baseProp The Property object representing the compound property,
+ * such as SpaceProperty.
+ * @param partName The name of the component whose value is specified.
+ * @param propertyList The propertyList being built.
+ * @param fo The FO whose properties are being set.
+ * @return A compound property object.
+ */
+ public Property make(Property baseProp, String partName,
+ PropertyList propertyList, String value,
+ FObj fo) throws FOPException {
+ if (baseProp == null) {
+ baseProp = makeCompound(propertyList, fo);
+ }
+ Maker spMaker = getSubpropMaker(partName);
+ if (spMaker != null) {
+ Property p = spMaker.make(propertyList, value, fo);
+ if (p != null) {
+ return setSubprop(baseProp, partName, p);
+ }
+ } else {
+ MessageHandler.errorln("WARNING: compound property component "
+ + partName + " unknown.");
+ }
+ return baseProp;
+ }
+
+ /**
+ * Set a component in a compound property and return the modified
+ * compound property object.
+ * This default implementation returns the original base property
+ * without modifying it.
+ * It is overridden by property maker subclasses which handle
+ * compound properties.
+ * @param baseProp The Property object representing the compound property,
+ * such as SpaceProperty.
+ * @param partName The name of the component whose value is specified.
+ * @param subProp A Property object holding the specified value of the
+ * component to be set.
+ * @return The modified compound property object.
+ */
+ protected Property setSubprop(Property baseProp, String partName,
+ Property subProp) {
+ return baseProp;
+ }
+
+ /**
+ * Create a Property object from an attribute specification.
+ * @param propertyList The PropertyList object being built for this FO.
+ * @param value The attribute value.
+ * @param fo The current FO whose properties are being set.
+ * @return The initialized Property object.
+ */
+ public Property make(PropertyList propertyList, String value,
+ FObj fo) throws FOPException {
+ try {
+ Property pret = null;
+ String pvalue = value;
+ pret = checkEnumValues(value);
+ if (pret == null) {
+ /* Check for keyword shorthand values to be substituted. */
+ pvalue = checkValueKeywords(value);
+ // Override parsePropertyValue in each subclass of Property.Maker
+ Property p = PropertyParser.parse(pvalue,
+ new PropertyInfo(this,
+ propertyList, fo));
+ pret = convertProperty(p, propertyList, fo);
+ } else if (isCompoundMaker()) {
+ pret = convertProperty(pret, propertyList, fo);
+ }
+ if (pret == null) {
+ throw new org.apache.fop.fo.expr.PropertyException("No conversion defined");
+ } else if (inheritsSpecified()) {
+ pret.setSpecifiedValue(pvalue);
+ }
+ return pret;
+ } catch (org.apache.fop.fo.expr.PropertyException propEx) {
+ MessageHandler.errorln("Error in " + propName
+ + " property value '" + value + "': "
+ + propEx);
+ throw new FOPException("Property error");
+ }
+ }
+
+ public Property convertShorthandProperty(PropertyList propertyList,
+ Property prop, FObj fo) {
+ Property pret = null;
+ try {
+ pret = convertProperty(prop, propertyList, fo);
+ if (pret == null) {
+ // If value is a name token, may be keyword or Enum
+ String sval = prop.getNCname();
+ if (sval != null) {
+ // System.err.println("Convert shorthand ncname " + sval);
+ pret = checkEnumValues(sval);
+ if (pret == null) {
+ /* Check for keyword shorthand values to be substituted. */
+ String pvalue = checkValueKeywords(sval);
+ if (!pvalue.equals(sval)) {
+ // System.err.println("Convert shorthand keyword" + pvalue);
+ // Substituted a value: must parse it
+ Property p =
+ PropertyParser.parse(pvalue,
+ new PropertyInfo(this,
+ propertyList,
+ fo));
+ pret = convertProperty(p, propertyList, fo);
+ }
+ }
+ }
+ }
+ } catch (FOPException e) {
+
+ MessageHandler.errorln("convertShorthandProperty caught FOPException "
+ + e);
+ } catch (org.apache.fop.fo.expr.PropertyException propEx) {
+ MessageHandler.errorln("convertShorthandProperty caught PropertyException "
+ + propEx);
+ }
+ if (pret != null) {
+ /*
+ * System.err.println("Return shorthand value " + pret.getString() +
+ * " for " + getPropName());
+ */
+ }
+ return pret;
+ }
+
+ protected boolean isCompoundMaker() {
+ return false;
+ }
+
+ public Property checkEnumValues(String value) {
+ return null;
+ }
+
+ /**
+ * Return a String to be parsed if the passed value corresponds to
+ * a keyword which can be parsed and used to initialize the property.
+ * For example, the border-width family of properties can have the
+ * initializers "thin", "medium", or "thick". The foproperties.xml
+ * file specifies a length value equivalent for these keywords,
+ * such as "0.5pt" for "thin". These values are considered parseable,
+ * since the Length object is no longer responsible for parsing
+ * unit expresssions.
+ * @param value The string value of property attribute.
+ * @return A String containging a parseable equivalent or null if
+ * the passed value isn't a keyword initializer for this Property.
+ */
+ protected String checkValueKeywords(String value) {
+ return value;
+ }
+
+ /**
+ * Return a Property object based on the passed Property object.
+ * This method is called if the Property object built by the parser
+ * isn't the right type for this property.
+ * It is overridden by subclasses when the property specification in
+ * foproperties.xml specifies conversion rules.
+ * @param p The Property object return by the expression parser
+ * @param propertyList The PropertyList object being built for this FO.
+ * @param fo The current FO whose properties are being set.
+ * @return A Property of the correct type or null if the parsed value
+ * can't be converted to the correct type.
+ */
+ public Property convertProperty(Property p,
+ PropertyList propertyList,
+ FObj fo) throws FOPException {
+ return null;
+ }
+
+ protected Property convertPropertyDatatype(Property p,
+ PropertyList propertyList,
+ FObj fo) {
+ return null;
+ }
+
+ /**
+ * Return a Property object representing the initial value.
+ * @param propertyList The PropertyList object being built for this FO.
+ */
+ public Property make(PropertyList propertyList) throws FOPException {
+ return null;
+ }
+
+ /**
+ * Return a Property object representing the initial value.
+ * @param propertyList The PropertyList object being built for this FO.
+ * @param parentFO The parent FO for the FO whose property is being made.
+ * @return a Property subclass object holding a "compound" property object
+ * initialized to the default values for each component.
+ */
+ protected Property makeCompound(PropertyList propertyList,
+ FObj parentFO) throws FOPException {
+ return null;
+ }
+
+ /**
+ * Return a Property object representing the value of this property,
+ * based on other property values for this FO.
+ * A special case is properties which inherit the specified value,
+ * rather than the computed value.
+ * @param propertyList The PropertyList for the FO.
+ * @return Property A computed Property value or null if no rules
+ * are specified (in foproperties.xml) to compute the value.
+ */
+ public Property compute(PropertyList propertyList)
+ throws FOPException {
+ if (inheritsSpecified()) {
+ // recalculate based on last specified value
+ // Climb up propertylist and find last spec'd value
+ // NEED PROPNAME!!! get from Maker
+ Property specProp =
+ propertyList.getNearestSpecified(propName);
+ if (specProp != null) {
+ // Only need to do this if the value is relative!!!
+ String specVal = specProp.getSpecifiedValue();
+ if (specVal != null) {
+ try {
+ return make(propertyList, specVal,
+ propertyList.getParentFObj());
+ } catch (FOPException e) {
+ MessageHandler.errorln("Error computing property value for "
+ + propName + " from "
+ + specVal);
+ return null;
+ }
+ }
+ }
+ }
+ return null; // standard
+ }
+
+ public boolean isCorrespondingForced(PropertyList propertyList) {
+ return false;
+ }
+
+ public Property getShorthand(PropertyList propertyList) {
+ return null;
+ }
+
+ } // end of nested Maker class
/**
- * Return the name of the property whose value is being set.
+ * The original specified value for properties which inherit
+ * specified values.
*/
- protected String getPropName() { return propName; }
+ private String specVal;
/**
- * Construct an instance of a Property.Maker for the given property.
- * @param propName The name of the property to be made.
+ * Set the original value specified for the property attribute.
+ * @param specVal The specified value.
*/
- protected Maker(String propName) {
- this.propName = propName;
+ public void setSpecifiedValue(String specVal) {
+ this.specVal = specVal;
}
/**
- * Construct an instance of a Property.Maker.
- * Note: the property name is set to "UNKNOWN".
+ * Return the original value specified for the property attribute.
+ * @return The specified value as a String.
*/
- protected Maker() {
- this.propName = UNKNOWN;
+ public String getSpecifiedValue() {
+ return specVal;
}
-
- /**
- * Default implementation of isInherited.
- * @return A boolean indicating whether this property is inherited.
- */
- public boolean isInherited() { return false; }
-
/**
- * Return a boolean indicating whether this property inherits the
- * "specified" value rather than the "computed" value. The default is
- * to inherit the "computed" value.
- * @return If true, property inherits the value specified.
+ * Accessor functions for all possible Property datatypes
*/
- public boolean inheritsSpecified() { return false; }
-
-
- /**
- * Return an object implementing the PercentBase interface.
- * This is used to handle properties specified as a percentage of
- * some "base length", such as the content width of their containing
- * box.
- * Overridden by subclasses which allow percent specifications. See
- * the documentation on properties.xsl for details.
- */
- public PercentBase getPercentBase(FObj fo, PropertyList pl) {
- return null;
+ public Length getLength() {
+ return null;
}
- /**
- * Return a Maker object which is used to set the values on components
- * of compound property types, such as "space".
- * Overridden by property maker subclasses which handle
- * compound properties.
- * @param subprop The name of the component for which a Maker is to
- * returned, for example "optimum", if the FO attribute is
- * space.optimum='10pt'.
- */
- protected Maker getSubpropMaker(String subprop) {
- return null;
+ public ColorType getColorType() {
+ return null;
}
- /**
- * Return a property value for the given component of a compound
- * property.
- * @param p A property value for a compound property type such as
- * SpaceProperty.
- * @param subprop The name of the component whose value is to be
- * returned.
- * NOTE: this is only to ease porting when calls are made to
- * PropertyList.get() using a component name of a compound property,
- * such as get("space.optimum"). The recommended technique is:
- * get("space").getOptimum().
- * Overridden by property maker subclasses which handle
- * compound properties.
- */
- public Property getSubpropValue(Property p, String subprop) {
- return null;
+ public CondLength getCondLength() {
+ return null;
}
- /**
- * Return a property value for a compound property. If the property
- * value is already partially initialized, this method will modify it.
- * @param baseProp The Property object representing the compound property,
- * such as SpaceProperty.
- * @param partName The name of the component whose value is specified.
- * @param propertyList The propertyList being built.
- * @param fo The FO whose properties are being set.
- * @return A compound property object.
- */
- public Property make(Property baseProp, String partName,
- PropertyList propertyList, String value, FObj fo)
- throws FOPException
- {
- if (baseProp==null) {
- baseProp = makeCompound(propertyList, fo);
- }
- Maker spMaker = getSubpropMaker(partName);
- if (spMaker != null) {
- Property p = spMaker.make(propertyList, value, fo);
- if (p != null) {
- return setSubprop(baseProp, partName, p);
- }
- }
- else {
- MessageHandler.errorln("WARNING: compound property component " + partName + " unknown.");
- }
- return baseProp;
+ public LengthRange getLengthRange() {
+ return null;
}
- /**
- * Set a component in a compound property and return the modified
- * compound property object.
- * This default implementation returns the original base property
- * without modifying it.
- * It is overridden by property maker subclasses which handle
- * compound properties.
- * @param baseProp The Property object representing the compound property,
- * such as SpaceProperty.
- * @param partName The name of the component whose value is specified.
- * @param subProp A Property object holding the specified value of the
- * component to be set.
- * @return The modified compound property object.
- */
- protected Property setSubprop(Property baseProp, String partName,
- Property subProp) {
- return baseProp;
+ public LengthPair getLengthPair() {
+ return null;
}
- /**
- * Create a Property object from an attribute specification.
- * @param propertyList The PropertyList object being built for this FO.
- * @param value The attribute value.
- * @param fo The current FO whose properties are being set.
- * @return The initialized Property object.
- */
- public Property make(PropertyList propertyList, String value, FObj fo)
- throws FOPException {
- try {
- Property pret=null;
- String pvalue=value;
- pret = checkEnumValues(value);
- if (pret == null) {
- /* Check for keyword shorthand values to be substituted. */
- pvalue = checkValueKeywords(value);
- // Override parsePropertyValue in each subclass of Property.Maker
- Property p = PropertyParser.parse(pvalue,
- new PropertyInfo(this, propertyList, fo));
- pret = convertProperty(p, propertyList, fo);
- }
- else if (isCompoundMaker()) {
- pret = convertProperty(pret, propertyList, fo);
- }
- if (pret == null) {
- throw new org.apache.fop.fo.expr.PropertyException("No conversion defined");
- }
- else if (inheritsSpecified()) {
- pret.setSpecifiedValue(pvalue);
- }
- return pret;
- } catch (org.apache.fop.fo.expr.PropertyException propEx) {
- MessageHandler.errorln("Error in " + propName + " property value '"
- + value + "': " + propEx);
- throw new FOPException("Property error");
- }
+ public Space getSpace() {
+ return null;
}
- public Property convertShorthandProperty(PropertyList propertyList,
- Property prop, FObj fo)
- {
- Property pret = null;
- try {
- pret = convertProperty(prop, propertyList, fo);
- if (pret == null) {
- // If value is a name token, may be keyword or Enum
- String sval = prop.getNCname();
- if (sval != null) {
- // System.err.println("Convert shorthand ncname " + sval);
- pret = checkEnumValues(sval);
- if (pret == null) {
- /* Check for keyword shorthand values to be substituted. */
- String pvalue = checkValueKeywords(sval);
- if (!pvalue.equals(sval)) {
- // System.err.println("Convert shorthand keyword" + pvalue);
- // Substituted a value: must parse it
- Property p = PropertyParser.parse(pvalue,
- new PropertyInfo(this, propertyList, fo));
- pret = convertProperty(p, propertyList, fo);
- }
- }
- }
- }
- } catch (FOPException e) {
-
- MessageHandler.errorln("convertShorthandProperty caught FOPException " + e);
- }
- catch (org.apache.fop.fo.expr.PropertyException propEx) {
- MessageHandler.errorln("convertShorthandProperty caught PropertyException " + propEx);
- }
- if (pret != null) {
- /* System.err.println("Return shorthand value " + pret.getString() +
- " for " + getPropName());*/
- }
- return pret;
+ public Keep getKeep() {
+ return null;
}
- protected boolean isCompoundMaker() {
- return false;
+ public int getEnum() {
+ return 0;
}
- public Property checkEnumValues(String value) {
- return null;
+ public char getCharacter() {
+ return 0;
}
- /**
- * Return a String to be parsed if the passed value corresponds to
- * a keyword which can be parsed and used to initialize the property.
- * For example, the border-width family of properties can have the
- * initializers "thin", "medium", or "thick". The foproperties.xml
- * file specifies a length value equivalent for these keywords,
- * such as "0.5pt" for "thin". These values are considered parseable,
- * since the Length object is no longer responsible for parsing
- * unit expresssions.
- * @param value The string value of property attribute.
- * @return A String containging a parseable equivalent or null if
- * the passed value isn't a keyword initializer for this Property.
- */
- protected String checkValueKeywords(String value) {
- return value;
- }
+ public Vector getList() {
+ return null;
+ } // List of Property objects
- /**
- * Return a Property object based on the passed Property object.
- * This method is called if the Property object built by the parser
- * isn't the right type for this property.
- * It is overridden by subclasses when the property specification in
- * foproperties.xml specifies conversion rules.
- * @param p The Property object return by the expression parser
- * @param propertyList The PropertyList object being built for this FO.
- * @param fo The current FO whose properties are being set.
- * @return A Property of the correct type or null if the parsed value
- * can't be converted to the correct type.
- */
- public Property convertProperty(Property p,
- PropertyList propertyList, FObj fo) throws FOPException {
- return null;
+ public Number getNumber() {
+ return null;
}
- protected Property convertPropertyDatatype(Property p,
- PropertyList propertyList, FObj fo) {
- return null;
+ // Classes used when evaluating property expressions
+ public Numeric getNumeric() {
+ return null;
}
- /**
- * Return a Property object representing the initial value.
- * @param propertyList The PropertyList object being built for this FO.
- */
- public Property make(PropertyList propertyList) throws FOPException {
- return null;
+ public String getNCname() {
+ return null;
}
- /**
- * Return a Property object representing the initial value.
- * @param propertyList The PropertyList object being built for this FO.
- * @param parentFO The parent FO for the FO whose property is being made.
- * @return a Property subclass object holding a "compound" property object
- * initialized to the default values for each component.
- */
- protected Property makeCompound(PropertyList propertyList, FObj parentFO) throws FOPException {
- return null;
+ public Object getObject() {
+ return null;
}
- /**
- * Return a Property object representing the value of this property,
- * based on other property values for this FO.
- * A special case is properties which inherit the specified value,
- * rather than the computed value.
- * @param propertyList The PropertyList for the FO.
- * @return Property A computed Property value or null if no rules
- * are specified (in foproperties.xml) to compute the value.
- */
- public Property compute(PropertyList propertyList) throws FOPException {
- if (inheritsSpecified()) {
- // recalculate based on last specified value
- // Climb up propertylist and find last spec'd value
- // NEED PROPNAME!!! get from Maker
- Property specProp = propertyList.getNearestSpecified(propName);
- if (specProp != null) {
- // Only need to do this if the value is relative!!!
- String specVal = specProp.getSpecifiedValue();
- if (specVal != null) {
- try {
- return make(propertyList, specVal, propertyList.getParentFObj());
- } catch (FOPException e) {
- MessageHandler.errorln("Error computing property value for " +
- propName + " from " + specVal);
- return null;
- }
- }
- }
- }
- return null; // standard
+ public String getString() {
+ Object o = getObject();
+ return (o == null) ? null : o.toString();
}
-
- public boolean isCorrespondingForced(PropertyList propertyList) {
- return false;
- }
-
- public Property getShorthand(PropertyList propertyList) {
- return null;
- }
-
- } // end of nested Maker class
-
- /** The original specified value for properties which inherit
- * specified values. */
- private String specVal;
-
- /**
- * Set the original value specified for the property attribute.
- * @param specVal The specified value.
- */
- public void setSpecifiedValue(String specVal) {
- this.specVal = specVal;
- }
-
- /**
- * Return the original value specified for the property attribute.
- * @return The specified value as a String.
- */
- public String getSpecifiedValue() {
- return specVal;
- }
-
- /**
- * Accessor functions for all possible Property datatypes
- */
- public Length getLength() { return null; }
- public ColorType getColorType() { return null; }
- public CondLength getCondLength() { return null; }
- public LengthRange getLengthRange() { return null; }
- public LengthPair getLengthPair() { return null; }
- public Space getSpace() { return null; }
- public Keep getKeep() { return null; }
- public int getEnum() { return 0; }
- public char getCharacter() { return 0;}
- public Vector getList() { return null; } // List of Property objects
-
- public Number getNumber() { return null; }
-
- // Classes used when evaluating property expressions
- public Numeric getNumeric() { return null; }
- public String getNCname() { return null; }
-
- public Object getObject() { return null; }
-
- public String getString() {
- Object o = getObject();
- return (o == null)? null : o.toString();
- }
}
diff --git a/src/org/apache/fop/fo/PropertyList.java b/src/org/apache/fop/fo/PropertyList.java
index 52109d4fb..90cf310d8 100644
--- a/src/org/apache/fop/fo/PropertyList.java
+++ b/src/org/apache/fop/fo/PropertyList.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo;
import java.util.Hashtable;
@@ -57,321 +14,345 @@ import org.apache.fop.apps.FOPException;
public class PropertyList extends Hashtable {
- private byte[] wmtable=null; // writing-mode values
- public static final int LEFT=0;
- public static final int RIGHT=1;
- public static final int TOP=2;
- public static final int BOTTOM=3;
- public static final int HEIGHT=4;
- public static final int WIDTH=5;
-
- public static final int START=0;
- public static final int END=1;
- public static final int BEFORE=2;
- public static final int AFTER=3;
- public static final int BLOCKPROGDIM=4;
- public static final int INLINEPROGDIM=5;
-
- private static final String[] sAbsNames= new String[]
- {"left", "right", "top", "bottom", "height", "width"};
-
- private static final String[] sRelNames= new String[]
- {"start", "end", "before", "after",
- "block-progression-dimension", "inline-progression-dimension"};
-
- static private final Hashtable wmtables = new Hashtable(4);
- {
- wmtables.put(new Integer(WritingMode.LR_TB), /* lr-tb */
- new byte[]{START, END, BEFORE, AFTER, BLOCKPROGDIM, INLINEPROGDIM });
- wmtables.put(new Integer(WritingMode.RL_TB), /* rl-tb */
- new byte[]{END, START, BEFORE, AFTER, BLOCKPROGDIM, INLINEPROGDIM });
- wmtables.put(new Integer(WritingMode.TB_RL), /* tb-rl */
- new byte[]{AFTER, BEFORE, START, END, INLINEPROGDIM, BLOCKPROGDIM });
- }
-
- private PropertyListBuilder builder;
- private PropertyList parentPropertyList = null;
- String namespace = "";
- String element = "";
- FObj fobj=null;
-
- public PropertyList(PropertyList parentPropertyList, String space, String el) {
- this.parentPropertyList = parentPropertyList;
- this.namespace = space;
- this.element = el;
- }
-
- public void setFObj(FObj fobj) {
- this.fobj = fobj;
- }
-
- public FObj getFObj() {
- return this.fobj;
- }
-
- public FObj getParentFObj() {
- if (parentPropertyList != null) {
- return parentPropertyList.getFObj();
+ private byte[] wmtable = null; // writing-mode values
+ public static final int LEFT = 0;
+ public static final int RIGHT = 1;
+ public static final int TOP = 2;
+ public static final int BOTTOM = 3;
+ public static final int HEIGHT = 4;
+ public static final int WIDTH = 5;
+
+ public static final int START = 0;
+ public static final int END = 1;
+ public static final int BEFORE = 2;
+ public static final int AFTER = 3;
+ public static final int BLOCKPROGDIM = 4;
+ public static final int INLINEPROGDIM = 5;
+
+ private static final String[] sAbsNames = new String[] {
+ "left", "right", "top", "bottom", "height", "width"
+ };
+
+ private static final String[] sRelNames = new String[] {
+ "start", "end", "before", "after", "block-progression-dimension",
+ "inline-progression-dimension"
+ };
+
+ static private final Hashtable wmtables = new Hashtable(4);
+ {
+ wmtables.put(new Integer(WritingMode.LR_TB), /* lr-tb */
+ new byte[] {
+ START, END, BEFORE, AFTER, BLOCKPROGDIM, INLINEPROGDIM
+ });
+ wmtables.put(new Integer(WritingMode.RL_TB), /* rl-tb */
+ new byte[] {
+ END, START, BEFORE, AFTER, BLOCKPROGDIM, INLINEPROGDIM
+ });
+ wmtables.put(new Integer(WritingMode.TB_RL), /* tb-rl */
+ new byte[] {
+ AFTER, BEFORE, START, END, INLINEPROGDIM, BLOCKPROGDIM
+ });
+ }
+
+ private PropertyListBuilder builder;
+ private PropertyList parentPropertyList = null;
+ String namespace = "";
+ String element = "";
+ FObj fobj = null;
+
+ public PropertyList(PropertyList parentPropertyList, String space,
+ String el) {
+ this.parentPropertyList = parentPropertyList;
+ this.namespace = space;
+ this.element = el;
+ }
+
+ public void setFObj(FObj fobj) {
+ this.fobj = fobj;
+ }
+
+ public FObj getFObj() {
+ return this.fobj;
}
- else return null;
- }
-
- /**
- * Return the value explicitly specified on this FO.
- * @param propertyName The name of the property whose value is desired.
- * It may be a compound name, such as space-before.optimum.
- * @return The value if the property is explicitly set or set by
- * a shorthand property, otherwise null.
- */
- public Property getExplicitOrShorthand(String propertyName) {
- /* Handle request for one part of a compound property */
- int sepchar = propertyName.indexOf('.');
- String baseName;
- if (sepchar > -1) {
- baseName = propertyName.substring(0,sepchar);
+
+ public FObj getParentFObj() {
+ if (parentPropertyList != null) {
+ return parentPropertyList.getFObj();
+ } else
+ return null;
}
- else baseName = propertyName;
- Property p =getExplicitBaseProp(baseName);
- if (p == null) {
- p = builder.getShorthand(this, namespace, element, baseName);
+
+ /**
+ * Return the value explicitly specified on this FO.
+ * @param propertyName The name of the property whose value is desired.
+ * It may be a compound name, such as space-before.optimum.
+ * @return The value if the property is explicitly set or set by
+ * a shorthand property, otherwise null.
+ */
+ public Property getExplicitOrShorthand(String propertyName) {
+ /* Handle request for one part of a compound property */
+ int sepchar = propertyName.indexOf('.');
+ String baseName;
+ if (sepchar > -1) {
+ baseName = propertyName.substring(0, sepchar);
+ } else
+ baseName = propertyName;
+ Property p = getExplicitBaseProp(baseName);
+ if (p == null) {
+ p = builder.getShorthand(this, namespace, element, baseName);
+ }
+ if (p != null && sepchar > -1) {
+ return builder.getSubpropValue(namespace, element, baseName, p,
+ propertyName.substring(sepchar
+ + 1));
+ }
+ return p;
}
- if (p != null && sepchar > -1) {
- return builder.getSubpropValue(namespace, element, baseName,
- p, propertyName.substring(sepchar+1));
+
+ /**
+ * Return the value explicitly specified on this FO.
+ * @param propertyName The name of the property whose value is desired.
+ * It may be a compound name, such as space-before.optimum.
+ * @return The value if the property is explicitly set, otherwise null.
+ */
+ public Property getExplicit(String propertyName) {
+ /* Handle request for one part of a compound property */
+ int sepchar = propertyName.indexOf('.');
+ if (sepchar > -1) {
+ String baseName = propertyName.substring(0, sepchar);
+ Property p = getExplicitBaseProp(baseName);
+ if (p != null) {
+ return this.builder.getSubpropValue(namespace, element,
+ baseName, p,
+ propertyName.substring(sepchar
+ + 1));
+ } else
+ return null;
+ }
+ return (Property)super.get(propertyName);
}
- return p;
- }
-
- /**
- * Return the value explicitly specified on this FO.
- * @param propertyName The name of the property whose value is desired.
- * It may be a compound name, such as space-before.optimum.
- * @return The value if the property is explicitly set, otherwise null.
- */
- public Property getExplicit(String propertyName) {
- /* Handle request for one part of a compound property */
- int sepchar = propertyName.indexOf('.');
- if (sepchar > -1) {
- String baseName = propertyName.substring(0,sepchar);
- Property p =getExplicitBaseProp(baseName);
- if (p != null) {
- return this.builder.getSubpropValue(namespace, element, baseName,
- p, propertyName.substring(sepchar+1));
- }
- else return null;
+
+ /**
+ * Return the value explicitly specified on this FO.
+ * @param propertyName The name of the base property whose value is desired.
+ * @return The value if the property is explicitly set, otherwise null.
+ */
+ public Property getExplicitBaseProp(String propertyName) {
+ return (Property)super.get(propertyName);
}
- return (Property)super.get(propertyName);
- }
-
- /**
- * Return the value explicitly specified on this FO.
- * @param propertyName The name of the base property whose value is desired.
- * @return The value if the property is explicitly set, otherwise null.
- */
- public Property getExplicitBaseProp(String propertyName) {
- return (Property)super.get(propertyName);
- }
-
- /**
- * Return the value of this property inherited by this FO.
- * Implements the inherited-property-value function.
- * The property must be inheritable!
- * @param propertyName The name of the property whose value is desired.
- * @return The inherited value, otherwise null.
- */
- public Property getInherited(String propertyName) {
- if (builder != null) {
- if (parentPropertyList != null &&
- builder.isInherited(namespace, element, propertyName)) {
- return parentPropertyList.get(propertyName);
- }
- else {
- // return the "initial" value
- try {
- return builder.makeProperty(this, namespace, element, propertyName);
- } catch (org.apache.fop.apps.FOPException e) {
- MessageHandler.errorln("Exception in getInherited(): property=" +
- propertyName + " : " + e);
- }
- }
+
+ /**
+ * Return the value of this property inherited by this FO.
+ * Implements the inherited-property-value function.
+ * The property must be inheritable!
+ * @param propertyName The name of the property whose value is desired.
+ * @return The inherited value, otherwise null.
+ */
+ public Property getInherited(String propertyName) {
+ if (builder != null) {
+ if (parentPropertyList != null
+ && builder.isInherited(namespace, element,
+ propertyName)) {
+ return parentPropertyList.get(propertyName);
+ } else {
+ // return the "initial" value
+ try {
+ return builder.makeProperty(this, namespace, element,
+ propertyName);
+ } catch (org.apache.fop.apps.FOPException e) {
+ MessageHandler.errorln("Exception in getInherited(): property="
+ + propertyName + " : " + e);
+ }
+ }
+ }
+ return null; // No builder or exception in makeProperty!
}
- return null; // No builder or exception in makeProperty!
- }
- /* If the property is a relative property with a corresponding absolute
+ /*
+ * If the property is a relative property with a corresponding absolute
* value specified, the absolute value is used. This is also true of
* the inheritance priority (I think...)
* If the property is an "absolute" property and it isn't specified, then
* we try to compute it from the corresponding relative property: this
* happends in computeProperty.
*/
- private Property findProperty(String propertyName, boolean bTryInherit) {
- Property p = null;
- if (builder.isCorrespondingForced(this, namespace, element, propertyName)) {
- p = builder.computeProperty(this,namespace, element, propertyName);
- }
- else {
- p = getExplicitBaseProp(propertyName);
- if (p == null) {
- p = this.builder.computeProperty(this,namespace, element, propertyName);
- }
- if (p == null) { // check for shorthand specification
- p = builder.getShorthand(this, namespace, element, propertyName);
- }
- if (p == null && bTryInherit) { // else inherit (if has parent and is inheritable)
- if (this.parentPropertyList != null &&
- builder.isInherited(namespace, element, propertyName)) {
- p = parentPropertyList.findProperty(propertyName, true);
+ private Property findProperty(String propertyName, boolean bTryInherit) {
+ Property p = null;
+ if (builder.isCorrespondingForced(this, namespace, element,
+ propertyName)) {
+ p = builder.computeProperty(this, namespace, element,
+ propertyName);
+ } else {
+ p = getExplicitBaseProp(propertyName);
+ if (p == null) {
+ p = this.builder.computeProperty(this, namespace, element,
+ propertyName);
+ }
+ if (p == null) { // check for shorthand specification
+ p = builder.getShorthand(this, namespace, element,
+ propertyName);
+ }
+ if (p == null
+ && bTryInherit) { // else inherit (if has parent and is inheritable)
+ if (this.parentPropertyList != null
+ && builder.isInherited(namespace, element,
+ propertyName)) {
+ p = parentPropertyList.findProperty(propertyName, true);
+ }
}
}
+ return p;
}
- return p;
- }
-
-
- /**
- * Return the property on the current FlowObject if it is specified, or if a
- * corresponding property is specified. If neither is specified, it returns null.
- */
- public Property getSpecified(String propertyName) {
- return get(propertyName, false, false);
- }
-
-
- /**
- * Return the property on the current FlowObject. If it isn't set explicitly,
- * this will try to compute it based on other properties, or if it is
- * inheritable, to return the inherited value. If all else fails, it returns
- * the default value.
- */
- public Property get(String propertyName) {
- return get(propertyName, true, true);
- }
-
- /**
- * Return the property on the current FlowObject. Depending on the passed flags,
- * this will try to compute it based on other properties, or if it is
- * inheritable, to return the inherited value. If all else fails, it returns
- * the default value.
- */
- private Property get(String propertyName, boolean bTryInherit, boolean bTryDefault) {
-
- if (builder == null)
- MessageHandler.errorln("OH OH, builder has not been set");
-
- /* Handle request for one part of a compound property */
- int sepchar = propertyName.indexOf('.');
- String subpropName = null;
- if (sepchar > -1) {
- subpropName = propertyName.substring(sepchar+1);
- propertyName = propertyName.substring(0,sepchar);
+
+
+ /**
+ * Return the property on the current FlowObject if it is specified, or if a
+ * corresponding property is specified. If neither is specified, it returns null.
+ */
+ public Property getSpecified(String propertyName) {
+ return get(propertyName, false, false);
+ }
+
+
+ /**
+ * Return the property on the current FlowObject. If it isn't set explicitly,
+ * this will try to compute it based on other properties, or if it is
+ * inheritable, to return the inherited value. If all else fails, it returns
+ * the default value.
+ */
+ public Property get(String propertyName) {
+ return get(propertyName, true, true);
}
- Property p = findProperty(propertyName, bTryInherit);
- if (p == null && bTryDefault) { // default value for this FO!
- try {
- p = this.builder.makeProperty(this,namespace, element,propertyName);
- } catch (FOPException e) {
- // don't know what to do here
- }
+ /**
+ * Return the property on the current FlowObject. Depending on the passed flags,
+ * this will try to compute it based on other properties, or if it is
+ * inheritable, to return the inherited value. If all else fails, it returns
+ * the default value.
+ */
+ private Property get(String propertyName, boolean bTryInherit,
+ boolean bTryDefault) {
+
+ if (builder == null)
+ MessageHandler.errorln("OH OH, builder has not been set");
+
+ /* Handle request for one part of a compound property */
+ int sepchar = propertyName.indexOf('.');
+ String subpropName = null;
+ if (sepchar > -1) {
+ subpropName = propertyName.substring(sepchar + 1);
+ propertyName = propertyName.substring(0, sepchar);
+ }
+
+ Property p = findProperty(propertyName, bTryInherit);
+ if (p == null && bTryDefault) { // default value for this FO!
+ try {
+ p = this.builder.makeProperty(this, namespace, element,
+ propertyName);
+ } catch (FOPException e) {
+ // don't know what to do here
+ }
+ }
+ if (subpropName != null && p != null) {
+ return this.builder.getSubpropValue(namespace, element,
+ propertyName, p, subpropName);
+ } else
+ return p;
}
- if (subpropName != null && p != null) {
- return this.builder.getSubpropValue(namespace, element, propertyName,
- p, subpropName);
+
+ public void setBuilder(PropertyListBuilder builder) {
+ this.builder = builder;
}
- else return p;
- }
-
- public void setBuilder(PropertyListBuilder builder) {
- this.builder = builder;
- }
-
- public String getNameSpace()
- {
- return namespace;
- }
-
- public String getElement()
- {
- return element;
- }
-
- /**
- * Return the "nearest" specified value for the given property.
- * Implements the from-nearest-specified-value function.
- * @param propertyName The name of the property whose value is desired.
- * @return The computed value if the property is explicitly set on some
- * ancestor of the current FO, else the initial value.
- */
- public Property getNearestSpecified(String propertyName) {
- Property p = null;
- for (PropertyList plist = this; p == null && plist != null;
- plist = plist.parentPropertyList) {
- p = plist.getExplicit(propertyName);
+
+ public String getNameSpace() {
+ return namespace;
}
- if (p == null) {
- // If no explicit setting found, return initial (default) value.
- try {
- p = this.builder.makeProperty(this,namespace, element,propertyName);
- } catch (FOPException e) {
- MessageHandler.errorln("Exception in getNearestSpecified(): property=" +
- propertyName + " : " + e);
- }
+
+ public String getElement() {
+ return element;
}
- return p;
- }
-
- /**
- * Return the value of this property on the parent of this FO.
- * Implements the from-parent function.
- * @param propertyName The name of the property whose value is desired.
- * @return The computed value on the parent or the initial value if this
- * FO is the root or is in a different namespace from its parent.
- */
- public Property getFromParent(String propertyName) {
- if (parentPropertyList != null) {
- return parentPropertyList.get(propertyName);
+
+ /**
+ * Return the "nearest" specified value for the given property.
+ * Implements the from-nearest-specified-value function.
+ * @param propertyName The name of the property whose value is desired.
+ * @return The computed value if the property is explicitly set on some
+ * ancestor of the current FO, else the initial value.
+ */
+ public Property getNearestSpecified(String propertyName) {
+ Property p = null;
+ for (PropertyList plist = this; p == null && plist != null;
+ plist = plist.parentPropertyList) {
+ p = plist.getExplicit(propertyName);
+ }
+ if (p == null) {
+ // If no explicit setting found, return initial (default) value.
+ try {
+ p = this.builder.makeProperty(this, namespace, element,
+ propertyName);
+ } catch (FOPException e) {
+ MessageHandler.errorln("Exception in getNearestSpecified(): property="
+ + propertyName + " : " + e);
+ }
+ }
+ return p;
}
- else if (builder != null) {
- // return the "initial" value
- try {
- return builder.makeProperty(this, namespace, element, propertyName);
- } catch (org.apache.fop.apps.FOPException e) {
- MessageHandler.errorln("Exception in getFromParent(): property=" +
- propertyName + " : " + e);
- }
+
+ /**
+ * Return the value of this property on the parent of this FO.
+ * Implements the from-parent function.
+ * @param propertyName The name of the property whose value is desired.
+ * @return The computed value on the parent or the initial value if this
+ * FO is the root or is in a different namespace from its parent.
+ */
+ public Property getFromParent(String propertyName) {
+ if (parentPropertyList != null) {
+ return parentPropertyList.get(propertyName);
+ } else if (builder != null) {
+ // return the "initial" value
+ try {
+ return builder.makeProperty(this, namespace, element,
+ propertyName);
+ } catch (org.apache.fop.apps.FOPException e) {
+ MessageHandler.errorln("Exception in getFromParent(): property="
+ + propertyName + " : " + e);
+ }
+ }
+ return null; // No builder or exception in makeProperty!
}
- return null; // No builder or exception in makeProperty!
- }
- /** Given an absolute direction (top, bottom, left, right),
+ /**
+ * Given an absolute direction (top, bottom, left, right),
* return the corresponding writing model relative direction name
* for the flow object. Uses the stored writingMode.
*/
public String wmAbsToRel(int absdir) {
- if (wmtable != null) {
- return sRelNames[wmtable[absdir]];
- }
- else return "";
+ if (wmtable != null) {
+ return sRelNames[wmtable[absdir]];
+ } else
+ return "";
}
- /** Given a writing mode relative direction (start, end, before, after)
+ /**
+ * Given a writing mode relative direction (start, end, before, after)
* return the corresponding absolute direction name
* for the flow object. Uses the stored writingMode.
*/
public String wmRelToAbs(int reldir) {
- if (wmtable != null) {
- for (int i=0; i < wmtable.length; i++) {
- if (wmtable[i]==reldir)
- return sAbsNames[i];
- }
- }
- return "";
+ if (wmtable != null) {
+ for (int i = 0; i < wmtable.length; i++) {
+ if (wmtable[i] == reldir)
+ return sAbsNames[i];
+ }
+ }
+ return "";
}
- /** Set the writing mode traits for the FO with this property list. */
+ /**
+ * Set the writing mode traits for the FO with this property list.
+ */
public void setWritingMode(int writingMode) {
- this.wmtable = (byte[])wmtables.get(new Integer(writingMode));
+ this.wmtable = (byte[])wmtables.get(new Integer(writingMode));
}
}
diff --git a/src/org/apache/fop/fo/PropertyListBuilder.java b/src/org/apache/fop/fo/PropertyListBuilder.java
index d7eaa7941..3cd2c6c1a 100644
--- a/src/org/apache/fop/fo/PropertyListBuilder.java
+++ b/src/org/apache/fop/fo/PropertyListBuilder.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo;
@@ -63,10 +19,12 @@ import org.xml.sax.Attributes;
import java.util.Hashtable;
public class PropertyListBuilder {
-
- /** Name of font-size property attribute to set first. */
+
+ /**
+ * Name of font-size property attribute to set first.
+ */
private static final String FONTSIZEATTR = "font-size";
-
+
private Hashtable propertyListTable;
private Hashtable elementTable;
@@ -75,206 +33,231 @@ public class PropertyListBuilder {
this.elementTable = new Hashtable();
}
- public void addList(Hashtable list)
- {
- propertyListTable = list; // should add all
+ public void addList(Hashtable list) {
+ propertyListTable = list; // should add all
}
- public void addElementList(String element, Hashtable list)
- {
+ public void addElementList(String element, Hashtable list) {
elementTable.put(element, list);
}
- public Property computeProperty(PropertyList propertyList, String space, String element, String propertyName) {
-
- Property p = null;
- Property.Maker propertyMaker = findMaker(space, element, propertyName);
- if (propertyMaker != null) {
- try {
- p = propertyMaker.compute(propertyList);
- } catch (FOPException e) {
- MessageHandler.errorln("ERROR: exception occurred while computing" +
- " value of property '" + propertyName +"': " + e.getMessage());
- }
- } else {
- MessageHandler.errorln("WARNING: property " + propertyName + " ignored");
- }
- return p;
+ public Property computeProperty(PropertyList propertyList, String space,
+ String element, String propertyName) {
+
+ Property p = null;
+ Property.Maker propertyMaker = findMaker(space, element,
+ propertyName);
+ if (propertyMaker != null) {
+ try {
+ p = propertyMaker.compute(propertyList);
+ } catch (FOPException e) {
+ MessageHandler.errorln("ERROR: exception occurred while computing"
+ + " value of property '"
+ + propertyName + "': "
+ + e.getMessage());
+ }
+ } else {
+ MessageHandler.errorln("WARNING: property " + propertyName
+ + " ignored");
+ }
+ return p;
}
-
- public boolean isInherited(String space, String element, String propertyName) {
- boolean b;
-
- Property.Maker propertyMaker = findMaker(space, element, propertyName);
- if (propertyMaker != null) {
- b = propertyMaker.isInherited();
- } else {
- //MessageHandler.errorln("WARNING: Unknown property " + propertyName);
- b = true;
- }
- return b;
+
+ public boolean isInherited(String space, String element,
+ String propertyName) {
+ boolean b;
+
+ Property.Maker propertyMaker = findMaker(space, element,
+ propertyName);
+ if (propertyMaker != null) {
+ b = propertyMaker.isInherited();
+ } else {
+ // MessageHandler.errorln("WARNING: Unknown property " + propertyName);
+ b = true;
+ }
+ return b;
}
-
- public PropertyList makeList(String elementName, Attributes attributes, PropertyList parentPropertyList, FObj parentFO) throws FOPException {
- int index = elementName.indexOf("^");
- String space = "http://www.w3.org/TR/1999/XSL/Format";
- if(index != -1) {
- space = elementName.substring(0, index);
- }
-
- PropertyList par = null;
- if(parentPropertyList != null && space.equals(parentPropertyList.getNameSpace())) {
- par = parentPropertyList;
- }
-// System.out.println(elementName.substring(index + 1));
- PropertyList p = new PropertyList(par, space, elementName.substring(index + 1));
- p.setBuilder(this);
- Hashtable table;
- table = (Hashtable)elementTable.get(elementName.substring(index + 1));
+
+ public PropertyList makeList(String elementName, Attributes attributes,
+ PropertyList parentPropertyList,
+ FObj parentFO) throws FOPException {
+ int index = elementName.indexOf("^");
+ String space = "http://www.w3.org/TR/1999/XSL/Format";
+ if (index != -1) {
+ space = elementName.substring(0, index);
+ }
+
+ PropertyList par = null;
+ if (parentPropertyList != null
+ && space.equals(parentPropertyList.getNameSpace())) {
+ par = parentPropertyList;
+ }
+ // System.out.println(elementName.substring(index + 1));
+ PropertyList p = new PropertyList(par, space,
+ elementName.substring(index + 1));
+ p.setBuilder(this);
+ Hashtable table;
+ table = (Hashtable)elementTable.get(elementName.substring(index + 1));
/* Store names of properties already set. */
- StringBuffer propsDone = new StringBuffer(256);
- propsDone.append(' ');
-
- /* If font-size is set on this FO, must set it first, since
- * other attributes specified in terms of "ems" depend on it.
- * When we do "shorthand" properties, must handle the "font"
- * property as well to see if font-size is set.
- */
- String fontsizeval=attributes.getValue(FONTSIZEATTR);
- if (fontsizeval != null) {
- Property.Maker propertyMaker = findMaker(table, FONTSIZEATTR);
- if (propertyMaker != null) {
- try {
- p.put(FONTSIZEATTR, propertyMaker.make(p,fontsizeval,parentFO));
- } catch (FOPException e) { }
- }
- // Put in the "done" list even if error or no Maker.
- propsDone.append(FONTSIZEATTR + ' ');
- }
-
- for (int i = 0; i < attributes.getLength(); i++) {
- String attributeName = attributes.getQName(i);
- /* Handle "compound" properties, ex. space-before.minimum */
- int sepchar = attributeName.indexOf('.');
- String propName = attributeName;
- String subpropName = null;
- Property propVal = null;
- if (sepchar > -1) {
- propName = attributeName.substring(0,sepchar);
- subpropName = attributeName.substring(sepchar+1);
- }
- else if (propsDone.toString().indexOf(' '+propName+' ') != -1) {
- // Already processed this property (base property
- // for a property with sub-components or font-size)
- continue;
- }
-
- Property.Maker propertyMaker =findMaker(table, propName);
-
- if (propertyMaker != null) {
- try {
- if (subpropName != null) {
- Property baseProp = p.getExplicitBaseProp(propName);
- if (baseProp == null) {
- // See if it is specified later in this list
- String baseValue = attributes.getValue(propName);
- if (baseValue != null) {
- baseProp = propertyMaker.make(p, baseValue, parentFO);
- propsDone.append(propName + ' ');
- }
- //else baseProp = propertyMaker.makeCompound(p, parentFO);
- }
- propVal = propertyMaker.make(baseProp, subpropName, p,
- attributes.getValue(i),parentFO);
- }
- else {
- propVal = propertyMaker.make(p,attributes.getValue(i),parentFO);
- }
- if (propVal != null) {
- p.put(propName,propVal);
- }
- } catch (FOPException e) { /* Do other props. */ }
- } else {
- if (! attributeName.startsWith("xmlns"))
- MessageHandler.errorln("WARNING: property '" +
- attributeName + "' ignored");
- }
- }
-
- return p;
+ StringBuffer propsDone = new StringBuffer(256);
+ propsDone.append(' ');
+
+ /*
+ * If font-size is set on this FO, must set it first, since
+ * other attributes specified in terms of "ems" depend on it.
+ * When we do "shorthand" properties, must handle the "font"
+ * property as well to see if font-size is set.
+ */
+ String fontsizeval = attributes.getValue(FONTSIZEATTR);
+ if (fontsizeval != null) {
+ Property.Maker propertyMaker = findMaker(table, FONTSIZEATTR);
+ if (propertyMaker != null) {
+ try {
+ p.put(FONTSIZEATTR,
+ propertyMaker.make(p, fontsizeval, parentFO));
+ } catch (FOPException e) {}
+ }
+ // Put in the "done" list even if error or no Maker.
+ propsDone.append(FONTSIZEATTR + ' ');
+ }
+
+ for (int i = 0; i < attributes.getLength(); i++) {
+ String attributeName = attributes.getQName(i);
+ /* Handle "compound" properties, ex. space-before.minimum */
+ int sepchar = attributeName.indexOf('.');
+ String propName = attributeName;
+ String subpropName = null;
+ Property propVal = null;
+ if (sepchar > -1) {
+ propName = attributeName.substring(0, sepchar);
+ subpropName = attributeName.substring(sepchar + 1);
+ } else if (propsDone.toString().indexOf(' ' + propName + ' ')
+ != -1) {
+ // Already processed this property (base property
+ // for a property with sub-components or font-size)
+ continue;
+ }
+
+ Property.Maker propertyMaker = findMaker(table, propName);
+
+ if (propertyMaker != null) {
+ try {
+ if (subpropName != null) {
+ Property baseProp = p.getExplicitBaseProp(propName);
+ if (baseProp == null) {
+ // See if it is specified later in this list
+ String baseValue = attributes.getValue(propName);
+ if (baseValue != null) {
+ baseProp = propertyMaker.make(p, baseValue,
+ parentFO);
+ propsDone.append(propName + ' ');
+ }
+ // else baseProp = propertyMaker.makeCompound(p, parentFO);
+ }
+ propVal = propertyMaker.make(baseProp, subpropName,
+ p,
+ attributes.getValue(i),
+ parentFO);
+ } else {
+ propVal = propertyMaker.make(p,
+ attributes.getValue(i),
+ parentFO);
+ }
+ if (propVal != null) {
+ p.put(propName, propVal);
+ }
+ } catch (FOPException e) { /* Do other props. */
+ }
+ } else {
+ if (!attributeName.startsWith("xmlns"))
+ MessageHandler.errorln("WARNING: property '"
+ + attributeName + "' ignored");
+ }
+ }
+
+ return p;
}
- public Property getSubpropValue(String space, String element,
- String propertyName, Property p,
- String subpropName) {
- Property.Maker maker = findMaker(space, element, propertyName);
- if (maker != null) {
- return maker.getSubpropValue(p, subpropName);
+ public Property getSubpropValue(String space, String element,
+ String propertyName, Property p,
+ String subpropName) {
+ Property.Maker maker = findMaker(space, element, propertyName);
+ if (maker != null) {
+ return maker.getSubpropValue(p, subpropName);
+ } else
+ return null;
}
- else return null;
- }
-
-
- public boolean isCorrespondingForced(PropertyList propertyList, String space,
- String element, String propertyName) {
- Property.Maker propertyMaker = findMaker(space, element, propertyName);
- if (propertyMaker != null) {
- return propertyMaker.isCorrespondingForced(propertyList);
- } else {
- MessageHandler.errorln("WARNING: no Maker for " + propertyName);
- }
- return false;
+
+
+ public boolean isCorrespondingForced(PropertyList propertyList,
+ String space, String element,
+ String propertyName) {
+ Property.Maker propertyMaker = findMaker(space, element,
+ propertyName);
+ if (propertyMaker != null) {
+ return propertyMaker.isCorrespondingForced(propertyList);
+ } else {
+ MessageHandler.errorln("WARNING: no Maker for " + propertyName);
+ }
+ return false;
}
-
+
public Property getShorthand(PropertyList propertyList, String space,
- String element, String propertyName) {
- Property.Maker propertyMaker = findMaker(space, element, propertyName);
- if (propertyMaker != null) {
- return propertyMaker.getShorthand(propertyList);
- } else {
- MessageHandler.errorln("WARNING: no Maker for " + propertyName);
+ String element, String propertyName) {
+ Property.Maker propertyMaker = findMaker(space, element,
+ propertyName);
+ if (propertyMaker != null) {
+ return propertyMaker.getShorthand(propertyList);
+ } else {
+ MessageHandler.errorln("WARNING: no Maker for " + propertyName);
return null;
- }
+ }
}
- public Property makeProperty(PropertyList propertyList, String space, String element, String propertyName) throws FOPException {
-
- Property p = null;
-
- Property.Maker propertyMaker = findMaker(space, element, propertyName);
- if (propertyMaker != null) {
- p = propertyMaker.make(propertyList);
- } else {
- MessageHandler.errorln("WARNING: property " + propertyName + " ignored");
- }
- return p;
- }
+ public Property makeProperty(PropertyList propertyList, String space,
+ String element,
+ String propertyName) throws FOPException {
- protected Property.Maker findMaker(String space, String elementName, String propertyName)
- {
- return findMaker((Hashtable)elementTable.get(elementName),
- propertyName);
+ Property p = null;
+
+ Property.Maker propertyMaker = findMaker(space, element,
+ propertyName);
+ if (propertyMaker != null) {
+ p = propertyMaker.make(propertyList);
+ } else {
+ MessageHandler.errorln("WARNING: property " + propertyName
+ + " ignored");
+ }
+ return p;
}
- /**
- * Convenience function to return the Maker for a given property
- * given the Hashtable containing properties specific to this element.
- * If table is non-null and
- * @param elemTable Element-specific properties or null if none.
- * @param propertyName Name of property.
- * @return A Maker for this property.
- */
- private Property.Maker findMaker(Hashtable elemTable, String propertyName) {
- Property.Maker propertyMaker = null;
- if (elemTable != null) {
- propertyMaker = (Property.Maker)elemTable.get(propertyName);
+ protected Property.Maker findMaker(String space, String elementName,
+ String propertyName) {
+ return findMaker((Hashtable)elementTable.get(elementName),
+ propertyName);
}
- if (propertyMaker == null) {
- propertyMaker = (Property.Maker)propertyListTable.get(propertyName);
+
+ /**
+ * Convenience function to return the Maker for a given property
+ * given the Hashtable containing properties specific to this element.
+ * If table is non-null and
+ * @param elemTable Element-specific properties or null if none.
+ * @param propertyName Name of property.
+ * @return A Maker for this property.
+ */
+ private Property.Maker findMaker(Hashtable elemTable,
+ String propertyName) {
+ Property.Maker propertyMaker = null;
+ if (elemTable != null) {
+ propertyMaker = (Property.Maker)elemTable.get(propertyName);
+ }
+ if (propertyMaker == null) {
+ propertyMaker =
+ (Property.Maker)propertyListTable.get(propertyName);
+ }
+ return propertyMaker;
}
- return propertyMaker;
- }
}
diff --git a/src/org/apache/fop/fo/PropertyManager.java b/src/org/apache/fop/fo/PropertyManager.java
index f8fb0ab9a..753cafd98 100644
--- a/src/org/apache/fop/fo/PropertyManager.java
+++ b/src/org/apache/fop/fo/PropertyManager.java
@@ -1,9 +1,10 @@
-/*-- $Id$ -- */
/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
+
package org.apache.fop.fo;
import org.apache.fop.layout.FontState;
@@ -28,15 +29,19 @@ public class PropertyManager {
private BorderAndPadding borderAndPadding = null;
private HyphenationProps hyphProps = null;
- private String[] saLeft ;
+ private String[] saLeft;
private String[] saRight;
- private String[] saTop ;
- private String[] saBottom ;
-
- private static MessageFormat msgColorFmt = new MessageFormat("border-{0}-color");
- private static MessageFormat msgStyleFmt = new MessageFormat("border-{0}-style");
- private static MessageFormat msgWidthFmt = new MessageFormat("border-{0}-width");
- private static MessageFormat msgPaddingFmt = new MessageFormat("padding-{0}");
+ private String[] saTop;
+ private String[] saBottom;
+
+ private static MessageFormat msgColorFmt =
+ new MessageFormat("border-{0}-color");
+ private static MessageFormat msgStyleFmt =
+ new MessageFormat("border-{0}-style");
+ private static MessageFormat msgWidthFmt =
+ new MessageFormat("border-{0}-width");
+ private static MessageFormat msgPaddingFmt =
+ new MessageFormat("padding-{0}");
public PropertyManager(PropertyList pList) {
this.properties = pList;
@@ -66,7 +71,7 @@ public class PropertyManager {
fontState = new FontState(fontInfo, fontFamily, fontStyle,
fontWeight, fontSize, fontVariant);
}
- return fontState ;
+ return fontState;
}
@@ -85,34 +90,27 @@ public class PropertyManager {
private void initBorderInfo(int whichSide, String[] saSide) {
borderAndPadding.setPadding(whichSide,
- properties.get(
- msgPaddingFmt.format(saSide)).getCondLength());
+ properties.get(msgPaddingFmt.format(saSide)).getCondLength());
// If style = none, force width to 0, don't get Color
int style = properties.get(msgStyleFmt.format(saSide)).getEnum();
if (style != Constants.NONE) {
borderAndPadding.setBorder(whichSide, style,
- properties.get(
- msgWidthFmt.format(saSide)).getCondLength(),
- properties.get(
- msgColorFmt.format(saSide)).getColorType());
+ properties.get(msgWidthFmt.format(saSide)).getCondLength(),
+ properties.get(msgColorFmt.format(saSide)).getColorType());
}
}
public HyphenationProps getHyphenationProps() {
if (hyphProps == null) {
this.hyphProps = new HyphenationProps();
- hyphProps.hyphenate =
- this.properties.get("hyphenate").getEnum();
- hyphProps.hyphenationChar = this.properties.get(
- "hyphenation-character").getCharacter();
- hyphProps.hyphenationPushCharacterCount = this.properties.get(
- "hyphenation-push-character-count").getNumber().
- intValue();
- hyphProps.hyphenationRemainCharacterCount = this.properties.get(
- "hyphenation-remain-character-count").getNumber().
- intValue();
- hyphProps.language =
- this.properties.get("language").getString();
+ hyphProps.hyphenate = this.properties.get("hyphenate").getEnum();
+ hyphProps.hyphenationChar =
+ this.properties.get("hyphenation-character").getCharacter();
+ hyphProps.hyphenationPushCharacterCount =
+ this.properties.get("hyphenation-push-character-count").getNumber().intValue();
+ hyphProps.hyphenationRemainCharacterCount =
+ this.properties.get("hyphenation-remain-character-count").getNumber().intValue();
+ hyphProps.language = this.properties.get("language").getString();
hyphProps.country = this.properties.get("country").getString();
}
return hyphProps;
@@ -121,94 +119,94 @@ public class PropertyManager {
public int checkBreakBefore(Area area) {
if (!(area instanceof ColumnArea)) {
switch (properties.get("break-before").getEnum()) {
- case BreakBefore.PAGE:
- return Status.FORCE_PAGE_BREAK;
- case BreakBefore.ODD_PAGE:
- return Status.FORCE_PAGE_BREAK_ODD;
- case BreakBefore.EVEN_PAGE:
- return Status.FORCE_PAGE_BREAK_EVEN;
- case BreakBefore.COLUMN:
- return Status.FORCE_COLUMN_BREAK;
- default:
- return Status.OK;
+ case BreakBefore.PAGE:
+ return Status.FORCE_PAGE_BREAK;
+ case BreakBefore.ODD_PAGE:
+ return Status.FORCE_PAGE_BREAK_ODD;
+ case BreakBefore.EVEN_PAGE:
+ return Status.FORCE_PAGE_BREAK_EVEN;
+ case BreakBefore.COLUMN:
+ return Status.FORCE_COLUMN_BREAK;
+ default:
+ return Status.OK;
}
} else {
- ColumnArea colArea = (ColumnArea) area;
+ ColumnArea colArea = (ColumnArea)area;
switch (properties.get("break-before").getEnum()) {
- case BreakBefore.PAGE:
- // if first ColumnArea, and empty, return OK
- if (!colArea.hasChildren() &&
- (colArea.getColumnIndex() == 1))
- return Status.OK;
- else
- return Status.FORCE_PAGE_BREAK;
- case BreakBefore.ODD_PAGE:
- // if first ColumnArea, empty, _and_ in odd page,
- // return OK
- if (!colArea.hasChildren() &&
- (colArea.getColumnIndex() == 1) &&
- (colArea.getPage().getNumber() % 2 != 0))
- return Status.OK;
- else
- return Status.FORCE_PAGE_BREAK_ODD;
- case BreakBefore.EVEN_PAGE:
- // if first ColumnArea, empty, _and_ in even page,
- // return OK
- if (!colArea.hasChildren() &&
- (colArea.getColumnIndex() == 1) &&
- (colArea.getPage().getNumber() % 2 == 0))
- return Status.OK;
- else
- return Status.FORCE_PAGE_BREAK_EVEN;
- case BreakBefore.COLUMN:
- // if ColumnArea is empty return OK
- if (!area.hasChildren())
- return Status.OK;
- else
- return Status.FORCE_COLUMN_BREAK;
- default:
+ case BreakBefore.PAGE:
+ // if first ColumnArea, and empty, return OK
+ if (!colArea.hasChildren() && (colArea.getColumnIndex() == 1))
+ return Status.OK;
+ else
+ return Status.FORCE_PAGE_BREAK;
+ case BreakBefore.ODD_PAGE:
+ // if first ColumnArea, empty, _and_ in odd page,
+ // return OK
+ if (!colArea.hasChildren() && (colArea.getColumnIndex() == 1)
+ && (colArea.getPage().getNumber() % 2 != 0))
+ return Status.OK;
+ else
+ return Status.FORCE_PAGE_BREAK_ODD;
+ case BreakBefore.EVEN_PAGE:
+ // if first ColumnArea, empty, _and_ in even page,
+ // return OK
+ if (!colArea.hasChildren() && (colArea.getColumnIndex() == 1)
+ && (colArea.getPage().getNumber() % 2 == 0))
return Status.OK;
+ else
+ return Status.FORCE_PAGE_BREAK_EVEN;
+ case BreakBefore.COLUMN:
+ // if ColumnArea is empty return OK
+ if (!area.hasChildren())
+ return Status.OK;
+ else
+ return Status.FORCE_COLUMN_BREAK;
+ default:
+ return Status.OK;
}
}
}
public int checkBreakAfter(Area area) {
switch (properties.get("break-after").getEnum()) {
- case BreakAfter.PAGE:
- return Status.FORCE_PAGE_BREAK;
- case BreakAfter.ODD_PAGE:
- return Status.FORCE_PAGE_BREAK_ODD;
- case BreakAfter.EVEN_PAGE:
- return Status.FORCE_PAGE_BREAK_EVEN;
- case BreakAfter.COLUMN:
- return Status.FORCE_COLUMN_BREAK;
- default:
- return Status.OK;
+ case BreakAfter.PAGE:
+ return Status.FORCE_PAGE_BREAK;
+ case BreakAfter.ODD_PAGE:
+ return Status.FORCE_PAGE_BREAK_ODD;
+ case BreakAfter.EVEN_PAGE:
+ return Status.FORCE_PAGE_BREAK_EVEN;
+ case BreakAfter.COLUMN:
+ return Status.FORCE_COLUMN_BREAK;
+ default:
+ return Status.OK;
}
}
-public MarginProps getMarginProps()
-{
-MarginProps props = new MarginProps();
-
-// Common Margin Properties-Block
- props.marginTop = this.properties.get("margin-top").getLength().mvalue();
- props.marginBottom = this.properties.get("margin-bottom").getLength().mvalue();
- props.marginLeft = this.properties.get("margin-left").getLength().mvalue();
- props.marginRight = this.properties.get("margin-right").getLength().mvalue();
-/*
-// need to get opt, min and max
- props.spaceBefore = this.properties.get("space-before").getLength().mvalue();
- props.spaceAfter = this.properties.get("space-after").getLength().mvalue();
- props.startIndent = this.properties.get("start-indent").getLength().mvalue();
- props.endIndent = this.properties.get("end-indent").getLength().mvalue();
-*/
-return props;
-}
+ public MarginProps getMarginProps() {
+ MarginProps props = new MarginProps();
+
+ // Common Margin Properties-Block
+ props.marginTop =
+ this.properties.get("margin-top").getLength().mvalue();
+ props.marginBottom =
+ this.properties.get("margin-bottom").getLength().mvalue();
+ props.marginLeft =
+ this.properties.get("margin-left").getLength().mvalue();
+ props.marginRight =
+ this.properties.get("margin-right").getLength().mvalue();
+ /*
+ * // need to get opt, min and max
+ * props.spaceBefore = this.properties.get("space-before").getLength().mvalue();
+ * props.spaceAfter = this.properties.get("space-after").getLength().mvalue();
+ * props.startIndent = this.properties.get("start-indent").getLength().mvalue();
+ * props.endIndent = this.properties.get("end-indent").getLength().mvalue();
+ */
+ return props;
+ }
-public BackgroundProps getBackgroundProps() {
-BackgroundProps bp = new BackgroundProps();
-return bp;
-}
+ public BackgroundProps getBackgroundProps() {
+ BackgroundProps bp = new BackgroundProps();
+ return bp;
+ }
}
diff --git a/src/org/apache/fop/fo/ShorthandParser.java b/src/org/apache/fop/fo/ShorthandParser.java
index a8a9a55b8..fabf1fc7f 100644
--- a/src/org/apache/fop/fo/ShorthandParser.java
+++ b/src/org/apache/fop/fo/ShorthandParser.java
@@ -1,6 +1,14 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.fo;
public interface ShorthandParser {
- public Property getValueForProperty(String propName, Property.Maker maker,
- PropertyList propertyList);
+ public Property getValueForProperty(String propName,
+ Property.Maker maker,
+ PropertyList propertyList);
}
diff --git a/src/org/apache/fop/fo/SpaceProperty.java b/src/org/apache/fop/fo/SpaceProperty.java
index a958eaca7..5aa9d184d 100644
--- a/src/org/apache/fop/fo/SpaceProperty.java
+++ b/src/org/apache/fop/fo/SpaceProperty.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo;
@@ -56,22 +12,30 @@ import org.apache.fop.datatypes.LengthRange;
public class SpaceProperty extends Property {
- public static class Maker extends LengthRangeProperty.Maker {
- protected Maker(String name) {
- super(name);
+ public static class Maker extends LengthRangeProperty.Maker {
+ protected Maker(String name) {
+ super(name);
+ }
+
}
- }
- private Space space ;
+ private Space space;
- public SpaceProperty(Space space) {
- this.space = space;
- }
+ public SpaceProperty(Space space) {
+ this.space = space;
+ }
- public Space getSpace() { return this.space; }
+ public Space getSpace() {
+ return this.space;
+ }
- /* Space extends LengthRange */
- public LengthRange getLengthRange() { return this.space; }
- public Object getObject() { return this.space; }
+ /* Space extends LengthRange */
+ public LengthRange getLengthRange() {
+ return this.space;
+ }
+
+ public Object getObject() {
+ return this.space;
+ }
}
diff --git a/src/org/apache/fop/fo/StandardElementMapping.java b/src/org/apache/fop/fo/StandardElementMapping.java
index 201a2bf77..132963ca1 100644
--- a/src/org/apache/fop/fo/StandardElementMapping.java
+++ b/src/org/apache/fop/fo/StandardElementMapping.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -24,8 +25,7 @@ public class StandardElementMapping implements ElementMapping {
builder.addMapping(uri, "declarations", Declarations.maker());
builder.addMapping(uri, "color-profile", ColorProfile.maker());
builder.addMapping(uri, "page-sequence", PageSequence.maker());
- builder.addMapping(uri, "layout-master-set",
- LayoutMasterSet.maker());
+ builder.addMapping(uri, "layout-master-set", LayoutMasterSet.maker());
builder.addMapping(uri, "page-sequence-master",
PageSequenceMaster.maker());
builder.addMapping(uri, "single-page-master-reference",
@@ -55,9 +55,9 @@ public class StandardElementMapping implements ElementMapping {
builder.addMapping(uri, "bidi-override", BidiOverride.maker());
builder.addMapping(uri, "character",
org.apache.fop.fo.flow.Character.maker());
- builder.addMapping(uri, "initial-property-set", InitialPropertySet.maker());
- builder.addMapping(uri, "external-graphic",
- ExternalGraphic.maker());
+ builder.addMapping(uri, "initial-property-set",
+ InitialPropertySet.maker());
+ builder.addMapping(uri, "external-graphic", ExternalGraphic.maker());
builder.addMapping(uri, "instream-foreign-object",
InstreamForeignObject.maker());
builder.addMapping(uri, "inline", Inline.maker());
@@ -90,10 +90,12 @@ public class StandardElementMapping implements ElementMapping {
builder.addMapping(uri, "multi-case", MultiCase.maker());
builder.addMapping(uri, "multi-toggle", MultiToggle.maker());
builder.addMapping(uri, "multi-properties", MultiProperties.maker());
- builder.addMapping(uri, "multi-property-set", MultiPropertySet.maker());
+ builder.addMapping(uri, "multi-property-set",
+ MultiPropertySet.maker());
// Out-of-Line Formatting Objects
- builder.addMapping(uri, "float", org.apache.fop.fo.flow.Float.maker());
+ builder.addMapping(uri, "float",
+ org.apache.fop.fo.flow.Float.maker());
builder.addMapping(uri, "footnote", Footnote.maker());
builder.addMapping(uri, "footnote-body", FootnoteBody.maker());
@@ -102,15 +104,15 @@ public class StandardElementMapping implements ElementMapping {
builder.addMapping(uri, "marker", Marker.maker());
builder.addMapping(uri, "retrieve-marker", RetrieveMarker.maker());
- builder.addPropertyList(uri,
- FOPropertyMapping.getGenericMappings());
+ builder.addPropertyList(uri, FOPropertyMapping.getGenericMappings());
/* Add any element mappings */
for (Enumeration e = FOPropertyMapping.getElementMappings();
- e.hasMoreElements();) {
- String elem = (String) e.nextElement();
+ e.hasMoreElements(); ) {
+ String elem = (String)e.nextElement();
builder.addElementPropertyList(uri, elem,
FOPropertyMapping.getElementMapping(elem));
}
}
+
}
diff --git a/src/org/apache/fop/fo/Status.java b/src/org/apache/fop/fo/Status.java
index 5fdb0566d..58f14c153 100644
--- a/src/org/apache/fop/fo/Status.java
+++ b/src/org/apache/fop/fo/Status.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo;
@@ -58,34 +14,35 @@ public class Status {
protected int code;
- public final static int OK = 1;
- public final static int AREA_FULL_NONE = 2;
- public final static int AREA_FULL_SOME = 3;
- public final static int FORCE_PAGE_BREAK = 4;
+ public final static int OK = 1;
+ public final static int AREA_FULL_NONE = 2;
+ public final static int AREA_FULL_SOME = 3;
+ public final static int FORCE_PAGE_BREAK = 4;
public final static int FORCE_PAGE_BREAK_EVEN = 5;
- public final static int FORCE_PAGE_BREAK_ODD = 6;
- public final static int FORCE_COLUMN_BREAK = 7;
- public final static int KEEP_WITH_NEXT = 8;
+ public final static int FORCE_PAGE_BREAK_ODD = 6;
+ public final static int FORCE_COLUMN_BREAK = 7;
+ public final static int KEEP_WITH_NEXT = 8;
public Status(int code) {
- this.code = code;
+ this.code = code;
}
public int getCode() {
- return this.code;
+ return this.code;
}
public boolean isIncomplete() {
- return ((this.code != OK) && (this.code != KEEP_WITH_NEXT));
+ return ((this.code != OK) && (this.code != KEEP_WITH_NEXT));
}
public boolean laidOutNone() {
- return (this.code == AREA_FULL_NONE);
+ return (this.code == AREA_FULL_NONE);
+ }
+
+ public boolean isPageBreak() {
+ return ((this.code == FORCE_PAGE_BREAK)
+ || (this.code == FORCE_PAGE_BREAK_EVEN)
+ || (this.code == FORCE_PAGE_BREAK_ODD));
}
-
- public boolean isPageBreak() {
- return ((this.code == FORCE_PAGE_BREAK)
- || (this.code == FORCE_PAGE_BREAK_EVEN)
- || (this.code == FORCE_PAGE_BREAK_ODD));
- }
+
}
diff --git a/src/org/apache/fop/fo/StringProperty.java b/src/org/apache/fop/fo/StringProperty.java
index e270bcf90..93ed10bca 100644
--- a/src/org/apache/fop/fo/StringProperty.java
+++ b/src/org/apache/fop/fo/StringProperty.java
@@ -1,95 +1,60 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo;
public class StringProperty extends Property {
- public static class Maker extends Property.Maker {
-
- public Maker(String propName) {
- super(propName);
+ public static class Maker extends Property.Maker {
+
+ public Maker(String propName) {
+ super(propName);
+ }
+
+ public Property make(PropertyList propertyList, String value,
+ FObj fo) {
+ // Work around the fact that most String properties are not
+ // specified as actual String literals (with "" or '') since
+ // the attribute values themselves are Strings!
+ // If the value starts with ' or ", make sure it also ends with
+ // this character
+ // Otherwise, just take the whole value as the String
+ int vlen = value.length() - 1;
+ if (vlen > 0) {
+ char q1 = value.charAt(0);
+ if (q1 == '"' || q1 == '\'') {
+ if (value.charAt(vlen) == q1) {
+ return new StringProperty(value.substring(1, vlen));
+ }
+ System.err.println("Warning String-valued property starts with quote"
+ + " but doesn't end with quote: "
+ + value);
+ // fall through and use the entire value, including first quote
+ }
+ }
+ return new StringProperty(value);
+ }
+
+ } // end String.Maker
+
+ private String str;
+
+ public StringProperty(String str) {
+ this.str = str;
+ // System.err.println("Set StringProperty: " + str);
}
- public Property make(PropertyList propertyList, String value, FObj fo) {
- // Work around the fact that most String properties are not
- // specified as actual String literals (with "" or '') since
- // the attribute values themselves are Strings!
- // If the value starts with ' or ", make sure it also ends with
- // this character
- // Otherwise, just take the whole value as the String
- int vlen = value.length()-1;
- if (vlen > 0) {
- char q1 = value.charAt(0);
- if (q1 == '"' || q1 == '\'') {
- if (value.charAt(vlen) == q1) {
- return new StringProperty(value.substring(1,vlen));
- }
- System.err.println("Warning String-valued property starts with quote" +
- " but doesn't end with quote: " + value);
- // fall through and use the entire value, including first quote
- }
- }
- return new StringProperty(value);
+ public Object getObject() {
+ return this.str;
}
- } // end String.Maker
-
- private String str ;
- public StringProperty(String str) {
- this.str = str;
- // System.err.println("Set StringProperty: " + str);
- }
-
- public Object getObject() { return this.str; }
+ public String getString() {
+ return this.str;
+ }
- public String getString() { return this.str; }
}
diff --git a/src/org/apache/fop/fo/Title.java b/src/org/apache/fop/fo/Title.java
index f14bb8412..dbe258ca4 100644
--- a/src/org/apache/fop/fo/Title.java
+++ b/src/org/apache/fop/fo/Title.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -23,6 +24,7 @@ public class Title extends ToBeImplementedElement {
PropertyList propertyList) throws FOPException {
return new Title(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -30,7 +32,7 @@ public class Title extends ToBeImplementedElement {
}
protected Title(FObj parent,
- PropertyList propertyList) throws FOPException {
+ PropertyList propertyList) throws FOPException {
super(parent, propertyList);
this.name = "fo:title";
}
diff --git a/src/org/apache/fop/fo/ToBeImplementedElement.java b/src/org/apache/fop/fo/ToBeImplementedElement.java
index 53aa8040a..914294553 100644
--- a/src/org/apache/fop/fo/ToBeImplementedElement.java
+++ b/src/org/apache/fop/fo/ToBeImplementedElement.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -18,14 +19,15 @@ import org.apache.fop.apps.FOPException;
*/
public class ToBeImplementedElement extends FObj {
- protected ToBeImplementedElement(FObj parent,
- PropertyList propertyList) throws FOPException {
+ protected ToBeImplementedElement(FObj parent, PropertyList propertyList)
+ throws FOPException {
super(parent, propertyList);
}
- public Status layout(Area area) throws FOPException {
- MessageHandler.logln("This element \"" + this.name + "\" is not yet implemented.");
- return new Status(Status.OK);
- }
+ public Status layout(Area area) throws FOPException {
+ MessageHandler.logln("This element \"" + this.name
+ + "\" is not yet implemented.");
+ return new Status(Status.OK);
+ }
}
diff --git a/src/org/apache/fop/fo/TreeBuilder.java b/src/org/apache/fop/fo/TreeBuilder.java
index 66391b904..1549f7dbe 100644
--- a/src/org/apache/fop/fo/TreeBuilder.java
+++ b/src/org/apache/fop/fo/TreeBuilder.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo;
// FOP
@@ -78,8 +35,9 @@ public interface TreeBuilder {
* @param namespaceURI namespace URI of formatting object element
* @param localName local name of formatting object element
* @param maker Maker for class representing formatting object
- */
- public void addMapping(String namespaceURI, String localName, FObj.Maker maker);
+ */
+ public void addMapping(String namespaceURI, String localName,
+ FObj.Maker maker);
/**
* add a mapping from element name to maker.
@@ -87,7 +45,7 @@ public interface TreeBuilder {
* @param namespaceURI namespace URI of formatting object element
* @param localName local name of formatting object element
* @param maker Maker for class representing formatting object
- */
+ */
public void addPropertyList(String namespaceURI, Hashtable list);
/**
@@ -96,7 +54,8 @@ public interface TreeBuilder {
* @param namespaceURI namespace URI of formatting object element
* @param localName local name of formatting object element
* @param maker Maker for class representing formatting object
- */
- public void addElementPropertyList(String namespaceURI, String localName, Hashtable list);
+ */
+ public void addElementPropertyList(String namespaceURI, String localName,
+ Hashtable list);
}
diff --git a/src/org/apache/fop/fo/XTElementMapping.java b/src/org/apache/fop/fo/XTElementMapping.java
index 2095a91d1..0cfb25930 100644
--- a/src/org/apache/fop/fo/XTElementMapping.java
+++ b/src/org/apache/fop/fo/XTElementMapping.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo;
public interface XTElementMapping {
diff --git a/src/org/apache/fop/fo/XTFOTreeBuilder.java b/src/org/apache/fop/fo/XTFOTreeBuilder.java
index 898138eb1..a827b3a15 100644
--- a/src/org/apache/fop/fo/XTFOTreeBuilder.java
+++ b/src/org/apache/fop/fo/XTFOTreeBuilder.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo;
// FOP
@@ -71,21 +28,22 @@ import java.io.IOException;
/**
* SAX Handler that builds the formatting object tree.
*/
-//public class XTFOTreeBuilder extends HandlerBase {
+// public class XTFOTreeBuilder extends HandlerBase {
public class XTFOTreeBuilder extends FOTreeBuilder
- implements DocumentHandler {
+ implements DocumentHandler {
// namespace implementation ideas pinched from John Cowan
protected static class NSMap {
- String prefix;
- String uri;
- int level;
-
- NSMap(String prefix, String uri, int level) {
- this.prefix = prefix;
- this.uri = uri;
- this.level = level;
- }
+ String prefix;
+ String uri;
+ int level;
+
+ NSMap(String prefix, String uri, int level) {
+ this.prefix = prefix;
+ this.uri = uri;
+ this.level = level;
+ }
+
}
protected int level = 0;
@@ -94,79 +52,85 @@ public class XTFOTreeBuilder extends FOTreeBuilder
protected Stack namespaceStack = new Stack();
{
- namespaceStack.push(new NSMap("xml",
- "http://www.w3.org/XML/1998/namespace",
- -1));
- namespaceStack.push(new NSMap("", "", -1));
+ namespaceStack.push(new NSMap("xml",
+ "http://www.w3.org/XML/1998/namespace",
+ -1));
+ namespaceStack.push(new NSMap("", "", -1));
}
protected String findURI(String prefix) {
- for (int i = namespaceStack.size() - 1; i >= 0; i--) {
- NSMap nsMap = (NSMap) (namespaceStack.elementAt(i));
- if (prefix.equals(nsMap.prefix)) return nsMap.uri;
- }
- return null;
+ for (int i = namespaceStack.size() - 1; i >= 0; i--) {
+ NSMap nsMap = (NSMap)(namespaceStack.elementAt(i));
+ if (prefix.equals(nsMap.prefix))
+ return nsMap.uri;
+ }
+ return null;
}
- protected String mapName(String name)
- throws SAXException {
-
- int colon = name.indexOf(':');
- String prefix = "";
- m_localPart = name;
- if (colon != -1) {
- prefix = name.substring(0, colon);
- m_localPart = name.substring(colon + 1);
- }
- m_uri = findURI(prefix);
- if (m_uri == null) {
- if (prefix.equals("")) {
- return name;
- } else {
- throw new SAXException(new FOPException("Unknown namespace prefix " + prefix));
- }
- }
- return m_uri + "^" + m_localPart;
+ protected String mapName(String name) throws SAXException {
+
+ int colon = name.indexOf(':');
+ String prefix = "";
+ m_localPart = name;
+ if (colon != -1) {
+ prefix = name.substring(0, colon);
+ m_localPart = name.substring(colon + 1);
+ }
+ m_uri = findURI(prefix);
+ if (m_uri == null) {
+ if (prefix.equals("")) {
+ return name;
+ } else {
+ throw new SAXException(new FOPException("Unknown namespace prefix "
+ + prefix));
+ }
+ }
+ return m_uri + "^" + m_localPart;
}
- /** SAX1 Handler for the end of an element */
+ /**
+ * SAX1 Handler for the end of an element
+ */
public void endElement(String rawName) throws SAXException {
- mapName(rawName);
- super.endElement(m_uri, m_localPart, rawName);
- level--;
- while (((NSMap) namespaceStack.peek()).level > level) {
- namespaceStack.pop();
- }
+ mapName(rawName);
+ super.endElement(m_uri, m_localPart, rawName);
+ level--;
+ while (((NSMap)namespaceStack.peek()).level > level) {
+ namespaceStack.pop();
+ }
}
- /** SAX1 Handler for the start of an element */
- public void startElement(String rawName, AttributeList attlist)
- throws SAXException {
-
- // SAX2 version of AttributeList
- AttributesImpl newAttrs = new AttributesImpl();
-
- level++;
- int length = attlist.getLength();
- for (int i = 0; i < length; i++) {
- String att = attlist.getName(i);
- if (att.equals("xmlns")) {
- namespaceStack.push( new NSMap("",
- attlist.getValue(i),
- level));
- } else if (att.startsWith("xmlns:")) {
- String value = attlist.getValue(i);
- namespaceStack.push(new NSMap(att.substring(6), value,
- level));
- } else {
- mapName(att);
- newAttrs.addAttribute(m_uri, m_localPart, att,
- attlist.getType(i), attlist.getValue(i));
- }
-
- }
-
- mapName(rawName);
- super.startElement(m_uri, m_localPart, rawName, newAttrs);
+ /**
+ * SAX1 Handler for the start of an element
+ */
+ public void startElement(String rawName,
+ AttributeList attlist) throws SAXException {
+
+ // SAX2 version of AttributeList
+ AttributesImpl newAttrs = new AttributesImpl();
+
+ level++;
+ int length = attlist.getLength();
+ for (int i = 0; i < length; i++) {
+ String att = attlist.getName(i);
+ if (att.equals("xmlns")) {
+ namespaceStack.push(new NSMap("", attlist.getValue(i),
+ level));
+ } else if (att.startsWith("xmlns:")) {
+ String value = attlist.getValue(i);
+ namespaceStack.push(new NSMap(att.substring(6), value,
+ level));
+ } else {
+ mapName(att);
+ newAttrs.addAttribute(m_uri, m_localPart, att,
+ attlist.getType(i),
+ attlist.getValue(i));
+ }
+
+ }
+
+ mapName(rawName);
+ super.startElement(m_uri, m_localPart, rawName, newAttrs);
}
+
}
diff --git a/src/org/apache/fop/fo/expr/AbsFunction.java b/src/org/apache/fop/fo/expr/AbsFunction.java
index 578aaffca..7a40c9d39 100644
--- a/src/org/apache/fop/fo/expr/AbsFunction.java
+++ b/src/org/apache/fop/fo/expr/AbsFunction.java
@@ -1,69 +1,28 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
public class AbsFunction extends FunctionBase {
- public int nbArgs() { return 1; }
+ public int nbArgs() {
+ return 1;
+ }
+
+ public Property eval(Property[] args,
+ PropertyInfo propInfo) throws PropertyException {
+ Numeric num = args[0].getNumeric();
+ if (num == null)
+ throw new PropertyException("Non numeric operand to abs function");
+ // What if has relative composants (percent, table-col units)?
+ return new NumericProperty(num.abs());
+ }
- public Property eval(Property[] args, PropertyInfo propInfo)
- throws PropertyException
- {
- Numeric num = args[0].getNumeric();
- if (num == null)
- throw new PropertyException("Non numeric operand to abs function");
- // What if has relative composants (percent, table-col units)?
- return new NumericProperty(num.abs());
- }
}
diff --git a/src/org/apache/fop/fo/expr/BodyStartFunction.java b/src/org/apache/fop/fo/expr/BodyStartFunction.java
index 56a3a1fb4..41c47ee55 100644
--- a/src/org/apache/fop/fo/expr/BodyStartFunction.java
+++ b/src/org/apache/fop/fo/expr/BodyStartFunction.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
@@ -56,24 +13,27 @@ import org.apache.fop.fo.flow.ListItem;
public class BodyStartFunction extends FunctionBase {
- public int nbArgs() { return 0; }
+ public int nbArgs() {
+ return 0;
+ }
+
+ public Property eval(Property[] args,
+ PropertyInfo pInfo) throws PropertyException {
+ Numeric distance =
+ pInfo.getPropertyList().get("provisional-distance-between-starts").getNumeric();
- public Property eval(Property[] args, PropertyInfo pInfo)
- throws PropertyException
- {
- Numeric distance
- = pInfo.getPropertyList().get("provisional-distance-between-starts").getNumeric();
+ FObj item = pInfo.getFO();
+ while (item != null &&!(item instanceof ListItem)) {
+ item = item.getParent();
+ }
+ if (item == null) {
+ throw new PropertyException("body-start() called from outside an fo:list-item");
+ }
- FObj item = pInfo.getFO();
- while(item != null && !(item instanceof ListItem)) {
- item = item.getParent();
- }
- if(item == null) {
- throw new PropertyException("body-start() called from outside an fo:list-item");
+ Numeric startIndent =
+ item.properties.get("start-indent").getNumeric();
+
+ return new NumericProperty(distance.add(startIndent));
}
- Numeric startIndent = item.properties.get("start-indent").getNumeric();
-
- return new NumericProperty(distance.add(startIndent));
- }
}
diff --git a/src/org/apache/fop/fo/expr/CeilingFunction.java b/src/org/apache/fop/fo/expr/CeilingFunction.java
index 5812b53a0..9f4200415 100644
--- a/src/org/apache/fop/fo/expr/CeilingFunction.java
+++ b/src/org/apache/fop/fo/expr/CeilingFunction.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
@@ -55,14 +12,16 @@ import org.apache.fop.fo.NumberProperty;
class CeilingFunction extends FunctionBase {
- public int nbArgs() { return 1; }
+ public int nbArgs() {
+ return 1;
+ }
+
+ public Property eval(Property[] args,
+ PropertyInfo pInfo) throws PropertyException {
+ Number dbl = args[0].getNumber();
+ if (dbl == null)
+ throw new PropertyException("Non number operand to ceiling function");
+ return new NumberProperty(Math.ceil(dbl.doubleValue()));
+ }
- public Property eval(Property[] args, PropertyInfo pInfo)
- throws PropertyException
- {
- Number dbl = args[0].getNumber();
- if (dbl == null)
- throw new PropertyException("Non number operand to ceiling function");
- return new NumberProperty(Math.ceil(dbl.doubleValue()));
- }
}
diff --git a/src/org/apache/fop/fo/expr/FloorFunction.java b/src/org/apache/fop/fo/expr/FloorFunction.java
index f9055db72..868067bd7 100644
--- a/src/org/apache/fop/fo/expr/FloorFunction.java
+++ b/src/org/apache/fop/fo/expr/FloorFunction.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
@@ -56,14 +13,16 @@ import org.apache.fop.fo.NumberProperty;
class FloorFunction extends FunctionBase {
- public int nbArgs() { return 1; }
+ public int nbArgs() {
+ return 1;
+ }
+
+ public Property eval(Property[] args,
+ PropertyInfo pInfo) throws PropertyException {
+ Number dbl = args[0].getNumber();
+ if (dbl == null)
+ throw new PropertyException("Non number operand to floor function");
+ return new NumberProperty(Math.floor(dbl.doubleValue()));
+ }
- public Property eval(Property[] args, PropertyInfo pInfo)
- throws PropertyException
- {
- Number dbl = args[0].getNumber();
- if (dbl == null)
- throw new PropertyException("Non number operand to floor function");
- return new NumberProperty(Math.floor(dbl.doubleValue()));
- }
}
diff --git a/src/org/apache/fop/fo/expr/FopPropValFunction.java b/src/org/apache/fop/fo/expr/FopPropValFunction.java
index 72fd8856d..b89719014 100644
--- a/src/org/apache/fop/fo/expr/FopPropValFunction.java
+++ b/src/org/apache/fop/fo/expr/FopPropValFunction.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
@@ -58,17 +15,18 @@ import org.apache.fop.fo.Property;
*/
public class FopPropValFunction extends FunctionBase {
- public int nbArgs() { return 1; }
+ public int nbArgs() {
+ return 1;
+ }
- public Property eval(Property[] args, PropertyInfo pInfo)
- throws PropertyException
- {
- String propName = args[0].getString();
- if (propName == null) {
- throw new PropertyException("Incorrect parameter to _int-property-value function");
+ public Property eval(Property[] args,
+ PropertyInfo pInfo) throws PropertyException {
+ String propName = args[0].getString();
+ if (propName == null) {
+ throw new PropertyException("Incorrect parameter to _int-property-value function");
+ }
+ // System.err.println("Get property-value for " + propName);
+ return pInfo.getPropertyList().get(propName);
}
- // System.err.println("Get property-value for " + propName);
- return pInfo.getPropertyList().get( propName);
- }
-}
+}
diff --git a/src/org/apache/fop/fo/expr/FromParentFunction.java b/src/org/apache/fop/fo/expr/FromParentFunction.java
index 4c66b4ffa..26c90c981 100644
--- a/src/org/apache/fop/fo/expr/FromParentFunction.java
+++ b/src/org/apache/fop/fo/expr/FromParentFunction.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
@@ -55,23 +12,25 @@ import org.apache.fop.fo.Property;
public class FromParentFunction extends FunctionBase {
- public int nbArgs() { return 1; }
+ public int nbArgs() {
+ return 1;
+ }
- public Property eval(Property[] args, PropertyInfo pInfo)
- throws PropertyException
- {
- String propName = args[0].getString();
- if (propName == null) {
- throw new PropertyException("Incorrect parameter to from-parent function");
+ public Property eval(Property[] args,
+ PropertyInfo pInfo) throws PropertyException {
+ String propName = args[0].getString();
+ if (propName == null) {
+ throw new PropertyException("Incorrect parameter to from-parent function");
+ }
+ // NOTE: special cases for shorthand property
+ // Should return COMPUTED VALUE
+ /*
+ * For now, this is the same as inherited-property-value(propName)
+ * (The only difference I can see is that this could work for
+ * non-inherited properties too. Perhaps the result is different for
+ * a property line line-height which "inherits specified"???
+ */
+ return pInfo.getPropertyList().getFromParent(propName);
}
- // NOTE: special cases for shorthand property
- // Should return COMPUTED VALUE
- /* For now, this is the same as inherited-property-value(propName)
- * (The only difference I can see is that this could work for
- * non-inherited properties too. Perhaps the result is different for
- * a property line line-height which "inherits specified"???
- */
- return pInfo.getPropertyList().getFromParent( propName);
- }
-}
+}
diff --git a/src/org/apache/fop/fo/expr/FromTableColumnFunction.java b/src/org/apache/fop/fo/expr/FromTableColumnFunction.java
index cd37b6a52..e164a2d8a 100644
--- a/src/org/apache/fop/fo/expr/FromTableColumnFunction.java
+++ b/src/org/apache/fop/fo/expr/FromTableColumnFunction.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
@@ -55,16 +12,17 @@ import org.apache.fop.fo.Property;
public class FromTableColumnFunction extends FunctionBase {
- public int nbArgs() { return 1; }
+ public int nbArgs() {
+ return 1;
+ }
- public Property eval(Property[] args, PropertyInfo pInfo)
- throws PropertyException
- {
- String propName = args[0].getString();
- if (propName == null) {
- throw new PropertyException("Incorrect parameter to from-table-column function");
+ public Property eval(Property[] args,
+ PropertyInfo pInfo) throws PropertyException {
+ String propName = args[0].getString();
+ if (propName == null) {
+ throw new PropertyException("Incorrect parameter to from-table-column function");
+ }
+ throw new PropertyException("from-table-column unimplemented!");
}
- throw new PropertyException("from-table-column unimplemented!");
- }
-}
+}
diff --git a/src/org/apache/fop/fo/expr/Function.java b/src/org/apache/fop/fo/expr/Function.java
index d0aba74f9..b2d0c04ec 100644
--- a/src/org/apache/fop/fo/expr/Function.java
+++ b/src/org/apache/fop/fo/expr/Function.java
@@ -1,62 +1,19 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
import org.apache.fop.datatypes.PercentBase;
public interface Function {
- int nbArgs() ;
- PercentBase getPercentBase();
- Property eval(Property[] args, PropertyInfo propInfo)
- throws PropertyException;
+ int nbArgs();
+ PercentBase getPercentBase();
+ Property eval(Property[] args,
+ PropertyInfo propInfo) throws PropertyException;
}
diff --git a/src/org/apache/fop/fo/expr/FunctionBase.java b/src/org/apache/fop/fo/expr/FunctionBase.java
index e14bf3eea..2ebf76ef5 100644
--- a/src/org/apache/fop/fo/expr/FunctionBase.java
+++ b/src/org/apache/fop/fo/expr/FunctionBase.java
@@ -1,69 +1,28 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
import org.apache.fop.datatypes.PercentBase;
public abstract class FunctionBase implements Function {
- // abstract int nbArgs() ;
+ // abstract int nbArgs() ;
- /**
- * By default, functions have no percent-based arguments.
- */
- public PercentBase getPercentBase() { return null; }
+ /**
+ * By default, functions have no percent-based arguments.
+ */
+ public PercentBase getPercentBase() {
+ return null;
+ }
- /*
- abstract Property eval(Property[] args, PropertyInfo propInfo)
- throws PropertyException;
- */
+ /*
+ * abstract Property eval(Property[] args, PropertyInfo propInfo)
+ * throws PropertyException;
+ */
}
diff --git a/src/org/apache/fop/fo/expr/InheritedPropFunction.java b/src/org/apache/fop/fo/expr/InheritedPropFunction.java
index 8b708e5fb..f00eacb19 100644
--- a/src/org/apache/fop/fo/expr/InheritedPropFunction.java
+++ b/src/org/apache/fop/fo/expr/InheritedPropFunction.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
@@ -55,16 +12,17 @@ import org.apache.fop.fo.Property;
public class InheritedPropFunction extends FunctionBase {
- public int nbArgs() { return 1; }
+ public int nbArgs() {
+ return 1;
+ }
- public Property eval(Property[] args, PropertyInfo pInfo)
- throws PropertyException
- {
- String propName = args[0].getString();
- if (propName == null) {
- throw new PropertyException("Incorrect parameter to inherited-property-value function");
+ public Property eval(Property[] args,
+ PropertyInfo pInfo) throws PropertyException {
+ String propName = args[0].getString();
+ if (propName == null) {
+ throw new PropertyException("Incorrect parameter to inherited-property-value function");
+ }
+ return pInfo.getPropertyList().getInherited(propName);
}
- return pInfo.getPropertyList().getInherited(propName);
- }
-}
+}
diff --git a/src/org/apache/fop/fo/expr/LabelEndFunction.java b/src/org/apache/fop/fo/expr/LabelEndFunction.java
index 6ab37cec7..46ec29160 100644
--- a/src/org/apache/fop/fo/expr/LabelEndFunction.java
+++ b/src/org/apache/fop/fo/expr/LabelEndFunction.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.datatypes.*;
@@ -58,39 +15,40 @@ import org.apache.fop.fo.flow.ListItem;
public class LabelEndFunction extends FunctionBase {
- public int nbArgs() { return 0; }
+ public int nbArgs() {
+ return 0;
+ }
- public Property eval(Property[] args, PropertyInfo pInfo)
- throws PropertyException {
+ public Property eval(Property[] args,
+ PropertyInfo pInfo) throws PropertyException {
- Length distance
- = pInfo.getPropertyList()
- .get("provisional-distance-between-starts").getLength();
- Length separation
- = pInfo.getPropertyList()
- .getNearestSpecified("provisional-label-separation").getLength();
+ Length distance =
+ pInfo.getPropertyList().get("provisional-distance-between-starts").getLength();
+ Length separation =
+ pInfo.getPropertyList().getNearestSpecified("provisional-label-separation").getLength();
- FObj item = pInfo.getFO();
- while(item != null && !(item instanceof ListItem)) {
- item = item.getParent();
- }
- if(item == null) {
- throw new PropertyException("label-end() called from outside an fo:list-item");
- }
- Length startIndent = item.properties.get("start-indent").getLength();
-
- LinearCombinationLength labelEnd = new LinearCombinationLength();
+ FObj item = pInfo.getFO();
+ while (item != null &&!(item instanceof ListItem)) {
+ item = item.getParent();
+ }
+ if (item == null) {
+ throw new PropertyException("label-end() called from outside an fo:list-item");
+ }
+ Length startIndent = item.properties.get("start-indent").getLength();
- // Should be CONTAINING_REFAREA but that doesn't work
- LengthBase base = new LengthBase(item, pInfo.getPropertyList(),
- LengthBase.CONTAINING_BOX);
- PercentLength refWidth = new PercentLength(1.0, base);
+ LinearCombinationLength labelEnd = new LinearCombinationLength();
- labelEnd.addTerm(1.0, refWidth);
- labelEnd.addTerm(-1.0, distance);
- labelEnd.addTerm(-1.0, startIndent);
- labelEnd.addTerm(1.0, separation);
+ // Should be CONTAINING_REFAREA but that doesn't work
+ LengthBase base = new LengthBase(item, pInfo.getPropertyList(),
+ LengthBase.CONTAINING_BOX);
+ PercentLength refWidth = new PercentLength(1.0, base);
- return new LengthProperty(labelEnd);
+ labelEnd.addTerm(1.0, refWidth);
+ labelEnd.addTerm(-1.0, distance);
+ labelEnd.addTerm(-1.0, startIndent);
+ labelEnd.addTerm(1.0, separation);
+
+ return new LengthProperty(labelEnd);
}
+
}
diff --git a/src/org/apache/fop/fo/expr/MaxFunction.java b/src/org/apache/fop/fo/expr/MaxFunction.java
index 2a986aee7..1a145a567 100644
--- a/src/org/apache/fop/fo/expr/MaxFunction.java
+++ b/src/org/apache/fop/fo/expr/MaxFunction.java
@@ -1,70 +1,28 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
public class MaxFunction extends FunctionBase {
- public int nbArgs() { return 2; }
+ public int nbArgs() {
+ return 2;
+ }
- // Handle "numerics" if no proportional/percent parts!
- public Property eval(Property[] args, PropertyInfo pInfo)
- throws PropertyException
- {
- Numeric n1 = args[0].getNumeric();
- Numeric n2 = args[1].getNumeric();
- if (n1 == null || n2 == null)
- throw new PropertyException("Non numeric operands to max function");
- return new NumericProperty(n1.max(n2));
- }
+ // Handle "numerics" if no proportional/percent parts!
+ public Property eval(Property[] args,
+ PropertyInfo pInfo) throws PropertyException {
+ Numeric n1 = args[0].getNumeric();
+ Numeric n2 = args[1].getNumeric();
+ if (n1 == null || n2 == null)
+ throw new PropertyException("Non numeric operands to max function");
+ return new NumericProperty(n1.max(n2));
+ }
-}
+}
diff --git a/src/org/apache/fop/fo/expr/MinFunction.java b/src/org/apache/fop/fo/expr/MinFunction.java
index 05643b225..4691e7588 100644
--- a/src/org/apache/fop/fo/expr/MinFunction.java
+++ b/src/org/apache/fop/fo/expr/MinFunction.java
@@ -1,69 +1,28 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
public class MinFunction extends FunctionBase {
- public int nbArgs() { return 2; }
+ public int nbArgs() {
+ return 2;
+ }
- // Handle "numerics" if no proportional/percent parts!
- public Property eval(Property[] args, PropertyInfo pInfo)
- throws PropertyException {
- Numeric n1 = args[0].getNumeric();
- Numeric n2 = args[1].getNumeric();
- if (n1 == null || n2 == null)
- throw new PropertyException("Non numeric operands to min function");
- return new NumericProperty(n1.min(n2));
- }
+ // Handle "numerics" if no proportional/percent parts!
+ public Property eval(Property[] args,
+ PropertyInfo pInfo) throws PropertyException {
+ Numeric n1 = args[0].getNumeric();
+ Numeric n2 = args[1].getNumeric();
+ if (n1 == null || n2 == null)
+ throw new PropertyException("Non numeric operands to min function");
+ return new NumericProperty(n1.min(n2));
+ }
-}
+}
diff --git a/src/org/apache/fop/fo/expr/NCnameProperty.java b/src/org/apache/fop/fo/expr/NCnameProperty.java
index abfcbcf85..aa2b64325 100644
--- a/src/org/apache/fop/fo/expr/NCnameProperty.java
+++ b/src/org/apache/fop/fo/expr/NCnameProperty.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
@@ -55,26 +12,26 @@ import org.apache.fop.datatypes.ColorType;
public class NCnameProperty extends Property {
- private final String ncName;
+ private final String ncName;
- public NCnameProperty(String ncName) {
- this.ncName = ncName;
- }
+ public NCnameProperty(String ncName) {
+ this.ncName = ncName;
+ }
- public ColorType getColor() throws PropertyException {
- // If a system color, return the corresponding value
- throw new PropertyException("Not a Color");
- }
+ public ColorType getColor() throws PropertyException {
+ // If a system color, return the corresponding value
+ throw new PropertyException("Not a Color");
+ }
- /**
- * Return the name as a String (should be specified with quotes!)
- */
- public String getString() {
- return this.ncName;
- }
+ /**
+ * Return the name as a String (should be specified with quotes!)
+ */
+ public String getString() {
+ return this.ncName;
+ }
- public String getNCname() {
- return this.ncName;
- }
+ public String getNCname() {
+ return this.ncName;
+ }
}
diff --git a/src/org/apache/fop/fo/expr/NearestSpecPropFunction.java b/src/org/apache/fop/fo/expr/NearestSpecPropFunction.java
index 0c62b346f..d4be00503 100644
--- a/src/org/apache/fop/fo/expr/NearestSpecPropFunction.java
+++ b/src/org/apache/fop/fo/expr/NearestSpecPropFunction.java
@@ -1,71 +1,29 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
public class NearestSpecPropFunction extends FunctionBase {
- public int nbArgs() { return 1; }
+ public int nbArgs() {
+ return 1;
+ }
- public Property eval(Property[] args, PropertyInfo pInfo)
- throws PropertyException
- {
- String propName = args[0].getString();
- if (propName == null) {
- throw new PropertyException("Incorrect parameter to from-nearest-specified-value function");
+ public Property eval(Property[] args,
+ PropertyInfo pInfo) throws PropertyException {
+ String propName = args[0].getString();
+ if (propName == null) {
+ throw new PropertyException("Incorrect parameter to from-nearest-specified-value function");
+ }
+ // NOTE: special cases for shorthand property
+ // Should return COMPUTED VALUE
+ return pInfo.getPropertyList().getNearestSpecified(propName);
}
- // NOTE: special cases for shorthand property
- // Should return COMPUTED VALUE
- return pInfo.getPropertyList().getNearestSpecified(propName);
- }
-}
+}
diff --git a/src/org/apache/fop/fo/expr/Numeric.java b/src/org/apache/fop/fo/expr/Numeric.java
index f13ccbc76..845327bff 100644
--- a/src/org/apache/fop/fo/expr/Numeric.java
+++ b/src/org/apache/fop/fo/expr/Numeric.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
@@ -71,336 +28,342 @@ import org.apache.fop.datatypes.PercentBase;
* It supports basic arithmetic operations involving Numerics.
*/
public class Numeric {
- // Bit fields
- public static final int ABS_LENGTH = 1; // abs units (or number)
- public static final int PC_LENGTH=2; // Percentage
- public static final int TCOL_LENGTH=4; // Table units
-
- private int valType ;
- private double absValue ;
- private double pcValue ;
- private PercentBase pcBase=null; // base value for PC_LENGTH component
- private double tcolValue;
- private int dim;
-
-
- /**
- * Construct a Numeric object by specifying one or more components,
- * including absolute length, percent length, table units.
- * @param valType A combination of bits representing the value types.
- * @param absValue The value of a Number or resolved Length value if
- * the ABS_LENGTH flag is set.
- * @param pcValue The decimal percent value if the PC_LENGTH flag is set
- * @param tcolValue The decimal table unit value if the TCOL_LENGTH flag
- * is set.
- * @param dim The dimension of the value. 0 for a Number, 1 for a Length
- * (any type), >1, <0 if Lengths have been multiplied or divided.
- * @pcBase The PercentBase object used to calculate an actual value for
- * a PC_LENGTH.
- */
- protected Numeric(int valType, double absValue,
- double pcValue, double tcolValue, int dim,
- PercentBase pcBase) {
- this.valType = valType;
- this.absValue = absValue;
- this.pcValue = pcValue;
- this.tcolValue = tcolValue;
- this.dim = dim;
- this.pcBase = pcBase;
- }
-
- /**
- * Construct a Numeric object of dimension 0 from a double.
- * @param valType A combination of bits representing the value types.
- * @param absValue The value of a Number or resolved Length value.
- */
- /***
- protected Numeric(int valType, double absValue) {
- this.valType = valType;
- this.absValue = absValue;
- }
- ***/
+ // Bit fields
+ public static final int ABS_LENGTH = 1; // abs units (or number)
+ public static final int PC_LENGTH = 2; // Percentage
+ public static final int TCOL_LENGTH = 4; // Table units
- /**
- * Construct a Numeric object from a Number.
- * @param num The number.
- */
- public Numeric(Number num) {
- this(ABS_LENGTH, num.doubleValue(), 0.0, 0.0, 0, null);
- }
+ private int valType;
+ private double absValue;
+ private double pcValue;
+ private PercentBase pcBase = null; // base value for PC_LENGTH component
+ private double tcolValue;
+ private int dim;
- /**
- * Construct a Numeric object from a Length.
- * @param l The Length.
- */
- public Numeric(Length l) {
- this(ABS_LENGTH, (double)l.mvalue(), 0.0, 0.0, 1, null);
- }
- /**
- * Construct a Numeric object from a PercentLength.
- * @param pclen The PercentLength.
- */
- public Numeric(PercentLength pclen) {
- this(PC_LENGTH, 0.0, pclen.value(), 0.0, 1, pclen.getBaseLength());
- }
+ /**
+ * Construct a Numeric object by specifying one or more components,
+ * including absolute length, percent length, table units.
+ * @param valType A combination of bits representing the value types.
+ * @param absValue The value of a Number or resolved Length value if
+ * the ABS_LENGTH flag is set.
+ * @param pcValue The decimal percent value if the PC_LENGTH flag is set
+ * @param tcolValue The decimal table unit value if the TCOL_LENGTH flag
+ * is set.
+ * @param dim The dimension of the value. 0 for a Number, 1 for a Length
+ * (any type), >1, <0 if Lengths have been multiplied or divided.
+ * @pcBase The PercentBase object used to calculate an actual value for
+ * a PC_LENGTH.
+ */
+ protected Numeric(int valType, double absValue, double pcValue,
+ double tcolValue, int dim, PercentBase pcBase) {
+ this.valType = valType;
+ this.absValue = absValue;
+ this.pcValue = pcValue;
+ this.tcolValue = tcolValue;
+ this.dim = dim;
+ this.pcBase = pcBase;
+ }
- /**
- * Construct a Numeric object from a TableColLength.
- * @param tclen The TableColLength.
- */
- public Numeric(TableColLength tclen) {
- this(TCOL_LENGTH, 0.0, 0.0, tclen.getTableUnits(), 1, null);
- }
+ /**
+ * Construct a Numeric object of dimension 0 from a double.
+ * @param valType A combination of bits representing the value types.
+ * @param absValue The value of a Number or resolved Length value.
+ */
+ /**
+ * *
+ * protected Numeric(int valType, double absValue) {
+ * this.valType = valType;
+ * this.absValue = absValue;
+ * }
+ */
- /**
- * Return the current value as a Length if possible. This constructs
- * a new Length or Length subclass based on the current value type
- * of the Numeric.
- * If the stored value has a unit dimension other than 1, null
- * is returned.
- */
- public Length asLength() {
- if (dim == 1) {
- if (valType == ABS_LENGTH) {
- return new Length((int)absValue);
- }
- PercentLength pclen = null;
- if ((valType & PC_LENGTH)!=0) {
- pclen = new PercentLength(pcValue, pcBase);
- if (valType == PC_LENGTH)
- return pclen;
- }
- if ((valType & TCOL_LENGTH) != 0) {
- return new TableColLength((int)absValue, pclen, tcolValue);
- }
- return new MixedLength((int)absValue, pclen);
- }
- else {
- // or throw exception???
- // can't make Length if dimension != 1
- return null;
+ /**
+ * Construct a Numeric object from a Number.
+ * @param num The number.
+ */
+ public Numeric(Number num) {
+ this(ABS_LENGTH, num.doubleValue(), 0.0, 0.0, 0, null);
}
- }
- /**
- * Return the current value as a Number if possible.
- * Calls asDouble().
- */
- public Number asNumber() {
- return asDouble();
- }
- public Double asDouble() {
- if (dim == 0 && valType==ABS_LENGTH) {
- return new Double(absValue);
- }
- else {
- // or throw exception???
- // can't make Number if dimension != 0
- return null;
+ /**
+ * Construct a Numeric object from a Length.
+ * @param l The Length.
+ */
+ public Numeric(Length l) {
+ this(ABS_LENGTH, (double)l.mvalue(), 0.0, 0.0, 1, null);
}
- }
- /**
- * Return the current value as a Integer if possible.
- * If the unit dimension is 0 and the value type is ABSOLUTE, an Integer
- * is returned. Otherwise null is returned. Note: the current value is
- * truncated if necessary to make an integer value.
- */
- /**
- public Integer asInteger() {
- if (dim == 0 && valType==ABS_LENGTH) {
- return new Integer((int)absValue);
+ /**
+ * Construct a Numeric object from a PercentLength.
+ * @param pclen The PercentLength.
+ */
+ public Numeric(PercentLength pclen) {
+ this(PC_LENGTH, 0.0, pclen.value(), 0.0, 1, pclen.getBaseLength());
}
- else {
- // or throw exception???
- // can't make Number if dimension != 0
- return null;
- }
- }
- **/
- /**
- * Return a boolean value indiciating whether the currently stored
- * value consists of different "types" of values (absolute, percent,
- * and/or table-unit.)
- */
- private boolean isMixedType() {
- int ntype = 0;
- for (int t = valType; t!=0; t=t>>1) {
- if ((t & 1) != 0) ++ntype;
+ /**
+ * Construct a Numeric object from a TableColLength.
+ * @param tclen The TableColLength.
+ */
+ public Numeric(TableColLength tclen) {
+ this(TCOL_LENGTH, 0.0, 0.0, tclen.getTableUnits(), 1, null);
}
- return ntype>1;
- }
- /**
- * Subtract the operand from the current value and return a new Numeric
- * representing the result.
- * @param op The value to subtract.
- * @return A Numeric representing the result.
- * @throws PropertyException If the dimension of the operand is different
- * from the dimension of this Numeric.
- */
- public Numeric subtract(Numeric op) throws PropertyException {
- // Check of same dimension
- // Add together absolute and table units
- // What about percentages??? Treat as colUnits if they can't be
- // in same property!
- if (dim == op.dim) {
- PercentBase npcBase = ((valType & PC_LENGTH)!=0)? pcBase : op.pcBase;
- // Subtract each type of value
- return new Numeric(valType|op.valType, absValue-op.absValue,
- pcValue-op.pcValue,
- tcolValue-op.tcolValue,dim, npcBase);
- }
- else {
- throw new PropertyException("Can't add Numerics of different dimensions");
- }
- }
- /**
- * Add the operand from the current value and return a new Numeric
- * representing the result.
- * @param op The value to add.
- * @return A Numeric representing the result.
- * @throws PropertyException If the dimension of the operand is different
- * from the dimension of this Numeric.
- */
- public Numeric add(Numeric op) throws PropertyException {
- // Check of same dimension
- // Add together absolute and table units
- // What about percentages??? Treat as colUnits if they can't be
- // in same property!
- if (dim == op.dim) {
- PercentBase npcBase = ((valType & PC_LENGTH)!=0)? pcBase : op.pcBase;
- // Add each type of value
- return new Numeric(valType | op.valType, absValue+op.absValue,
- pcValue+op.pcValue,
- tcolValue+op.tcolValue, dim, npcBase);
- }
- else {
- throw new PropertyException("Can't add Numerics of different dimensions");
- }
- }
- /**
- * Multiply the the current value by the operand and return a new Numeric
- * representing the result.
- * @param op The multiplier.
- * @return A Numeric representing the result.
- * @throws PropertyException If both Numerics have "mixed" type.
- */
- public Numeric multiply(Numeric op) throws PropertyException {
- // Multiply together absolute units and add dimensions (exponents)
- // What about percentages??? Treat as colUnits if they can't be
- // in same property!
- if (dim == 0) {
- // This is a dimensionless quantity, ie. a "Number"
- return new Numeric(op.valType, absValue*op.absValue,
- absValue*op.pcValue,
- absValue*op.tcolValue, op.dim,
- op.pcBase);
+ /**
+ * Return the current value as a Length if possible. This constructs
+ * a new Length or Length subclass based on the current value type
+ * of the Numeric.
+ * If the stored value has a unit dimension other than 1, null
+ * is returned.
+ */
+ public Length asLength() {
+ if (dim == 1) {
+ if (valType == ABS_LENGTH) {
+ return new Length((int)absValue);
+ }
+ PercentLength pclen = null;
+ if ((valType & PC_LENGTH) != 0) {
+ pclen = new PercentLength(pcValue, pcBase);
+ if (valType == PC_LENGTH)
+ return pclen;
+ }
+ if ((valType & TCOL_LENGTH) != 0) {
+ return new TableColLength((int)absValue, pclen, tcolValue);
+ }
+ return new MixedLength((int)absValue, pclen);
+ } else {
+ // or throw exception???
+ // can't make Length if dimension != 1
+ return null;
+ }
}
- else if (op.dim == 0) {
- double opval = op.absValue;
- return new Numeric(valType, opval*absValue,
- opval*pcValue, opval*tcolValue, dim, pcBase);
+
+ /**
+ * Return the current value as a Number if possible.
+ * Calls asDouble().
+ */
+ public Number asNumber() {
+ return asDouble();
}
- else if (valType == op.valType && !isMixedType()) {
- // Check same relbase and pcbase ???
- PercentBase npcBase = ((valType & PC_LENGTH)!=0)? pcBase : op.pcBase;
- return new Numeric(valType, absValue * op.absValue,
- pcValue*op.pcValue,
- tcolValue*op.tcolValue,dim+op.dim,
- npcBase);
+
+ public Double asDouble() {
+ if (dim == 0 && valType == ABS_LENGTH) {
+ return new Double(absValue);
+ } else {
+ // or throw exception???
+ // can't make Number if dimension != 0
+ return null;
+ }
}
- else {
- throw new PropertyException("Can't multiply mixed Numerics");
+
+ /**
+ * Return the current value as a Integer if possible.
+ * If the unit dimension is 0 and the value type is ABSOLUTE, an Integer
+ * is returned. Otherwise null is returned. Note: the current value is
+ * truncated if necessary to make an integer value.
+ */
+
+ /**
+ * public Integer asInteger() {
+ * if (dim == 0 && valType==ABS_LENGTH) {
+ * return new Integer((int)absValue);
+ * }
+ * else {
+ * // or throw exception???
+ * // can't make Number if dimension != 0
+ * return null;
+ * }
+ * }
+ */
+
+ /**
+ * Return a boolean value indiciating whether the currently stored
+ * value consists of different "types" of values (absolute, percent,
+ * and/or table-unit.)
+ */
+ private boolean isMixedType() {
+ int ntype = 0;
+ for (int t = valType; t != 0; t = t >> 1) {
+ if ((t & 1) != 0)
+ ++ntype;
+ }
+ return ntype > 1;
}
- }
- /**
- * Divide the the current value by the operand and return a new Numeric
- * representing the result.
- * @param op The divisor.
- * @return A Numeric representing the result.
- * @throws PropertyException If both Numerics have "mixed" type.
- */
- public Numeric divide(Numeric op) throws PropertyException {
- // Multiply together absolute units and add dimensions (exponents)
- // What about percentages??? Treat as colUnits if they can't be
- // in same property!
- if (dim == 0) {
- // This is a dimensionless quantity, ie. a "Number"
- return new Numeric(op.valType, absValue/op.absValue,
- absValue/op.pcValue,
- absValue/op.tcolValue, -op.dim, op.pcBase);
+ /**
+ * Subtract the operand from the current value and return a new Numeric
+ * representing the result.
+ * @param op The value to subtract.
+ * @return A Numeric representing the result.
+ * @throws PropertyException If the dimension of the operand is different
+ * from the dimension of this Numeric.
+ */
+ public Numeric subtract(Numeric op) throws PropertyException {
+ // Check of same dimension
+ // Add together absolute and table units
+ // What about percentages??? Treat as colUnits if they can't be
+ // in same property!
+ if (dim == op.dim) {
+ PercentBase npcBase = ((valType & PC_LENGTH) != 0) ? pcBase
+ : op.pcBase;
+ // Subtract each type of value
+ return new Numeric(valType | op.valType, absValue - op.absValue,
+ pcValue - op.pcValue,
+ tcolValue - op.tcolValue, dim, npcBase);
+ } else {
+ throw new PropertyException("Can't add Numerics of different dimensions");
+ }
}
- else if (op.dim == 0) {
- double opval = op.absValue;
- return new Numeric(valType, absValue/opval,
- pcValue/opval, tcolValue/opval, dim, pcBase);
+
+ /**
+ * Add the operand from the current value and return a new Numeric
+ * representing the result.
+ * @param op The value to add.
+ * @return A Numeric representing the result.
+ * @throws PropertyException If the dimension of the operand is different
+ * from the dimension of this Numeric.
+ */
+ public Numeric add(Numeric op) throws PropertyException {
+ // Check of same dimension
+ // Add together absolute and table units
+ // What about percentages??? Treat as colUnits if they can't be
+ // in same property!
+ if (dim == op.dim) {
+ PercentBase npcBase = ((valType & PC_LENGTH) != 0) ? pcBase
+ : op.pcBase;
+ // Add each type of value
+ return new Numeric(valType | op.valType, absValue + op.absValue,
+ pcValue + op.pcValue,
+ tcolValue + op.tcolValue, dim, npcBase);
+ } else {
+ throw new PropertyException("Can't add Numerics of different dimensions");
+ }
}
- else if (valType == op.valType && !isMixedType()) {
- PercentBase npcBase = ((valType & PC_LENGTH)!=0)? pcBase : op.pcBase;
- return new Numeric(valType,
- (valType==ABS_LENGTH? absValue/op.absValue:0.0),
- (valType==PC_LENGTH? pcValue/op.pcValue:0.0),
- (valType==TCOL_LENGTH? tcolValue/op.tcolValue:0.0),
- dim-op.dim, npcBase);
+
+ /**
+ * Multiply the the current value by the operand and return a new Numeric
+ * representing the result.
+ * @param op The multiplier.
+ * @return A Numeric representing the result.
+ * @throws PropertyException If both Numerics have "mixed" type.
+ */
+ public Numeric multiply(Numeric op) throws PropertyException {
+ // Multiply together absolute units and add dimensions (exponents)
+ // What about percentages??? Treat as colUnits if they can't be
+ // in same property!
+ if (dim == 0) {
+ // This is a dimensionless quantity, ie. a "Number"
+ return new Numeric(op.valType, absValue * op.absValue,
+ absValue * op.pcValue,
+ absValue * op.tcolValue, op.dim, op.pcBase);
+ } else if (op.dim == 0) {
+ double opval = op.absValue;
+ return new Numeric(valType, opval * absValue, opval * pcValue,
+ opval * tcolValue, dim, pcBase);
+ } else if (valType == op.valType &&!isMixedType()) {
+ // Check same relbase and pcbase ???
+ PercentBase npcBase = ((valType & PC_LENGTH) != 0) ? pcBase
+ : op.pcBase;
+ return new Numeric(valType, absValue * op.absValue,
+ pcValue * op.pcValue,
+ tcolValue * op.tcolValue, dim + op.dim,
+ npcBase);
+ } else {
+ throw new PropertyException("Can't multiply mixed Numerics");
+ }
}
- else {
- throw new PropertyException("Can't divide mixed Numerics.");
+
+ /**
+ * Divide the the current value by the operand and return a new Numeric
+ * representing the result.
+ * @param op The divisor.
+ * @return A Numeric representing the result.
+ * @throws PropertyException If both Numerics have "mixed" type.
+ */
+ public Numeric divide(Numeric op) throws PropertyException {
+ // Multiply together absolute units and add dimensions (exponents)
+ // What about percentages??? Treat as colUnits if they can't be
+ // in same property!
+ if (dim == 0) {
+ // This is a dimensionless quantity, ie. a "Number"
+ return new Numeric(op.valType, absValue / op.absValue,
+ absValue / op.pcValue,
+ absValue / op.tcolValue, -op.dim, op.pcBase);
+ } else if (op.dim == 0) {
+ double opval = op.absValue;
+ return new Numeric(valType, absValue / opval, pcValue / opval,
+ tcolValue / opval, dim, pcBase);
+ } else if (valType == op.valType &&!isMixedType()) {
+ PercentBase npcBase = ((valType & PC_LENGTH) != 0) ? pcBase
+ : op.pcBase;
+ return new Numeric(valType,
+ (valType == ABS_LENGTH ? absValue / op.absValue : 0.0),
+ (valType == PC_LENGTH ? pcValue / op.pcValue : 0.0),
+ (valType == TCOL_LENGTH ? tcolValue / op.tcolValue : 0.0),
+ dim - op.dim, npcBase);
+ } else {
+ throw new PropertyException("Can't divide mixed Numerics.");
+ }
}
- }
- /**
- * Return the absolute value of this Numeric.
- * @return A new Numeric object representing the absolute value.
- */
- public Numeric abs() {
- return new Numeric(valType, Math.abs(absValue),
- Math.abs(pcValue), Math.abs(tcolValue), dim, pcBase);
- }
+ /**
+ * Return the absolute value of this Numeric.
+ * @return A new Numeric object representing the absolute value.
+ */
+ public Numeric abs() {
+ return new Numeric(valType, Math.abs(absValue), Math.abs(pcValue),
+ Math.abs(tcolValue), dim, pcBase);
+ }
- /**
- * Return a Numeric which is the maximum of the current value and the
- * operand.
- * @throws PropertyException If the dimensions or value types of the
- * object and the operand are different.
- */
- public Numeric max(Numeric op) throws PropertyException {
- double rslt = 0.0;
- // Only compare if have same dimension and value type!
- if (dim == op.dim && valType == op.valType && !isMixedType()) {
- if (valType==ABS_LENGTH) rslt = absValue - op.absValue;
- else if (valType==PC_LENGTH) rslt = pcValue - op.pcValue;
- else if (valType==TCOL_LENGTH) rslt = tcolValue - op.tcolValue;
- if (rslt > 0.0)
- return this;
- else return op;
+ /**
+ * Return a Numeric which is the maximum of the current value and the
+ * operand.
+ * @throws PropertyException If the dimensions or value types of the
+ * object and the operand are different.
+ */
+ public Numeric max(Numeric op) throws PropertyException {
+ double rslt = 0.0;
+ // Only compare if have same dimension and value type!
+ if (dim == op.dim && valType == op.valType &&!isMixedType()) {
+ if (valType == ABS_LENGTH)
+ rslt = absValue - op.absValue;
+ else if (valType == PC_LENGTH)
+ rslt = pcValue - op.pcValue;
+ else if (valType == TCOL_LENGTH)
+ rslt = tcolValue - op.tcolValue;
+ if (rslt > 0.0)
+ return this;
+ else
+ return op;
+ }
+ throw new PropertyException("Arguments to max() must have same dimension and value type.");
}
- throw new PropertyException("Arguments to max() must have same dimension and value type.");
- }
- /**
- * Return a Numeric which is the minimum of the current value and the
- * operand.
- * @throws PropertyException If the dimensions or value types of the
- * object and the operand are different.
- */
- public Numeric min(Numeric op) throws PropertyException {
- double rslt = 0.0;
- // Only compare if have same dimension and value type!
- if (dim == op.dim && valType == op.valType && !isMixedType()) {
- if (valType==ABS_LENGTH) rslt = absValue - op.absValue;
- else if (valType==PC_LENGTH) rslt = pcValue - op.pcValue;
- else if (valType==TCOL_LENGTH) rslt = tcolValue - op.tcolValue;
- if (rslt > 0.0)
- return op;
- else return this;
+ /**
+ * Return a Numeric which is the minimum of the current value and the
+ * operand.
+ * @throws PropertyException If the dimensions or value types of the
+ * object and the operand are different.
+ */
+ public Numeric min(Numeric op) throws PropertyException {
+ double rslt = 0.0;
+ // Only compare if have same dimension and value type!
+ if (dim == op.dim && valType == op.valType &&!isMixedType()) {
+ if (valType == ABS_LENGTH)
+ rslt = absValue - op.absValue;
+ else if (valType == PC_LENGTH)
+ rslt = pcValue - op.pcValue;
+ else if (valType == TCOL_LENGTH)
+ rslt = tcolValue - op.tcolValue;
+ if (rslt > 0.0)
+ return op;
+ else
+ return this;
+ }
+ throw new PropertyException("Arguments to min() must have same dimension and value type.");
}
- throw new PropertyException("Arguments to min() must have same dimension and value type.");
- }
}
diff --git a/src/org/apache/fop/fo/expr/NumericProperty.java b/src/org/apache/fop/fo/expr/NumericProperty.java
index 49d08920d..524ec0c20 100644
--- a/src/org/apache/fop/fo/expr/NumericProperty.java
+++ b/src/org/apache/fop/fo/expr/NumericProperty.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo.expr;
@@ -55,30 +11,31 @@ import org.apache.fop.datatypes.Length;
import org.apache.fop.datatypes.ColorType;
class NumericProperty extends Property {
- private Numeric numeric ;
+ private Numeric numeric;
+
+ NumericProperty(Numeric value) {
+ this.numeric = value;
+ }
- NumericProperty(Numeric value) {
- this.numeric = value;
- }
+ public Numeric getNumeric() {
+ return this.numeric;
+ }
- public Numeric getNumeric() {
- return this.numeric;
- }
+ public Number getNumber() {
+ return numeric.asNumber();
+ }
- public Number getNumber() {
- return numeric.asNumber();
- }
+ public Length getLength() {
+ return numeric.asLength();
+ }
- public Length getLength() {
- return numeric.asLength();
- }
+ public ColorType getColorType() {
+ // try converting to numeric number and then to color
+ return null;
+ }
- public ColorType getColorType() {
- // try converting to numeric number and then to color
- return null;
- }
+ public Object getObject() {
+ return this.numeric;
+ }
- public Object getObject() {
- return this.numeric;
- }
}
diff --git a/src/org/apache/fop/fo/expr/PPColWidthFunction.java b/src/org/apache/fop/fo/expr/PPColWidthFunction.java
index 1e2501d42..c3bd3eada 100644
--- a/src/org/apache/fop/fo/expr/PPColWidthFunction.java
+++ b/src/org/apache/fop/fo/expr/PPColWidthFunction.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
@@ -57,20 +14,21 @@ import org.apache.fop.datatypes.TableColLength;
public class PPColWidthFunction extends FunctionBase {
- public int nbArgs() { return 1; }
-
- public Property eval(Property[] args, PropertyInfo pInfo)
- throws PropertyException
- {
- Number d = args[0].getNumber();
- if (d == null) {
- throw new PropertyException("Non number operand to proportional-column-width function");
+ public int nbArgs() {
+ return 1;
}
- if (!pInfo.getPropertyList().getElement().equals("table-column")) {
- throw new PropertyException("proportional-column-width function may only be used on table-column FO");
+
+ public Property eval(Property[] args,
+ PropertyInfo pInfo) throws PropertyException {
+ Number d = args[0].getNumber();
+ if (d == null) {
+ throw new PropertyException("Non number operand to proportional-column-width function");
+ }
+ if (!pInfo.getPropertyList().getElement().equals("table-column")) {
+ throw new PropertyException("proportional-column-width function may only be used on table-column FO");
+ }
+ // Check if table-layout is "fixed"...
+ return new LengthProperty(new TableColLength(d.doubleValue()));
}
- // Check if table-layout is "fixed"...
- return new LengthProperty(new TableColLength(d.doubleValue()));
- }
-}
+}
diff --git a/src/org/apache/fop/fo/expr/PropertyException.java b/src/org/apache/fop/fo/expr/PropertyException.java
index 2e0f17b50..d73c37734 100644
--- a/src/org/apache/fop/fo/expr/PropertyException.java
+++ b/src/org/apache/fop/fo/expr/PropertyException.java
@@ -1,57 +1,15 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
public class PropertyException extends Exception {
- public PropertyException(String detail) {
- super(detail);
- }
+ public PropertyException(String detail) {
+ super(detail);
+ }
+
}
diff --git a/src/org/apache/fop/fo/expr/PropertyInfo.java b/src/org/apache/fop/fo/expr/PropertyInfo.java
index 5416ebfbe..747ec17af 100644
--- a/src/org/apache/fop/fo/expr/PropertyInfo.java
+++ b/src/org/apache/fop/fo/expr/PropertyInfo.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import java.util.Stack;
@@ -65,68 +22,73 @@ import org.apache.fop.datatypes.PercentBase;
* built, and the FObj parent of the FObj for which the property is being set.
*/
public class PropertyInfo {
- private Property.Maker maker;
- private PropertyList plist;
- private FObj fo;
- private Stack stkFunction; // Stack of functions being evaluated
+ private Property.Maker maker;
+ private PropertyList plist;
+ private FObj fo;
+ private Stack stkFunction; // Stack of functions being evaluated
- public PropertyInfo(Property.Maker maker, PropertyList plist, FObj fo) {
- this.maker = maker;
- this.plist = plist;
- this.fo = fo;
- }
+ public PropertyInfo(Property.Maker maker, PropertyList plist, FObj fo) {
+ this.maker = maker;
+ this.plist = plist;
+ this.fo = fo;
+ }
- /**
- * Return whether this property inherits specified values.
- * Propagates to the Maker.
- * @return true if the property inherits specified values, false if it
- * inherits computed values.
- */
- public boolean inheritsSpecified() {
- return maker.inheritsSpecified();
- }
+ /**
+ * Return whether this property inherits specified values.
+ * Propagates to the Maker.
+ * @return true if the property inherits specified values, false if it
+ * inherits computed values.
+ */
+ public boolean inheritsSpecified() {
+ return maker.inheritsSpecified();
+ }
- /**
- * Return the PercentBase object used to calculate the absolute value from
- * a percent specification.
- * Propagates to the Maker.
- * @return The PercentBase object or null if percentLengthOK()=false.
- */
- public PercentBase getPercentBase() {
- PercentBase pcbase = getFunctionPercentBase();
- return (pcbase != null)? pcbase : maker.getPercentBase(fo, plist);
- }
+ /**
+ * Return the PercentBase object used to calculate the absolute value from
+ * a percent specification.
+ * Propagates to the Maker.
+ * @return The PercentBase object or null if percentLengthOK()=false.
+ */
+ public PercentBase getPercentBase() {
+ PercentBase pcbase = getFunctionPercentBase();
+ return (pcbase != null) ? pcbase : maker.getPercentBase(fo, plist);
+ }
- /**
- * Return the current font-size value as base units (milli-points).
- */
- public int currentFontSize() {
- return plist.get("font-size").getLength().mvalue();
- }
+ /**
+ * Return the current font-size value as base units (milli-points).
+ */
+ public int currentFontSize() {
+ return plist.get("font-size").getLength().mvalue();
+ }
- public FObj getFO() { return fo; }
+ public FObj getFO() {
+ return fo;
+ }
- public PropertyList getPropertyList() { return plist; }
+ public PropertyList getPropertyList() {
+ return plist;
+ }
- public void pushFunction(Function func) {
- if (stkFunction == null) {
- stkFunction = new Stack();
+ public void pushFunction(Function func) {
+ if (stkFunction == null) {
+ stkFunction = new Stack();
+ }
+ stkFunction.push(func);
}
- stkFunction.push(func);
- }
- public void popFunction() {
- if (stkFunction != null)
- stkFunction.pop();
- }
+ public void popFunction() {
+ if (stkFunction != null)
+ stkFunction.pop();
+ }
- private PercentBase getFunctionPercentBase() {
- if (stkFunction != null) {
- Function f = (Function)stkFunction.peek();
- if (f != null) {
- return f.getPercentBase();
- }
+ private PercentBase getFunctionPercentBase() {
+ if (stkFunction != null) {
+ Function f = (Function)stkFunction.peek();
+ if (f != null) {
+ return f.getPercentBase();
+ }
+ }
+ return null;
}
- return null;
- }
+
}
diff --git a/src/org/apache/fop/fo/expr/PropertyParser.java b/src/org/apache/fop/fo/expr/PropertyParser.java
index 9195a1ada..2d5a89c61 100644
--- a/src/org/apache/fop/fo/expr/PropertyParser.java
+++ b/src/org/apache/fop/fo/expr/PropertyParser.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
import org.apache.fop.fo.Property;
@@ -66,415 +23,420 @@ import java.util.Hashtable;
* XT, an XSLT processor.
*/
public class PropertyParser extends PropertyTokenizer {
- private PropertyInfo propInfo; // Maker and propertyList related info
-
- static private final String RELUNIT = "em";
- static private final Numeric negOne = new Numeric(new Double(-1.0));
- static final private Hashtable functionTable = new Hashtable();
-
- static {
- // Initialize the Hashtable of XSL-defined functions
- functionTable.put("ceiling", new CeilingFunction());
- functionTable.put("floor", new FloorFunction());
- functionTable.put("round", new RoundFunction());
- functionTable.put("min", new MinFunction());
- functionTable.put("max", new MaxFunction());
- functionTable.put("abs", new AbsFunction());
- functionTable.put("rgb", new RGBColorFunction());
- functionTable.put("from-table-column", new FromTableColumnFunction());
- functionTable.put("inherited-property-value", new InheritedPropFunction());
- functionTable.put("from-parent", new FromParentFunction());
- functionTable.put("from-nearest-specified-value", new NearestSpecPropFunction());
- functionTable.put("proportional-column-width", new PPColWidthFunction());
- functionTable.put("label-end", new LabelEndFunction());
- functionTable.put("body-start", new BodyStartFunction());
- // NOTE: used from code generated for corresponding properties
- functionTable.put("_fop-property-value", new FopPropValFunction());
-
- /*** NOT YET IMPLEMENTED!!!
- functionTable.put("icc-color", new ICCcolorFunction());
- functionTable.put("system-color", new SystemColorFunction());
-
- functionTable.put("system-font", new SystemFontFunction());
-
- functionTable.put("merge-property-values", new MergePropsFunction());
- ***/
- }
-
-
- /**
- * Public entrypoint to the Property expression parser.
- * @param expr The specified value (attribute on the xml element).
- * @param propInfo A PropertyInfo object representing the context in
- * which the property expression is to be evaluated.
- * @return A Property object holding the parsed result.
- * @throws PropertyException If the "expr" cannot be parsed as a Property.
- */
- public static Property parse(String expr, PropertyInfo propInfo)
- throws PropertyException {
- return new PropertyParser(expr, propInfo).parseProperty();
- }
-
-
- /**
- * Private constructor. Called by the static parse() method.
- * @param propExpr The specified value (attribute on the xml element).
- * @param propInfo A PropertyInfo object representing the context in
- * which the property expression is to be evaluated.
- */
- private PropertyParser(String propExpr, PropertyInfo pInfo) {
- super(propExpr);
- this.propInfo = pInfo;
- }
-
- /**
- * Parse the property expression described in the instance variables.
- * Note: If the property expression String is empty, a StringProperty
- * object holding an empty String is returned.
- * @return A Property object holding the parsed result.
- * @throws PropertyException If the "expr" cannot be parsed as a Property.
- */
- private Property parseProperty() throws PropertyException {
- next();
- if (currentToken == TOK_EOF) {
- // if prop value is empty string, force to StringProperty
- return new StringProperty("");
+ private PropertyInfo propInfo; // Maker and propertyList related info
+
+ static private final String RELUNIT = "em";
+ static private final Numeric negOne = new Numeric(new Double(-1.0));
+ static final private Hashtable functionTable = new Hashtable();
+
+ static {
+ // Initialize the Hashtable of XSL-defined functions
+ functionTable.put("ceiling", new CeilingFunction());
+ functionTable.put("floor", new FloorFunction());
+ functionTable.put("round", new RoundFunction());
+ functionTable.put("min", new MinFunction());
+ functionTable.put("max", new MaxFunction());
+ functionTable.put("abs", new AbsFunction());
+ functionTable.put("rgb", new RGBColorFunction());
+ functionTable.put("from-table-column", new FromTableColumnFunction());
+ functionTable.put("inherited-property-value",
+ new InheritedPropFunction());
+ functionTable.put("from-parent", new FromParentFunction());
+ functionTable.put("from-nearest-specified-value",
+ new NearestSpecPropFunction());
+ functionTable.put("proportional-column-width",
+ new PPColWidthFunction());
+ functionTable.put("label-end", new LabelEndFunction());
+ functionTable.put("body-start", new BodyStartFunction());
+ // NOTE: used from code generated for corresponding properties
+ functionTable.put("_fop-property-value", new FopPropValFunction());
+
+ /**
+ * * NOT YET IMPLEMENTED!!!
+ * functionTable.put("icc-color", new ICCcolorFunction());
+ * functionTable.put("system-color", new SystemColorFunction());
+ * functionTable.put("system-font", new SystemFontFunction());
+ *
+ * functionTable.put("merge-property-values", new MergePropsFunction());
+ */
}
- ListProperty propList = null;
- while (true) {
- Property prop = parseAdditiveExpr();
- if (currentToken == TOK_EOF) {
- if (propList != null) {
- propList.addProperty(prop);
- return propList;
- }
- else return prop;
- }
- else {
- if (propList == null) {
- propList = new ListProperty(prop);
+
+
+ /**
+ * Public entrypoint to the Property expression parser.
+ * @param expr The specified value (attribute on the xml element).
+ * @param propInfo A PropertyInfo object representing the context in
+ * which the property expression is to be evaluated.
+ * @return A Property object holding the parsed result.
+ * @throws PropertyException If the "expr" cannot be parsed as a Property.
+ */
+ public static Property parse(String expr, PropertyInfo propInfo)
+ throws PropertyException {
+ return new PropertyParser(expr, propInfo).parseProperty();
+ }
+
+
+ /**
+ * Private constructor. Called by the static parse() method.
+ * @param propExpr The specified value (attribute on the xml element).
+ * @param propInfo A PropertyInfo object representing the context in
+ * which the property expression is to be evaluated.
+ */
+ private PropertyParser(String propExpr, PropertyInfo pInfo) {
+ super(propExpr);
+ this.propInfo = pInfo;
+ }
+
+ /**
+ * Parse the property expression described in the instance variables.
+ * Note: If the property expression String is empty, a StringProperty
+ * object holding an empty String is returned.
+ * @return A Property object holding the parsed result.
+ * @throws PropertyException If the "expr" cannot be parsed as a Property.
+ */
+ private Property parseProperty() throws PropertyException {
+ next();
+ if (currentToken == TOK_EOF) {
+ // if prop value is empty string, force to StringProperty
+ return new StringProperty("");
}
- else {
- propList.addProperty(prop);
+ ListProperty propList = null;
+ while (true) {
+ Property prop = parseAdditiveExpr();
+ if (currentToken == TOK_EOF) {
+ if (propList != null) {
+ propList.addProperty(prop);
+ return propList;
+ } else
+ return prop;
+ } else {
+ if (propList == null) {
+ propList = new ListProperty(prop);
+ } else {
+ propList.addProperty(prop);
+ }
+ }
+ // throw new PropertyException("unexpected token");
}
- }
- //throw new PropertyException("unexpected token");
+ // return prop;
}
- //return prop;
- }
-
- /**
- * Try to parse an addition or subtraction expression and return the
- * resulting Property.
- */
- private Property parseAdditiveExpr() throws PropertyException {
- // Evaluate and put result on the operand stack
- Property prop = parseMultiplicativeExpr();
- loop:
- for (;;) {
- switch (currentToken) {
- case TOK_PLUS:
- next();
- prop = evalAddition(prop.getNumeric(),
- parseMultiplicativeExpr().getNumeric() );
- break;
- case TOK_MINUS:
- next();
- prop = evalSubtraction(prop.getNumeric(),
- parseMultiplicativeExpr().getNumeric() );
- break;
- default:
- break loop;
- }
+
+ /**
+ * Try to parse an addition or subtraction expression and return the
+ * resulting Property.
+ */
+ private Property parseAdditiveExpr() throws PropertyException {
+ // Evaluate and put result on the operand stack
+ Property prop = parseMultiplicativeExpr();
+ loop:
+ for (; ; ) {
+ switch (currentToken) {
+ case TOK_PLUS:
+ next();
+ prop = evalAddition(prop.getNumeric(),
+ parseMultiplicativeExpr().getNumeric());
+ break;
+ case TOK_MINUS:
+ next();
+ prop =
+ evalSubtraction(prop.getNumeric(),
+ parseMultiplicativeExpr().getNumeric());
+ break;
+ default:
+ break loop;
+ }
+ }
+ return prop;
}
- return prop;
- }
-
- /**
- * Try to parse a multiply, divide or modulo expression and return
- * the resulting Property.
- */
- private Property parseMultiplicativeExpr() throws PropertyException {
- Property prop = parseUnaryExpr();
- loop:
- for (;;) {
- switch (currentToken) {
- case TOK_DIV:
- next();
- prop = evalDivide(prop.getNumeric(), parseUnaryExpr().getNumeric() );
- break;
- case TOK_MOD:
- next();
- prop = evalModulo(prop.getNumber(), parseUnaryExpr().getNumber() );
- break;
- case TOK_MULTIPLY:
- next();
- prop = evalMultiply(prop.getNumeric(), parseUnaryExpr().getNumeric());
- break;
- default:
- break loop;
- }
+
+ /**
+ * Try to parse a multiply, divide or modulo expression and return
+ * the resulting Property.
+ */
+ private Property parseMultiplicativeExpr() throws PropertyException {
+ Property prop = parseUnaryExpr();
+ loop:
+ for (; ; ) {
+ switch (currentToken) {
+ case TOK_DIV:
+ next();
+ prop = evalDivide(prop.getNumeric(),
+ parseUnaryExpr().getNumeric());
+ break;
+ case TOK_MOD:
+ next();
+ prop = evalModulo(prop.getNumber(),
+ parseUnaryExpr().getNumber());
+ break;
+ case TOK_MULTIPLY:
+ next();
+ prop = evalMultiply(prop.getNumeric(),
+ parseUnaryExpr().getNumeric());
+ break;
+ default:
+ break loop;
+ }
+ }
+ return prop;
}
- return prop;
- }
-
- /**
- * Try to parse a unary minus expression and return the
- * resulting Property.
- */
- private Property parseUnaryExpr() throws PropertyException {
- if (currentToken == TOK_MINUS) {
- next();
- return evalNegate(parseUnaryExpr().getNumeric());
+
+ /**
+ * Try to parse a unary minus expression and return the
+ * resulting Property.
+ */
+ private Property parseUnaryExpr() throws PropertyException {
+ if (currentToken == TOK_MINUS) {
+ next();
+ return evalNegate(parseUnaryExpr().getNumeric());
+ }
+ return parsePrimaryExpr();
}
- return parsePrimaryExpr();
- }
-
-
- /**
- * Checks that the current token is a right parenthesis
- * and throws an exception if this isn't the case.
- */
- private final void expectRpar() throws PropertyException {
- if (currentToken != TOK_RPAR)
- throw new PropertyException("expected )");
- next();
- }
-
- /**
- * Try to parse a primary expression and return the
- * resulting Property.
- * A primary expression is either a parenthesized expression or an
- * expression representing a primitive Property datatype, such as a
- * string literal, an NCname, a number or a unit expression, or a
- * function call expression.
- */
- private Property parsePrimaryExpr() throws PropertyException {
- Property prop;
- switch (currentToken) {
- case TOK_LPAR:
- next();
- prop = parseAdditiveExpr();
- expectRpar();
- return prop;
-
- case TOK_LITERAL:
- prop = new StringProperty(currentTokenValue);
- break;
-
- case TOK_NCNAME:
- // Interpret this in context of the property or do it later?
- prop = new NCnameProperty(currentTokenValue);
- break;
-
- case TOK_FLOAT:
- prop = new NumberProperty(new Double(currentTokenValue));
- break;
-
- case TOK_INTEGER:
- prop = new NumberProperty(new Integer(currentTokenValue));
- break;
-
- case TOK_PERCENT:
- /* Get the length base value object from the Maker. If null, then
- * this property can't have % values. Treat it as a real number.
- */
- double pcval = new Double(currentTokenValue.substring(0,
- currentTokenValue.length()-1)).
- doubleValue()/100.0;
- // LengthBase lbase = this.propInfo.getPercentLengthBase();
- PercentBase pcBase = this.propInfo.getPercentBase();
- if (pcBase != null) {
- if (pcBase.getDimension() == 0) {
- prop = new NumberProperty(pcval * pcBase.getBaseValue());
- }
- else if (pcBase.getDimension() == 1) {
- prop = new LengthProperty(new PercentLength(pcval, pcBase));
- }
- else {
- throw new PropertyException("Illegal percent dimension value");
- }
- }
- else {
- // WARNING? Interpret as a decimal fraction, eg. 50% = .5
- prop = new NumberProperty(pcval);
- }
- break;
-
- case TOK_NUMERIC:
- // A number plus a valid unit name.
- int numLen = currentTokenValue.length()-currentUnitLength;
- String unitPart = currentTokenValue.substring(numLen);
- Double numPart = new Double(currentTokenValue.substring(0,numLen));
- Length length= null;
- if (unitPart.equals(RELUNIT)) {
- length = new Length(numPart.doubleValue(),
- propInfo.currentFontSize());
- }
- else
- length = new Length(numPart.doubleValue(), unitPart);
- if (length == null) {
- throw new PropertyException("unrecognized unit name: "+ currentTokenValue);
- }
- else prop = new LengthProperty(length);
- break;
-
- case TOK_COLORSPEC:
- prop = new ColorTypeProperty(new ColorType(currentTokenValue));
- break;
-
- case TOK_FUNCTION_LPAR:
- {
- Function function = (Function)functionTable.get(currentTokenValue);
- if (function == null) {
- throw new PropertyException("no such function: " + currentTokenValue);
- }
- next();
- // Push new function (for function context: getPercentBase())
- propInfo.pushFunction(function);
- prop = function.eval(parseArgs(function.nbArgs()), propInfo);
- propInfo.popFunction();
- return prop;
- }
- default:
- throw new PropertyException("syntax error");
+
+
+ /**
+ * Checks that the current token is a right parenthesis
+ * and throws an exception if this isn't the case.
+ */
+ private final void expectRpar() throws PropertyException {
+ if (currentToken != TOK_RPAR)
+ throw new PropertyException("expected )");
+ next();
}
- next();
- return prop;
- }
-
- /**
- * Parse a comma separated list of function arguments. Each argument
- * may itself be an expression. This method consumes the closing right
- * parenthesis of the argument list.
- * @param nbArgs The number of arguments expected by the function.
- * @return An array of Property objects representing the arguments
- * found.
- * @throws PropertyException If the number of arguments found isn't equal
- * to the number expected.
- */
- Property[] parseArgs(int nbArgs) throws PropertyException {
- Property[] args = new Property[nbArgs];
- Property prop;
- int i=0;
- if (currentToken == TOK_RPAR) {
- // No args: func()
- next();
+
+ /**
+ * Try to parse a primary expression and return the
+ * resulting Property.
+ * A primary expression is either a parenthesized expression or an
+ * expression representing a primitive Property datatype, such as a
+ * string literal, an NCname, a number or a unit expression, or a
+ * function call expression.
+ */
+ private Property parsePrimaryExpr() throws PropertyException {
+ Property prop;
+ switch (currentToken) {
+ case TOK_LPAR:
+ next();
+ prop = parseAdditiveExpr();
+ expectRpar();
+ return prop;
+
+ case TOK_LITERAL:
+ prop = new StringProperty(currentTokenValue);
+ break;
+
+ case TOK_NCNAME:
+ // Interpret this in context of the property or do it later?
+ prop = new NCnameProperty(currentTokenValue);
+ break;
+
+ case TOK_FLOAT:
+ prop = new NumberProperty(new Double(currentTokenValue));
+ break;
+
+ case TOK_INTEGER:
+ prop = new NumberProperty(new Integer(currentTokenValue));
+ break;
+
+ case TOK_PERCENT:
+ /*
+ * Get the length base value object from the Maker. If null, then
+ * this property can't have % values. Treat it as a real number.
+ */
+ double pcval =
+ new Double(currentTokenValue.substring(0, currentTokenValue.length() - 1)).doubleValue()
+ / 100.0;
+ // LengthBase lbase = this.propInfo.getPercentLengthBase();
+ PercentBase pcBase = this.propInfo.getPercentBase();
+ if (pcBase != null) {
+ if (pcBase.getDimension() == 0) {
+ prop = new NumberProperty(pcval * pcBase.getBaseValue());
+ } else if (pcBase.getDimension() == 1) {
+ prop = new LengthProperty(new PercentLength(pcval,
+ pcBase));
+ } else {
+ throw new PropertyException("Illegal percent dimension value");
+ }
+ } else {
+ // WARNING? Interpret as a decimal fraction, eg. 50% = .5
+ prop = new NumberProperty(pcval);
+ }
+ break;
+
+ case TOK_NUMERIC:
+ // A number plus a valid unit name.
+ int numLen = currentTokenValue.length() - currentUnitLength;
+ String unitPart = currentTokenValue.substring(numLen);
+ Double numPart = new Double(currentTokenValue.substring(0,
+ numLen));
+ Length length = null;
+ if (unitPart.equals(RELUNIT)) {
+ length = new Length(numPart.doubleValue(),
+ propInfo.currentFontSize());
+ } else
+ length = new Length(numPart.doubleValue(), unitPart);
+ if (length == null) {
+ throw new PropertyException("unrecognized unit name: "
+ + currentTokenValue);
+ } else
+ prop = new LengthProperty(length);
+ break;
+
+ case TOK_COLORSPEC:
+ prop = new ColorTypeProperty(new ColorType(currentTokenValue));
+ break;
+
+ case TOK_FUNCTION_LPAR: {
+ Function function =
+ (Function)functionTable.get(currentTokenValue);
+ if (function == null) {
+ throw new PropertyException("no such function: "
+ + currentTokenValue);
+ }
+ next();
+ // Push new function (for function context: getPercentBase())
+ propInfo.pushFunction(function);
+ prop = function.eval(parseArgs(function.nbArgs()), propInfo);
+ propInfo.popFunction();
+ return prop;
+ }
+ default:
+ throw new PropertyException("syntax error");
+ }
+ next();
+ return prop;
+ }
+
+ /**
+ * Parse a comma separated list of function arguments. Each argument
+ * may itself be an expression. This method consumes the closing right
+ * parenthesis of the argument list.
+ * @param nbArgs The number of arguments expected by the function.
+ * @return An array of Property objects representing the arguments
+ * found.
+ * @throws PropertyException If the number of arguments found isn't equal
+ * to the number expected.
+ */
+ Property[] parseArgs(int nbArgs) throws PropertyException {
+ Property[] args = new Property[nbArgs];
+ Property prop;
+ int i = 0;
+ if (currentToken == TOK_RPAR) {
+ // No args: func()
+ next();
+ } else {
+ while (true) {
+
+ prop = parseAdditiveExpr();
+ if (i < nbArgs) {
+ args[i++] = prop;
+ }
+ // ignore extra args
+ if (currentToken != TOK_COMMA)
+ break;
+ next();
+ }
+ expectRpar();
+ }
+ if (nbArgs != i) {
+ throw new PropertyException("Wrong number of args for function");
+ }
+ return args;
}
- else {
- while(true) {
-
- prop = parseAdditiveExpr();
- if (i < nbArgs) {
- args[i++] = prop;
- }
- // ignore extra args
- if (currentToken != TOK_COMMA)
- break;
- next();
- }
- expectRpar();
+
+
+ /**
+ * Evaluate an addition operation. If either of the arguments is null,
+ * this means that it wasn't convertible to a Numeric value.
+ * @param op1 A Numeric object (Number or Length-type object)
+ * @param op2 A Numeric object (Number or Length-type object)
+ * @return A new NumericProperty object holding an object which represents
+ * the sum of the two operands.
+ * @throws PropertyException If either operand is null.
+ */
+ private Property evalAddition(Numeric op1,
+ Numeric op2) throws PropertyException {
+ if (op1 == null || op2 == null)
+ throw new PropertyException("Non numeric operand in addition");
+ return new NumericProperty(op1.add(op2));
+ }
+
+ /**
+ * Evaluate a subtraction operation. If either of the arguments is null,
+ * this means that it wasn't convertible to a Numeric value.
+ * @param op1 A Numeric object (Number or Length-type object)
+ * @param op2 A Numeric object (Number or Length-type object)
+ * @return A new NumericProperty object holding an object which represents
+ * the difference of the two operands.
+ * @throws PropertyException If either operand is null.
+ */
+ private Property evalSubtraction(Numeric op1,
+ Numeric op2) throws PropertyException {
+ if (op1 == null || op2 == null)
+ throw new PropertyException("Non numeric operand in subtraction");
+ return new NumericProperty(op1.subtract(op2));
}
- if (nbArgs != i) {
- throw new PropertyException("Wrong number of args for function");
+
+ /**
+ * Evaluate a unary minus operation. If the argument is null,
+ * this means that it wasn't convertible to a Numeric value.
+ * @param op A Numeric object (Number or Length-type object)
+ * @return A new NumericProperty object holding an object which represents
+ * the negative of the operand (multiplication by *1).
+ * @throws PropertyException If the operand is null.
+ */
+ private Property evalNegate(Numeric op) throws PropertyException {
+ if (op == null)
+ throw new PropertyException("Non numeric operand to unary minus");
+ return new NumericProperty(op.multiply(negOne));
+ }
+
+ /**
+ * Evaluate a multiplication operation. If either of the arguments is null,
+ * this means that it wasn't convertible to a Numeric value.
+ * @param op1 A Numeric object (Number or Length-type object)
+ * @param op2 A Numeric object (Number or Length-type object)
+ * @return A new NumericProperty object holding an object which represents
+ * the product of the two operands.
+ * @throws PropertyException If either operand is null.
+ */
+ private Property evalMultiply(Numeric op1,
+ Numeric op2) throws PropertyException {
+ if (op1 == null || op2 == null)
+ throw new PropertyException("Non numeric operand in multiplication");
+ return new NumericProperty(op1.multiply(op2));
+ }
+
+
+ /**
+ * Evaluate a division operation. If either of the arguments is null,
+ * this means that it wasn't convertible to a Numeric value.
+ * @param op1 A Numeric object (Number or Length-type object)
+ * @param op2 A Numeric object (Number or Length-type object)
+ * @return A new NumericProperty object holding an object which represents
+ * op1 divided by op2.
+ * @throws PropertyException If either operand is null.
+ */
+ private Property evalDivide(Numeric op1,
+ Numeric op2) throws PropertyException {
+ if (op1 == null || op2 == null)
+ throw new PropertyException("Non numeric operand in division");
+ return new NumericProperty(op1.divide(op2));
+ }
+
+ /**
+ * Evaluate a modulo operation. If either of the arguments is null,
+ * this means that it wasn't convertible to a Number value.
+ * @param op1 A Number object
+ * @param op2 A Number object
+ * @return A new NumberProperty object holding an object which represents
+ * op1 mod op2.
+ * @throws PropertyException If either operand is null.
+ */
+ private Property evalModulo(Number op1,
+ Number op2) throws PropertyException {
+ if (op1 == null || op2 == null)
+ throw new PropertyException("Non number operand to modulo");
+ return new NumberProperty(op1.doubleValue() % op2.doubleValue());
}
- return args;
- }
-
-
- /**
- * Evaluate an addition operation. If either of the arguments is null,
- * this means that it wasn't convertible to a Numeric value.
- * @param op1 A Numeric object (Number or Length-type object)
- * @param op2 A Numeric object (Number or Length-type object)
- * @return A new NumericProperty object holding an object which represents
- * the sum of the two operands.
- * @throws PropertyException If either operand is null.
- */
- private Property evalAddition(Numeric op1, Numeric op2)
- throws PropertyException {
- if (op1 == null || op2 == null)
- throw new PropertyException("Non numeric operand in addition");
- return new NumericProperty(op1.add(op2));
- }
-
- /**
- * Evaluate a subtraction operation. If either of the arguments is null,
- * this means that it wasn't convertible to a Numeric value.
- * @param op1 A Numeric object (Number or Length-type object)
- * @param op2 A Numeric object (Number or Length-type object)
- * @return A new NumericProperty object holding an object which represents
- * the difference of the two operands.
- * @throws PropertyException If either operand is null.
- */
- private Property evalSubtraction(Numeric op1, Numeric op2)
- throws PropertyException {
- if (op1 == null || op2 == null)
- throw new PropertyException("Non numeric operand in subtraction");
- return new NumericProperty(op1.subtract(op2));
- }
-
- /**
- * Evaluate a unary minus operation. If the argument is null,
- * this means that it wasn't convertible to a Numeric value.
- * @param op A Numeric object (Number or Length-type object)
- * @return A new NumericProperty object holding an object which represents
- * the negative of the operand (multiplication by *1).
- * @throws PropertyException If the operand is null.
- */
- private Property evalNegate(Numeric op) throws PropertyException {
- if (op == null)
- throw new PropertyException("Non numeric operand to unary minus");
- return new NumericProperty(op.multiply(negOne));
- }
-
- /**
- * Evaluate a multiplication operation. If either of the arguments is null,
- * this means that it wasn't convertible to a Numeric value.
- * @param op1 A Numeric object (Number or Length-type object)
- * @param op2 A Numeric object (Number or Length-type object)
- * @return A new NumericProperty object holding an object which represents
- * the product of the two operands.
- * @throws PropertyException If either operand is null.
- */
- private Property evalMultiply(Numeric op1, Numeric op2)
- throws PropertyException {
- if (op1 == null || op2 == null)
- throw new PropertyException("Non numeric operand in multiplication");
- return new NumericProperty(op1.multiply(op2));
- }
-
-
- /**
- * Evaluate a division operation. If either of the arguments is null,
- * this means that it wasn't convertible to a Numeric value.
- * @param op1 A Numeric object (Number or Length-type object)
- * @param op2 A Numeric object (Number or Length-type object)
- * @return A new NumericProperty object holding an object which represents
- * op1 divided by op2.
- * @throws PropertyException If either operand is null.
- */
- private Property evalDivide(Numeric op1, Numeric op2)
- throws PropertyException {
- if (op1 == null || op2 == null)
- throw new PropertyException("Non numeric operand in division");
- return new NumericProperty(op1.divide(op2));
- }
-
- /**
- * Evaluate a modulo operation. If either of the arguments is null,
- * this means that it wasn't convertible to a Number value.
- * @param op1 A Number object
- * @param op2 A Number object
- * @return A new NumberProperty object holding an object which represents
- * op1 mod op2.
- * @throws PropertyException If either operand is null.
- */
- private Property evalModulo(Number op1, Number op2)
- throws PropertyException {
- if (op1 == null || op2 == null)
- throw new PropertyException("Non number operand to modulo");
- return new NumberProperty(op1.doubleValue()%op2.doubleValue());
- }
}
diff --git a/src/org/apache/fop/fo/expr/PropertyTokenizer.java b/src/org/apache/fop/fo/expr/PropertyTokenizer.java
index fc3094403..025c68695 100644
--- a/src/org/apache/fop/fo/expr/PropertyTokenizer.java
+++ b/src/org/apache/fop/fo/expr/PropertyTokenizer.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
@@ -59,326 +16,329 @@ package org.apache.fop.fo.expr;
*/
class PropertyTokenizer {
- static final int TOK_EOF = 0;
- static final int TOK_NCNAME = TOK_EOF + 1;
- static final int TOK_MULTIPLY = TOK_NCNAME + 1;
- static final int TOK_LPAR = TOK_MULTIPLY + 1;
- static final int TOK_RPAR = TOK_LPAR + 1;
- static final int TOK_LITERAL = TOK_RPAR + 1;
- static final int TOK_NUMBER = TOK_LITERAL + 1;
- static final int TOK_FUNCTION_LPAR = TOK_NUMBER + 1;
- static final int TOK_PLUS = TOK_FUNCTION_LPAR + 1;
- static final int TOK_MINUS = TOK_PLUS + 1;
- static final int TOK_MOD = TOK_MINUS + 1;
- static final int TOK_DIV = TOK_MOD + 1;
- static final int TOK_NUMERIC = TOK_DIV + 1;
- static final int TOK_COMMA = TOK_NUMERIC + 1;
- static final int TOK_PERCENT = TOK_COMMA + 1;
- static final int TOK_COLORSPEC = TOK_PERCENT + 1;
- static final int TOK_FLOAT = TOK_COLORSPEC + 1;
- static final int TOK_INTEGER = TOK_FLOAT + 1;
+ static final int TOK_EOF = 0;
+ static final int TOK_NCNAME = TOK_EOF + 1;
+ static final int TOK_MULTIPLY = TOK_NCNAME + 1;
+ static final int TOK_LPAR = TOK_MULTIPLY + 1;
+ static final int TOK_RPAR = TOK_LPAR + 1;
+ static final int TOK_LITERAL = TOK_RPAR + 1;
+ static final int TOK_NUMBER = TOK_LITERAL + 1;
+ static final int TOK_FUNCTION_LPAR = TOK_NUMBER + 1;
+ static final int TOK_PLUS = TOK_FUNCTION_LPAR + 1;
+ static final int TOK_MINUS = TOK_PLUS + 1;
+ static final int TOK_MOD = TOK_MINUS + 1;
+ static final int TOK_DIV = TOK_MOD + 1;
+ static final int TOK_NUMERIC = TOK_DIV + 1;
+ static final int TOK_COMMA = TOK_NUMERIC + 1;
+ static final int TOK_PERCENT = TOK_COMMA + 1;
+ static final int TOK_COLORSPEC = TOK_PERCENT + 1;
+ static final int TOK_FLOAT = TOK_COLORSPEC + 1;
+ static final int TOK_INTEGER = TOK_FLOAT + 1;
+
+ int currentToken = TOK_EOF;
+ String currentTokenValue = null;
+ protected int currentUnitLength = 0;
- int currentToken = TOK_EOF;
- String currentTokenValue = null;
- protected int currentUnitLength = 0;
+ private int currentTokenStartIndex = 0;
+ private /* final */ String expr;
+ private int exprIndex = 0;
+ private int exprLength;
+ private boolean recognizeOperator = false;
- private int currentTokenStartIndex = 0;
- private /*final*/ String expr;
- private int exprIndex = 0;
- private int exprLength;
- private boolean recognizeOperator = false;
-
- /**
- * Construct a new PropertyTokenizer object to tokenize the passed
- * String.
- * @param s The Property expressio to tokenize.
- */
- PropertyTokenizer(String s) {
- this.expr = s;
- this.exprLength = s.length();
- }
+ /**
+ * Construct a new PropertyTokenizer object to tokenize the passed
+ * String.
+ * @param s The Property expressio to tokenize.
+ */
+ PropertyTokenizer(String s) {
+ this.expr = s;
+ this.exprLength = s.length();
+ }
+
+ /**
+ * Return the next token in the expression string.
+ * This sets the following package visible variables:
+ * currentToken An enumerated value identifying the recognized token
+ * currentTokenValue A String containing the token contents
+ * currentUnitLength If currentToken = TOK_NUMERIC, the number of
+ * characters in the unit name.
+ * @throws PropertyException If un unrecognized token is encountered.
+ */
+ void next() throws PropertyException {
+ currentTokenValue = null;
+ currentTokenStartIndex = exprIndex;
+ boolean currentMaybeOperator = recognizeOperator;
+ boolean bSawDecimal;
+ recognizeOperator = true;
+ for (; ; ) {
+ if (exprIndex >= exprLength) {
+ currentToken = TOK_EOF;
+ return;
+ }
+ char c = expr.charAt(exprIndex++);
+ switch (c) {
+ case ' ':
+ case '\t':
+ case '\r':
+ case '\n':
+ currentTokenStartIndex = exprIndex;
+ break;
+ case ',':
+ recognizeOperator = false;
+ currentToken = TOK_COMMA;
+ return;
+ case '+':
+ recognizeOperator = false;
+ currentToken = TOK_PLUS;
+ return;
+ case '-':
+ recognizeOperator = false;
+ currentToken = TOK_MINUS;
+ return;
+ case '(':
+ currentToken = TOK_LPAR;
+ recognizeOperator = false;
+ return;
+ case ')':
+ currentToken = TOK_RPAR;
+ return;
+ case '"':
+ case '\'':
+ exprIndex = expr.indexOf(c, exprIndex);
+ if (exprIndex < 0) {
+ exprIndex = currentTokenStartIndex + 1;
+ throw new PropertyException("missing quote");
+ }
+ currentTokenValue = expr.substring(currentTokenStartIndex
+ + 1, exprIndex++);
+ currentToken = TOK_LITERAL;
+ return;
+ case '*':
+ /*
+ * if (currentMaybeOperator) {
+ * recognizeOperator = false;
+ */
+ currentToken = TOK_MULTIPLY;
+ /*
+ * }
+ * else
+ * throw new PropertyException("illegal operator *");
+ */
+ return;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ scanDigits();
+ if (exprIndex < exprLength && expr.charAt(exprIndex) == '.') {
+ exprIndex++;
+ bSawDecimal = true;
+ if (exprIndex < exprLength
+ && isDigit(expr.charAt(exprIndex))) {
+ exprIndex++;
+ scanDigits();
+ }
+ } else
+ bSawDecimal = false;
+ if (exprIndex < exprLength && expr.charAt(exprIndex) == '%') {
+ exprIndex++;
+ currentToken = TOK_PERCENT;
+ } else {
+ // Check for possible unit name following number
+ currentUnitLength = exprIndex;
+ scanName();
+ currentUnitLength = exprIndex - currentUnitLength;
+ currentToken = (currentUnitLength > 0) ? TOK_NUMERIC
+ : (bSawDecimal ? TOK_FLOAT : TOK_INTEGER);
+ }
+ currentTokenValue = expr.substring(currentTokenStartIndex,
+ exprIndex);
+ return;
- /**
- * Return the next token in the expression string.
- * This sets the following package visible variables:
- * currentToken An enumerated value identifying the recognized token
- * currentTokenValue A String containing the token contents
- * currentUnitLength If currentToken = TOK_NUMERIC, the number of
- * characters in the unit name.
- * @throws PropertyException If un unrecognized token is encountered.
- */
- void next() throws PropertyException {
- currentTokenValue = null;
- currentTokenStartIndex = exprIndex;
- boolean currentMaybeOperator = recognizeOperator;
- boolean bSawDecimal ;
- recognizeOperator = true;
- for (;;) {
- if (exprIndex >= exprLength) {
- currentToken = TOK_EOF;
- return;
- }
- char c = expr.charAt(exprIndex++);
- switch (c) {
- case ' ':
- case '\t':
- case '\r':
- case '\n':
- currentTokenStartIndex = exprIndex;
- break;
- case ',':
- recognizeOperator = false;
- currentToken = TOK_COMMA;
- return;
- case '+':
- recognizeOperator = false;
- currentToken = TOK_PLUS;
- return;
- case '-':
- recognizeOperator = false;
- currentToken = TOK_MINUS;
- return;
- case '(':
- currentToken = TOK_LPAR;
- recognizeOperator = false;
- return;
- case ')':
- currentToken = TOK_RPAR;
- return;
- case '"':
- case '\'':
- exprIndex = expr.indexOf(c, exprIndex);
- if (exprIndex < 0) {
- exprIndex = currentTokenStartIndex + 1;
- throw new PropertyException("missing quote");
- }
- currentTokenValue = expr.substring(currentTokenStartIndex + 1,
- exprIndex++);
- currentToken = TOK_LITERAL;
- return;
- case '*':
- /*if (currentMaybeOperator) {
- recognizeOperator = false;*/
- currentToken = TOK_MULTIPLY;
- /*}
- else
- throw new PropertyException("illegal operator *");*/
- return;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- scanDigits();
- if (exprIndex < exprLength
- && expr.charAt(exprIndex) == '.') {
- exprIndex++;
- bSawDecimal=true;
- if (exprIndex < exprLength
- && isDigit(expr.charAt(exprIndex))) {
- exprIndex++;
- scanDigits();
- }
- }
- else bSawDecimal=false;
- if (exprIndex < exprLength && expr.charAt(exprIndex) == '%') {
- exprIndex++;
- currentToken = TOK_PERCENT ;
- }
- else {
- // Check for possible unit name following number
- currentUnitLength = exprIndex;
- scanName();
- currentUnitLength = exprIndex-currentUnitLength;
- currentToken = (currentUnitLength>0)? TOK_NUMERIC :
- (bSawDecimal? TOK_FLOAT : TOK_INTEGER) ;
- }
- currentTokenValue = expr.substring(currentTokenStartIndex,
- exprIndex);
- return;
+ case '.':
+ if (exprIndex < exprLength
+ && isDigit(expr.charAt(exprIndex))) {
+ ++exprIndex;
+ scanDigits();
+ if (exprIndex < exprLength
+ && expr.charAt(exprIndex) == '%') {
+ exprIndex++;
+ currentToken = TOK_PERCENT;
+ } else {
+ // Check for possible unit name following number
+ currentUnitLength = exprIndex;
+ scanName();
+ currentUnitLength = exprIndex - currentUnitLength;
+ currentToken = (currentUnitLength > 0) ? TOK_NUMERIC
+ : TOK_FLOAT;
+ }
+ currentTokenValue = expr.substring(currentTokenStartIndex,
+ exprIndex);
+ return;
+ }
+ throw new PropertyException("illegal character '.'");
- case '.':
- if (exprIndex < exprLength && isDigit(expr.charAt(exprIndex))) {
- ++exprIndex;
- scanDigits();
- if (exprIndex < exprLength && expr.charAt(exprIndex) == '%') {
- exprIndex++;
- currentToken = TOK_PERCENT ;
- }
- else {
- // Check for possible unit name following number
- currentUnitLength = exprIndex;
- scanName();
- currentUnitLength = exprIndex-currentUnitLength;
- currentToken = (currentUnitLength>0)? TOK_NUMERIC : TOK_FLOAT;
- }
- currentTokenValue = expr.substring(currentTokenStartIndex,
- exprIndex);
- return;
- }
- throw new PropertyException("illegal character '.'");
+ case '#': // Start of color value
+ if (exprIndex < exprLength
+ && isHexDigit(expr.charAt(exprIndex))) {
+ ++exprIndex;
+ scanHexDigits();
+ currentToken = TOK_COLORSPEC;
+ currentTokenValue = expr.substring(currentTokenStartIndex,
+ exprIndex);
+ // Probably should have some multiple of 3 for length!
+ return;
+ } else
+ throw new PropertyException("illegal character '#'");
- case '#': // Start of color value
- if (exprIndex < exprLength && isHexDigit(expr.charAt(exprIndex))) {
- ++exprIndex;
- scanHexDigits();
- currentToken = TOK_COLORSPEC;
- currentTokenValue = expr.substring(currentTokenStartIndex,
- exprIndex);
- // Probably should have some multiple of 3 for length!
- return;
- }
- else throw new PropertyException("illegal character '#'");
-
- default:
- --exprIndex;
- scanName();
- if (exprIndex == currentTokenStartIndex)
- throw new PropertyException("illegal character");
- currentTokenValue = expr.substring(currentTokenStartIndex,
- exprIndex);
- // if (currentMaybeOperator) {
- if (currentTokenValue.equals("mod")) {
- currentToken = TOK_MOD;
- return;
- }
- else if (currentTokenValue.equals("div")) {
- currentToken = TOK_DIV;
- return;
- }
- /*else
- throw new PropertyException("unrecognized operator name");
- recognizeOperator = false;
- return;
- }*/
- if (followingParen()) {
- currentToken = TOK_FUNCTION_LPAR;
- recognizeOperator = false;
- }
- else {
- currentToken = TOK_NCNAME;
- recognizeOperator = false;
- }
- return;
- }
+ default:
+ --exprIndex;
+ scanName();
+ if (exprIndex == currentTokenStartIndex)
+ throw new PropertyException("illegal character");
+ currentTokenValue = expr.substring(currentTokenStartIndex,
+ exprIndex);
+ // if (currentMaybeOperator) {
+ if (currentTokenValue.equals("mod")) {
+ currentToken = TOK_MOD;
+ return;
+ } else if (currentTokenValue.equals("div")) {
+ currentToken = TOK_DIV;
+ return;
+ }
+ /*
+ * else
+ * throw new PropertyException("unrecognized operator name");
+ * recognizeOperator = false;
+ * return;
+ * }
+ */
+ if (followingParen()) {
+ currentToken = TOK_FUNCTION_LPAR;
+ recognizeOperator = false;
+ } else {
+ currentToken = TOK_NCNAME;
+ recognizeOperator = false;
+ }
+ return;
+ }
+ }
}
- }
- /**
- * Attempt to recognize a valid NAME token in the input expression.
- */
- private void scanName() {
- if (exprIndex < exprLength
- && isNameStartChar(expr.charAt(exprIndex)))
- while (++exprIndex < exprLength
- && isNameChar(expr.charAt(exprIndex)))
- ;
- }
+ /**
+ * Attempt to recognize a valid NAME token in the input expression.
+ */
+ private void scanName() {
+ if (exprIndex < exprLength && isNameStartChar(expr.charAt(exprIndex)))
+ while (++exprIndex < exprLength
+ && isNameChar(expr.charAt(exprIndex)));
+ }
- /**
- * Attempt to recognize a valid sequence of decimal digits in the
- * input expression.
- */
- private void scanDigits() {
- while (exprIndex < exprLength && isDigit(expr.charAt(exprIndex)))
- exprIndex++;
- }
+ /**
+ * Attempt to recognize a valid sequence of decimal digits in the
+ * input expression.
+ */
+ private void scanDigits() {
+ while (exprIndex < exprLength && isDigit(expr.charAt(exprIndex)))
+ exprIndex++;
+ }
- /**
- * Attempt to recognize a valid sequence of hexadecimal digits in the
- * input expression.
- */
- private void scanHexDigits() {
- while (exprIndex < exprLength && isHexDigit(expr.charAt(exprIndex)))
- exprIndex++;
- }
+ /**
+ * Attempt to recognize a valid sequence of hexadecimal digits in the
+ * input expression.
+ */
+ private void scanHexDigits() {
+ while (exprIndex < exprLength && isHexDigit(expr.charAt(exprIndex)))
+ exprIndex++;
+ }
- /**
- * Return a boolean value indicating whether the following non-whitespace
- * character is an opening parenthesis.
- */
- private boolean followingParen() {
- for (int i = exprIndex; i < exprLength; i++) {
- switch (expr.charAt(i)) {
- case '(':
- exprIndex = i + 1;
- return true;
- case ' ':
- case '\r':
- case '\n':
- case '\t':
- break;
- default:
- return false;
- }
+ /**
+ * Return a boolean value indicating whether the following non-whitespace
+ * character is an opening parenthesis.
+ */
+ private boolean followingParen() {
+ for (int i = exprIndex; i < exprLength; i++) {
+ switch (expr.charAt(i)) {
+ case '(':
+ exprIndex = i + 1;
+ return true;
+ case ' ':
+ case '\r':
+ case '\n':
+ case '\t':
+ break;
+ default:
+ return false;
+ }
+ }
+ return false;
}
- return false;
- }
- static private final String nameStartChars =
- "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
- static private final String nameChars = ".-0123456789";
- static private final String digits = "0123456789";
- static private final String hexchars = digits + "abcdefABCDEF";
+ static private final String nameStartChars =
+ "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
+ static private final String nameChars = ".-0123456789";
+ static private final String digits = "0123456789";
+ static private final String hexchars = digits + "abcdefABCDEF";
- /**
- * Return a boolean value indicating whether the argument is a
- * decimal digit (0-9).
- * @param c The character to check
- */
- private static final boolean isDigit(char c) {
- return digits.indexOf(c) >= 0;
- }
+ /**
+ * Return a boolean value indicating whether the argument is a
+ * decimal digit (0-9).
+ * @param c The character to check
+ */
+ private static final boolean isDigit(char c) {
+ return digits.indexOf(c) >= 0;
+ }
- /**
- * Return a boolean value indicating whether the argument is a
- * hexadecimal digit (0-9, A-F, a-f).
- * @param c The character to check
- */
- private static final boolean isHexDigit(char c) {
- return hexchars.indexOf(c) >=0;
- }
+ /**
+ * Return a boolean value indicating whether the argument is a
+ * hexadecimal digit (0-9, A-F, a-f).
+ * @param c The character to check
+ */
+ private static final boolean isHexDigit(char c) {
+ return hexchars.indexOf(c) >= 0;
+ }
- /**
- * Return a boolean value indicating whether the argument is whitespace
- * as defined by XSL (space, newline, CR, tab).
- * @param c The character to check
- */
- private static final boolean isSpace(char c) {
- switch(c) {
- case ' ':
- case '\r':
- case '\n':
- case '\t':
- return true;
+ /**
+ * Return a boolean value indicating whether the argument is whitespace
+ * as defined by XSL (space, newline, CR, tab).
+ * @param c The character to check
+ */
+ private static final boolean isSpace(char c) {
+ switch (c) {
+ case ' ':
+ case '\r':
+ case '\n':
+ case '\t':
+ return true;
+ }
+ return false;
}
- return false;
- }
- /**
- * Return a boolean value indicating whether the argument is a valid name
- * start character, ie. can start a NAME as defined by XSL.
- * @param c The character to check
- */
- private static final boolean isNameStartChar(char c) {
- return nameStartChars.indexOf(c) >= 0 || c >= 0x80;
- }
+ /**
+ * Return a boolean value indicating whether the argument is a valid name
+ * start character, ie. can start a NAME as defined by XSL.
+ * @param c The character to check
+ */
+ private static final boolean isNameStartChar(char c) {
+ return nameStartChars.indexOf(c) >= 0 || c >= 0x80;
+ }
- /**
- * Return a boolean value indicating whether the argument is a valid name
- * character, ie. can occur in a NAME as defined by XSL.
- * @param c The character to check
- */
- private static final boolean isNameChar(char c) {
- return nameStartChars.indexOf(c) >= 0 ||
- nameChars.indexOf(c) >= 0 || c >= 0x80;
- }
+ /**
+ * Return a boolean value indicating whether the argument is a valid name
+ * character, ie. can occur in a NAME as defined by XSL.
+ * @param c The character to check
+ */
+ private static final boolean isNameChar(char c) {
+ return nameStartChars.indexOf(c) >= 0 || nameChars.indexOf(c) >= 0
+ || c >= 0x80;
+ }
}
diff --git a/src/org/apache/fop/fo/expr/RGBColorFunction.java b/src/org/apache/fop/fo/expr/RGBColorFunction.java
index 16f619494..6627fb36d 100644
--- a/src/org/apache/fop/fo/expr/RGBColorFunction.java
+++ b/src/org/apache/fop/fo/expr/RGBColorFunction.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
@@ -57,42 +14,53 @@ import org.apache.fop.datatypes.ColorType;
import org.apache.fop.datatypes.PercentBase;
class RGBColorFunction extends FunctionBase {
- public int nbArgs() { return 3; }
+ public int nbArgs() {
+ return 3;
+ }
+
+ /**
+ * Return an object which implements the PercentBase interface.
+ * Percents in arguments to this function are interpreted relative
+ * to 255.
+ */
+ public PercentBase getPercentBase() {
+ return new RGBPercentBase();
+ }
- /**
- * Return an object which implements the PercentBase interface.
- * Percents in arguments to this function are interpreted relative
- * to 255.
- */
- public PercentBase getPercentBase() { return new RGBPercentBase(); }
+ public Property eval(Property[] args,
+ PropertyInfo pInfo) throws PropertyException {
+ // Using CSS rules, numbers are either supposed to be 0-255
+ // or percentage values. If percentages value, they've already
+ // been converted to reals.
+ float[] cfvals = new float[3]; // RGB
+ for (int i = 0; i < 3; i++) {
+ Number cval = args[i].getNumber();
+ if (cval == null) {
+ throw new PropertyException("Argument to rgb() must be a Number");
+ }
+ float colorVal = cval.floatValue() / 255f;
+ if (colorVal < 0.0 || colorVal > 255.0) {
+ throw new PropertyException("Arguments to rgb() must normalize to the range 0 to 1");
+ }
+ cfvals[i] = colorVal;
+ }
+ return new ColorTypeProperty(new ColorType(cfvals[0], cfvals[1],
+ cfvals[2]));
- public Property eval(Property[] args, PropertyInfo pInfo)
- throws PropertyException
- {
- // Using CSS rules, numbers are either supposed to be 0-255
- // or percentage values. If percentages value, they've already
- // been converted to reals.
- float[] cfvals = new float[3]; // RGB
- for (int i=0; i<3; i++) {
- Number cval = args[i].getNumber();
- if (cval == null) {
- throw new PropertyException("Argument to rgb() must be a Number");
- }
- float colorVal = cval.floatValue()/255f;
- if (colorVal < 0.0 || colorVal > 255.0) {
- throw new PropertyException("Arguments to rgb() must normalize to the range 0 to 1");
- }
- cfvals[i] = colorVal;
}
- return new ColorTypeProperty( new ColorType(cfvals[0],
- cfvals[1],
- cfvals[2]));
- }
+ static class RGBPercentBase implements PercentBase {
+ public int getDimension() {
+ return 0;
+ }
+
+ public double getBaseValue() {
+ return 255f;
+ }
- static class RGBPercentBase implements PercentBase {
- public int getDimension() { return 0; }
- public double getBaseValue() { return 255f ; }
- public int getBaseLength() { return 0; }
- }
+ public int getBaseLength() {
+ return 0;
+ }
+
+ }
}
diff --git a/src/org/apache/fop/fo/expr/RoundFunction.java b/src/org/apache/fop/fo/expr/RoundFunction.java
index 43cf2e3b1..81d51b113 100644
--- a/src/org/apache/fop/fo/expr/RoundFunction.java
+++ b/src/org/apache/fop/fo/expr/RoundFunction.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.expr;
@@ -55,18 +12,20 @@ import org.apache.fop.fo.Property;
import org.apache.fop.fo.NumberProperty;
class RoundFunction extends FunctionBase {
- public int nbArgs() { return 1; }
+ public int nbArgs() {
+ return 1;
+ }
+
+ public Property eval(Property[] args,
+ PropertyInfo pInfo) throws PropertyException {
+ Number dbl = args[0].getNumber();
+ if (dbl == null)
+ throw new PropertyException("Non number operand to round function");
+ double n = dbl.doubleValue();
+ double r = Math.floor(n + 0.5);
+ if (r == 0.0 && n < 0.0)
+ r = -r; // round(-0.2) returns -0 not 0
+ return new NumberProperty(r);
+ }
- public Property eval(Property[] args, PropertyInfo pInfo)
- throws PropertyException
- {
- Number dbl = args[0].getNumber();
- if (dbl == null)
- throw new PropertyException("Non number operand to round function");
- double n = dbl.doubleValue();
- double r = Math.floor(n + 0.5);
- if (r == 0.0 && n < 0.0)
- r = -r; // round(-0.2) returns -0 not 0
- return new NumberProperty(r);
- }
}
diff --git a/src/org/apache/fop/fo/flow/BasicLink.java b/src/org/apache/fop/fo/flow/BasicLink.java
index 8ada63de8..7de5f71f2 100644
--- a/src/org/apache/fop/fo/flow/BasicLink.java
+++ b/src/org/apache/fop/fo/flow/BasicLink.java
@@ -1,56 +1,10 @@
/*
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
-/* this class contributed by Arved Sandstrom with minor modifications
- by James Tauber */
-
package org.apache.fop.fo.flow;
// FOP
@@ -67,84 +21,82 @@ import java.awt.Rectangle;
public class BasicLink extends FObjMixed {
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new BasicLink(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new BasicLink(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new BasicLink.Maker();
+ return new BasicLink.Maker();
}
- public BasicLink(FObj parent, PropertyList propertyList)
- throws FOPException {
- super(parent, propertyList);
- this.name = "fo:basic-link";
+ public BasicLink(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ super(parent, propertyList);
+ this.name = "fo:basic-link";
- if (parent.getName().equals("fo:flow")) {
- throw new FOPException("basic-link can't be directly"
- + " under flow");
- }
+ if (parent.getName().equals("fo:flow")) {
+ throw new FOPException("basic-link can't be directly"
+ + " under flow");
+ }
}
public Status layout(Area area) throws FOPException {
String destination;
int linkType;
- if ( !(destination = this.properties.get("internal-destination").getString()).equals(""))
- {
- linkType=LinkSet.INTERNAL;
- }
- else if ( !(destination = this.properties.get("external-destination").getString()).equals("") )
- {
- linkType=LinkSet.EXTERNAL;
- }
- else
- {
+ if (!(destination =
+ this.properties.get("internal-destination").getString()).equals("")) {
+ linkType = LinkSet.INTERNAL;
+ } else if (!(destination =
+ this.properties.get("external-destination").getString()).equals("")) {
+ linkType = LinkSet.EXTERNAL;
+ } else {
throw new FOPException("internal-destination or external-destination must be specified in basic-link");
}
- if (this.marker == START) {
- // initialize id
+ if (this.marker == START) {
+ // initialize id
String id = this.properties.get("id").getString();
- area.getIDReferences().initializeID(id,area);
- this.marker = 0;
- }
-
- // new LinkedArea to gather up inlines
- LinkSet ls = new LinkSet(destination, area, linkType);
-
- Page p = area.getPage();
-
- AreaContainer ac = p.getBody().getCurrentColumnArea();
- if (ac == null)
- {
- throw new FOPException("Couldn't get ancestor AreaContainer when processing basic-link");
- }
-
- int numChildren = this.children.size();
- for (int i = this.marker; i < numChildren; i++) {
- FONode fo = (FONode) children.elementAt(i);
- fo.setLinkSet(ls);
-
- Status status;
- if ((status = fo.layout(area)).isIncomplete()) {
- this.marker = i;
- return status;
- }
- }
-
- ls.applyAreaContainerOffsets(ac, area);
-
- // pass on command line
- String mergeLinks = System.getProperty( "links.merge" );
- if ((null != mergeLinks) && !mergeLinks.equalsIgnoreCase("no")) {
- ls.mergeLinks();
- }
-
- p.addLinkSet(ls);
-
- return new Status(Status.OK);
+ area.getIDReferences().initializeID(id, area);
+ this.marker = 0;
+ }
+
+ // new LinkedArea to gather up inlines
+ LinkSet ls = new LinkSet(destination, area, linkType);
+
+ Page p = area.getPage();
+
+ AreaContainer ac = p.getBody().getCurrentColumnArea();
+ if (ac == null) {
+ throw new FOPException("Couldn't get ancestor AreaContainer when processing basic-link");
+ }
+
+ int numChildren = this.children.size();
+ for (int i = this.marker; i < numChildren; i++) {
+ FONode fo = (FONode)children.elementAt(i);
+ fo.setLinkSet(ls);
+
+ Status status;
+ if ((status = fo.layout(area)).isIncomplete()) {
+ this.marker = i;
+ return status;
+ }
+ }
+
+ ls.applyAreaContainerOffsets(ac, area);
+
+ // pass on command line
+ String mergeLinks = System.getProperty("links.merge");
+ if ((null != mergeLinks) &&!mergeLinks.equalsIgnoreCase("no")) {
+ ls.mergeLinks();
+ }
+
+ p.addLinkSet(ls);
+
+ return new Status(Status.OK);
}
+
}
diff --git a/src/org/apache/fop/fo/flow/BidiOverride.java b/src/org/apache/fop/fo/flow/BidiOverride.java
index 5fd7227e0..c6d7a1ba3 100644
--- a/src/org/apache/fop/fo/flow/BidiOverride.java
+++ b/src/org/apache/fop/fo/flow/BidiOverride.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -23,6 +24,7 @@ public class BidiOverride extends ToBeImplementedElement {
PropertyList propertyList) throws FOPException {
return new BidiOverride(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -30,7 +32,7 @@ public class BidiOverride extends ToBeImplementedElement {
}
protected BidiOverride(FObj parent,
- PropertyList propertyList) throws FOPException {
+ PropertyList propertyList) throws FOPException {
super(parent, propertyList);
this.name = "fo:bidi-override";
}
diff --git a/src/org/apache/fop/fo/flow/Block.java b/src/org/apache/fop/fo/flow/Block.java
index 97c716132..8b85f806a 100644
--- a/src/org/apache/fop/fo/flow/Block.java
+++ b/src/org/apache/fop/fo/flow/Block.java
@@ -1,5 +1,6 @@
-/*-- $Id$-- */
-/* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
@@ -16,267 +17,274 @@ import org.apache.fop.apps.FOPException;
public class Block extends FObjMixed {
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent,
- PropertyList propertyList) throws FOPException {
- return new Block(parent, propertyList);
- }
- }
-
- public static FObj.Maker maker() {
- return new Block.Maker();
- }
-
- int align;
- int alignLast;
- int breakAfter;
- int lineHeight;
- int startIndent;
- int endIndent;
- int spaceBefore;
- int spaceAfter;
- int textIndent;
- int keepWithNext;
- ColorType backgroundColor;
- int blockWidows;
- int blockOrphans;
-
- String id;
- int span;
-
- BlockArea blockArea;
-
- // this may be helpful on other FOs too
- boolean anythingLaidOut = false;
-
- public Block(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:block";
- this.span = this.properties.get("span").getEnum();
- }
-
- public Status layout(Area area) throws FOPException {
- // MessageHandler.error(" b:LAY[" + marker + "] ");
-
-
- if (this.marker == BREAK_AFTER) {
- return new Status(Status.OK);
- }
-
- if (this.marker == START) {
-
- this.align = this.properties.get("text-align").getEnum();
- this.alignLast =
- this.properties.get("text-align-last").getEnum();
- this.breakAfter = this.properties.get("break-after").getEnum();
- this.lineHeight = this.properties.get(
- "line-height").getLength().mvalue();
- this.startIndent = this.properties.get(
- "start-indent").getLength().mvalue();
- this.endIndent = this.properties.get(
- "end-indent").getLength().mvalue();
- this.spaceBefore = this.properties.get(
- "space-before.optimum").getLength().mvalue();
- this.spaceAfter = this.properties.get(
- "space-after.optimum").getLength().mvalue();
- this.textIndent = this.properties.get(
- "text-indent").getLength().mvalue();
- this.keepWithNext =
- this.properties.get("keep-with-next").getEnum();
- this.backgroundColor = this.properties.get("background-color").getColorType();
-
- this.blockWidows =
- this.properties.get("widows").getNumber().intValue();
- this.blockOrphans =
- this.properties.get("orphans").getNumber().intValue();
-
-
-
- this.id = this.properties.get("id").getString();
-
- if (area instanceof BlockArea) {
- area.end();
- }
-
- if(area.getIDReferences() != null)
- area.getIDReferences().createID(id);
-
- this.marker = 0;
-
- // no break if first in area tree, or leading in context
- // area
- int breakBeforeStatus = propMgr.checkBreakBefore(area);
- if (breakBeforeStatus != Status.OK) {
- return new Status(breakBeforeStatus);
- }
-
- int numChildren = this.children.size();
- for (int i = 0; i < numChildren; i++) {
- FONode fo = (FONode) children.elementAt(i);
- if (fo instanceof FOText) {
- if (((FOText) fo).willCreateArea()) {
- fo.setWidows(blockWidows);
- break;
- } else {
- children.removeElementAt(i);
- numChildren = this.children.size();
- i--;
- }
- } else {
- fo.setWidows(blockWidows);
- break;
- }
- }
-
- for (int i = numChildren - 1; i >= 0; i--) {
- FONode fo = (FONode) children.elementAt(i);
- if (fo instanceof FOText) {
- if (((FOText) fo).willCreateArea()) {
- fo.setOrphans(blockOrphans);
- break;
- }
- } else {
- fo.setOrphans(blockOrphans);
- break;
- }
- }
- }
-
- if ((spaceBefore != 0) && (this.marker == 0)) {
- area.addDisplaySpace(spaceBefore);
- }
-
- if (anythingLaidOut) {
- this.textIndent = 0;
- }
-
- if (marker == 0 && area.getIDReferences() != null) {
- area.getIDReferences().configureID(id, area);
- }
-
- int spaceLeft = area.spaceLeft();
- this.blockArea = new BlockArea(propMgr.getFontState(area.getFontInfo()), area.getAllocationWidth(),
- area.spaceLeft(), startIndent, endIndent, textIndent,
- align, alignLast, lineHeight);
- this.blockArea.setGeneratedBy(this);
- this.areasGenerated++;
- if (this.areasGenerated == 1)
- this.blockArea.isFirst(true);
- // for normal areas this should be the only pair
- this.blockArea.addLineagePair(this, this.areasGenerated);
-
- // markers
- if (this.hasMarkers())
- this.blockArea.addMarkers(this.getMarkers());
-
- this.blockArea.setParent(area); // BasicLink needs it
- blockArea.setPage(area.getPage());
- blockArea.setBackgroundColor(backgroundColor);
- blockArea.setBorderAndPadding(propMgr.getBorderAndPadding());
- blockArea.setHyphenation(propMgr.getHyphenationProps());
- blockArea.start();
-
- blockArea.setAbsoluteHeight(area.getAbsoluteHeight());
- blockArea.setIDReferences(area.getIDReferences());
-
- blockArea.setTableCellXOffset(area.getTableCellXOffset());
-
- int numChildren = this.children.size();
- for (int i = this.marker; i < numChildren; i++) {
- FONode fo = (FONode) children.elementAt(i);
- Status status;
- if ((status = fo.layout(blockArea)).isIncomplete()) {
- this.marker = i;
- // this block was modified by
- // Hani Elabed 11/27/2000
- //if ((i != 0) && (status.getCode() == Status.AREA_FULL_NONE))
- //{
- // status = new Status(Status.AREA_FULL_SOME);
- //}
-
- // new block to replace the one above
- // Hani Elabed 11/27/2000
- if (status.getCode() == Status.AREA_FULL_NONE) {
- // something has already been laid out
- if ((i != 0)) {
- status = new Status(Status.AREA_FULL_SOME);
- area.addChild(blockArea);
- area.setMaxHeight(area.getMaxHeight() - spaceLeft + blockArea.getMaxHeight());
- area.increaseHeight(blockArea.getHeight());
- area.setAbsoluteHeight(
- blockArea.getAbsoluteHeight());
- anythingLaidOut = true;
-
- return status;
- } else // i == 0 nothing was laid out..
- {
- anythingLaidOut = false;
- return status;
- }
- }
-
- //blockArea.end();
- area.addChild(blockArea);
- area.setMaxHeight(area.getMaxHeight() - spaceLeft + blockArea.getMaxHeight());
- area.increaseHeight(blockArea.getHeight());
- area.setAbsoluteHeight(blockArea.getAbsoluteHeight());
- anythingLaidOut = true;
- return status;
- }
- anythingLaidOut = true;
- }
-
- blockArea.end();
-
- area.setMaxHeight(area.getMaxHeight() - spaceLeft + blockArea.getMaxHeight());
-
- area.addChild(blockArea);
-
- /* should this be combined into above? */
- area.increaseHeight(blockArea.getHeight());
-
- area.setAbsoluteHeight(blockArea.getAbsoluteHeight());
-
- if (spaceAfter != 0) {
- area.addDisplaySpace(spaceAfter);
- }
-
- if (area instanceof BlockArea) {
- area.start();
- }
-
- // no break if last in area tree, or trailing in context
- // area
- int breakAfterStatus = propMgr.checkBreakAfter(area);
- if (breakAfterStatus != Status.OK) {
- this.marker = BREAK_AFTER;
- return new Status(breakAfterStatus);
- }
-
- if (keepWithNext != 0) {
- return new Status(Status.KEEP_WITH_NEXT);
- }
-
- //MessageHandler.error(" b:OK" + marker + " ");
- this.blockArea.isLast(true);
- return new Status(Status.OK);
- }
-
- public int getAreaHeight() {
- return blockArea.getHeight();
- }
-
-
- /**
- * Return the content width of the boxes generated by this FO.
- */
- public int getContentWidth() {
- if (blockArea != null)
- return blockArea.getContentWidth(); //getAllocationWidth()??
- else return 0; // not laid out yet
- }
-
- public int getSpan() {
- return this.span;
- }
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new Block(parent, propertyList);
+ }
+
+ }
+
+ public static FObj.Maker maker() {
+ return new Block.Maker();
+ }
+
+ int align;
+ int alignLast;
+ int breakAfter;
+ int lineHeight;
+ int startIndent;
+ int endIndent;
+ int spaceBefore;
+ int spaceAfter;
+ int textIndent;
+ int keepWithNext;
+ ColorType backgroundColor;
+ int blockWidows;
+ int blockOrphans;
+
+ String id;
+ int span;
+
+ BlockArea blockArea;
+
+ // this may be helpful on other FOs too
+ boolean anythingLaidOut = false;
+
+ public Block(FObj parent, PropertyList propertyList) {
+ super(parent, propertyList);
+ this.name = "fo:block";
+ this.span = this.properties.get("span").getEnum();
+ }
+
+ public Status layout(Area area) throws FOPException {
+ // MessageHandler.error(" b:LAY[" + marker + "] ");
+
+
+ if (this.marker == BREAK_AFTER) {
+ return new Status(Status.OK);
+ }
+
+ if (this.marker == START) {
+
+ this.align = this.properties.get("text-align").getEnum();
+ this.alignLast = this.properties.get("text-align-last").getEnum();
+ this.breakAfter = this.properties.get("break-after").getEnum();
+ this.lineHeight =
+ this.properties.get("line-height").getLength().mvalue();
+ this.startIndent =
+ this.properties.get("start-indent").getLength().mvalue();
+ this.endIndent =
+ this.properties.get("end-indent").getLength().mvalue();
+ this.spaceBefore =
+ this.properties.get("space-before.optimum").getLength().mvalue();
+ this.spaceAfter =
+ this.properties.get("space-after.optimum").getLength().mvalue();
+ this.textIndent =
+ this.properties.get("text-indent").getLength().mvalue();
+ this.keepWithNext =
+ this.properties.get("keep-with-next").getEnum();
+ this.backgroundColor =
+ this.properties.get("background-color").getColorType();
+
+ this.blockWidows =
+ this.properties.get("widows").getNumber().intValue();
+ this.blockOrphans =
+ this.properties.get("orphans").getNumber().intValue();
+
+
+
+ this.id = this.properties.get("id").getString();
+
+ if (area instanceof BlockArea) {
+ area.end();
+ }
+
+ if (area.getIDReferences() != null)
+ area.getIDReferences().createID(id);
+
+ this.marker = 0;
+
+ // no break if first in area tree, or leading in context
+ // area
+ int breakBeforeStatus = propMgr.checkBreakBefore(area);
+ if (breakBeforeStatus != Status.OK) {
+ return new Status(breakBeforeStatus);
+ }
+
+ int numChildren = this.children.size();
+ for (int i = 0; i < numChildren; i++) {
+ FONode fo = (FONode)children.elementAt(i);
+ if (fo instanceof FOText) {
+ if (((FOText)fo).willCreateArea()) {
+ fo.setWidows(blockWidows);
+ break;
+ } else {
+ children.removeElementAt(i);
+ numChildren = this.children.size();
+ i--;
+ }
+ } else {
+ fo.setWidows(blockWidows);
+ break;
+ }
+ }
+
+ for (int i = numChildren - 1; i >= 0; i--) {
+ FONode fo = (FONode)children.elementAt(i);
+ if (fo instanceof FOText) {
+ if (((FOText)fo).willCreateArea()) {
+ fo.setOrphans(blockOrphans);
+ break;
+ }
+ } else {
+ fo.setOrphans(blockOrphans);
+ break;
+ }
+ }
+ }
+
+ if ((spaceBefore != 0) && (this.marker == 0)) {
+ area.addDisplaySpace(spaceBefore);
+ }
+
+ if (anythingLaidOut) {
+ this.textIndent = 0;
+ }
+
+ if (marker == 0 && area.getIDReferences() != null) {
+ area.getIDReferences().configureID(id, area);
+ }
+
+ int spaceLeft = area.spaceLeft();
+ this.blockArea =
+ new BlockArea(propMgr.getFontState(area.getFontInfo()),
+ area.getAllocationWidth(), area.spaceLeft(),
+ startIndent, endIndent, textIndent, align,
+ alignLast, lineHeight);
+ this.blockArea.setGeneratedBy(this);
+ this.areasGenerated++;
+ if (this.areasGenerated == 1)
+ this.blockArea.isFirst(true);
+ // for normal areas this should be the only pair
+ this.blockArea.addLineagePair(this, this.areasGenerated);
+
+ // markers
+ if (this.hasMarkers())
+ this.blockArea.addMarkers(this.getMarkers());
+
+ this.blockArea.setParent(area); // BasicLink needs it
+ blockArea.setPage(area.getPage());
+ blockArea.setBackgroundColor(backgroundColor);
+ blockArea.setBorderAndPadding(propMgr.getBorderAndPadding());
+ blockArea.setHyphenation(propMgr.getHyphenationProps());
+ blockArea.start();
+
+ blockArea.setAbsoluteHeight(area.getAbsoluteHeight());
+ blockArea.setIDReferences(area.getIDReferences());
+
+ blockArea.setTableCellXOffset(area.getTableCellXOffset());
+
+ int numChildren = this.children.size();
+ for (int i = this.marker; i < numChildren; i++) {
+ FONode fo = (FONode)children.elementAt(i);
+ Status status;
+ if ((status = fo.layout(blockArea)).isIncomplete()) {
+ this.marker = i;
+ // this block was modified by
+ // Hani Elabed 11/27/2000
+ // if ((i != 0) && (status.getCode() == Status.AREA_FULL_NONE))
+ // {
+ // status = new Status(Status.AREA_FULL_SOME);
+ // }
+
+ // new block to replace the one above
+ // Hani Elabed 11/27/2000
+ if (status.getCode() == Status.AREA_FULL_NONE) {
+ // something has already been laid out
+ if ((i != 0)) {
+ status = new Status(Status.AREA_FULL_SOME);
+ area.addChild(blockArea);
+ area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ + blockArea.getMaxHeight());
+ area.increaseHeight(blockArea.getHeight());
+ area.setAbsoluteHeight(blockArea.getAbsoluteHeight());
+ anythingLaidOut = true;
+
+ return status;
+ } else // i == 0 nothing was laid out..
+ {
+ anythingLaidOut = false;
+ return status;
+ }
+ }
+
+ // blockArea.end();
+ area.addChild(blockArea);
+ area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ + blockArea.getMaxHeight());
+ area.increaseHeight(blockArea.getHeight());
+ area.setAbsoluteHeight(blockArea.getAbsoluteHeight());
+ anythingLaidOut = true;
+ return status;
+ }
+ anythingLaidOut = true;
+ }
+
+ blockArea.end();
+
+ area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ + blockArea.getMaxHeight());
+
+ area.addChild(blockArea);
+
+ /* should this be combined into above? */
+ area.increaseHeight(blockArea.getHeight());
+
+ area.setAbsoluteHeight(blockArea.getAbsoluteHeight());
+
+ if (spaceAfter != 0) {
+ area.addDisplaySpace(spaceAfter);
+ }
+
+ if (area instanceof BlockArea) {
+ area.start();
+ }
+
+ // no break if last in area tree, or trailing in context
+ // area
+ int breakAfterStatus = propMgr.checkBreakAfter(area);
+ if (breakAfterStatus != Status.OK) {
+ this.marker = BREAK_AFTER;
+ return new Status(breakAfterStatus);
+ }
+
+ if (keepWithNext != 0) {
+ return new Status(Status.KEEP_WITH_NEXT);
+ }
+
+ // MessageHandler.error(" b:OK" + marker + " ");
+ this.blockArea.isLast(true);
+ return new Status(Status.OK);
+ }
+
+ public int getAreaHeight() {
+ return blockArea.getHeight();
+ }
+
+
+ /**
+ * Return the content width of the boxes generated by this FO.
+ */
+ public int getContentWidth() {
+ if (blockArea != null)
+ return blockArea.getContentWidth(); // getAllocationWidth()??
+ else
+ return 0; // not laid out yet
+ }
+
+ public int getSpan() {
+ return this.span;
+ }
+
}
diff --git a/src/org/apache/fop/fo/flow/BlockContainer.java b/src/org/apache/fop/fo/flow/BlockContainer.java
index c8b8ae234..4d565a8a0 100644
--- a/src/org/apache/fop/fo/flow/BlockContainer.java
+++ b/src/org/apache/fop/fo/flow/BlockContainer.java
@@ -1,8 +1,8 @@
-//-- $Id$ --
-/*
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo.flow;
@@ -21,139 +21,135 @@ import java.util.Enumeration;
public class BlockContainer extends FObj {
- ColorType backgroundColor;
- int position;
-
- int top;
- int bottom;
- int left;
- int right;
- int width;
- int height;
-
- int span;
-
- AreaContainer areaContainer;
-
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new BlockContainer(parent, propertyList);
- }
- }
-
- public static FObj.Maker maker() {
- return new BlockContainer.Maker();
- }
-
- PageSequence pageSequence;
-
- protected BlockContainer(FObj parent, PropertyList propertyList)
- throws FOPException {
- super(parent, propertyList);
- this.name = "fo:block-container";
- this.span = this.properties.get("span").getEnum();
- }
-
- public Status layout(Area area) throws FOPException {
- if (this.marker == START) {
- this.marker = 0;
-
- this.backgroundColor =
- this.properties.get("background-color").getColorType();
-
- this.position =
- this.properties.get("position").getEnum();
- this.top =
- this.properties.get("top").getLength().mvalue();
- this.bottom =
- this.properties.get("bottom").getLength().mvalue();
- this.left =
- this.properties.get("left").getLength().mvalue();
- this.right =
- this.properties.get("right").getLength().mvalue();
- this.width =
- this.properties.get("width").getLength().mvalue();
- this.height =
- this.properties.get("height").getLength().mvalue();
- span = this.properties.get("span").getEnum();
-
- // initialize id
- String id = this.properties.get("id").getString();
- area.getIDReferences().initializeID(id,area);
+ ColorType backgroundColor;
+ int position;
+
+ int top;
+ int bottom;
+ int left;
+ int right;
+ int width;
+ int height;
+
+ int span;
+
+ AreaContainer areaContainer;
+
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new BlockContainer(parent, propertyList);
+ }
+
+ }
+
+ public static FObj.Maker maker() {
+ return new BlockContainer.Maker();
+ }
+
+ PageSequence pageSequence;
+
+ protected BlockContainer(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ super(parent, propertyList);
+ this.name = "fo:block-container";
+ this.span = this.properties.get("span").getEnum();
+ }
+
+ public Status layout(Area area) throws FOPException {
+ if (this.marker == START) {
+ this.marker = 0;
+
+ this.backgroundColor =
+ this.properties.get("background-color").getColorType();
+
+ this.position = this.properties.get("position").getEnum();
+ this.top = this.properties.get("top").getLength().mvalue();
+ this.bottom = this.properties.get("bottom").getLength().mvalue();
+ this.left = this.properties.get("left").getLength().mvalue();
+ this.right = this.properties.get("right").getLength().mvalue();
+ this.width = this.properties.get("width").getLength().mvalue();
+ this.height = this.properties.get("height").getLength().mvalue();
+ span = this.properties.get("span").getEnum();
+
+ // initialize id
+ String id = this.properties.get("id").getString();
+ area.getIDReferences().initializeID(id, area);
+ }
+
+ boolean prevChildMustKeepWithNext = false;
+
+ AreaContainer container = (AreaContainer)area;
+ if ((this.width == 0) && (this.height == 0)) {
+ width = right - left;
+ height = bottom - top;
+ }
+
+ this.areaContainer =
+ new AreaContainer(propMgr.getFontState(container.getFontInfo()),
+ container.getXPosition() + left,
+ container.getYPosition() - top, width, height,
+ position);
+
+ areaContainer.setPage(area.getPage());
+ areaContainer.setBackgroundColor(backgroundColor);
+ areaContainer.setBorderAndPadding(propMgr.getBorderAndPadding());
+ areaContainer.start();
+
+ areaContainer.setAbsoluteHeight(area.getAbsoluteHeight());
+ areaContainer.setIDReferences(area.getIDReferences());
+
+ int numChildren = this.children.size();
+ for (int i = this.marker; i < numChildren; i++) {
+ FObj fo = (FObj)children.elementAt(i);
+ Status status;
+ if ((status = fo.layout(areaContainer)).isIncomplete()) {
+ /*
+ * if ((prevChildMustKeepWithNext) && (status.laidOutNone())) {
+ * this.marker = i - 1;
+ * FObj prevChild = (FObj) children.elementAt(this.marker);
+ * prevChild.removeAreas();
+ * prevChild.resetMarker();
+ * return new Status(Status.AREA_FULL_SOME);
+ * // should probably return AREA_FULL_NONE if first
+ * // or perhaps an entirely new status code
+ * } else {
+ * this.marker = i;
+ * return status;
+ * }
+ */
+ }
+ if (status.getCode() == Status.KEEP_WITH_NEXT) {
+ prevChildMustKeepWithNext = true;
+ }
+ }
+ area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
+
+ areaContainer.end();
+ if (position == Position.ABSOLUTE)
+ areaContainer.setHeight(height);
+ area.addChild(areaContainer);
+
+ return new Status(Status.OK);
+ }
+
+ /**
+ * Return the content width of the boxes generated by this block
+ * container FO.
+ */
+ public int getContentWidth() {
+ if (areaContainer != null)
+ return areaContainer.getContentWidth(); // getAllocationWidth()??
+ else
+ return 0; // not laid out yet
+ }
+
+ public boolean generatesReferenceAreas() {
+ return true;
+ }
+
+ public int getSpan() {
+ return this.span;
}
- boolean prevChildMustKeepWithNext = false;
-
- AreaContainer container = (AreaContainer)area;
- if ((this.width == 0) && (this.height == 0)) {
- width = right - left;
- height = bottom - top;
- }
-
- this.areaContainer =
- new AreaContainer(propMgr.getFontState(container.getFontInfo()),
- container.getXPosition() + left,
- container.getYPosition() - top, width, height,
- position);
-
- areaContainer.setPage(area.getPage());
- areaContainer.setBackgroundColor(backgroundColor);
- areaContainer.setBorderAndPadding(propMgr.getBorderAndPadding());
- areaContainer.start();
-
- areaContainer.setAbsoluteHeight(area.getAbsoluteHeight());
- areaContainer.setIDReferences(area.getIDReferences());
-
- int numChildren = this.children.size();
- for (int i = this.marker; i < numChildren; i++) {
- FObj fo = (FObj) children.elementAt(i);
- Status status;
- if ((status = fo.layout(areaContainer)).isIncomplete()) {
- /*
- if ((prevChildMustKeepWithNext) && (status.laidOutNone())) {
- this.marker = i - 1;
- FObj prevChild = (FObj) children.elementAt(this.marker);
- prevChild.removeAreas();
- prevChild.resetMarker();
- return new Status(Status.AREA_FULL_SOME);
- // should probably return AREA_FULL_NONE if first
- // or perhaps an entirely new status code
- } else {
- this.marker = i;
- return status;
- }
- */
- }
- if (status.getCode() == Status.KEEP_WITH_NEXT) {
- prevChildMustKeepWithNext = true;
- }
- }
- area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
-
- areaContainer.end();
- if (position == Position.ABSOLUTE)
- areaContainer.setHeight(height);
- area.addChild(areaContainer);
-
- return new Status(Status.OK);
- }
-
- /**
- * Return the content width of the boxes generated by this block
- * container FO.
- */
- public int getContentWidth() {
- if (areaContainer != null)
- return areaContainer.getContentWidth(); //getAllocationWidth()??
- else return 0; // not laid out yet
- }
-
- public boolean generatesReferenceAreas() {
- return true;
- }
-
- public int getSpan() {
- return this.span;
- }
}
diff --git a/src/org/apache/fop/fo/flow/Character.java b/src/org/apache/fop/fo/flow/Character.java
index a9a7c3c83..5701792b8 100644
--- a/src/org/apache/fop/fo/flow/Character.java
+++ b/src/org/apache/fop/fo/flow/Character.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -6,7 +7,7 @@
package org.apache.fop.fo.flow;
-//fop
+// fop
import org.apache.fop.fo.*;
import org.apache.fop.fo.properties.*;
import org.apache.fop.datatypes.ColorType;
@@ -21,76 +22,77 @@ import org.apache.fop.messaging.MessageHandler;
/**
- * this class represents the flow object 'fo:character'. Its use is defined by
- * the spec: "The fo:character flow object represents a character that is mapped to
- * a glyph for presentation. It is an atomic unit to the formatter.
- * When the result tree is interpreted as a tree of formatting objects,
- * a character in the result tree is treated as if it were an empty
- * element of type fo:character with a character attribute
- * equal to the Unicode representation of the character.
- * The semantics of an "auto" value for character properties, which is
- * typically their initial value, are based on the Unicode codepoint.
- * Overrides may be specified in an implementation-specific manner." (6.6.3)
+ * this class represents the flow object 'fo:character'. Its use is defined by
+ * the spec: "The fo:character flow object represents a character that is mapped to
+ * a glyph for presentation. It is an atomic unit to the formatter.
+ * When the result tree is interpreted as a tree of formatting objects,
+ * a character in the result tree is treated as if it were an empty
+ * element of type fo:character with a character attribute
+ * equal to the Unicode representation of the character.
+ * The semantics of an "auto" value for character properties, which is
+ * typically their initial value, are based on the Unicode codepoint.
+ * Overrides may be specified in an implementation-specific manner." (6.6.3)
*
*/
-public class Character extends FObj {
- public final static int OK = 0;
- public final static int DOESNOT_FIT = 1;
+public class Character extends FObj {
+ public final static int OK = 0;
+ public final static int DOESNOT_FIT = 1;
- public Character(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:character";
- }
+ public Character(FObj parent, PropertyList propertyList) {
+ super(parent, propertyList);
+ this.name = "fo:character";
+ }
- public static FObj.Maker maker() {
- return new Character.Maker();
- }
+ public static FObj.Maker maker() {
+ return new Character.Maker();
+ }
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent,
- PropertyList propertyList) throws FOPException {
- return new Character(parent, propertyList);
- }
- }
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new Character(parent, propertyList);
+ }
+
+ }
- public Status layout(Area area) throws FOPException {
- BlockArea blockArea;
- if(!(area instanceof BlockArea)) {
+ public Status layout(Area area) throws FOPException {
+ BlockArea blockArea;
+ if (!(area instanceof BlockArea)) {
MessageHandler.errorln("WARNING: currently Character can only be in a BlockArea");
return new Status(Status.OK);
}
- blockArea = (BlockArea) area;
- boolean textDecoration;
-
- //color properties
- ColorType c = this.properties.get("color").getColorType();
- float red = c.red();
- float green = c.green();
- float blue = c.blue();
-
- int whiteSpaceCollapse = this.properties.get(
- "white-space-collapse").getEnum();
- int wrapOption = this.parent.properties.get("wrap-option").getEnum();
-
- int tmp = this.properties.get("text-decoration").getEnum();
- if (tmp == org.apache.fop.fo.properties.TextDecoration.UNDERLINE) {
- textDecoration = true;
- } else {
- textDecoration = false;
- }
+ blockArea = (BlockArea)area;
+ boolean textDecoration;
+
+ // color properties
+ ColorType c = this.properties.get("color").getColorType();
+ float red = c.red();
+ float green = c.green();
+ float blue = c.blue();
+
+ int whiteSpaceCollapse =
+ this.properties.get("white-space-collapse").getEnum();
+ int wrapOption = this.parent.properties.get("wrap-option").getEnum();
+
+ int tmp = this.properties.get("text-decoration").getEnum();
+ if (tmp == org.apache.fop.fo.properties.TextDecoration.UNDERLINE) {
+ textDecoration = true;
+ } else {
+ textDecoration = false;
+ }
- //Character specific properties
- char characterValue = this.properties.get("character").getCharacter();
+ // Character specific properties
+ char characterValue = this.properties.get("character").getCharacter();
- // initialize id
- String id = this.properties.get("id").getString();
- blockArea.getIDReferences().initializeID(id, blockArea);
+ // initialize id
+ String id = this.properties.get("id").getString();
+ blockArea.getIDReferences().initializeID(id, blockArea);
LineArea la = blockArea.getCurrentLineArea();
- if(la == null) {
+ if (la == null) {
return new Status(Status.AREA_FULL_NONE);
}
la.changeFont(propMgr.getFontState(area.getFontInfo()));
@@ -98,10 +100,11 @@ public class Character extends FObj {
la.changeWrapOption(wrapOption);
la.changeWhiteSpaceCollapse(whiteSpaceCollapse);
blockArea.setupLinkSet(this.getLinkSet());
- int result = la.addCharacter(characterValue, this.getLinkSet(), textDecoration);
+ int result = la.addCharacter(characterValue, this.getLinkSet(),
+ textDecoration);
if (result == Character.DOESNOT_FIT) {
la = blockArea.createNextLineArea();
- if(la == null) {
+ if (la == null) {
return new Status(Status.AREA_FULL_NONE);
}
la.changeFont(propMgr.getFontState(area.getFontInfo()));
@@ -109,10 +112,11 @@ public class Character extends FObj {
la.changeWrapOption(wrapOption);
la.changeWhiteSpaceCollapse(whiteSpaceCollapse);
blockArea.setupLinkSet(this.getLinkSet());
- la.addCharacter(characterValue, this.getLinkSet(), textDecoration);
+ la.addCharacter(characterValue, this.getLinkSet(),
+ textDecoration);
}
- return new Status(Status.OK);
+ return new Status(Status.OK);
- }
+ }
}
diff --git a/src/org/apache/fop/fo/flow/ExternalGraphic.java b/src/org/apache/fop/fo/flow/ExternalGraphic.java
index d828a5d06..802db0e25 100644
--- a/src/org/apache/fop/fo/flow/ExternalGraphic.java
+++ b/src/org/apache/fop/fo/flow/ExternalGraphic.java
@@ -1,42 +1,9 @@
/*
- * ============================================================================
- * The Apache Software License, Version 1.1
- * ============================================================================
- * Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
- * Redistribution and use in source and binary forms, with or without modifica-
- * tion, are permitted provided that the following conditions are met:
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The end-user documentation included with the redistribution, if any, must
- * include the following acknowledgment: "This product includes software
- * developed by the Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgment may appear in the software itself, if
- * and wherever such third-party acknowledgments normally appear.
- * 4. The names "FOP" and "Apache Software Foundation" must not be used to
- * endorse or promote products derived from this software without prior
- * written permission. For written permission, please contact
- * apache@apache.org.
- * 5. Products derived from this software may not be called "Apache", nor may
- * "Apache" appear in their name, without prior written permission of the
- * Apache Software Foundation.
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * This software consists of voluntary contributions made by many individuals
- * on behalf of the Apache Software Foundation and was originally created by
- * James Tauber . For more information on the Apache
- * Software Foundation, please see . */
-/* Modified by Eric SCHAEFFER */
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.fo.flow;
@@ -56,211 +23,206 @@ import java.net.MalformedURLException;
public class ExternalGraphic extends FObj {
- int breakAfter;
- int breakBefore;
- int align;
- int startIndent;
- int endIndent;
- int spaceBefore;
- int spaceAfter;
- String src;
- int height;
- int width;
- String id;
-
- ImageArea imageArea;
-
-
- public ExternalGraphic(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:external-graphic";
- }
-
-
- public Status layout(Area area) throws FOPException {
-
- if (this.marker == START) {
- // FIXME
- this.align = this.properties.get("text-align").getEnum();
-
- this.startIndent = this.properties.get(
- "start-indent").getLength().mvalue();
- this.endIndent = this.properties.get(
- "end-indent").getLength().mvalue();
-
- this.spaceBefore = this.properties.get(
- "space-before.optimum").getLength().mvalue();
- this.spaceAfter = this.properties.get(
- "space-after.optimum").getLength().mvalue();
-
- this.src = this.properties.get("src").getString();
-
- this.width = this.properties.get("width").getLength().mvalue();
-
- this.height =
- this.properties.get("height").getLength().mvalue();
-
- this.id = this.properties.get("id").getString();
-
- area.getIDReferences().createID(id);
-/*
- if (area instanceof BlockArea) {
- area.end();
- }
-
- if (this.isInTableCell) {
- startIndent += forcedStartOffset;
- endIndent = area.getAllocationWidth() - forcedWidth -
- forcedStartOffset;
- }
-
-*/
- this.marker = 0;
- }
-
- try {
- FopImage img = FopImageFactory.Make(src);
- // if width / height needs to be computed
- if ((width == 0) || (height == 0)) {
- // aspect ratio
- double imgWidth = img.getWidth();
- double imgHeight = img.getHeight();
- if ((width == 0) && (height == 0)) {
- width = (int) ((imgWidth * 1000d));
- height = (int) ((imgHeight * 1000d));
- }
- else if (height == 0) {
- height = (int) ((imgHeight * ((double) width)) /
- imgWidth);
- }
- else if (width == 0) {
- width = (int) ((imgWidth * ((double) height)) /
- imgHeight);
- }
- }
-
- // scale image if it doesn't fit in the area/page
- // Need to be more tested...
- double ratio = ((double) width) / ((double) height);
- int areaWidth = area.getAllocationWidth() - startIndent - endIndent;
- int pageHeight = area.getPage().getHeight();
- if (height > pageHeight) {
- height = pageHeight;
- width = (int) (ratio * ((double) height));
- }
- if (width > areaWidth) {
- width = areaWidth;
- height = (int) (((double) width) / ratio);
- }
-
- if (area.spaceLeft() < (height + spaceBefore)) {
- return new Status(Status.AREA_FULL_NONE);
- }
-
- this.imageArea =
- new ImageArea(propMgr.getFontState(area.getFontInfo()),
- img, area.getAllocationWidth(),
- width, height, startIndent, endIndent, align);
-
- if ((spaceBefore != 0) && (this.marker == 0)) {
- area.addDisplaySpace(spaceBefore);
- }
-
- if (marker == 0) {
- // configure id
- area.getIDReferences().configureID(id, area);
- }
-
- imageArea.start();
- imageArea.end();
- //area.addChild(imageArea);
- //area.increaseHeight(imageArea.getHeight());
-
- if (spaceAfter != 0) {
- area.addDisplaySpace(spaceAfter);
- }
- if (breakBefore == BreakBefore.PAGE || ((spaceBefore + imageArea.getHeight()) > area.spaceLeft())) {
- return new Status(Status.FORCE_PAGE_BREAK);
- }
-
- if (breakBefore == BreakBefore.ODD_PAGE) {
- return new Status(Status.FORCE_PAGE_BREAK_ODD);
- }
-
- if (breakBefore == BreakBefore.EVEN_PAGE) {
- return new Status(Status.FORCE_PAGE_BREAK_EVEN);
- }
-
-
- if (area instanceof BlockArea) {
- BlockArea ba = (BlockArea)area;
- LineArea la = ba.getCurrentLineArea();
- if(la == null) {
- return new Status(Status.AREA_FULL_NONE);
- }
- la.addPending();
- if(imageArea.getContentWidth() > la.getRemainingWidth()) {
- la = ba.createNextLineArea();
- if(la == null) {
- return new Status(Status.AREA_FULL_NONE);
- }
- }
- la.addInlineArea(imageArea);
- } else {
- area.addChild(imageArea);
- area.increaseHeight(imageArea.getContentHeight());
- }
- imageArea.setPage(area.getPage());
-
- if (breakAfter == BreakAfter.PAGE) {
- this.marker = BREAK_AFTER;
- return new Status(Status.FORCE_PAGE_BREAK);
- }
-
- if (breakAfter == BreakAfter.ODD_PAGE) {
- this.marker = BREAK_AFTER;
- return new Status(Status.FORCE_PAGE_BREAK_ODD);
- }
-
- if (breakAfter == BreakAfter.EVEN_PAGE) {
- this.marker = BREAK_AFTER;
- return new Status(Status.FORCE_PAGE_BREAK_EVEN);
- }
-
-
-
-
-
- }
- catch (MalformedURLException urlex) {
- // bad URL
- MessageHandler.errorln("Error while creating area : " +
- urlex.getMessage());
- }
- catch (FopImageException imgex) {
- // image error
- MessageHandler.errorln("Error while creating area : " +
- imgex.getMessage());
- }
-
- //if (area instanceof BlockArea) {
- // area.start();
- //}
-
- return new Status(Status.OK);
- }
-
-
- public static FObj.Maker maker() {
- return new ExternalGraphic.Maker();
- }
-
-
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent,
- PropertyList propertyList) throws FOPException {
- return new ExternalGraphic(parent, propertyList);
- }
- }
+ int breakAfter;
+ int breakBefore;
+ int align;
+ int startIndent;
+ int endIndent;
+ int spaceBefore;
+ int spaceAfter;
+ String src;
+ int height;
+ int width;
+ String id;
+
+ ImageArea imageArea;
+
+
+ public ExternalGraphic(FObj parent, PropertyList propertyList) {
+ super(parent, propertyList);
+ this.name = "fo:external-graphic";
+ }
+
+
+ public Status layout(Area area) throws FOPException {
+
+ if (this.marker == START) {
+ // FIXME
+ this.align = this.properties.get("text-align").getEnum();
+
+ this.startIndent =
+ this.properties.get("start-indent").getLength().mvalue();
+ this.endIndent =
+ this.properties.get("end-indent").getLength().mvalue();
+
+ this.spaceBefore =
+ this.properties.get("space-before.optimum").getLength().mvalue();
+ this.spaceAfter =
+ this.properties.get("space-after.optimum").getLength().mvalue();
+
+ this.src = this.properties.get("src").getString();
+
+ this.width = this.properties.get("width").getLength().mvalue();
+
+ this.height = this.properties.get("height").getLength().mvalue();
+
+ this.id = this.properties.get("id").getString();
+
+ area.getIDReferences().createID(id);
+ /*
+ * if (area instanceof BlockArea) {
+ * area.end();
+ * }
+ * if (this.isInTableCell) {
+ * startIndent += forcedStartOffset;
+ * endIndent = area.getAllocationWidth() - forcedWidth -
+ * forcedStartOffset;
+ * }
+ */
+ this.marker = 0;
+ }
+
+ try {
+ FopImage img = FopImageFactory.Make(src);
+ // if width / height needs to be computed
+ if ((width == 0) || (height == 0)) {
+ // aspect ratio
+ double imgWidth = img.getWidth();
+ double imgHeight = img.getHeight();
+ if ((width == 0) && (height == 0)) {
+ width = (int)((imgWidth * 1000d));
+ height = (int)((imgHeight * 1000d));
+ } else if (height == 0) {
+ height = (int)((imgHeight * ((double)width)) / imgWidth);
+ } else if (width == 0) {
+ width = (int)((imgWidth * ((double)height)) / imgHeight);
+ }
+ }
+
+ // scale image if it doesn't fit in the area/page
+ // Need to be more tested...
+ double ratio = ((double)width) / ((double)height);
+ int areaWidth = area.getAllocationWidth() - startIndent
+ - endIndent;
+ int pageHeight = area.getPage().getHeight();
+ if (height > pageHeight) {
+ height = pageHeight;
+ width = (int)(ratio * ((double)height));
+ }
+ if (width > areaWidth) {
+ width = areaWidth;
+ height = (int)(((double)width) / ratio);
+ }
+
+ if (area.spaceLeft() < (height + spaceBefore)) {
+ return new Status(Status.AREA_FULL_NONE);
+ }
+
+ this.imageArea =
+ new ImageArea(propMgr.getFontState(area.getFontInfo()), img,
+ area.getAllocationWidth(), width, height,
+ startIndent, endIndent, align);
+
+ if ((spaceBefore != 0) && (this.marker == 0)) {
+ area.addDisplaySpace(spaceBefore);
+ }
+
+ if (marker == 0) {
+ // configure id
+ area.getIDReferences().configureID(id, area);
+ }
+
+ imageArea.start();
+ imageArea.end();
+ // area.addChild(imageArea);
+ // area.increaseHeight(imageArea.getHeight());
+
+ if (spaceAfter != 0) {
+ area.addDisplaySpace(spaceAfter);
+ }
+ if (breakBefore == BreakBefore.PAGE
+ || ((spaceBefore + imageArea.getHeight())
+ > area.spaceLeft())) {
+ return new Status(Status.FORCE_PAGE_BREAK);
+ }
+
+ if (breakBefore == BreakBefore.ODD_PAGE) {
+ return new Status(Status.FORCE_PAGE_BREAK_ODD);
+ }
+
+ if (breakBefore == BreakBefore.EVEN_PAGE) {
+ return new Status(Status.FORCE_PAGE_BREAK_EVEN);
+ }
+
+
+ if (area instanceof BlockArea) {
+ BlockArea ba = (BlockArea)area;
+ LineArea la = ba.getCurrentLineArea();
+ if (la == null) {
+ return new Status(Status.AREA_FULL_NONE);
+ }
+ la.addPending();
+ if (imageArea.getContentWidth() > la.getRemainingWidth()) {
+ la = ba.createNextLineArea();
+ if (la == null) {
+ return new Status(Status.AREA_FULL_NONE);
+ }
+ }
+ la.addInlineArea(imageArea);
+ } else {
+ area.addChild(imageArea);
+ area.increaseHeight(imageArea.getContentHeight());
+ }
+ imageArea.setPage(area.getPage());
+
+ if (breakAfter == BreakAfter.PAGE) {
+ this.marker = BREAK_AFTER;
+ return new Status(Status.FORCE_PAGE_BREAK);
+ }
+
+ if (breakAfter == BreakAfter.ODD_PAGE) {
+ this.marker = BREAK_AFTER;
+ return new Status(Status.FORCE_PAGE_BREAK_ODD);
+ }
+
+ if (breakAfter == BreakAfter.EVEN_PAGE) {
+ this.marker = BREAK_AFTER;
+ return new Status(Status.FORCE_PAGE_BREAK_EVEN);
+ }
+
+
+
+
+
+ } catch (MalformedURLException urlex) {
+ // bad URL
+ MessageHandler.errorln("Error while creating area : "
+ + urlex.getMessage());
+ } catch (FopImageException imgex) {
+ // image error
+ MessageHandler.errorln("Error while creating area : "
+ + imgex.getMessage());
+ }
+
+ // if (area instanceof BlockArea) {
+ // area.start();
+ // }
+
+ return new Status(Status.OK);
+ }
+
+
+ public static FObj.Maker maker() {
+ return new ExternalGraphic.Maker();
+ }
+
+
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new ExternalGraphic(parent, propertyList);
+ }
+
+ }
}
diff --git a/src/org/apache/fop/fo/flow/Float.java b/src/org/apache/fop/fo/flow/Float.java
index 00f769dc4..3fb948c40 100644
--- a/src/org/apache/fop/fo/flow/Float.java
+++ b/src/org/apache/fop/fo/flow/Float.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -23,6 +24,7 @@ public class Float extends ToBeImplementedElement {
PropertyList propertyList) throws FOPException {
return new Float(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -30,7 +32,7 @@ public class Float extends ToBeImplementedElement {
}
protected Float(FObj parent,
- PropertyList propertyList) throws FOPException {
+ PropertyList propertyList) throws FOPException {
super(parent, propertyList);
this.name = "fo:float";
}
diff --git a/src/org/apache/fop/fo/flow/Flow.java b/src/org/apache/fop/fo/flow/Flow.java
index 716e58f8a..9f90dca51 100644
--- a/src/org/apache/fop/fo/flow/Flow.java
+++ b/src/org/apache/fop/fo/flow/Flow.java
@@ -1,4 +1,5 @@
-/*-- $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -21,205 +22,207 @@ import java.util.Enumeration;
import java.util.Vector;
public class Flow extends FObj {
-
+
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new Flow(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new Flow(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new Flow.Maker();
+ return new Flow.Maker();
}
- /** PageSequence container */
+ /**
+ * PageSequence container
+ */
private PageSequence pageSequence;
- /** Area in which we lay out our kids */
- private Area area;
+ /**
+ * Area in which we lay out our kids
+ */
+ private Area area;
- /** Vector to store snapshot */
- private Vector markerSnapshot;
+ /**
+ * Vector to store snapshot
+ */
+ private Vector markerSnapshot;
- /** flow-name attribute */
+ /**
+ * flow-name attribute
+ */
private String _flowName;
-
+
private Status _status = new Status(Status.AREA_FULL_NONE);
-
-
- protected Flow(FObj parent, PropertyList propertyList)
- throws FOPException {
- super(parent, propertyList);
- this.name = getElementName();
-
- if (parent.getName().equals("fo:page-sequence")) {
- this.pageSequence = (PageSequence) parent;
- } else {
- throw new FOPException("flow must be child of "
- + "page-sequence, not "
- + parent.getName());
- }
- setFlowName(getProperty("flow-name").getString());
-
- // according to communication from Paul Grosso (XSL-List,
- // 001228, Number 406), confusion in spec section 6.4.5 about
- // multiplicity of fo:flow in XSL 1.0 is cleared up - one (1)
- // fo:flow per fo:page-sequence only.
-
- if (pageSequence.isFlowSet()) {
- if (this.name.equals("fo:flow")) {
- throw new FOPException("Only a single fo:flow permitted"
- + " per fo:page-sequence");
- }
- else {
- throw new FOPException(this.name+" not allowed after fo:flow");
- }
- }
- pageSequence.addFlow(this);
+
+
+ protected Flow(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ super(parent, propertyList);
+ this.name = getElementName();
+
+ if (parent.getName().equals("fo:page-sequence")) {
+ this.pageSequence = (PageSequence)parent;
+ } else {
+ throw new FOPException("flow must be child of "
+ + "page-sequence, not "
+ + parent.getName());
+ }
+ setFlowName(getProperty("flow-name").getString());
+
+ // according to communication from Paul Grosso (XSL-List,
+ // 001228, Number 406), confusion in spec section 6.4.5 about
+ // multiplicity of fo:flow in XSL 1.0 is cleared up - one (1)
+ // fo:flow per fo:page-sequence only.
+
+ if (pageSequence.isFlowSet()) {
+ if (this.name.equals("fo:flow")) {
+ throw new FOPException("Only a single fo:flow permitted"
+ + " per fo:page-sequence");
+ } else {
+ throw new FOPException(this.name
+ + " not allowed after fo:flow");
+ }
+ }
+ pageSequence.addFlow(this);
}
- protected void setFlowName(String name)
- throws FOPException
- {
- if (name == null || name.equals("")) {
- MessageHandler.errorln("WARNING: A 'flow-name' is required for "+getElementName()+". This constraint will be enforced in future versions of FOP");
- _flowName = "xsl-region-body";
- }
- else {
- _flowName = name;
- }
-
+ protected void setFlowName(String name) throws FOPException {
+ if (name == null || name.equals("")) {
+ MessageHandler.errorln("WARNING: A 'flow-name' is required for "
+ + getElementName()
+ + ". This constraint will be enforced in future versions of FOP");
+ _flowName = "xsl-region-body";
+ } else {
+ _flowName = name;
+ }
+
}
-
- public String getFlowName()
- {
- return _flowName;
+
+ public String getFlowName() {
+ return _flowName;
}
-
+
public Status layout(Area area) throws FOPException {
- return layout(area, null);
-
+ return layout(area, null);
+
}
-
+
public Status layout(Area area, Region region) throws FOPException {
- if (this.marker == START) {
- this.marker = 0;
- }
-
- // flow is *always* laid out into a BodyAreaContainer
- BodyAreaContainer bac = (BodyAreaContainer)area;
-
- boolean prevChildMustKeepWithNext = false;
- Vector pageMarker = this.getMarkerSnapshot(new Vector());
-
- int numChildren = this.children.size();
- if (numChildren == 0)
- {
- throw new FOPException("fo:flow must contain block-level children");
- }
- for (int i = this.marker; i < numChildren; i++) {
- FObj fo = (FObj) children.elementAt(i);
-
- if (bac.isBalancingRequired(fo))
- {
- // reset the the just-done span area in preparation
- // for a backtrack for balancing
- bac.resetSpanArea();
-
- this.rollback(markerSnapshot);
- // one less because of the "continue"
- i = this.marker - 1;
- continue;
- }
- // current column area
- Area currentArea = bac.getNextArea(fo);
- // temporary hack for IDReferences
- currentArea.setIDReferences(bac.getIDReferences());
- if (bac.isNewSpanArea())
- {
- this.marker = i;
- markerSnapshot = this.getMarkerSnapshot(new Vector());
- }
-
- _status = fo.layout(currentArea);
-
-/* if((_status.isPageBreak() || i == numChildren - 1) && bac.needsFootnoteAdjusting()) {
- bac.adjustFootnoteArea();
- this.rollback(pageMarker);
- i = this.marker - 1;
- Area mainReferenceArea = bac.getMainReferenceArea();
- // remove areas
- continue;
- }*/
- if (_status.isIncomplete()) {
- if ((prevChildMustKeepWithNext) && (_status.laidOutNone())) {
- this.marker = i - 1;
- FObj prevChild = (FObj) children.elementAt(this.marker);
- prevChild.removeAreas();
- prevChild.resetMarker();
- prevChild.removeID(area.getIDReferences());
- _status = new Status(Status.AREA_FULL_SOME);
- return _status;
- // should probably return AREA_FULL_NONE if first
- // or perhaps an entirely new status code
- }
- if (bac.isLastColumn())
- if (_status.getCode() == Status.FORCE_COLUMN_BREAK) {
- this.marker = i;
- _status = new Status(Status.FORCE_PAGE_BREAK); // same thing
- return _status;
- }
- else {
- this.marker = i;
- return _status;
- }
- else
- {
- // not the last column, but could be page breaks
- if (_status.isPageBreak())
- {
- this.marker = i;
- return _status;
- }
- // I don't much like exposing this. (AHS 001217)
- ((org.apache.fop.layout.ColumnArea)currentArea).incrementSpanIndex();
- i--;
- }
- }
- if (_status.getCode() == Status.KEEP_WITH_NEXT) {
- prevChildMustKeepWithNext = true;
- }
- else {
- prevChildMustKeepWithNext = false;
- }
- }
- return _status;
+ if (this.marker == START) {
+ this.marker = 0;
+ }
+
+ // flow is *always* laid out into a BodyAreaContainer
+ BodyAreaContainer bac = (BodyAreaContainer)area;
+
+ boolean prevChildMustKeepWithNext = false;
+ Vector pageMarker = this.getMarkerSnapshot(new Vector());
+
+ int numChildren = this.children.size();
+ if (numChildren == 0) {
+ throw new FOPException("fo:flow must contain block-level children");
+ }
+ for (int i = this.marker; i < numChildren; i++) {
+ FObj fo = (FObj)children.elementAt(i);
+
+ if (bac.isBalancingRequired(fo)) {
+ // reset the the just-done span area in preparation
+ // for a backtrack for balancing
+ bac.resetSpanArea();
+
+ this.rollback(markerSnapshot);
+ // one less because of the "continue"
+ i = this.marker - 1;
+ continue;
+ }
+ // current column area
+ Area currentArea = bac.getNextArea(fo);
+ // temporary hack for IDReferences
+ currentArea.setIDReferences(bac.getIDReferences());
+ if (bac.isNewSpanArea()) {
+ this.marker = i;
+ markerSnapshot = this.getMarkerSnapshot(new Vector());
+ }
+
+ _status = fo.layout(currentArea);
+
+ /*
+ * if((_status.isPageBreak() || i == numChildren - 1) && bac.needsFootnoteAdjusting()) {
+ * bac.adjustFootnoteArea();
+ * this.rollback(pageMarker);
+ * i = this.marker - 1;
+ * Area mainReferenceArea = bac.getMainReferenceArea();
+ * // remove areas
+ * continue;
+ * }
+ */
+ if (_status.isIncomplete()) {
+ if ((prevChildMustKeepWithNext) && (_status.laidOutNone())) {
+ this.marker = i - 1;
+ FObj prevChild = (FObj)children.elementAt(this.marker);
+ prevChild.removeAreas();
+ prevChild.resetMarker();
+ prevChild.removeID(area.getIDReferences());
+ _status = new Status(Status.AREA_FULL_SOME);
+ return _status;
+ // should probably return AREA_FULL_NONE if first
+ // or perhaps an entirely new status code
+ }
+ if (bac.isLastColumn())
+ if (_status.getCode() == Status.FORCE_COLUMN_BREAK) {
+ this.marker = i;
+ _status =
+ new Status(Status.FORCE_PAGE_BREAK); // same thing
+ return _status;
+ } else {
+ this.marker = i;
+ return _status;
+ }
+ else {
+ // not the last column, but could be page breaks
+ if (_status.isPageBreak()) {
+ this.marker = i;
+ return _status;
+ }
+ // I don't much like exposing this. (AHS 001217)
+ ((org.apache.fop.layout.ColumnArea)currentArea).incrementSpanIndex();
+ i--;
+ }
+ }
+ if (_status.getCode() == Status.KEEP_WITH_NEXT) {
+ prevChildMustKeepWithNext = true;
+ } else {
+ prevChildMustKeepWithNext = false;
+ }
+ }
+ return _status;
}
- /**
- * Return the content width of this flow (really of the region
- * in which it is flowing).
- */
- public int getContentWidth() {
- if (area != null)
- return area.getContentWidth(); //getAllocationWidth()??
- else return 0; // not laid out yet
- }
-
- protected String getElementName()
- {
- return "fo:flow";
+ /**
+ * Return the content width of this flow (really of the region
+ * in which it is flowing).
+ */
+ public int getContentWidth() {
+ if (area != null)
+ return area.getContentWidth(); // getAllocationWidth()??
+ else
+ return 0; // not laid out yet
}
-
- public Status getStatus()
- {
- return _status;
+
+ protected String getElementName() {
+ return "fo:flow";
}
-
- public boolean generatesReferenceAreas() {
- return true;
- }
+ public Status getStatus() {
+ return _status;
+ }
+
+
+ public boolean generatesReferenceAreas() {
+ return true;
+ }
}
diff --git a/src/org/apache/fop/fo/flow/Footnote.java b/src/org/apache/fop/fo/flow/Footnote.java
index 3d66d665c..3f72d49fb 100644
--- a/src/org/apache/fop/fo/flow/Footnote.java
+++ b/src/org/apache/fop/fo/flow/Footnote.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo.flow;
@@ -64,86 +20,89 @@ import java.util.Vector;
public class Footnote extends FObj {
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new Footnote(parent, propertyList);
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new Footnote(parent, propertyList);
+ }
+
}
- }
- public static FObj.Maker maker() {
- return new Footnote.Maker();
- }
+ public static FObj.Maker maker() {
+ return new Footnote.Maker();
+ }
- public Footnote(FObj parent, PropertyList propertyList)
- throws FOPException {
- super(parent, propertyList);
- this.name = "fo:footnote";
- }
+ public Footnote(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ super(parent, propertyList);
+ this.name = "fo:footnote";
+ }
public Status layout(Area area) throws FOPException {
FONode inline = null;
FONode fbody = null;
- if(this.marker == START) {
+ if (this.marker == START) {
this.marker = 0;
}
int numChildren = this.children.size();
for (int i = this.marker; i < numChildren; i++) {
- FONode fo = (FONode) children.elementAt(i);
- if(fo instanceof Inline) {
+ FONode fo = (FONode)children.elementAt(i);
+ if (fo instanceof Inline) {
inline = fo;
Status status = fo.layout(area);
- if(status.isIncomplete()) {
+ if (status.isIncomplete()) {
return status;
}
- } else if(inline != null && fo instanceof FootnoteBody) {
+ } else if (inline != null && fo instanceof FootnoteBody) {
// add footnote to current page or next if it can't fit
fbody = fo;
- if(area instanceof BlockArea) {
+ if (area instanceof BlockArea) {
((BlockArea)area).addFootnote((FootnoteBody)fbody);
} else {
Page page = area.getPage();
layoutFootnote(page, (FootnoteBody)fbody, area);
- }
+ }
}
}
- if(fbody == null) {
- MessageHandler.errorln("WARNING: no footnote-body in footnote");
- }
- if (area instanceof BlockArea) {
+ if (fbody == null) {
+ MessageHandler.errorln("WARNING: no footnote-body in footnote");
}
+ if (area instanceof BlockArea) {}
return new Status(Status.OK);
}
- public static boolean layoutFootnote(Page p, FootnoteBody fb, Area area)
- {
+ public static boolean layoutFootnote(Page p, FootnoteBody fb, Area area) {
try {
BodyAreaContainer bac = p.getBody();
AreaContainer footArea = bac.getFootnoteReferenceArea();
footArea.setIDReferences(bac.getIDReferences());
- int basePos = footArea.getCurrentYPosition() - footArea.getHeight();
+ int basePos = footArea.getCurrentYPosition()
+ - footArea.getHeight();
int oldHeight = footArea.getHeight();
- if(area != null) {
- footArea.setMaxHeight(area.getMaxHeight() - area.getHeight() + footArea.getHeight());
+ if (area != null) {
+ footArea.setMaxHeight(area.getMaxHeight() - area.getHeight()
+ + footArea.getHeight());
} else {
- footArea.setMaxHeight(bac.getMaxHeight() + footArea.getHeight());
+ footArea.setMaxHeight(bac.getMaxHeight()
+ + footArea.getHeight());
}
Status status = fb.layout(footArea);
- if(status.isIncomplete()) {
+ if (status.isIncomplete()) {
// add as a pending footnote
return false;
} else {
- if(area != null) {
- area.setMaxHeight(area.getMaxHeight() - footArea.getHeight() + oldHeight);
+ if (area != null) {
+ area.setMaxHeight(area.getMaxHeight()
+ - footArea.getHeight() + oldHeight);
}
- //bac.setMaxHeight(bac.getMaxHeight() - footArea.getHeight() + oldHeight);
- if(bac.getFootnoteState() == 0) {
+ // bac.setMaxHeight(bac.getMaxHeight() - footArea.getHeight() + oldHeight);
+ if (bac.getFootnoteState() == 0) {
Area ar = bac.getMainReferenceArea();
decreaseMaxHeight(ar, footArea.getHeight() - oldHeight);
footArea.setYPosition(basePos + footArea.getHeight());
}
}
- } catch(FOPException fope) {
+ } catch (FOPException fope) {
return false;
}
return true;
@@ -152,12 +111,13 @@ public class Footnote extends FObj {
protected static void decreaseMaxHeight(Area ar, int change) {
ar.setMaxHeight(ar.getMaxHeight() - change);
Vector childs = ar.getChildren();
- for(Enumeration en = childs.elements(); en.hasMoreElements(); ) {
+ for (Enumeration en = childs.elements(); en.hasMoreElements(); ) {
Object obj = en.nextElement();
- if(obj instanceof Area) {
+ if (obj instanceof Area) {
Area childArea = (Area)obj;
decreaseMaxHeight(childArea, change);
}
}
}
+
}
diff --git a/src/org/apache/fop/fo/flow/FootnoteBody.java b/src/org/apache/fop/fo/flow/FootnoteBody.java
index 90e7c81a5..029ea5b92 100644
--- a/src/org/apache/fop/fo/flow/FootnoteBody.java
+++ b/src/org/apache/fop/fo/flow/FootnoteBody.java
@@ -1,4 +1,5 @@
-/*-- $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -19,63 +20,65 @@ import java.util.Enumeration;
public class FootnoteBody extends FObj {
- int align;
- int alignLast;
- int lineHeight;
- int startIndent;
- int endIndent;
- int textIndent;
+ int align;
+ int alignLast;
+ int lineHeight;
+ int startIndent;
+ int endIndent;
+ int textIndent;
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new FootnoteBody(parent, propertyList);
- }
- }
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new FootnoteBody(parent, propertyList);
+ }
- public static FObj.Maker maker() {
- return new FootnoteBody.Maker();
- }
+ }
+
+ public static FObj.Maker maker() {
+ return new FootnoteBody.Maker();
+ }
- public FootnoteBody(FObj parent, PropertyList propertyList)
- throws FOPException {
- super(parent, propertyList);
- this.name = "fo:footnote-body";
- this.areaClass = AreaClass.setAreaClass(AreaClass.XSL_FOOTNOTE);
- }
+ public FootnoteBody(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ super(parent, propertyList);
+ this.name = "fo:footnote-body";
+ this.areaClass = AreaClass.setAreaClass(AreaClass.XSL_FOOTNOTE);
+ }
public Status layout(Area area) throws FOPException {
- if(this.marker == START) {
- this.marker = 0;
- }
- BlockArea blockArea =
- new BlockArea(propMgr.getFontState(area.getFontInfo()),
- area.getAllocationWidth(),
- area.spaceLeft(), startIndent, endIndent, textIndent,
- align, alignLast, lineHeight);
- blockArea.setGeneratedBy(this);
- blockArea.isFirst(true);
- blockArea.setPage(area.getPage());
- blockArea.start();
+ if (this.marker == START) {
+ this.marker = 0;
+ }
+ BlockArea blockArea =
+ new BlockArea(propMgr.getFontState(area.getFontInfo()),
+ area.getAllocationWidth(), area.spaceLeft(),
+ startIndent, endIndent, textIndent, align,
+ alignLast, lineHeight);
+ blockArea.setGeneratedBy(this);
+ blockArea.isFirst(true);
+ blockArea.setPage(area.getPage());
+ blockArea.start();
+
+ blockArea.setAbsoluteHeight(area.getAbsoluteHeight());
+ blockArea.setIDReferences(area.getIDReferences());
- blockArea.setAbsoluteHeight(area.getAbsoluteHeight());
- blockArea.setIDReferences(area.getIDReferences());
-
- blockArea.setTableCellXOffset(area.getTableCellXOffset());
+ blockArea.setTableCellXOffset(area.getTableCellXOffset());
- int numChildren = this.children.size();
- for ( int i = this.marker; i < numChildren; i++ ) {
- FONode fo = (FONode) children.elementAt(i);
- Status status;
- if ( (status = fo.layout(blockArea)).isIncomplete() ) {
- this.resetMarker();
- return status;
- }
- }
- blockArea.end();
- area.addChild(blockArea);
- area.increaseHeight(blockArea.getHeight());
- blockArea.isLast(true);
- return new Status(Status.OK);
+ int numChildren = this.children.size();
+ for (int i = this.marker; i < numChildren; i++) {
+ FONode fo = (FONode)children.elementAt(i);
+ Status status;
+ if ((status = fo.layout(blockArea)).isIncomplete()) {
+ this.resetMarker();
+ return status;
+ }
+ }
+ blockArea.end();
+ area.addChild(blockArea);
+ area.increaseHeight(blockArea.getHeight());
+ blockArea.isLast(true);
+ return new Status(Status.OK);
}
+
}
diff --git a/src/org/apache/fop/fo/flow/InitialPropertySet.java b/src/org/apache/fop/fo/flow/InitialPropertySet.java
index 26ae86e1c..63746b12e 100644
--- a/src/org/apache/fop/fo/flow/InitialPropertySet.java
+++ b/src/org/apache/fop/fo/flow/InitialPropertySet.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -23,14 +24,15 @@ public class InitialPropertySet extends ToBeImplementedElement {
PropertyList propertyList) throws FOPException {
return new InitialPropertySet(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
return new InitialPropertySet.Maker();
}
- protected InitialPropertySet(FObj parent,
- PropertyList propertyList) throws FOPException {
+ protected InitialPropertySet(FObj parent, PropertyList propertyList)
+ throws FOPException {
super(parent, propertyList);
this.name = "fo:initial-property-set";
}
diff --git a/src/org/apache/fop/fo/flow/Inline.java b/src/org/apache/fop/fo/flow/Inline.java
index 2730640ef..0f37ed191 100644
--- a/src/org/apache/fop/fo/flow/Inline.java
+++ b/src/org/apache/fop/fo/flow/Inline.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -17,56 +18,56 @@ import java.util.Enumeration;
public class Inline extends FObjMixed {
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new Inline(parent, propertyList);
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new Inline(parent, propertyList);
+ }
+
}
- }
- public static FObj.Maker maker() {
- return new Inline.Maker();
- }
+ public static FObj.Maker maker() {
+ return new Inline.Maker();
+ }
- // Textdecoration
- protected boolean underlined = false;
- protected boolean overlined = false;
- protected boolean lineThrough = false;
+ // Textdecoration
+ protected boolean underlined = false;
+ protected boolean overlined = false;
+ protected boolean lineThrough = false;
-
- public Inline(FObj parent, PropertyList propertyList)
- throws FOPException {
- super(parent, propertyList);
- this.name = "fo:inline";
- int textDecoration =
- this.properties.get("text-decoration").getEnum();
+ public Inline(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ super(parent, propertyList);
+ this.name = "fo:inline";
- if (textDecoration == TextDecoration.UNDERLINE) {
- this.underlined = true;
- }
+ int textDecoration = this.properties.get("text-decoration").getEnum();
- if (textDecoration == TextDecoration.OVERLINE) {
- this.overlined = true;
- }
+ if (textDecoration == TextDecoration.UNDERLINE) {
+ this.underlined = true;
+ }
- if (textDecoration == TextDecoration.LINE_THROUGH) {
- this.lineThrough = true;
- }
+ if (textDecoration == TextDecoration.OVERLINE) {
+ this.overlined = true;
+ }
- if (parent.getName().equals("fo:flow")) {
- throw new FOPException("fo:inline can't be directly"
- + " under flow");
- }
+ if (textDecoration == TextDecoration.LINE_THROUGH) {
+ this.lineThrough = true;
+ }
+
+ if (parent.getName().equals("fo:flow")) {
+ throw new FOPException("fo:inline can't be directly"
+ + " under flow");
+ }
- }
+ }
- protected void addCharacters(char data[], int start, int length) {
- FOText ft = new FOText(data,start,length, this);
- ft.setUnderlined(underlined);
- ft.setOverlined(overlined);
- ft.setLineThrough(lineThrough);
- children.addElement(ft);
- }
+ protected void addCharacters(char data[], int start, int length) {
+ FOText ft = new FOText(data, start, length, this);
+ ft.setUnderlined(underlined);
+ ft.setOverlined(overlined);
+ ft.setLineThrough(lineThrough);
+ children.addElement(ft);
+ }
}
diff --git a/src/org/apache/fop/fo/flow/InlineContainer.java b/src/org/apache/fop/fo/flow/InlineContainer.java
index 3a05b85a5..31bfd008c 100644
--- a/src/org/apache/fop/fo/flow/InlineContainer.java
+++ b/src/org/apache/fop/fo/flow/InlineContainer.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -23,6 +24,7 @@ public class InlineContainer extends ToBeImplementedElement {
PropertyList propertyList) throws FOPException {
return new InlineContainer(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -30,7 +32,7 @@ public class InlineContainer extends ToBeImplementedElement {
}
protected InlineContainer(FObj parent,
- PropertyList propertyList) throws FOPException {
+ PropertyList propertyList) throws FOPException {
super(parent, propertyList);
this.name = "fo:inline-container";
}
diff --git a/src/org/apache/fop/fo/flow/InstreamForeignObject.java b/src/org/apache/fop/fo/flow/InstreamForeignObject.java
index 1cd432c82..b8273206b 100644
--- a/src/org/apache/fop/fo/flow/InstreamForeignObject.java
+++ b/src/org/apache/fop/fo/flow/InstreamForeignObject.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -19,6 +20,7 @@ import org.apache.fop.apps.FOPException;
import java.util.Enumeration;
public class InstreamForeignObject extends FObj {
+
/**
* inner class for making SVG objects.
*/
@@ -36,6 +38,7 @@ public class InstreamForeignObject extends FObj {
PropertyList propertyList) throws FOPException {
return new InstreamForeignObject(parent, propertyList);
}
+
}
/**
@@ -96,39 +99,37 @@ public class InstreamForeignObject extends FObj {
int valign = this.properties.get("vertical-align").getEnum();
int overflow = this.properties.get("overflow").getEnum();
- this.breakBefore =
- this.properties.get("break-before").getEnum();
+ this.breakBefore = this.properties.get("break-before").getEnum();
this.breakAfter = this.properties.get("break-after").getEnum();
this.width = this.properties.get("width").getLength().mvalue();
- this.height =
- this.properties.get("height").getLength().mvalue();
- this.contwidth = this.properties.get(
- "content-width").getLength().mvalue();
- this.contheight = this.properties.get(
- "content-height").getLength().mvalue();
+ this.height = this.properties.get("height").getLength().mvalue();
+ this.contwidth =
+ this.properties.get("content-width").getLength().mvalue();
+ this.contheight =
+ this.properties.get("content-height").getLength().mvalue();
this.wauto = this.properties.get("width").getLength().isAuto();
this.hauto = this.properties.get("height").getLength().isAuto();
- this.cwauto = this.properties.get(
- "content-width").getLength().isAuto();
- this.chauto = this.properties.get(
- "content-height").getLength().isAuto();
-
- this.startIndent = this.properties.get(
- "start-indent").getLength().mvalue();
- this.endIndent = this.properties.get(
- "end-indent").getLength().mvalue();
- this.spaceBefore = this.properties.get(
- "space-before.optimum").getLength().mvalue();
- this.spaceAfter = this.properties.get(
- "space-after.optimum").getLength().mvalue();
+ this.cwauto =
+ this.properties.get("content-width").getLength().isAuto();
+ this.chauto =
+ this.properties.get("content-height").getLength().isAuto();
+
+ this.startIndent =
+ this.properties.get("start-indent").getLength().mvalue();
+ this.endIndent =
+ this.properties.get("end-indent").getLength().mvalue();
+ this.spaceBefore =
+ this.properties.get("space-before.optimum").getLength().mvalue();
+ this.spaceAfter =
+ this.properties.get("space-after.optimum").getLength().mvalue();
this.scaling = this.properties.get("scaling").getEnum();
area.getIDReferences().createID(id);
if (this.areaCurrent == null) {
- this.areaCurrent = new ForeignObjectArea(
- propMgr.getFontState(area.getFontInfo()),
- area.getAllocationWidth());
+ this.areaCurrent =
+ new ForeignObjectArea(propMgr.getFontState(area.getFontInfo()),
+ area.getAllocationWidth());
this.areaCurrent.start();
areaCurrent.setWidth(this.width);
@@ -151,11 +152,11 @@ public class InstreamForeignObject extends FObj {
}
/* layout foreign object */
if (this.children.size() > 0) {
- FONode fo = (FONode) children.elementAt(0);
+ FONode fo = (FONode)children.elementAt(0);
Status status;
// currently FONode must be an SVG
if ((status =
- fo.layout(this.areaCurrent)).isIncomplete()) {
+ fo.layout(this.areaCurrent)).isIncomplete()) {
return status;
}
@@ -166,9 +167,9 @@ public class InstreamForeignObject extends FObj {
this.marker = 0;
- if (breakBefore == BreakBefore.PAGE ||
- ((spaceBefore + areaCurrent.getEffectiveHeight()) >
- area.spaceLeft())) {
+ if (breakBefore == BreakBefore.PAGE
+ || ((spaceBefore + areaCurrent.getEffectiveHeight())
+ > area.spaceLeft())) {
return new Status(Status.FORCE_PAGE_BREAK);
}
@@ -186,7 +187,7 @@ public class InstreamForeignObject extends FObj {
}
if (area instanceof BlockArea) {
- BlockArea ba = (BlockArea) area;
+ BlockArea ba = (BlockArea)area;
LineArea la = ba.getCurrentLineArea();
if (la == null) {
return new Status(Status.AREA_FULL_NONE);
@@ -206,31 +207,33 @@ public class InstreamForeignObject extends FObj {
if (this.isInTableCell) {
startIndent += forcedStartOffset;
- /* endIndent = areaCurrent.getEffectiveWidth() - forcedWidth -
- forcedStartOffset;*/
+ /*
+ * endIndent = areaCurrent.getEffectiveWidth() - forcedWidth -
+ * forcedStartOffset;
+ */
}
areaCurrent.setStartIndent(startIndent);
- // areaCurrent.setEndIndent(endIndent);
+ // areaCurrent.setEndIndent(endIndent);
/* if there is a space-before */
if (spaceBefore != 0) {
/* add a display space */
- // area.addDisplaySpace(spaceBefore);
+ // area.addDisplaySpace(spaceBefore);
}
/* add the SVG area to the containing area */
- // area.addChild(areaCurrent);
+ // area.addChild(areaCurrent);
areaCurrent.setPage(area.getPage());
/* increase the height of the containing area accordingly */
- // area.increaseHeight(areaCurrent.getEffectiveHeight());
+ // area.increaseHeight(areaCurrent.getEffectiveHeight());
/* if there is a space-after */
if (spaceAfter != 0) {
/* add a display space */
- // area.addDisplaySpace(spaceAfter);
+ // area.addDisplaySpace(spaceAfter);
}
@@ -253,4 +256,5 @@ public class InstreamForeignObject extends FObj {
/* return status */
return new Status(Status.OK);
}
+
}
diff --git a/src/org/apache/fop/fo/flow/Leader.java b/src/org/apache/fop/fo/flow/Leader.java
index 4599509d3..6447d0082 100644
--- a/src/org/apache/fop/fo/flow/Leader.java
+++ b/src/org/apache/fop/fo/flow/Leader.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.flow;
// FOP
@@ -70,143 +27,145 @@ import org.apache.fop.messaging.MessageHandler;
public class Leader extends FObjMixed {
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent,
- PropertyList propertyList) throws FOPException {
- return new Leader(parent, propertyList);
- }
- }
-
- public static FObj.Maker maker() {
- return new Leader.Maker();
- }
-
- public Leader(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:leader";
- }
-
- public Status layout(Area area) throws FOPException {
- BlockArea blockArea;
- //restriction in this version
- if (!(area instanceof BlockArea)) {
- MessageHandler.errorln("WARNING: in this version of Fop fo:leader must be a direct child of fo:block ");
- return new Status(Status.OK);
- } else {
- blockArea = (BlockArea) area;
- }
-
- //color properties
- ColorType c = this.properties.get("color").getColorType();
- float red = c.red();
- float green = c.green();
- float blue = c.blue();
-
- //fo:leader specific properties
- //determines the pattern of leader; allowed values: space, rule,dots, use-content
- int leaderPattern = this.properties.get("leader-pattern").getEnum();
- //length of the leader
- int leaderLengthOptimum = this.properties.get(
- "leader-length.optimum").getLength().mvalue();
- int leaderLengthMinimum = this.properties.get(
- "leader-length.minimum").getLength().mvalue();
- int leaderLengthMaximum = this.properties.get(
- "leader-length.maximum").getLength().mvalue();
- //the following properties only apply for leader-pattern = "rule"
- int ruleThickness = this.properties.get(
- "rule-thickness").getLength().mvalue();
- int ruleStyle = this.properties.get("rule-style").getEnum();
- // if leaderPatternWidth = 0 = default = use-font-metric
- int leaderPatternWidth = this.properties.get(
- "leader-pattern-width").getLength().mvalue();
- int leaderAlignment =
- this.properties.get("leader-alignment").getEnum();
-
- // initialize id
- String id = this.properties.get("id").getString();
- blockArea.getIDReferences().initializeID(id, blockArea);
-
- //adds leader to blockarea, there the leaderArea is generated
- int succeeded = addLeader(blockArea, propMgr.getFontState(area.getFontInfo()), red, green, blue,
- leaderPattern, leaderLengthMinimum,
- leaderLengthOptimum, leaderLengthMaximum,
- ruleThickness, ruleStyle, leaderPatternWidth,
- leaderAlignment);
- if (succeeded == 1) {
- return new Status(Status.OK);
- } else {
- //not sure that this is the correct Status here
- return new Status(Status.AREA_FULL_SOME);
- }
- }
-
- /* //should only be necessary for use-content
- protected void addCharacters(char data[], int start, int length) {
- FOText textNode = new FOText(data,start,length, this);
- children.addElement(textNode);
- }
- */
-
-
- /**
- * adds a leader to current line area of containing block area
- * the actual leader area is created in the line area
- *
- * @return int +1 for success and -1 for none
- */
- public int addLeader(BlockArea ba, FontState fontState, float red, float green,
- float blue, int leaderPattern, int leaderLengthMinimum,
- int leaderLengthOptimum, int leaderLengthMaximum,
- int ruleThickness, int ruleStyle, int leaderPatternWidth,
- int leaderAlignment) {
-
- LineArea la = ba.getCurrentLineArea();
- //this should start a new page
- if (la == null) {
- return -1;
- }
-
- la.changeFont(fontState);
- la.changeColor(red, green, blue);
-
- //check whether leader fits into the (rest of the) line
- //using length.optimum to determine where to break the line as defined
- // in the xsl:fo spec: "User agents may choose to use the value of 'leader-length.optimum'
- // to determine where to break the line" (7.20.4)
- //if leader is longer then create a new LineArea and put leader there
- if (leaderLengthOptimum <= (la.getRemainingWidth())) {
- la.addLeader(leaderPattern,
- leaderLengthMinimum, leaderLengthOptimum,
- leaderLengthMaximum, ruleStyle, ruleThickness,
- leaderPatternWidth, leaderAlignment);
- } else {
- la = ba.createNextLineArea();
- if(la == null) {
- // not enough room
- return -1;
- }
- la.changeFont(fontState);
- la.changeColor(red, green, blue);
-
- //check whether leader fits into LineArea at all, otherwise
- //clip it (should honor the clip option of containing area)
- if (leaderLengthMinimum <=
- la.getContentWidth()) {
- la.addLeader(leaderPattern,
- leaderLengthMinimum, leaderLengthOptimum,
- leaderLengthMaximum, ruleStyle, ruleThickness,
- leaderPatternWidth, leaderAlignment);
- } else {
- MessageHandler.errorln("Leader doesn't fit into line, it will be clipped to fit.");
- la.addLeader(leaderPattern,
- la.getRemainingWidth(),
- leaderLengthOptimum, leaderLengthMaximum,
- ruleStyle, ruleThickness, leaderPatternWidth,
- leaderAlignment);
- }
- }
-// this.hasLines = true;
- return 1;
- }
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new Leader(parent, propertyList);
+ }
+
+ }
+
+ public static FObj.Maker maker() {
+ return new Leader.Maker();
+ }
+
+ public Leader(FObj parent, PropertyList propertyList) {
+ super(parent, propertyList);
+ this.name = "fo:leader";
+ }
+
+ public Status layout(Area area) throws FOPException {
+ BlockArea blockArea;
+ // restriction in this version
+ if (!(area instanceof BlockArea)) {
+ MessageHandler.errorln("WARNING: in this version of Fop fo:leader must be a direct child of fo:block ");
+ return new Status(Status.OK);
+ } else {
+ blockArea = (BlockArea)area;
+ }
+
+ // color properties
+ ColorType c = this.properties.get("color").getColorType();
+ float red = c.red();
+ float green = c.green();
+ float blue = c.blue();
+
+ // fo:leader specific properties
+ // determines the pattern of leader; allowed values: space, rule,dots, use-content
+ int leaderPattern = this.properties.get("leader-pattern").getEnum();
+ // length of the leader
+ int leaderLengthOptimum =
+ this.properties.get("leader-length.optimum").getLength().mvalue();
+ int leaderLengthMinimum =
+ this.properties.get("leader-length.minimum").getLength().mvalue();
+ int leaderLengthMaximum =
+ this.properties.get("leader-length.maximum").getLength().mvalue();
+ // the following properties only apply for leader-pattern = "rule"
+ int ruleThickness =
+ this.properties.get("rule-thickness").getLength().mvalue();
+ int ruleStyle = this.properties.get("rule-style").getEnum();
+ // if leaderPatternWidth = 0 = default = use-font-metric
+ int leaderPatternWidth =
+ this.properties.get("leader-pattern-width").getLength().mvalue();
+ int leaderAlignment =
+ this.properties.get("leader-alignment").getEnum();
+
+ // initialize id
+ String id = this.properties.get("id").getString();
+ blockArea.getIDReferences().initializeID(id, blockArea);
+
+ // adds leader to blockarea, there the leaderArea is generated
+ int succeeded = addLeader(blockArea,
+ propMgr.getFontState(area.getFontInfo()),
+ red, green, blue, leaderPattern,
+ leaderLengthMinimum, leaderLengthOptimum,
+ leaderLengthMaximum, ruleThickness,
+ ruleStyle, leaderPatternWidth,
+ leaderAlignment);
+ if (succeeded == 1) {
+ return new Status(Status.OK);
+ } else {
+ // not sure that this is the correct Status here
+ return new Status(Status.AREA_FULL_SOME);
+ }
+ }
+
+ /*
+ * //should only be necessary for use-content
+ * protected void addCharacters(char data[], int start, int length) {
+ * FOText textNode = new FOText(data,start,length, this);
+ * children.addElement(textNode);
+ * }
+ */
+
+
+ /**
+ * adds a leader to current line area of containing block area
+ * the actual leader area is created in the line area
+ *
+ * @return int +1 for success and -1 for none
+ */
+ public int addLeader(BlockArea ba, FontState fontState, float red,
+ float green, float blue, int leaderPattern,
+ int leaderLengthMinimum, int leaderLengthOptimum,
+ int leaderLengthMaximum, int ruleThickness,
+ int ruleStyle, int leaderPatternWidth,
+ int leaderAlignment) {
+
+ LineArea la = ba.getCurrentLineArea();
+ // this should start a new page
+ if (la == null) {
+ return -1;
+ }
+
+ la.changeFont(fontState);
+ la.changeColor(red, green, blue);
+
+ // check whether leader fits into the (rest of the) line
+ // using length.optimum to determine where to break the line as defined
+ // in the xsl:fo spec: "User agents may choose to use the value of 'leader-length.optimum'
+ // to determine where to break the line" (7.20.4)
+ // if leader is longer then create a new LineArea and put leader there
+ if (leaderLengthOptimum <= (la.getRemainingWidth())) {
+ la.addLeader(leaderPattern, leaderLengthMinimum,
+ leaderLengthOptimum, leaderLengthMaximum, ruleStyle,
+ ruleThickness, leaderPatternWidth, leaderAlignment);
+ } else {
+ la = ba.createNextLineArea();
+ if (la == null) {
+ // not enough room
+ return -1;
+ }
+ la.changeFont(fontState);
+ la.changeColor(red, green, blue);
+
+ // check whether leader fits into LineArea at all, otherwise
+ // clip it (should honor the clip option of containing area)
+ if (leaderLengthMinimum <= la.getContentWidth()) {
+ la.addLeader(leaderPattern, leaderLengthMinimum,
+ leaderLengthOptimum, leaderLengthMaximum,
+ ruleStyle, ruleThickness, leaderPatternWidth,
+ leaderAlignment);
+ } else {
+ MessageHandler.errorln("Leader doesn't fit into line, it will be clipped to fit.");
+ la.addLeader(leaderPattern, la.getRemainingWidth(),
+ leaderLengthOptimum, leaderLengthMaximum,
+ ruleStyle, ruleThickness, leaderPatternWidth,
+ leaderAlignment);
+ }
+ }
+ // this.hasLines = true;
+ return 1;
+ }
}
diff --git a/src/org/apache/fop/fo/flow/ListBlock.java b/src/org/apache/fop/fo/flow/ListBlock.java
index 4f187c87e..6b7534da8 100644
--- a/src/org/apache/fop/fo/flow/ListBlock.java
+++ b/src/org/apache/fop/fo/flow/ListBlock.java
@@ -1,4 +1,5 @@
-/*-- $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -21,134 +22,135 @@ import java.util.Enumeration;
public class ListBlock extends FObj {
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent,
- PropertyList propertyList) throws FOPException {
- return new ListBlock(parent, propertyList);
- }
- }
-
- public static FObj.Maker maker() {
- return new ListBlock.Maker();
- }
-
- int align;
- int alignLast;
- int breakBefore;
- int breakAfter;
- int lineHeight;
- int startIndent;
- int endIndent;
- int spaceBefore;
- int spaceAfter;
- int spaceBetweenListRows = 0;
- ColorType backgroundColor;
-
- public ListBlock(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:list-block";
- }
-
- public Status layout(Area area) throws FOPException {
- if (this.marker == START) {
-
- this.align = this.properties.get("text-align").getEnum();
- this.alignLast =
- this.properties.get("text-align-last").getEnum();
- this.lineHeight = this.properties.get(
- "line-height").getLength().mvalue();
- this.startIndent = this.properties.get(
- "start-indent").getLength().mvalue();
- this.endIndent = this.properties.get(
- "end-indent").getLength().mvalue();
- this.spaceBefore = this.properties.get(
- "space-before.optimum").getLength().mvalue();
- this.spaceAfter = this.properties.get(
- "space-after.optimum").getLength().mvalue();
- this.spaceBetweenListRows = 0; // not used at present
- this.backgroundColor = this.properties.get(
- "background-color").getColorType();
-
- this.marker = 0;
-
- if (area instanceof BlockArea) {
- area.end();
- }
-
- if (spaceBefore != 0) {
- area.addDisplaySpace(spaceBefore);
- }
-
- if (this.isInTableCell) {
- startIndent += forcedStartOffset;
- endIndent += area.getAllocationWidth() - forcedWidth -
- forcedStartOffset;
- }
-
- // initialize id
- String id = this.properties.get("id").getString();
- area.getIDReferences().initializeID(id, area);
- }
-
- BlockArea blockArea = new BlockArea(propMgr.getFontState(area.getFontInfo()),
- area.getAllocationWidth(),
- area.spaceLeft(), startIndent, endIndent, 0, align,
- alignLast, lineHeight);
- blockArea.setGeneratedBy(this);
- this.areasGenerated++;
- if (this.areasGenerated == 1)
- blockArea.isFirst(true);
- // for normal areas this should be the only pair
- blockArea.addLineagePair(this, this.areasGenerated);
-
- // markers
- if (this.hasMarkers())
- blockArea.addMarkers(this.getMarkers());
-
-
- blockArea.setPage(area.getPage());
- blockArea.setBackgroundColor(backgroundColor);
- blockArea.start();
-
- blockArea.setAbsoluteHeight(area.getAbsoluteHeight());
- blockArea.setIDReferences(area.getIDReferences());
-
- int numChildren = this.children.size();
- for (int i = this.marker; i < numChildren; i++) {
- if (!(children.elementAt(i) instanceof ListItem)) {
- MessageHandler.errorln("children of list-blocks must be list-items");
- return new Status(Status.OK);
- }
- ListItem listItem = (ListItem) children.elementAt(i);
- Status status;
- if ((status = listItem.layout(blockArea)).isIncomplete()) {
- if(status.getCode() == Status.AREA_FULL_NONE && i > 0) {
- status = new Status(Status.AREA_FULL_SOME);
- }
- this.marker = i;
- blockArea.end();
- area.addChild(blockArea);
- area.increaseHeight(blockArea.getHeight());
- area.setAbsoluteHeight(blockArea.getAbsoluteHeight());
- return status;
- }
- }
-
- blockArea.end();
- area.addChild(blockArea);
- area.increaseHeight(blockArea.getHeight());
- area.setAbsoluteHeight(blockArea.getAbsoluteHeight());
-
- if (spaceAfter != 0) {
- area.addDisplaySpace(spaceAfter);
- }
-
- if (area instanceof BlockArea) {
- area.start();
- }
-
- blockArea.isLast(true);
- return new Status(Status.OK);
- }
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new ListBlock(parent, propertyList);
+ }
+
+ }
+
+ public static FObj.Maker maker() {
+ return new ListBlock.Maker();
+ }
+
+ int align;
+ int alignLast;
+ int breakBefore;
+ int breakAfter;
+ int lineHeight;
+ int startIndent;
+ int endIndent;
+ int spaceBefore;
+ int spaceAfter;
+ int spaceBetweenListRows = 0;
+ ColorType backgroundColor;
+
+ public ListBlock(FObj parent, PropertyList propertyList) {
+ super(parent, propertyList);
+ this.name = "fo:list-block";
+ }
+
+ public Status layout(Area area) throws FOPException {
+ if (this.marker == START) {
+
+ this.align = this.properties.get("text-align").getEnum();
+ this.alignLast = this.properties.get("text-align-last").getEnum();
+ this.lineHeight =
+ this.properties.get("line-height").getLength().mvalue();
+ this.startIndent =
+ this.properties.get("start-indent").getLength().mvalue();
+ this.endIndent =
+ this.properties.get("end-indent").getLength().mvalue();
+ this.spaceBefore =
+ this.properties.get("space-before.optimum").getLength().mvalue();
+ this.spaceAfter =
+ this.properties.get("space-after.optimum").getLength().mvalue();
+ this.spaceBetweenListRows = 0; // not used at present
+ this.backgroundColor =
+ this.properties.get("background-color").getColorType();
+
+ this.marker = 0;
+
+ if (area instanceof BlockArea) {
+ area.end();
+ }
+
+ if (spaceBefore != 0) {
+ area.addDisplaySpace(spaceBefore);
+ }
+
+ if (this.isInTableCell) {
+ startIndent += forcedStartOffset;
+ endIndent += area.getAllocationWidth() - forcedWidth
+ - forcedStartOffset;
+ }
+
+ // initialize id
+ String id = this.properties.get("id").getString();
+ area.getIDReferences().initializeID(id, area);
+ }
+
+ BlockArea blockArea =
+ new BlockArea(propMgr.getFontState(area.getFontInfo()),
+ area.getAllocationWidth(), area.spaceLeft(),
+ startIndent, endIndent, 0, align, alignLast,
+ lineHeight);
+ blockArea.setGeneratedBy(this);
+ this.areasGenerated++;
+ if (this.areasGenerated == 1)
+ blockArea.isFirst(true);
+ // for normal areas this should be the only pair
+ blockArea.addLineagePair(this, this.areasGenerated);
+
+ // markers
+ if (this.hasMarkers())
+ blockArea.addMarkers(this.getMarkers());
+
+
+ blockArea.setPage(area.getPage());
+ blockArea.setBackgroundColor(backgroundColor);
+ blockArea.start();
+
+ blockArea.setAbsoluteHeight(area.getAbsoluteHeight());
+ blockArea.setIDReferences(area.getIDReferences());
+
+ int numChildren = this.children.size();
+ for (int i = this.marker; i < numChildren; i++) {
+ if (!(children.elementAt(i) instanceof ListItem)) {
+ MessageHandler.errorln("children of list-blocks must be list-items");
+ return new Status(Status.OK);
+ }
+ ListItem listItem = (ListItem)children.elementAt(i);
+ Status status;
+ if ((status = listItem.layout(blockArea)).isIncomplete()) {
+ if (status.getCode() == Status.AREA_FULL_NONE && i > 0) {
+ status = new Status(Status.AREA_FULL_SOME);
+ }
+ this.marker = i;
+ blockArea.end();
+ area.addChild(blockArea);
+ area.increaseHeight(blockArea.getHeight());
+ area.setAbsoluteHeight(blockArea.getAbsoluteHeight());
+ return status;
+ }
+ }
+
+ blockArea.end();
+ area.addChild(blockArea);
+ area.increaseHeight(blockArea.getHeight());
+ area.setAbsoluteHeight(blockArea.getAbsoluteHeight());
+
+ if (spaceAfter != 0) {
+ area.addDisplaySpace(spaceAfter);
+ }
+
+ if (area instanceof BlockArea) {
+ area.start();
+ }
+
+ blockArea.isLast(true);
+ return new Status(Status.OK);
+ }
}
diff --git a/src/org/apache/fop/fo/flow/ListItem.java b/src/org/apache/fop/fo/flow/ListItem.java
index 6e51598ba..08d268853 100644
--- a/src/org/apache/fop/fo/flow/ListItem.java
+++ b/src/org/apache/fop/fo/flow/ListItem.java
@@ -1,4 +1,5 @@
-/*-- $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -20,14 +21,15 @@ import java.util.Enumeration;
public class ListItem extends FObj {
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new ListItem(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new ListItem(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new ListItem.Maker();
+ return new ListItem.Maker();
}
int align;
@@ -41,109 +43,107 @@ public class ListItem extends FObj {
int spaceAfter;
String id;
BlockArea blockArea;
-
+
public ListItem(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:list-item";
+ super(parent, propertyList);
+ this.name = "fo:list-item";
}
public Status layout(Area area) throws FOPException {
- if (this.marker == START) {
-
- this.align = this.properties.get("text-align").getEnum();
- this.alignLast =
- this.properties.get("text-align-last").getEnum();
- this.lineHeight =
- this.properties.get("line-height").getLength().mvalue();
- this.spaceBefore =
- this.properties.get("space-before.optimum").getLength().mvalue();
- this.spaceAfter =
- this.properties.get("space-after.optimum").getLength().mvalue();
- this.id =
- this.properties.get("id").getString();
+ if (this.marker == START) {
+
+ this.align = this.properties.get("text-align").getEnum();
+ this.alignLast = this.properties.get("text-align-last").getEnum();
+ this.lineHeight =
+ this.properties.get("line-height").getLength().mvalue();
+ this.spaceBefore =
+ this.properties.get("space-before.optimum").getLength().mvalue();
+ this.spaceAfter =
+ this.properties.get("space-after.optimum").getLength().mvalue();
+ this.id = this.properties.get("id").getString();
area.getIDReferences().createID(id);
- this.marker = 0;
- }
-
- /* not sure this is needed given we know area is from list block */
- if (area instanceof BlockArea) {
- area.end();
- }
-
- if (spaceBefore != 0) {
- area.addDisplaySpace(spaceBefore);
- }
-
- this.blockArea =
- new BlockArea(propMgr.getFontState(area.getFontInfo()), area.getAllocationWidth(),
- area.spaceLeft(), 0, 0,
- 0, align, alignLast, lineHeight);
- this.blockArea.setGeneratedBy(this);
- this.areasGenerated++;
- if (this.areasGenerated == 1)
- this.blockArea.isFirst(true);
- // for normal areas this should be the only pair
- this.blockArea.addLineagePair(this, this.areasGenerated);
-
- // markers
- if (this.hasMarkers())
- this.blockArea.addMarkers(this.getMarkers());
-
- blockArea.setPage(area.getPage());
- blockArea.start();
-
- blockArea.setAbsoluteHeight(area.getAbsoluteHeight());
- blockArea.setIDReferences(area.getIDReferences());
-
- int numChildren = this.children.size();
- if (numChildren != 2) {
- throw new FOPException("list-item must have exactly two children");
- }
- ListItemLabel label = (ListItemLabel) children.elementAt(0);
- ListItemBody body = (ListItemBody) children.elementAt(1);
-
- Status status;
-
- // what follows doesn't yet take into account whether the
- // body failed completely or only got some text in
-
- if (this.marker == 0) {
- // configure id
- area.getIDReferences().configureID(id,area);
-
- status = label.layout(blockArea);
- if (status.isIncomplete()) {
- return status;
- }
- }
-
- status = body.layout(blockArea);
- if (status.isIncomplete()) {
- blockArea.end();
- area.addChild(blockArea);
- area.increaseHeight(blockArea.getHeight());
- area.setAbsoluteHeight(blockArea.getAbsoluteHeight());
- this.marker = 1;
- return status;
- }
-
- blockArea.end();
- area.addChild(blockArea);
- area.increaseHeight(blockArea.getHeight());
- area.setAbsoluteHeight(blockArea.getAbsoluteHeight());
-
- if (spaceAfter != 0) {
- area.addDisplaySpace(spaceAfter);
- }
-
- /* not sure this is needed given we know area is from list block */
- if (area instanceof BlockArea) {
- area.start();
- }
- this.blockArea.isLast(true);
- return new Status(Status.OK);
+ this.marker = 0;
+ }
+
+ /* not sure this is needed given we know area is from list block */
+ if (area instanceof BlockArea) {
+ area.end();
+ }
+
+ if (spaceBefore != 0) {
+ area.addDisplaySpace(spaceBefore);
+ }
+
+ this.blockArea =
+ new BlockArea(propMgr.getFontState(area.getFontInfo()),
+ area.getAllocationWidth(), area.spaceLeft(), 0, 0,
+ 0, align, alignLast, lineHeight);
+ this.blockArea.setGeneratedBy(this);
+ this.areasGenerated++;
+ if (this.areasGenerated == 1)
+ this.blockArea.isFirst(true);
+ // for normal areas this should be the only pair
+ this.blockArea.addLineagePair(this, this.areasGenerated);
+
+ // markers
+ if (this.hasMarkers())
+ this.blockArea.addMarkers(this.getMarkers());
+
+ blockArea.setPage(area.getPage());
+ blockArea.start();
+
+ blockArea.setAbsoluteHeight(area.getAbsoluteHeight());
+ blockArea.setIDReferences(area.getIDReferences());
+
+ int numChildren = this.children.size();
+ if (numChildren != 2) {
+ throw new FOPException("list-item must have exactly two children");
+ }
+ ListItemLabel label = (ListItemLabel)children.elementAt(0);
+ ListItemBody body = (ListItemBody)children.elementAt(1);
+
+ Status status;
+
+ // what follows doesn't yet take into account whether the
+ // body failed completely or only got some text in
+
+ if (this.marker == 0) {
+ // configure id
+ area.getIDReferences().configureID(id, area);
+
+ status = label.layout(blockArea);
+ if (status.isIncomplete()) {
+ return status;
+ }
+ }
+
+ status = body.layout(blockArea);
+ if (status.isIncomplete()) {
+ blockArea.end();
+ area.addChild(blockArea);
+ area.increaseHeight(blockArea.getHeight());
+ area.setAbsoluteHeight(blockArea.getAbsoluteHeight());
+ this.marker = 1;
+ return status;
+ }
+
+ blockArea.end();
+ area.addChild(blockArea);
+ area.increaseHeight(blockArea.getHeight());
+ area.setAbsoluteHeight(blockArea.getAbsoluteHeight());
+
+ if (spaceAfter != 0) {
+ area.addDisplaySpace(spaceAfter);
+ }
+
+ /* not sure this is needed given we know area is from list block */
+ if (area instanceof BlockArea) {
+ area.start();
+ }
+ this.blockArea.isLast(true);
+ return new Status(Status.OK);
}
/**
@@ -151,8 +151,9 @@ public class ListItem extends FObj {
*/
public int getContentWidth() {
if (blockArea != null)
- return blockArea.getContentWidth(); //getAllocationWidth()??
- else return 0; // not laid out yet
+ return blockArea.getContentWidth(); // getAllocationWidth()??
+ else
+ return 0; // not laid out yet
}
}
diff --git a/src/org/apache/fop/fo/flow/ListItemBody.java b/src/org/apache/fop/fo/flow/ListItemBody.java
index 135644f1f..d39cbe82f 100644
--- a/src/org/apache/fop/fo/flow/ListItemBody.java
+++ b/src/org/apache/fop/fo/flow/ListItemBody.java
@@ -1,4 +1,5 @@
-/*-- $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -19,48 +20,52 @@ import java.util.Enumeration;
public class ListItemBody extends FObj {
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new ListItemBody(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new ListItemBody(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new ListItemBody.Maker();
+ return new ListItemBody.Maker();
}
-
+
public ListItemBody(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:list-item-body";
+ super(parent, propertyList);
+ this.name = "fo:list-item-body";
}
public Status layout(Area area) throws FOPException {
- if (this.marker == START) {
- this.marker = 0;
- // initialize id
- String id = this.properties.get("id").getString();
- area.getIDReferences().initializeID(id,area);
- }
+ if (this.marker == START) {
+ this.marker = 0;
+ // initialize id
+ String id = this.properties.get("id").getString();
+ area.getIDReferences().initializeID(id, area);
+ }
- /* For calculating the lineage - The fo:list-item-body formatting object
- * does not generate any areas. The fo:list-item-body formatting object
- * returns the sequence of areas created by concatenating the sequences
- * of areas returned by each of the children of the fo:list-item-body. */
-
- int numChildren = this.children.size();
- for (int i = this.marker; i < numChildren; i++) {
- FObj fo = (FObj) children.elementAt(i);
+ /*
+ * For calculating the lineage - The fo:list-item-body formatting object
+ * does not generate any areas. The fo:list-item-body formatting object
+ * returns the sequence of areas created by concatenating the sequences
+ * of areas returned by each of the children of the fo:list-item-body.
+ */
- Status status;
- if ((status = fo.layout(area)).isIncomplete()) {
- this.marker = i;
- if ((i == 0) && (status.getCode() == Status.AREA_FULL_NONE)) {
- return new Status(Status.AREA_FULL_NONE);
- } else {
- return new Status(Status.AREA_FULL_SOME);
- }
- }
- }
- return new Status(Status.OK);
+ int numChildren = this.children.size();
+ for (int i = this.marker; i < numChildren; i++) {
+ FObj fo = (FObj)children.elementAt(i);
+
+ Status status;
+ if ((status = fo.layout(area)).isIncomplete()) {
+ this.marker = i;
+ if ((i == 0) && (status.getCode() == Status.AREA_FULL_NONE)) {
+ return new Status(Status.AREA_FULL_NONE);
+ } else {
+ return new Status(Status.AREA_FULL_SOME);
+ }
+ }
+ }
+ return new Status(Status.OK);
}
+
}
diff --git a/src/org/apache/fop/fo/flow/ListItemLabel.java b/src/org/apache/fop/fo/flow/ListItemLabel.java
index 607e15bca..b044e29bd 100644
--- a/src/org/apache/fop/fo/flow/ListItemLabel.java
+++ b/src/org/apache/fop/fo/flow/ListItemLabel.java
@@ -1,4 +1,5 @@
-/*-- $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -19,42 +20,46 @@ import java.util.Enumeration;
public class ListItemLabel extends FObj {
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new ListItemLabel(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new ListItemLabel(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new ListItemLabel.Maker();
+ return new ListItemLabel.Maker();
}
public ListItemLabel(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:list-item-label";
+ super(parent, propertyList);
+ this.name = "fo:list-item-label";
}
public Status layout(Area area) throws FOPException {
- int numChildren = this.children.size();
-
- if (numChildren != 1) {
- throw new FOPException("list-item-label must have exactly one block in this version of FOP");
- }
-
- // initialize id
- String id = this.properties.get("id").getString();
- area.getIDReferences().initializeID(id,area);
-
- Block block = (Block) children.elementAt(0);
-
- /* For calculating the lineage - The fo:list-item-label formatting object
- * does not generate any areas. The fo:list-item-label formatting object
- * returns the sequence of areas created by concatenating the sequences
- * of areas returned by each of the children of the fo:list-item-label. */
-
- Status status;
- status = block.layout(area);
- area.addDisplaySpace(-block.getAreaHeight());
- return status;
+ int numChildren = this.children.size();
+
+ if (numChildren != 1) {
+ throw new FOPException("list-item-label must have exactly one block in this version of FOP");
+ }
+
+ // initialize id
+ String id = this.properties.get("id").getString();
+ area.getIDReferences().initializeID(id, area);
+
+ Block block = (Block)children.elementAt(0);
+
+ /*
+ * For calculating the lineage - The fo:list-item-label formatting object
+ * does not generate any areas. The fo:list-item-label formatting object
+ * returns the sequence of areas created by concatenating the sequences
+ * of areas returned by each of the children of the fo:list-item-label.
+ */
+
+ Status status;
+ status = block.layout(area);
+ area.addDisplaySpace(-block.getAreaHeight());
+ return status;
}
+
}
diff --git a/src/org/apache/fop/fo/flow/Marker.java b/src/org/apache/fop/fo/flow/Marker.java
index 1b9ad20e7..aba8b54a9 100644
--- a/src/org/apache/fop/fo/flow/Marker.java
+++ b/src/org/apache/fop/fo/flow/Marker.java
@@ -1,5 +1,5 @@
-/*-- $Id$-- */
/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -17,68 +17,73 @@ import org.apache.fop.apps.FOPException;
public class Marker extends FObjMixed {
- private String markerClassName;
- private Area registryArea;
-
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList) throws FOPException {
- return new Marker(parent, propertyList);
- }
- }
-
- public static FObj.Maker maker() {
- return new Marker.Maker();
- }
-
- public Marker(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:marker";
-
- // do check to see that 'this' is under fo:flow
-
- this.markerClassName = this.properties.get("marker-class-name").getString();
-
- // check to ensure that no other marker with same parent
- // has this 'marker-class-name' is in addMarker() method
- try {
- parent.addMarker(this);
- } catch (FOPException fopex) {
- MessageHandler.error("marker cannot be added to '" + parent + "'");
- }
- }
-
- public Status layout(Area area) throws FOPException {
- // no layout action desired
- this.registryArea = area;
- area.addMarker(this);
- area.getPage().registerMarker(this);
- // System.out.println("Marker being registered in area '" + area + "'");
- return new Status(Status.OK);
- }
-
- public Status layoutMarker(Area area) throws FOPException {
- if (this.marker == START)
- this.marker = 0;
-
- int numChildren = this.children.size();
- for (int i = this.marker; i < numChildren; i++) {
- FONode fo = (FONode) children.elementAt(i);
-
- Status status;
- if ((status = fo.layout(area)).isIncomplete()) {
- this.marker = i;
- return status;
- }
- }
-
- return new Status(Status.OK);
- }
-
- public String getMarkerClassName() {
- return markerClassName;
- }
-
- public Area getRegistryArea() {
- return registryArea;
- }
+ private String markerClassName;
+ private Area registryArea;
+
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new Marker(parent, propertyList);
+ }
+
+ }
+
+ public static FObj.Maker maker() {
+ return new Marker.Maker();
+ }
+
+ public Marker(FObj parent, PropertyList propertyList) {
+ super(parent, propertyList);
+ this.name = "fo:marker";
+
+ // do check to see that 'this' is under fo:flow
+
+ this.markerClassName =
+ this.properties.get("marker-class-name").getString();
+
+ // check to ensure that no other marker with same parent
+ // has this 'marker-class-name' is in addMarker() method
+ try {
+ parent.addMarker(this);
+ } catch (FOPException fopex) {
+ MessageHandler.error("marker cannot be added to '" + parent
+ + "'");
+ }
+ }
+
+ public Status layout(Area area) throws FOPException {
+ // no layout action desired
+ this.registryArea = area;
+ area.addMarker(this);
+ area.getPage().registerMarker(this);
+ // System.out.println("Marker being registered in area '" + area + "'");
+ return new Status(Status.OK);
+ }
+
+ public Status layoutMarker(Area area) throws FOPException {
+ if (this.marker == START)
+ this.marker = 0;
+
+ int numChildren = this.children.size();
+ for (int i = this.marker; i < numChildren; i++) {
+ FONode fo = (FONode)children.elementAt(i);
+
+ Status status;
+ if ((status = fo.layout(area)).isIncomplete()) {
+ this.marker = i;
+ return status;
+ }
+ }
+
+ return new Status(Status.OK);
+ }
+
+ public String getMarkerClassName() {
+ return markerClassName;
+ }
+
+ public Area getRegistryArea() {
+ return registryArea;
+ }
+
}
diff --git a/src/org/apache/fop/fo/flow/MultiCase.java b/src/org/apache/fop/fo/flow/MultiCase.java
index ff7c9ae38..6f9ca52bf 100644
--- a/src/org/apache/fop/fo/flow/MultiCase.java
+++ b/src/org/apache/fop/fo/flow/MultiCase.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -23,6 +24,7 @@ public class MultiCase extends ToBeImplementedElement {
PropertyList propertyList) throws FOPException {
return new MultiCase(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -30,7 +32,7 @@ public class MultiCase extends ToBeImplementedElement {
}
protected MultiCase(FObj parent,
- PropertyList propertyList) throws FOPException {
+ PropertyList propertyList) throws FOPException {
super(parent, propertyList);
this.name = "fo:multi-case";
}
diff --git a/src/org/apache/fop/fo/flow/MultiProperties.java b/src/org/apache/fop/fo/flow/MultiProperties.java
index d2dcf3fb5..ab6df05e7 100644
--- a/src/org/apache/fop/fo/flow/MultiProperties.java
+++ b/src/org/apache/fop/fo/flow/MultiProperties.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -23,6 +24,7 @@ public class MultiProperties extends ToBeImplementedElement {
PropertyList propertyList) throws FOPException {
return new MultiProperties(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -30,7 +32,7 @@ public class MultiProperties extends ToBeImplementedElement {
}
protected MultiProperties(FObj parent,
- PropertyList propertyList) throws FOPException {
+ PropertyList propertyList) throws FOPException {
super(parent, propertyList);
this.name = "fo:multi-properties";
}
diff --git a/src/org/apache/fop/fo/flow/MultiPropertySet.java b/src/org/apache/fop/fo/flow/MultiPropertySet.java
index 88a2baa6a..739dbf0d6 100644
--- a/src/org/apache/fop/fo/flow/MultiPropertySet.java
+++ b/src/org/apache/fop/fo/flow/MultiPropertySet.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -23,14 +24,15 @@ public class MultiPropertySet extends ToBeImplementedElement {
PropertyList propertyList) throws FOPException {
return new MultiPropertySet(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
return new MultiPropertySet.Maker();
}
- protected MultiPropertySet(FObj parent,
- PropertyList propertyList) throws FOPException {
+ protected MultiPropertySet(FObj parent, PropertyList propertyList)
+ throws FOPException {
super(parent, propertyList);
this.name = "fo:multi-property-set";
}
diff --git a/src/org/apache/fop/fo/flow/MultiSwitch.java b/src/org/apache/fop/fo/flow/MultiSwitch.java
index 3252739ae..a68380f8d 100644
--- a/src/org/apache/fop/fo/flow/MultiSwitch.java
+++ b/src/org/apache/fop/fo/flow/MultiSwitch.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -23,6 +24,7 @@ public class MultiSwitch extends ToBeImplementedElement {
PropertyList propertyList) throws FOPException {
return new MultiSwitch(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -30,7 +32,7 @@ public class MultiSwitch extends ToBeImplementedElement {
}
protected MultiSwitch(FObj parent,
- PropertyList propertyList) throws FOPException {
+ PropertyList propertyList) throws FOPException {
super(parent, propertyList);
this.name = "fo:multi-switch";
}
diff --git a/src/org/apache/fop/fo/flow/MultiToggle.java b/src/org/apache/fop/fo/flow/MultiToggle.java
index f8d8c32d5..97da2ea9f 100644
--- a/src/org/apache/fop/fo/flow/MultiToggle.java
+++ b/src/org/apache/fop/fo/flow/MultiToggle.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -23,6 +24,7 @@ public class MultiToggle extends ToBeImplementedElement {
PropertyList propertyList) throws FOPException {
return new MultiToggle(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -30,7 +32,7 @@ public class MultiToggle extends ToBeImplementedElement {
}
protected MultiToggle(FObj parent,
- PropertyList propertyList) throws FOPException {
+ PropertyList propertyList) throws FOPException {
super(parent, propertyList);
this.name = "fo:multi-toggle";
}
diff --git a/src/org/apache/fop/fo/flow/PageNumber.java b/src/org/apache/fop/fo/flow/PageNumber.java
index 7ec9584ef..fc830df1e 100644
--- a/src/org/apache/fop/fo/flow/PageNumber.java
+++ b/src/org/apache/fop/fo/flow/PageNumber.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo.flow;
@@ -64,56 +20,60 @@ import java.util.Enumeration;
public class PageNumber extends FObj {
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent,
- PropertyList propertyList) throws FOPException {
- return new PageNumber(parent, propertyList);
- }
- }
-
- public static FObj.Maker maker() {
- return new PageNumber.Maker();
- }
-
- float red;
- float green;
- float blue;
- int wrapOption;
- int whiteSpaceCollapse;
- TextState ts;
-
- public PageNumber(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:page-number";
- }
-
- public Status layout(Area area) throws FOPException {
- if (!(area instanceof BlockArea)) {
- MessageHandler.errorln("WARNING: page-number outside block area");
- return new Status(Status.OK);
- }
- if (this.marker == START) {
-
- ColorType c = this.properties.get("color").getColorType();
- this.red = c.red();
- this.green = c.green();
- this.blue = c.blue();
-
- this.wrapOption = this.properties.get("wrap-option").getEnum();
- this.whiteSpaceCollapse =
- this.properties.get("white-space-collapse").getEnum();
- ts = new TextState();
- this.marker = 0;
-
- // initialize id
- String id = this.properties.get("id").getString();
- area.getIDReferences().initializeID(id, area);
- }
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new PageNumber(parent, propertyList);
+ }
+
+ }
+
+ public static FObj.Maker maker() {
+ return new PageNumber.Maker();
+ }
+
+ float red;
+ float green;
+ float blue;
+ int wrapOption;
+ int whiteSpaceCollapse;
+ TextState ts;
+
+ public PageNumber(FObj parent, PropertyList propertyList) {
+ super(parent, propertyList);
+ this.name = "fo:page-number";
+ }
+
+ public Status layout(Area area) throws FOPException {
+ if (!(area instanceof BlockArea)) {
+ MessageHandler.errorln("WARNING: page-number outside block area");
+ return new Status(Status.OK);
+ }
+ if (this.marker == START) {
+
+ ColorType c = this.properties.get("color").getColorType();
+ this.red = c.red();
+ this.green = c.green();
+ this.blue = c.blue();
+
+ this.wrapOption = this.properties.get("wrap-option").getEnum();
+ this.whiteSpaceCollapse =
+ this.properties.get("white-space-collapse").getEnum();
+ ts = new TextState();
+ this.marker = 0;
+
+ // initialize id
+ String id = this.properties.get("id").getString();
+ area.getIDReferences().initializeID(id, area);
+ }
+
+ String p = area.getPage().getFormattedNumber();
+ this.marker = FOText.addText((BlockArea)area,
+ propMgr.getFontState(area.getFontInfo()),
+ red, green, blue, wrapOption, null,
+ whiteSpaceCollapse, p.toCharArray(), 0,
+ p.length(), ts, VerticalAlign.BASELINE);
+ return new Status(Status.OK);
+ }
- String p = area.getPage().getFormattedNumber();
- this.marker = FOText.addText((BlockArea) area, propMgr.getFontState(area.getFontInfo()), red, green, blue,
- wrapOption, null, whiteSpaceCollapse, p.toCharArray(),
- 0, p.length(), ts, VerticalAlign.BASELINE);
- return new Status(Status.OK);
- }
}
diff --git a/src/org/apache/fop/fo/flow/PageNumberCitation.java b/src/org/apache/fop/fo/flow/PageNumberCitation.java
index c3b6d664b..78ec9f0ff 100644
--- a/src/org/apache/fop/fo/flow/PageNumberCitation.java
+++ b/src/org/apache/fop/fo/flow/PageNumberCitation.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo.flow;
@@ -62,164 +18,168 @@ import org.apache.fop.apps.FOPException;
/**
-* 6.6.11 fo:page-number-citation
-*
-* Common Usage:
-* The fo:page-number-citation is used to reference the page-number for the page containing the first normal area returned by
-* the cited formatting object.
-*
-* NOTE:
-* It may be used to provide the page-numbers in the table of contents, cross-references, and index entries.
-*
-* Areas:
-* The fo:page-number-citation formatting object generates and returns a single normal inline-area.
-* Constraints:
-*
-* The cited page-number is the number of the page containing, as a descendant, the first normal area returned by the
-* formatting object with an id trait matching the ref-id trait of the fo:page-number-citation (the referenced formatting
-* object).
-*
-* The cited page-number string is obtained by converting the cited page-number in accordance with the number to string
-* conversion properties specified on the ancestor fo:page-sequence of the referenced formatting object.
-*
-* The child areas of the generated inline-area are the same as the result of formatting a result-tree fragment consisting of
-* fo:character flow objects; one for each character in the cited page-number string and with only the "character" property
-* specified.
-*
-* Contents:
-*
-* EMPTY
-*
-* The following properties apply to this formatting object:
-*
-* [7.3 Common Accessibility Properties]
-* [7.5 Common Aural Properties]
-* [7.6 Common Border, Padding, and Background Properties]
-* [7.7 Common Font Properties]
-* [7.10 Common Margin Properties-Inline]
-* [7.11.1 "alignment-adjust"]
-* [7.11.2 "baseline-identifier"]
-* [7.11.3 "baseline-shift"]
-* [7.11.5 "dominant-baseline"]
-* [7.36.2 "id"]
-* [7.17.4 "keep-with-next"]
-* [7.17.5 "keep-with-previous"]
-* [7.14.2 "letter-spacing"]
-* [7.13.4 "line-height"]
-* [7.13.5 "line-height-shift-adjustment"]
-* [7.36.5 "ref-id"]
-* [7.18.4 "relative-position"]
-* [7.36.6 "score-spaces"]
-* [7.14.4 "text-decoration"]
-* [7.14.5 "text-shadow"]
-* [7.14.6 "text-transform"]
-* [7.14.8 "word-spacing"]
-*/
+ * 6.6.11 fo:page-number-citation
+ *
+ * Common Usage:
+ * The fo:page-number-citation is used to reference the page-number for the page containing the first normal area returned by
+ * the cited formatting object.
+ *
+ * NOTE:
+ * It may be used to provide the page-numbers in the table of contents, cross-references, and index entries.
+ *
+ * Areas:
+ * The fo:page-number-citation formatting object generates and returns a single normal inline-area.
+ * Constraints:
+ *
+ * The cited page-number is the number of the page containing, as a descendant, the first normal area returned by the
+ * formatting object with an id trait matching the ref-id trait of the fo:page-number-citation (the referenced formatting
+ * object).
+ *
+ * The cited page-number string is obtained by converting the cited page-number in accordance with the number to string
+ * conversion properties specified on the ancestor fo:page-sequence of the referenced formatting object.
+ *
+ * The child areas of the generated inline-area are the same as the result of formatting a result-tree fragment consisting of
+ * fo:character flow objects; one for each character in the cited page-number string and with only the "character" property
+ * specified.
+ *
+ * Contents:
+ *
+ * EMPTY
+ *
+ * The following properties apply to this formatting object:
+ *
+ * [7.3 Common Accessibility Properties]
+ * [7.5 Common Aural Properties]
+ * [7.6 Common Border, Padding, and Background Properties]
+ * [7.7 Common Font Properties]
+ * [7.10 Common Margin Properties-Inline]
+ * [7.11.1 "alignment-adjust"]
+ * [7.11.2 "baseline-identifier"]
+ * [7.11.3 "baseline-shift"]
+ * [7.11.5 "dominant-baseline"]
+ * [7.36.2 "id"]
+ * [7.17.4 "keep-with-next"]
+ * [7.17.5 "keep-with-previous"]
+ * [7.14.2 "letter-spacing"]
+ * [7.13.4 "line-height"]
+ * [7.13.5 "line-height-shift-adjustment"]
+ * [7.36.5 "ref-id"]
+ * [7.18.4 "relative-position"]
+ * [7.36.6 "score-spaces"]
+ * [7.14.4 "text-decoration"]
+ * [7.14.5 "text-shadow"]
+ * [7.14.6 "text-transform"]
+ * [7.14.8 "word-spacing"]
+ */
public class PageNumberCitation extends FObj {
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent,
- PropertyList propertyList) throws FOPException {
- return new PageNumberCitation(parent, propertyList);
- }
- }
-
- public static FObj.Maker maker() {
- return new PageNumberCitation.Maker();
- }
-
- float red;
- float green;
- float blue;
- int wrapOption;
- int whiteSpaceCollapse;
- Area area;
- String pageNumber;
- String refId;
- String id;
- TextState ts;
-
-
- public PageNumberCitation(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:page-number-citation";
- }
-
-
- public Status layout(Area area) throws FOPException {
- if (!(area instanceof BlockArea)) {
- MessageHandler.errorln("WARNING: page-number-citation outside block area");
- return new Status(Status.OK);
- }
-
- IDReferences idReferences = area.getIDReferences();
- this.area = area;
- if (this.marker == START) {
-
- ColorType c = this.properties.get("color").getColorType();
- this.red = c.red();
- this.green = c.green();
- this.blue = c.blue();
-
- this.wrapOption = this.properties.get("wrap-option").getEnum();
- this.whiteSpaceCollapse =
- this.properties.get("white-space-collapse").getEnum();
-
- this.refId = this.properties.get("ref-id").getString();
-
- if (this.refId.equals("")) {
- throw new FOPException("page-number-citation must contain \"ref-id\"");
- }
-
- // create id
- this.id = this.properties.get("id").getString();
- idReferences.createID(id);
- ts = new TextState();
-
- this.marker = 0;
- }
-
- if (marker == 0) {
- idReferences.configureID(id, area);
- }
-
-
- pageNumber = idReferences.getPageNumber(refId);
-
- if (pageNumber != null) { // if we already know the page number
- this.marker = FOText.addText((BlockArea) area,
- propMgr.getFontState(area.getFontInfo()),
- red, green, blue,
- wrapOption, null, whiteSpaceCollapse,
- pageNumber.toCharArray(), 0, pageNumber.length(),
- ts, VerticalAlign.BASELINE);
- } else { // add pageNumberCitation to area to be resolved during rendering
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new PageNumberCitation(parent, propertyList);
+ }
+
+ }
+
+ public static FObj.Maker maker() {
+ return new PageNumberCitation.Maker();
+ }
+
+ float red;
+ float green;
+ float blue;
+ int wrapOption;
+ int whiteSpaceCollapse;
+ Area area;
+ String pageNumber;
+ String refId;
+ String id;
+ TextState ts;
+
+
+ public PageNumberCitation(FObj parent, PropertyList propertyList) {
+ super(parent, propertyList);
+ this.name = "fo:page-number-citation";
+ }
+
+
+ public Status layout(Area area) throws FOPException {
+ if (!(area instanceof BlockArea)) {
+ MessageHandler.errorln("WARNING: page-number-citation outside block area");
+ return new Status(Status.OK);
+ }
+
+ IDReferences idReferences = area.getIDReferences();
+ this.area = area;
+ if (this.marker == START) {
+
+ ColorType c = this.properties.get("color").getColorType();
+ this.red = c.red();
+ this.green = c.green();
+ this.blue = c.blue();
+
+ this.wrapOption = this.properties.get("wrap-option").getEnum();
+ this.whiteSpaceCollapse =
+ this.properties.get("white-space-collapse").getEnum();
+
+ this.refId = this.properties.get("ref-id").getString();
+
+ if (this.refId.equals("")) {
+ throw new FOPException("page-number-citation must contain \"ref-id\"");
+ }
+
+ // create id
+ this.id = this.properties.get("id").getString();
+ idReferences.createID(id);
+ ts = new TextState();
+
+ this.marker = 0;
+ }
+
+ if (marker == 0) {
+ idReferences.configureID(id, area);
+ }
+
+
+ pageNumber = idReferences.getPageNumber(refId);
+
+ if (pageNumber != null) { // if we already know the page number
+ this.marker =
+ FOText.addText((BlockArea)area,
+ propMgr.getFontState(area.getFontInfo()), red,
+ green, blue, wrapOption, null,
+ whiteSpaceCollapse, pageNumber.toCharArray(),
+ 0, pageNumber.length(), ts,
+ VerticalAlign.BASELINE);
+ } else { // add pageNumberCitation to area to be resolved during rendering
BlockArea blockArea = (BlockArea)area;
LineArea la = blockArea.getCurrentLineArea();
- if(la == null) {
- return new Status(Status.AREA_FULL_NONE);
+ if (la == null) {
+ return new Status(Status.AREA_FULL_NONE);
}
la.changeFont(propMgr.getFontState(area.getFontInfo()));
la.changeColor(red, green, blue);
la.changeWrapOption(wrapOption);
la.changeWhiteSpaceCollapse(whiteSpaceCollapse);
-/* la.changeHyphenation(language, country, hyphenate,
- hyphenationChar, hyphenationPushCharacterCount,
- hyphenationRemainCharacterCount);*/
+ /*
+ * la.changeHyphenation(language, country, hyphenate,
+ * hyphenationChar, hyphenationPushCharacterCount,
+ * hyphenationRemainCharacterCount);
+ */
-// blockArea.setupLinkSet(null);
+ // blockArea.setupLinkSet(null);
la.addPageNumberCitation(refId, null);
this.marker = -1;
- }
+ }
- if (this.marker == -1) {
- return new Status(Status.OK);
- } else {
- return new Status(Status.AREA_FULL_NONE);
- }
+ if (this.marker == -1) {
+ return new Status(Status.OK);
+ } else {
+ return new Status(Status.AREA_FULL_NONE);
+ }
- }
+ }
}
diff --git a/src/org/apache/fop/fo/flow/RetrieveMarker.java b/src/org/apache/fop/fo/flow/RetrieveMarker.java
index 6e36cbd5a..55376ac65 100644
--- a/src/org/apache/fop/fo/flow/RetrieveMarker.java
+++ b/src/org/apache/fop/fo/flow/RetrieveMarker.java
@@ -1,5 +1,5 @@
-/*-- $Id$-- */
/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -20,135 +20,143 @@ import java.util.Vector;
public class RetrieveMarker extends FObjMixed {
- private String retrieveClassName;
- private int retrievePosition;
- private int retrieveBoundary;
-
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList) throws FOPException {
- return new RetrieveMarker(parent, propertyList);
- }
- }
-
- public static FObj.Maker maker() {
- return new RetrieveMarker.Maker();
- }
-
- public RetrieveMarker(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:retrieve-marker";
-
- this.retrieveClassName = this.properties.get("retrieve-class-name").getString();
- this.retrievePosition = this.properties.get("retrieve-position").getEnum();
- this.retrieveBoundary = this.properties.get("retrieve-boundary").getEnum();
- }
-
- public Status layout(Area area) throws FOPException {
- // locate qualifying areas by 'marker-class-name' and
- // 'retrieve-boundary'. Initially we will always check
- // the containing page
- Page containingPage = area.getPage();
- Marker bestMarker = searchPage(containingPage, true);
-
- // if marker not yet found, and 'retrieve-boundary' permits,
- // search forward by Page
- if ((null == bestMarker) && (retrieveBoundary != RetrieveBoundary.PAGE)) {
- // System.out.println("Null bestMarker and searching...");
- Page currentPage = containingPage;
- boolean isFirstCall = true;
- while (bestMarker == null) {
- Page previousPage =
- locatePreviousPage(currentPage, retrieveBoundary, isFirstCall);
- isFirstCall = false;
- // System.out.println("Previous page = '" + previousPage + "'");
- bestMarker = searchPage(previousPage, false);
- currentPage = previousPage;
- }
- }
-
- Status status = new Status(Status.AREA_FULL_NONE);
- if (null != bestMarker) {
- // System.out.println("Laying out marker '" + bestMarker + "' in area '" + area + "'");
- // the 'markers' referred to in this method are internal; they have
- // nothing to do with fo:marker
- bestMarker.resetMarker();
- status = bestMarker.layoutMarker(area);
- }
-
- return status;
- }
-
- private Marker searchPage(Page page, boolean isContainingPage)
- throws FOPException {
- Vector pageMarkers = page.getMarkers();
- if (pageMarkers.isEmpty()) {
- // System.out.println("No markers on page");
- return null;
- }
-
- // if no longer the containing page (fo:retrieve-marker, or the page
- // being processed), grab the last qualifying marker on this one
- if (!isContainingPage) {
- for (int c = pageMarkers.size(); c > 0; c--) {
- Marker currentMarker = (Marker)pageMarkers.elementAt(c-1);
- if (currentMarker.getMarkerClassName().equals(retrieveClassName)) {
- return currentMarker;
- }
- }
- }
-
- // search forward if 'first-starting-within-page' or
- // 'first-including-carryover'
- if (retrievePosition == RetrievePosition.FIC) {
- for (int c = 0; c < pageMarkers.size(); c++) {
- Marker currentMarker = (Marker)pageMarkers.elementAt(c);
- if (currentMarker.getMarkerClassName().equals(retrieveClassName)) {
- return currentMarker;
- }
- }
-
- } else if (retrievePosition == RetrievePosition.FSWP) {
- for (int c = 0; c < pageMarkers.size(); c++) {
- Marker currentMarker = (Marker)pageMarkers.elementAt(c);
- if (currentMarker.getMarkerClassName().equals(retrieveClassName)) {
- if (currentMarker.getRegistryArea().isFirst()) {
- return currentMarker;
- }
- }
- }
-
- } else if (retrievePosition == RetrievePosition.LSWP) {
- for (int c = pageMarkers.size(); c > 0; c--) {
- Marker currentMarker = (Marker)pageMarkers.elementAt(c-1);
- if (currentMarker.getMarkerClassName().equals(retrieveClassName)) {
- if (currentMarker.getRegistryArea().isFirst()) {
- return currentMarker;
- }
- }
- }
-
- } else if (retrievePosition == RetrievePosition.LEWP) {
- for (int c = pageMarkers.size(); c > 0; c--) {
- Marker currentMarker = (Marker)pageMarkers.elementAt(c-1);
- if (currentMarker.getMarkerClassName().equals(retrieveClassName)) {
- if (currentMarker.getRegistryArea().isLast()) {
- return currentMarker;
- }
- }
- }
-
- } else {
- throw new FOPException("Illegal 'retrieve-position' value");
- }
- return null;
- }
-
- private Page locatePreviousPage(Page page, int retrieveBoundary,
- boolean isFirstCall) {
- boolean pageWithinSequence = true;
- if (retrieveBoundary == RetrieveBoundary.DOCUMENT)
- pageWithinSequence = false;
- return page.getAreaTree().getPreviousPage(page, pageWithinSequence,
- isFirstCall);
- }
+ private String retrieveClassName;
+ private int retrievePosition;
+ private int retrieveBoundary;
+
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new RetrieveMarker(parent, propertyList);
+ }
+
+ }
+
+ public static FObj.Maker maker() {
+ return new RetrieveMarker.Maker();
+ }
+
+ public RetrieveMarker(FObj parent, PropertyList propertyList) {
+ super(parent, propertyList);
+ this.name = "fo:retrieve-marker";
+
+ this.retrieveClassName =
+ this.properties.get("retrieve-class-name").getString();
+ this.retrievePosition =
+ this.properties.get("retrieve-position").getEnum();
+ this.retrieveBoundary =
+ this.properties.get("retrieve-boundary").getEnum();
+ }
+
+ public Status layout(Area area) throws FOPException {
+ // locate qualifying areas by 'marker-class-name' and
+ // 'retrieve-boundary'. Initially we will always check
+ // the containing page
+ Page containingPage = area.getPage();
+ Marker bestMarker = searchPage(containingPage, true);
+
+ // if marker not yet found, and 'retrieve-boundary' permits,
+ // search forward by Page
+ if ((null == bestMarker)
+ && (retrieveBoundary != RetrieveBoundary.PAGE)) {
+ // System.out.println("Null bestMarker and searching...");
+ Page currentPage = containingPage;
+ boolean isFirstCall = true;
+ while (bestMarker == null) {
+ Page previousPage = locatePreviousPage(currentPage,
+ retrieveBoundary,
+ isFirstCall);
+ isFirstCall = false;
+ // System.out.println("Previous page = '" + previousPage + "'");
+ bestMarker = searchPage(previousPage, false);
+ currentPage = previousPage;
+ }
+ }
+
+ Status status = new Status(Status.AREA_FULL_NONE);
+ if (null != bestMarker) {
+ // System.out.println("Laying out marker '" + bestMarker + "' in area '" + area + "'");
+ // the 'markers' referred to in this method are internal; they have
+ // nothing to do with fo:marker
+ bestMarker.resetMarker();
+ status = bestMarker.layoutMarker(area);
+ }
+
+ return status;
+ }
+
+ private Marker searchPage(Page page,
+ boolean isContainingPage) throws FOPException {
+ Vector pageMarkers = page.getMarkers();
+ if (pageMarkers.isEmpty()) {
+ // System.out.println("No markers on page");
+ return null;
+ }
+
+ // if no longer the containing page (fo:retrieve-marker, or the page
+ // being processed), grab the last qualifying marker on this one
+ if (!isContainingPage) {
+ for (int c = pageMarkers.size(); c > 0; c--) {
+ Marker currentMarker = (Marker)pageMarkers.elementAt(c - 1);
+ if (currentMarker.getMarkerClassName().equals(retrieveClassName)) {
+ return currentMarker;
+ }
+ }
+ }
+
+ // search forward if 'first-starting-within-page' or
+ // 'first-including-carryover'
+ if (retrievePosition == RetrievePosition.FIC) {
+ for (int c = 0; c < pageMarkers.size(); c++) {
+ Marker currentMarker = (Marker)pageMarkers.elementAt(c);
+ if (currentMarker.getMarkerClassName().equals(retrieveClassName)) {
+ return currentMarker;
+ }
+ }
+
+ } else if (retrievePosition == RetrievePosition.FSWP) {
+ for (int c = 0; c < pageMarkers.size(); c++) {
+ Marker currentMarker = (Marker)pageMarkers.elementAt(c);
+ if (currentMarker.getMarkerClassName().equals(retrieveClassName)) {
+ if (currentMarker.getRegistryArea().isFirst()) {
+ return currentMarker;
+ }
+ }
+ }
+
+ } else if (retrievePosition == RetrievePosition.LSWP) {
+ for (int c = pageMarkers.size(); c > 0; c--) {
+ Marker currentMarker = (Marker)pageMarkers.elementAt(c - 1);
+ if (currentMarker.getMarkerClassName().equals(retrieveClassName)) {
+ if (currentMarker.getRegistryArea().isFirst()) {
+ return currentMarker;
+ }
+ }
+ }
+
+ } else if (retrievePosition == RetrievePosition.LEWP) {
+ for (int c = pageMarkers.size(); c > 0; c--) {
+ Marker currentMarker = (Marker)pageMarkers.elementAt(c - 1);
+ if (currentMarker.getMarkerClassName().equals(retrieveClassName)) {
+ if (currentMarker.getRegistryArea().isLast()) {
+ return currentMarker;
+ }
+ }
+ }
+
+ } else {
+ throw new FOPException("Illegal 'retrieve-position' value");
+ }
+ return null;
+ }
+
+ private Page locatePreviousPage(Page page, int retrieveBoundary,
+ boolean isFirstCall) {
+ boolean pageWithinSequence = true;
+ if (retrieveBoundary == RetrieveBoundary.DOCUMENT)
+ pageWithinSequence = false;
+ return page.getAreaTree().getPreviousPage(page, pageWithinSequence,
+ isFirstCall);
+ }
+
}
diff --git a/src/org/apache/fop/fo/flow/RowSpanMgr.java b/src/org/apache/fop/fo/flow/RowSpanMgr.java
index 96853307d..363963b62 100644
--- a/src/org/apache/fop/fo/flow/RowSpanMgr.java
+++ b/src/org/apache/fop/fo/flow/RowSpanMgr.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * -- $Id$ --
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -11,96 +12,98 @@ import java.util.Enumeration;
public class RowSpanMgr {
class SpanInfo {
- int cellHeight;
- int totalRowHeight;
- int rowsRemaining;
- //int numCols; // both V and H span
- TableCell cell;
-
- SpanInfo(TableCell cell, int cellHeight, int rowsSpanned) {
- this.cell = cell;
- this.cellHeight = cellHeight;
- this.totalRowHeight = 0;
- this.rowsRemaining = rowsSpanned;
- }
-
- /**
- * Return the height remaining in the span.
- */
- int heightRemaining() {
- int hl = cellHeight - totalRowHeight;
- return (hl>0)? hl : 0;
- }
-
- boolean isInLastRow() {
- return (rowsRemaining == 1);
- }
-
- boolean finishRow(int rowHeight) {
- totalRowHeight += rowHeight;
- if (--rowsRemaining == 0) {
- if (cell != null) {
- cell.setRowHeight(totalRowHeight);
- }
- return true;
- }
- else return false;
- }
+ int cellHeight;
+ int totalRowHeight;
+ int rowsRemaining;
+ // int numCols; // both V and H span
+ TableCell cell;
+
+ SpanInfo(TableCell cell, int cellHeight, int rowsSpanned) {
+ this.cell = cell;
+ this.cellHeight = cellHeight;
+ this.totalRowHeight = 0;
+ this.rowsRemaining = rowsSpanned;
+ }
+
+ /**
+ * Return the height remaining in the span.
+ */
+ int heightRemaining() {
+ int hl = cellHeight - totalRowHeight;
+ return (hl > 0) ? hl : 0;
+ }
+
+ boolean isInLastRow() {
+ return (rowsRemaining == 1);
+ }
+
+ boolean finishRow(int rowHeight) {
+ totalRowHeight += rowHeight;
+ if (--rowsRemaining == 0) {
+ if (cell != null) {
+ cell.setRowHeight(totalRowHeight);
+ }
+ return true;
+ } else
+ return false;
+ }
+
}
private SpanInfo spanInfo[];
public RowSpanMgr(int numCols) {
- this.spanInfo = new SpanInfo[numCols];
+ this.spanInfo = new SpanInfo[numCols];
}
public void addRowSpan(TableCell cell, int firstCol, int numCols,
- int cellHeight, int rowsSpanned) {
- spanInfo[firstCol-1] = new SpanInfo(cell, cellHeight, rowsSpanned);
- for (int i=0; i columns.size()) {
- columns.setSize(currentColumnNumber);
- }
- columns.setElementAt(c, currentColumnNumber - 1);
- c.setColumnOffset(offset);
- c.layout(areaContainer);
- offset += c.getColumnWidth();
- }
- }
- }
- areaContainer.setAllocationWidth(offset);
-
- for (int i = this.marker; i < numChildren; i++) {
- FONode fo = (FONode) children.elementAt(i);
- if (fo instanceof TableHeader) {
- if (columns.size() == 0) {
- MessageHandler.errorln("WARNING: current implementation of tables requires a table-column for each column, indicating column-width");
- return new Status(Status.OK);
- }
- tableHeader = (TableHeader) fo;
- tableHeader.setColumns(columns);
- } else if (fo instanceof TableFooter) {
- if (columns.size() == 0) {
- MessageHandler.errorln("WARNING: current implementation of tables requires a table-column for each column, indicating column-width");
- return new Status(Status.OK);
- }
- tableFooter = (TableFooter) fo;
- tableFooter.setColumns(columns);
- } else if (fo instanceof TableBody) {
- if (columns.size() == 0) {
- MessageHandler.errorln("WARNING: current implementation of tables requires a table-column for each column, indicating column-width");
- return new Status(Status.OK);
- }
- Status status;
- if (tableHeader != null && !addedHeader) {
- if ((status = tableHeader.layout(areaContainer)).
- isIncomplete()) {
- return new Status(Status.AREA_FULL_NONE);
- }
- addedHeader = true;
- tableHeader.resetMarker();
- area.setMaxHeight(area.getMaxHeight() - spaceLeft + this.areaContainer.getMaxHeight());
- }
- if (tableFooter != null && !this.omitFooterAtBreak && !addedFooter) {
- if ((status = tableFooter.layout(areaContainer)).
- isIncomplete()) {
- return new Status(Status.AREA_FULL_NONE);
- }
- addedFooter = true;
- tableFooter.resetMarker();
- }
- fo.setWidows(widows);
- fo.setOrphans(orphans);
- ((TableBody) fo).setColumns(columns);
-
- if ((status = fo.layout(areaContainer)).isIncomplete()) {
- this.marker = i;
- if (bodyCount == 0 && status.getCode() == Status.AREA_FULL_NONE) {
- if (tableHeader != null)
- tableHeader.removeLayout(areaContainer);
- if (tableFooter != null)
- tableFooter.removeLayout(areaContainer);
- resetMarker();
- // status = new Status(Status.AREA_FULL_SOME);
- }
- //areaContainer.end();
- if (areaContainer.getContentHeight() > 0) {
- area.addChild(areaContainer);
- area.increaseHeight(areaContainer.getHeight());
- area.setAbsoluteHeight(
- areaContainer.getAbsoluteHeight());
- if(this.omitHeaderAtBreak) {
- // remove header, no longer needed
- tableHeader = null;
- }
- if (tableFooter != null && !this.omitFooterAtBreak) {
- // move footer to bottom of area and move up body
- ((TableBody) fo).setYPosition(
- tableFooter.getYPosition());
- tableFooter.setYPosition(
- tableFooter.getYPosition() +
- ((TableBody) fo).getHeight());
- }
- setupColumnHeights();
- status = new Status(Status.AREA_FULL_SOME);
- }
- return status;
- } else {
- bodyCount++;
- }
- area.setMaxHeight(area.getMaxHeight() - spaceLeft + this.areaContainer.getMaxHeight());
- if (tableFooter != null && !this.omitFooterAtBreak) {
- // move footer to bottom of area and move up body
- // space before and after footer will make this wrong
- ((TableBody) fo).setYPosition(
- tableFooter.getYPosition());
- tableFooter.setYPosition( tableFooter.getYPosition() +
- ((TableBody) fo).getHeight());
- }
- }
- }
-
- if (tableFooter != null && this.omitFooterAtBreak) {
- if (tableFooter.layout(areaContainer).isIncomplete()) {
- // this is a problem since we need to remove a row
- // from the last table body and place it on the
- // next page so that it can have a footer at
- // the end of the table.
- MessageHandler.errorln("WARNING: footer could not fit on page, moving last body row to next page");
- area.addChild(areaContainer);
- area.increaseHeight(areaContainer.getHeight());
- area.setAbsoluteHeight(
- areaContainer.getAbsoluteHeight());
- if(this.omitHeaderAtBreak) {
- // remove header, no longer needed
- tableHeader = null;
- }
- tableFooter.removeLayout(areaContainer);
- tableFooter.resetMarker();
- return new Status(Status.AREA_FULL_SOME);
- }
- }
-
- if (height != 0)
- areaContainer.setHeight(height);
-
- setupColumnHeights();
-
- areaContainer.end();
- area.addChild(areaContainer);
-
- /* should this be combined into above? */
- area.increaseHeight(areaContainer.getHeight());
-
- area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
-
- if (spaceAfter != 0) {
- area.addDisplaySpace(spaceAfter);
- }
-
- if (area instanceof BlockArea) {
- area.start();
- }
-
- if (breakAfter == BreakAfter.PAGE) {
- this.marker = BREAK_AFTER;
- return new Status(Status.FORCE_PAGE_BREAK);
- }
-
- if (breakAfter == BreakAfter.ODD_PAGE) {
- this.marker = BREAK_AFTER;
- return new Status(Status.FORCE_PAGE_BREAK_ODD);
- }
-
- if (breakAfter == BreakAfter.EVEN_PAGE) {
- this.marker = BREAK_AFTER;
- return new Status(Status.FORCE_PAGE_BREAK_EVEN);
- }
-
- return new Status(Status.OK);
- }
-
- protected void setupColumnHeights()
- {
- int numChildren = this.children.size();
- for (int i = 0; i < numChildren; i++) {
- FONode fo = (FONode) children.elementAt(i);
- if (fo instanceof TableColumn) {
- ((TableColumn) fo).setHeight(areaContainer.getContentHeight());
- }
- }
- }
-
- public int getAreaHeight() {
- return areaContainer.getHeight();
- }
-
- /**
- * Return the content width of the boxes generated by this table FO.
- */
- public int getContentWidth() {
- if (areaContainer != null)
- return areaContainer.getContentWidth(); //getAllocationWidth()??
- else
- return 0; // not laid out yet
- }
-
-// /**
-// * Return the last TableRow in the header or null if no header or
-// * no header in non-first areas.
-// * @param bForInitialArea If true, return the header row for the
-// * initial table area, else for a continuation area, taking into
-// * account the omit-header-at-break property.
-// */
-// TableRow getLastHeaderRow(boolean bForInitialArea) {
-// // Check omit...
-// if ((tableHeader != null) &&
-// (bForInitialArea || omitHeaderAtBreak == false)) {
-// return tableHeader.children.lastElement();
-// }
-// return null;
-// }
-
-// /**
-// * Return the first TableRow in the footer or null if no footer or
-// * no footer in non-last areas.
-// * @param bForFinalArea If true, return the footer row for the
-// * final table area, else for a non-final area, taking into
-// * account the omit-footer-at-break property.
-// */
-// TableRow getLastFooterRow(boolean bForFinalArea) {
-// if ((tableFooter != null) &&
-// (bForFinalArea || omitFooterAtBreak == false)) {
-// return tableFooter.children.firstElement();
-// }
-// return null;
-// }
-
-
-// /**
-// * Return border information for the side (start/end) of the column
-// * whose number is iColNumber (first column = 1).
-// * ATTENTION: for now we assume columns are in order in the array!
-// */
-// BorderInfo getColumnBorder(BorderInfo.Side side, int iColNumber) {
-// TableColumn col = (TableColumn)columns.elementAt(iColNumber);
-// return col.getBorderInfo(side);
-// }
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new Table(parent, propertyList);
+ }
+
+ }
+
+ public static FObj.Maker maker() {
+ return new Table.Maker();
+ }
+
+ int breakBefore;
+ int breakAfter;
+ int spaceBefore;
+ int spaceAfter;
+ ColorType backgroundColor;
+ int width;
+ int height;
+ String id;
+ TableHeader tableHeader = null;
+ TableFooter tableFooter = null;
+ boolean omitHeaderAtBreak = false;
+ boolean omitFooterAtBreak = false;
+
+ Vector columns = new Vector();
+ int currentColumnNumber = 0;
+ int bodyCount = 0;
+
+ AreaContainer areaContainer;
+
+ public Table(FObj parent, PropertyList propertyList) {
+ super(parent, propertyList);
+ this.name = "fo:table";
+ }
+
+ public Status layout(Area area) throws FOPException {
+ if (this.marker == BREAK_AFTER) {
+ return new Status(Status.OK);
+ }
+
+ if (this.marker == START) {
+ this.breakBefore = this.properties.get("break-before").getEnum();
+ this.breakAfter = this.properties.get("break-after").getEnum();
+ this.spaceBefore =
+ this.properties.get("space-before.optimum").getLength().mvalue();
+ this.spaceAfter =
+ this.properties.get("space-after.optimum").getLength().mvalue();
+ this.backgroundColor =
+ this.properties.get("background-color").getColorType();
+ this.width = this.properties.get("width").getLength().mvalue();
+ this.height = this.properties.get("height").getLength().mvalue();
+
+ this.id = this.properties.get("id").getString();
+
+ this.omitHeaderAtBreak =
+ this.properties.get("table-omit-header-at-break").getEnum()
+ == TableOmitHeaderAtBreak.TRUE;
+ this.omitFooterAtBreak =
+ this.properties.get("table-omit-footer-at-break").getEnum()
+ == TableOmitFooterAtBreak.TRUE;
+
+ if (area instanceof BlockArea) {
+ area.end();
+ }
+ if (this.areaContainer
+ == null) { // check if anything was previously laid out
+ area.getIDReferences().createID(id);
+ }
+
+
+ this.marker = 0;
+
+ if (breakBefore == BreakBefore.PAGE) {
+ return new Status(Status.FORCE_PAGE_BREAK);
+ }
+
+ if (breakBefore == BreakBefore.ODD_PAGE) {
+ return new Status(Status.FORCE_PAGE_BREAK_ODD);
+ }
+
+ if (breakBefore == BreakBefore.EVEN_PAGE) {
+ return new Status(Status.FORCE_PAGE_BREAK_EVEN);
+ }
+ }
+
+ if ((spaceBefore != 0) && (this.marker == 0)) {
+ area.addDisplaySpace(spaceBefore);
+ }
+
+ if (marker == 0 && areaContainer == null) {
+ // configure id
+ area.getIDReferences().configureID(id, area);
+ }
+
+ int spaceLeft = area.spaceLeft();
+ this.areaContainer =
+ new AreaContainer(propMgr.getFontState(area.getFontInfo()), 0, 0,
+ area.getAllocationWidth(), area.spaceLeft(),
+ Position.STATIC);
+ areaContainer.foCreator = this; // G Seshadri
+ areaContainer.setPage(area.getPage());
+ areaContainer.setBackgroundColor(backgroundColor);
+ areaContainer.setBorderAndPadding(propMgr.getBorderAndPadding());
+ areaContainer.start();
+
+ areaContainer.setAbsoluteHeight(area.getAbsoluteHeight());
+ areaContainer.setIDReferences(area.getIDReferences());
+
+ // added by Eric Schaeffer
+ currentColumnNumber = 0;
+ int offset = 0;
+
+ boolean addedHeader = false;
+ boolean addedFooter = false;
+ int numChildren = this.children.size();
+ for (int i = 0; i < numChildren; i++) {
+ FONode fo = (FONode)children.elementAt(i);
+ if (fo instanceof TableColumn) {
+ TableColumn c = (TableColumn)fo;
+ c.doSetup(areaContainer);
+ int numColumnsRepeated = c.getNumColumnsRepeated();
+ // int currentColumnNumber = c.getColumnNumber();
+
+ for (int j = 0; j < numColumnsRepeated; j++) {
+ currentColumnNumber++;
+ if (currentColumnNumber > columns.size()) {
+ columns.setSize(currentColumnNumber);
+ }
+ columns.setElementAt(c, currentColumnNumber - 1);
+ c.setColumnOffset(offset);
+ c.layout(areaContainer);
+ offset += c.getColumnWidth();
+ }
+ }
+ }
+ areaContainer.setAllocationWidth(offset);
+
+ for (int i = this.marker; i < numChildren; i++) {
+ FONode fo = (FONode)children.elementAt(i);
+ if (fo instanceof TableHeader) {
+ if (columns.size() == 0) {
+ MessageHandler.errorln("WARNING: current implementation of tables requires a table-column for each column, indicating column-width");
+ return new Status(Status.OK);
+ }
+ tableHeader = (TableHeader)fo;
+ tableHeader.setColumns(columns);
+ } else if (fo instanceof TableFooter) {
+ if (columns.size() == 0) {
+ MessageHandler.errorln("WARNING: current implementation of tables requires a table-column for each column, indicating column-width");
+ return new Status(Status.OK);
+ }
+ tableFooter = (TableFooter)fo;
+ tableFooter.setColumns(columns);
+ } else if (fo instanceof TableBody) {
+ if (columns.size() == 0) {
+ MessageHandler.errorln("WARNING: current implementation of tables requires a table-column for each column, indicating column-width");
+ return new Status(Status.OK);
+ }
+ Status status;
+ if (tableHeader != null &&!addedHeader) {
+ if ((status =
+ tableHeader.layout(areaContainer)).isIncomplete()) {
+ return new Status(Status.AREA_FULL_NONE);
+ }
+ addedHeader = true;
+ tableHeader.resetMarker();
+ area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ + this.areaContainer.getMaxHeight());
+ }
+ if (tableFooter != null &&!this.omitFooterAtBreak
+ &&!addedFooter) {
+ if ((status =
+ tableFooter.layout(areaContainer)).isIncomplete()) {
+ return new Status(Status.AREA_FULL_NONE);
+ }
+ addedFooter = true;
+ tableFooter.resetMarker();
+ }
+ fo.setWidows(widows);
+ fo.setOrphans(orphans);
+ ((TableBody)fo).setColumns(columns);
+
+ if ((status = fo.layout(areaContainer)).isIncomplete()) {
+ this.marker = i;
+ if (bodyCount == 0
+ && status.getCode() == Status.AREA_FULL_NONE) {
+ if (tableHeader != null)
+ tableHeader.removeLayout(areaContainer);
+ if (tableFooter != null)
+ tableFooter.removeLayout(areaContainer);
+ resetMarker();
+ // status = new Status(Status.AREA_FULL_SOME);
+ }
+ // areaContainer.end();
+ if (areaContainer.getContentHeight() > 0) {
+ area.addChild(areaContainer);
+ area.increaseHeight(areaContainer.getHeight());
+ area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
+ if (this.omitHeaderAtBreak) {
+ // remove header, no longer needed
+ tableHeader = null;
+ }
+ if (tableFooter != null &&!this.omitFooterAtBreak) {
+ // move footer to bottom of area and move up body
+ ((TableBody)fo).setYPosition(tableFooter.getYPosition());
+ tableFooter.setYPosition(tableFooter.getYPosition()
+ + ((TableBody)fo).getHeight());
+ }
+ setupColumnHeights();
+ status = new Status(Status.AREA_FULL_SOME);
+ }
+ return status;
+ } else {
+ bodyCount++;
+ }
+ area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ + this.areaContainer.getMaxHeight());
+ if (tableFooter != null &&!this.omitFooterAtBreak) {
+ // move footer to bottom of area and move up body
+ // space before and after footer will make this wrong
+ ((TableBody)fo).setYPosition(tableFooter.getYPosition());
+ tableFooter.setYPosition(tableFooter.getYPosition()
+ + ((TableBody)fo).getHeight());
+ }
+ }
+ }
+
+ if (tableFooter != null && this.omitFooterAtBreak) {
+ if (tableFooter.layout(areaContainer).isIncomplete()) {
+ // this is a problem since we need to remove a row
+ // from the last table body and place it on the
+ // next page so that it can have a footer at
+ // the end of the table.
+ MessageHandler.errorln("WARNING: footer could not fit on page, moving last body row to next page");
+ area.addChild(areaContainer);
+ area.increaseHeight(areaContainer.getHeight());
+ area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
+ if (this.omitHeaderAtBreak) {
+ // remove header, no longer needed
+ tableHeader = null;
+ }
+ tableFooter.removeLayout(areaContainer);
+ tableFooter.resetMarker();
+ return new Status(Status.AREA_FULL_SOME);
+ }
+ }
+
+ if (height != 0)
+ areaContainer.setHeight(height);
+
+ setupColumnHeights();
+
+ areaContainer.end();
+ area.addChild(areaContainer);
+
+ /* should this be combined into above? */
+ area.increaseHeight(areaContainer.getHeight());
+
+ area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
+
+ if (spaceAfter != 0) {
+ area.addDisplaySpace(spaceAfter);
+ }
+
+ if (area instanceof BlockArea) {
+ area.start();
+ }
+
+ if (breakAfter == BreakAfter.PAGE) {
+ this.marker = BREAK_AFTER;
+ return new Status(Status.FORCE_PAGE_BREAK);
+ }
+
+ if (breakAfter == BreakAfter.ODD_PAGE) {
+ this.marker = BREAK_AFTER;
+ return new Status(Status.FORCE_PAGE_BREAK_ODD);
+ }
+
+ if (breakAfter == BreakAfter.EVEN_PAGE) {
+ this.marker = BREAK_AFTER;
+ return new Status(Status.FORCE_PAGE_BREAK_EVEN);
+ }
+
+ return new Status(Status.OK);
+ }
+
+ protected void setupColumnHeights() {
+ int numChildren = this.children.size();
+ for (int i = 0; i < numChildren; i++) {
+ FONode fo = (FONode)children.elementAt(i);
+ if (fo instanceof TableColumn) {
+ ((TableColumn)fo).setHeight(areaContainer.getContentHeight());
+ }
+ }
+ }
+
+ public int getAreaHeight() {
+ return areaContainer.getHeight();
+ }
+
+ /**
+ * Return the content width of the boxes generated by this table FO.
+ */
+ public int getContentWidth() {
+ if (areaContainer != null)
+ return areaContainer.getContentWidth(); // getAllocationWidth()??
+ else
+ return 0; // not laid out yet
+ }
+
+ // /**
+ // * Return the last TableRow in the header or null if no header or
+ // * no header in non-first areas.
+ // * @param bForInitialArea If true, return the header row for the
+ // * initial table area, else for a continuation area, taking into
+ // * account the omit-header-at-break property.
+ // */
+ // TableRow getLastHeaderRow(boolean bForInitialArea) {
+ // // Check omit...
+ // if ((tableHeader != null) &&
+ // (bForInitialArea || omitHeaderAtBreak == false)) {
+ // return tableHeader.children.lastElement();
+ // }
+ // return null;
+ // }
+
+ // /**
+ // * Return the first TableRow in the footer or null if no footer or
+ // * no footer in non-last areas.
+ // * @param bForFinalArea If true, return the footer row for the
+ // * final table area, else for a non-final area, taking into
+ // * account the omit-footer-at-break property.
+ // */
+ // TableRow getLastFooterRow(boolean bForFinalArea) {
+ // if ((tableFooter != null) &&
+ // (bForFinalArea || omitFooterAtBreak == false)) {
+ // return tableFooter.children.firstElement();
+ // }
+ // return null;
+ // }
+
+
+ // /**
+ // * Return border information for the side (start/end) of the column
+ // * whose number is iColNumber (first column = 1).
+ // * ATTENTION: for now we assume columns are in order in the array!
+ // */
+ // BorderInfo getColumnBorder(BorderInfo.Side side, int iColNumber) {
+ // TableColumn col = (TableColumn)columns.elementAt(iColNumber);
+ // return col.getBorderInfo(side);
+ // }
}
diff --git a/src/org/apache/fop/fo/flow/TableAndCaption.java b/src/org/apache/fop/fo/flow/TableAndCaption.java
index d2c97b2df..9f28d6633 100644
--- a/src/org/apache/fop/fo/flow/TableAndCaption.java
+++ b/src/org/apache/fop/fo/flow/TableAndCaption.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * -- $Id$ --
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -23,6 +24,7 @@ public class TableAndCaption extends ToBeImplementedElement {
PropertyList propertyList) throws FOPException {
return new TableAndCaption(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -30,7 +32,7 @@ public class TableAndCaption extends ToBeImplementedElement {
}
protected TableAndCaption(FObj parent,
- PropertyList propertyList) throws FOPException {
+ PropertyList propertyList) throws FOPException {
super(parent, propertyList);
this.name = "fo:table-and-caption";
}
diff --git a/src/org/apache/fop/fo/flow/TableBody.java b/src/org/apache/fop/fo/flow/TableBody.java
index 69b95db25..ca9cee8f4 100644
--- a/src/org/apache/fop/fo/flow/TableBody.java
+++ b/src/org/apache/fop/fo/flow/TableBody.java
@@ -1,8 +1,8 @@
-/*-- $Id$ --
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo.flow;
@@ -25,6 +25,7 @@ public class TableBody extends FObj {
PropertyList propertyList) throws FOPException {
return new TableBody(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -37,7 +38,7 @@ public class TableBody extends FObj {
String id;
Vector columns;
- RowSpanMgr rowSpanMgr; // manage information about spanning rows
+ RowSpanMgr rowSpanMgr; // manage information about spanning rows
AreaContainer areaContainer;
@@ -69,12 +70,12 @@ public class TableBody extends FObj {
if (this.marker == START) {
- this.spaceBefore = this.properties.get(
- "space-before.optimum").getLength().mvalue();
- this.spaceAfter = this.properties.get(
- "space-after.optimum").getLength().mvalue();
- this.backgroundColor = this.properties.get(
- "background-color").getColorType();
+ this.spaceBefore =
+ this.properties.get("space-before.optimum").getLength().mvalue();
+ this.spaceAfter =
+ this.properties.get("space-after.optimum").getLength().mvalue();
+ this.backgroundColor =
+ this.properties.get("background-color").getColorType();
this.id = this.properties.get("id").getString();
area.getIDReferences().createID(id);
@@ -83,13 +84,13 @@ public class TableBody extends FObj {
area.end();
}
- if (rowSpanMgr == null) {
- rowSpanMgr = new RowSpanMgr(columns.size());
- }
+ if (rowSpanMgr == null) {
+ rowSpanMgr = new RowSpanMgr(columns.size());
+ }
- //if (this.isInListBody) {
- //startIndent += bodyIndent + distanceBetweenStarts;
- //}
+ // if (this.isInListBody) {
+ // startIndent += bodyIndent + distanceBetweenStarts;
+ // }
this.marker = 0;
@@ -106,17 +107,19 @@ public class TableBody extends FObj {
int spaceLeft = area.spaceLeft();
- /* Note: the parent FO must be a Table. The parent Area is the Block
+ /*
+ * Note: the parent FO must be a Table. The parent Area is the Block
* type area created by the Table, which is also a reference area.
* The content "width" (IPD) of the TableBody is the same as that
* of the containing table area, and its relative position is 0,0.
* Strictly speaking (CR), this FO should generate no areas!
*/
- this.areaContainer = new AreaContainer(
- propMgr.getFontState(area.getFontInfo()), 0,
- area.getContentHeight(), area.getContentWidth(), // IPD
- area.spaceLeft() , Position.RELATIVE);
- areaContainer.foCreator = this; // G Seshadri
+ this.areaContainer =
+ new AreaContainer(propMgr.getFontState(area.getFontInfo()), 0,
+ area.getContentHeight(),
+ area.getContentWidth(), // IPD
+ area.spaceLeft(), Position.RELATIVE);
+ areaContainer.foCreator = this; // G Seshadri
areaContainer.setPage(area.getPage());
areaContainer.setBackgroundColor(backgroundColor);
areaContainer.setBorderAndPadding(propMgr.getBorderAndPadding());
@@ -134,14 +137,15 @@ public class TableBody extends FObj {
if (!(child instanceof TableRow)) {
throw new FOPException("Currently only Table Rows are supported in table body, header and footer");
}
- TableRow row = (TableRow) child;
+ TableRow row = (TableRow)child;
row.setRowSpanMgr(rowSpanMgr);
row.setColumns(columns);
row.doSetup(areaContainer);
- if (row.getKeepWithPrevious().getType() !=
- KeepValue.KEEP_WITH_AUTO && lastRow != null &&
- keepWith.indexOf(lastRow) == -1) {
+ if (row.getKeepWithPrevious().getType()
+ != KeepValue.KEEP_WITH_AUTO && lastRow != null
+ && keepWith.indexOf(lastRow)
+ == -1) {
keepWith.addElement(lastRow);
} else {
if (endKeepGroup && keepWith.size() > 0) {
@@ -151,15 +155,14 @@ public class TableBody extends FObj {
Status status;
if ((status = row.layout(areaContainer)).isIncomplete()) {
- // BUG!!! don't distinguish between break-before and after!
+ // BUG!!! don't distinguish between break-before and after!
if (status.isPageBreak()) {
this.marker = i;
area.addChild(areaContainer);
- //areaContainer.end();
+ // areaContainer.end();
area.increaseHeight(areaContainer.getHeight());
- area.setAbsoluteHeight(
- areaContainer.getAbsoluteHeight());
+ area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
if (i == numChildren - 1) {
this.marker = BREAK_AFTER;
if (spaceAfter != 0) {
@@ -168,12 +171,13 @@ public class TableBody extends FObj {
}
return status;
}
- if (keepWith.size() > 0) { // && status.getCode() == Status.AREA_FULL_NONE
- // FIXME!!! Handle rows spans!!!
+ if (keepWith.size()
+ > 0) { // && status.getCode() == Status.AREA_FULL_NONE
+ // FIXME!!! Handle rows spans!!!
row.removeLayout(areaContainer);
for (Enumeration e = keepWith.elements();
- e.hasMoreElements();) {
- TableRow tr = (TableRow) e.nextElement();
+ e.hasMoreElements(); ) {
+ TableRow tr = (TableRow)e.nextElement();
tr.removeLayout(areaContainer);
i--;
}
@@ -183,30 +187,27 @@ public class TableBody extends FObj {
}
}
this.marker = i;
- if ((i != 0) &&
- (status.getCode() == Status.AREA_FULL_NONE)) {
+ if ((i != 0) && (status.getCode() == Status.AREA_FULL_NONE)) {
status = new Status(Status.AREA_FULL_SOME);
}
- if (!((i == 0) &&
- (areaContainer.getContentHeight() <= 0))) {
+ if (!((i == 0) && (areaContainer.getContentHeight() <= 0))) {
area.addChild(areaContainer);
- //areaContainer.end();
+ // areaContainer.end();
area.increaseHeight(areaContainer.getHeight());
- area.setAbsoluteHeight(
- areaContainer.getAbsoluteHeight());
+ area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
}
return status;
- } else if (status.getCode() == Status.KEEP_WITH_NEXT ||
- rowSpanMgr.hasUnfinishedSpans()) {
+ } else if (status.getCode() == Status.KEEP_WITH_NEXT
+ || rowSpanMgr.hasUnfinishedSpans()) {
keepWith.addElement(row);
endKeepGroup = false;
} else {
endKeepGroup = true;
}
lastRow = row;
- area.setMaxHeight(area.getMaxHeight() - spaceLeft +
- this.areaContainer.getMaxHeight());
+ area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ + this.areaContainer.getMaxHeight());
spaceLeft = area.spaceLeft();
}
area.addChild(areaContainer);
@@ -241,4 +242,5 @@ public class TableBody extends FObj {
this.resetMarker();
this.removeID(area.getIDReferences());
}
+
}
diff --git a/src/org/apache/fop/fo/flow/TableCaption.java b/src/org/apache/fop/fo/flow/TableCaption.java
index 1679c2bc5..0c617f471 100644
--- a/src/org/apache/fop/fo/flow/TableCaption.java
+++ b/src/org/apache/fop/fo/flow/TableCaption.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * -- $Id$ --
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -23,6 +24,7 @@ public class TableCaption extends ToBeImplementedElement {
PropertyList propertyList) throws FOPException {
return new TableCaption(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -30,7 +32,7 @@ public class TableCaption extends ToBeImplementedElement {
}
protected TableCaption(FObj parent,
- PropertyList propertyList) throws FOPException {
+ PropertyList propertyList) throws FOPException {
super(parent, propertyList);
this.name = "fo:table-caption";
}
diff --git a/src/org/apache/fop/fo/flow/TableCell.java b/src/org/apache/fop/fo/flow/TableCell.java
index c5a8a0676..23643552c 100644
--- a/src/org/apache/fop/fo/flow/TableCell.java
+++ b/src/org/apache/fop/fo/flow/TableCell.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * -- $Id$ --
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -15,391 +16,411 @@ import org.apache.fop.datatypes.*;
public class TableCell extends FObj {
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new TableCell(parent, propertyList);
- }
- }
-
- public static FObj.Maker maker() {
- return new TableCell.Maker();
- }
-
- // int spaceBefore;
- // int spaceAfter;
- ColorType backgroundColor;
-
- String id;
- int numColumnsSpanned;
- int numRowsSpanned;
- int iColNumber = -1; // uninitialized
-
- /** Offset of content rectangle in inline-progression-direction,
- * relative to table.
- */
- protected int startOffset;
-
- /** Dimension of allocation rectangle in inline-progression-direction,
- * determined by the width of the column(s) occupied by the cell
- */
- protected int width;
-
- /** Offset of content rectangle, in block-progression-direction,
- * relative to the row.
- */
- protected int beforeOffset=0;
-
- /** Offset of content rectangle, in inline-progression-direction,
- * relative to the column start edge.
- */
- protected int startAdjust=0;
-
- /** Adjust to theoretical column width to obtain content width
- * relative to the column start edge.
- */
- protected int widthAdjust=0;
-
- /* For collapsed border style */
- protected int borderHeight = 0;
- /**
- * Minimum ontent height of cell.
- */
- protected int minCellHeight = 0;
-
- protected int height = 0;
- protected int top; // Ypos of cell ???
- protected int verticalAlign ;
- protected boolean bRelativeAlign = false;
-
- // boolean setup = false;
- boolean bSepBorders = true;
-
- /** Border separation value in the block-progression dimension.
- * Used in calculating cells height.
- */
- int m_borderSeparation = 0;
-
- AreaContainer cellArea;
-
- public TableCell(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:table-cell";
- doSetup(); // init some basic property values
- }
-
- // Set position relative to table (set by body?)
- public void setStartOffset(int offset) {
- startOffset = offset;
- }
-
- // Initially same as the column width containg this cell or the
- // sum of the spanned columns if numColumnsSpanned > 1
- public void setWidth(int width) {
- this.width = width;
- }
-
- public int getColumnNumber()
- {
- return iColNumber;
- }
-
- public int getNumColumnsSpanned()
- {
- return numColumnsSpanned;
- }
-
- public int getNumRowsSpanned()
- {
- return numRowsSpanned;
- }
-
- public void doSetup()// throws FOPException
- {
- this.iColNumber = properties.get("column-number").getNumber().intValue();
- if (iColNumber < 0) { iColNumber = 0; }
- this.numColumnsSpanned =
- this.properties.get("number-columns-spanned").getNumber().intValue();
- if (numColumnsSpanned < 1) { numColumnsSpanned = 1; }
- this.numRowsSpanned =
- this.properties.get("number-rows-spanned").getNumber().intValue();
- if (numRowsSpanned < 1) { numRowsSpanned = 1; }
-
- this.backgroundColor =
- this.properties.get("background-color").getColorType();
-
- this.id = this.properties.get("id").getString();
-
- bSepBorders = (this.properties.get("border-collapse").getEnum() ==
- BorderCollapse.SEPARATE);
-
- calcBorders(propMgr.getBorderAndPadding());
-
- // Vertical cell alignment
- verticalAlign = this.properties.get("display-align").getEnum();
- if (verticalAlign == DisplayAlign.AUTO) {
- // Depends on all cells starting in row
- bRelativeAlign = true;
- verticalAlign = this.properties.get("relative-align").getEnum();
- }
- else bRelativeAlign = false; // Align on a per-cell basis
-
- this.minCellHeight = this.properties.get("height").getLength().mvalue();
- }
-
-
- public Status layout(Area area) throws FOPException {
- int originalAbsoluteHeight = area.getAbsoluteHeight();
- if (this.marker == BREAK_AFTER) {
- return new Status(Status.OK);
- }
-
- if (this.marker == START) {
-// if (!setup) {
-// doSetup(area);
-// }
-
- // Calculate cell borders
- // calcBorders(propMgr.getBorderAndPadding());
-
- area.getIDReferences().createID(id);
-
- this.marker = 0;
- }
-
- /*
- if ((spaceBefore != 0) && (this.marker ==0)) {
- area.increaseHeight(spaceBefore);
- }
- */
-
- if ( marker==0 ) {
- // configure id
- area.getIDReferences().configureID(id,area);
- }
-
- // int spaceLeft = area.spaceLeft() - m_borderSeparation/2 + borderHeight/2 ;
- int spaceLeft = area.spaceLeft() - m_borderSeparation ;
- // The Area position defines the content rectangle! Borders
- // and padding are outside of this rectangle.
- this.cellArea =
- new AreaContainer(propMgr.getFontState(area.getFontInfo()),
- startOffset+startAdjust,
- beforeOffset,
- width-widthAdjust, spaceLeft,
- Position.RELATIVE);
-
- cellArea.foCreator=this; // G Seshadri
- cellArea.setPage(area.getPage());
- cellArea.setBorderAndPadding(propMgr.getBorderAndPadding());
- cellArea.setBackgroundColor(this.backgroundColor);
- cellArea.start();
-
- cellArea.setAbsoluteHeight(area.getAbsoluteHeight()); //???
- cellArea.setIDReferences(area.getIDReferences());
- //******** CHECK THIS: we've changed startOffset (KL)
- cellArea.setTableCellXOffset(startOffset);
-
- int numChildren = this.children.size();
- for (int i = this.marker; i < numChildren; i++) {
- FObj fo = (FObj) children.elementAt(i);
- fo.setIsInTableCell();
- fo.forceWidth(width); // ???
-
- // Overflows may cause a row to be re-layedout,
- // need to pass already processed content.
- this.marker = i;
-
- Status status;
- if ((status = fo.layout(cellArea)).isIncomplete()) {
- //this.marker = i;
- if ((i == 0) && (status.getCode() == Status.AREA_FULL_NONE)) {
- return new Status(Status.AREA_FULL_NONE);
- } else {
- // hani Elabed 11/21/2000
- area.addChild(cellArea);
- // area.setAbsoluteHeight(cellArea.getAbsoluteHeight());
- return new Status(Status.AREA_FULL_SOME);
- }
- }
-
- area.setMaxHeight(area.getMaxHeight() - spaceLeft +
- this.cellArea.getMaxHeight());
- }
- cellArea.end();
- area.addChild(cellArea);
-
- // Adjust for minimum cell content height
- if (minCellHeight > cellArea.getContentHeight()) {
- cellArea.setHeight(minCellHeight);
- }
-
- // This is the allocation height of the cell (including borders
- // and padding
- // ALSO need to include offsets if using "separate borders"
- height = cellArea.getHeight();
- top = cellArea.getCurrentYPosition(); // CHECK THIS!!!
-
- // reset absoluteHeight to beginning of row
- // area.setHeight(cellArea.getHeight() + spaceBefore + spaceAfter);
- // I don't think we should do this here (KL) !!!
- // area.setHeight(cellArea.getHeight());
- //area.setAbsoluteHeight(originalAbsoluteHeight);
-
- return new Status(Status.OK);
- }
-
- /**
- * Return the allocation height of the cell area.
- * Note: called by TableRow.
- * We adjust the actual allocation height of the area by the value
- * of border separation (for separate borders) or border height
- * adjustment for collapse style (because current scheme makes cell
- * overestimate the allocation height).
- */
- public int getHeight() {
- return cellArea.getHeight() + m_borderSeparation - borderHeight;
- }
-
- /**
- * Set the final size of cell content rectangles to the actual row height
- * and to vertically align the actual content within the cell rectangle.
- * @param h Height of this row in the grid which is based on
- * the allocation height of all the cells in the row, including any
- * border separation values.
- */
- public void setRowHeight(int h) {
- int delta = h - getHeight();
- // cellArea.increaseHeight(h + borderHeight/2 - cellArea.getHeight());
- if (bRelativeAlign) {
- // Must get info for all cells starting in row!
- // verticalAlign can be BEFORE or BASELINE
- // For now just treat like "before"
- cellArea.increaseHeight(delta);
- }
- else if (delta > 0) {
- BorderAndPadding cellBP = cellArea.getBorderAndPadding();
- switch(verticalAlign) {
- case DisplayAlign.CENTER:
- // Increase cell padding before and after and change
- // "Y" position of content rectangle
- cellArea.shiftYPosition(delta/2);
- cellBP.setPaddingLength(BorderAndPadding.TOP,
- cellBP.getPaddingTop(false)+delta/2);
- cellBP.setPaddingLength(BorderAndPadding.BOTTOM,
- cellBP.getPaddingBottom(false) +
- delta-delta/2);
- break;
- case DisplayAlign.AFTER:
- // Increase cell padding before and change
- // "Y" position of content rectangle
- cellBP.setPaddingLength(BorderAndPadding.TOP,
- cellBP.getPaddingTop(false)+delta);
- cellArea.shiftYPosition(delta);
- break;
- case DisplayAlign.BEFORE:
- //cellArea.increaseHeight(delta);
- cellBP.setPaddingLength(BorderAndPadding.BOTTOM,
- cellBP.getPaddingBottom(false)+delta);
-
- default: // OK
- break;
- }
- }
- }
-
- /**
- * Calculate cell border and padding, including offset of content
- * rectangle from the theoretical grid position.
- */
- private void calcBorders(BorderAndPadding bp) {
- if (this.bSepBorders) {
- /* Easy case.
- * Cell border is the property specified directly on cell.
- * Offset content rect by half the border-separation value,
- * in addition to the border and padding values. Note:
- * border-separate should only be specified on the table object,
- * but it inherits.
- */
- int iSep = properties.get("border-separation.inline-progression-direction").getLength().mvalue();
- this.startAdjust = iSep/2 + bp.getBorderLeftWidth(false) +
- bp.getPaddingLeft(false);
- /*
- int contentOffset = iSep + bp.getBorderStartWidth(false) +
- bp.getPaddingStart(false);
- */
- this.widthAdjust = startAdjust + iSep - iSep/2 +
- bp.getBorderRightWidth(false) + bp.getPaddingRight(false);
- // bp.getBorderEndWidth(false) + bp.getPaddingEnd(false);
- // Offset of content rectangle in the block-progression direction
- m_borderSeparation =
- properties.get("border-separation.block-progression-direction").getLength().mvalue();
- this.beforeOffset = m_borderSeparation/2 +
- bp.getBorderTopWidth(false) + bp.getPaddingTop(false);
- // bp.getBorderBeforeWidth(false) + bp.getPaddingBefore(false);
-
- }
- else {
- //System.err.println("Collapse borders");
- /* Hard case.
- * Cell border is combination of other cell borders, or table
- * border for edge cells. Also seems to border values specified
- * on row and column FO in the table (if I read CR correclty.)
- */
-
- // Set up before and after borders, taking into account row
- // and table border properties.
- // ??? What about table-body, header,footer
-
- /* We can't calculate before and after because we aren't sure
- * whether this row will be the first or last in its area, due
- * to redoing break decisions (at least in the "new" architecture.)
- * So in the general case, we will calculate two possible values:
- * the first/last one and the "middle" one.
- * Example: border-before
- * 1. If the cell is in the first row in the first table body, it
- * will combine with the last row of the header, or with the
- * top (before) table border if there is no header.
- * 2. Otherwise there are two cases:
- * a. the row is first in its (non-first) Area.
- * The border can combine with either:
- * i. the last row of table-header and its cells, or
- * ii. the table before border (no table-header or it is
- * omitted on non-first Areas).
- * b. the row isn't first in its Area.
- * The border combines with the border of the previous
- * row and the cells which end in that row.
- */
-
- /* if-first
- * Calculate the effective border of the cell before-border,
- * it's parent row before-border, the last header row after-border,
- * the after border of the cell(s) which end in the last header
- * row.
- */
- /* if-not-first
- * Calculate the effective border of the cell before-border,
- * it's parent row before-border, the previous row after-border,
- * the after border of the cell(s) which end in the previous
- * row.
- */
-
-
- /* ivan demakov */
- int borderStart = bp.getBorderLeftWidth(false);
- int borderEnd = bp.getBorderRightWidth(false);
- int borderBefore = bp.getBorderTopWidth(false);
- int borderAfter = bp.getBorderBottomWidth(false);
-
- this.startAdjust = borderStart/2 + bp.getPaddingLeft(false);
-
- this.widthAdjust = startAdjust + borderEnd/2 +
- bp.getPaddingRight(false);
- this.beforeOffset = borderBefore/2 + bp.getPaddingTop(false);
- // Half border height to fix overestimate of area size!
- this.borderHeight = (borderBefore + borderAfter)/2;
- }
- }
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new TableCell(parent, propertyList);
+ }
+
+ }
+
+ public static FObj.Maker maker() {
+ return new TableCell.Maker();
+ }
+
+ // int spaceBefore;
+ // int spaceAfter;
+ ColorType backgroundColor;
+
+ String id;
+ int numColumnsSpanned;
+ int numRowsSpanned;
+ int iColNumber = -1; // uninitialized
+
+ /**
+ * Offset of content rectangle in inline-progression-direction,
+ * relative to table.
+ */
+ protected int startOffset;
+
+ /**
+ * Dimension of allocation rectangle in inline-progression-direction,
+ * determined by the width of the column(s) occupied by the cell
+ */
+ protected int width;
+
+ /**
+ * Offset of content rectangle, in block-progression-direction,
+ * relative to the row.
+ */
+ protected int beforeOffset = 0;
+
+ /**
+ * Offset of content rectangle, in inline-progression-direction,
+ * relative to the column start edge.
+ */
+ protected int startAdjust = 0;
+
+ /**
+ * Adjust to theoretical column width to obtain content width
+ * relative to the column start edge.
+ */
+ protected int widthAdjust = 0;
+
+ /* For collapsed border style */
+ protected int borderHeight = 0;
+
+ /**
+ * Minimum ontent height of cell.
+ */
+ protected int minCellHeight = 0;
+
+ protected int height = 0;
+ protected int top; // Ypos of cell ???
+ protected int verticalAlign;
+ protected boolean bRelativeAlign = false;
+
+ // boolean setup = false;
+ boolean bSepBorders = true;
+
+ /**
+ * Border separation value in the block-progression dimension.
+ * Used in calculating cells height.
+ */
+ int m_borderSeparation = 0;
+
+ AreaContainer cellArea;
+
+ public TableCell(FObj parent, PropertyList propertyList) {
+ super(parent, propertyList);
+ this.name = "fo:table-cell";
+ doSetup(); // init some basic property values
+ }
+
+ // Set position relative to table (set by body?)
+ public void setStartOffset(int offset) {
+ startOffset = offset;
+ }
+
+ // Initially same as the column width containg this cell or the
+ // sum of the spanned columns if numColumnsSpanned > 1
+ public void setWidth(int width) {
+ this.width = width;
+ }
+
+ public int getColumnNumber() {
+ return iColNumber;
+ }
+
+ public int getNumColumnsSpanned() {
+ return numColumnsSpanned;
+ }
+
+ public int getNumRowsSpanned() {
+ return numRowsSpanned;
+ }
+
+ public void doSetup() // throws FOPException
+ {
+ this.iColNumber =
+ properties.get("column-number").getNumber().intValue();
+ if (iColNumber < 0) {
+ iColNumber = 0;
+ }
+ this.numColumnsSpanned =
+ this.properties.get("number-columns-spanned").getNumber().intValue();
+ if (numColumnsSpanned < 1) {
+ numColumnsSpanned = 1;
+ }
+ this.numRowsSpanned =
+ this.properties.get("number-rows-spanned").getNumber().intValue();
+ if (numRowsSpanned < 1) {
+ numRowsSpanned = 1;
+ }
+
+ this.backgroundColor =
+ this.properties.get("background-color").getColorType();
+
+ this.id = this.properties.get("id").getString();
+
+ bSepBorders = (this.properties.get("border-collapse").getEnum()
+ == BorderCollapse.SEPARATE);
+
+ calcBorders(propMgr.getBorderAndPadding());
+
+ // Vertical cell alignment
+ verticalAlign = this.properties.get("display-align").getEnum();
+ if (verticalAlign == DisplayAlign.AUTO) {
+ // Depends on all cells starting in row
+ bRelativeAlign = true;
+ verticalAlign = this.properties.get("relative-align").getEnum();
+ } else
+ bRelativeAlign = false; // Align on a per-cell basis
+
+ this.minCellHeight =
+ this.properties.get("height").getLength().mvalue();
+ }
+
+
+ public Status layout(Area area) throws FOPException {
+ int originalAbsoluteHeight = area.getAbsoluteHeight();
+ if (this.marker == BREAK_AFTER) {
+ return new Status(Status.OK);
+ }
+
+ if (this.marker == START) {
+ // if (!setup) {
+ // doSetup(area);
+ // }
+
+ // Calculate cell borders
+ // calcBorders(propMgr.getBorderAndPadding());
+
+ area.getIDReferences().createID(id);
+
+ this.marker = 0;
+ }
+
+ /*
+ * if ((spaceBefore != 0) && (this.marker ==0)) {
+ * area.increaseHeight(spaceBefore);
+ * }
+ */
+
+ if (marker == 0) {
+ // configure id
+ area.getIDReferences().configureID(id, area);
+ }
+
+ // int spaceLeft = area.spaceLeft() - m_borderSeparation/2 + borderHeight/2 ;
+ int spaceLeft = area.spaceLeft() - m_borderSeparation;
+ // The Area position defines the content rectangle! Borders
+ // and padding are outside of this rectangle.
+ this.cellArea =
+ new AreaContainer(propMgr.getFontState(area.getFontInfo()),
+ startOffset + startAdjust, beforeOffset,
+ width - widthAdjust, spaceLeft,
+ Position.RELATIVE);
+
+ cellArea.foCreator = this; // G Seshadri
+ cellArea.setPage(area.getPage());
+ cellArea.setBorderAndPadding(propMgr.getBorderAndPadding());
+ cellArea.setBackgroundColor(this.backgroundColor);
+ cellArea.start();
+
+ cellArea.setAbsoluteHeight(area.getAbsoluteHeight()); // ???
+ cellArea.setIDReferences(area.getIDReferences());
+ // ******** CHECK THIS: we've changed startOffset (KL)
+ cellArea.setTableCellXOffset(startOffset);
+
+ int numChildren = this.children.size();
+ for (int i = this.marker; i < numChildren; i++) {
+ FObj fo = (FObj)children.elementAt(i);
+ fo.setIsInTableCell();
+ fo.forceWidth(width); // ???
+
+ // Overflows may cause a row to be re-layedout,
+ // need to pass already processed content.
+ this.marker = i;
+
+ Status status;
+ if ((status = fo.layout(cellArea)).isIncomplete()) {
+ // this.marker = i;
+ if ((i == 0) && (status.getCode() == Status.AREA_FULL_NONE)) {
+ return new Status(Status.AREA_FULL_NONE);
+ } else {
+ // hani Elabed 11/21/2000
+ area.addChild(cellArea);
+ // area.setAbsoluteHeight(cellArea.getAbsoluteHeight());
+ return new Status(Status.AREA_FULL_SOME);
+ }
+ }
+
+ area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ + this.cellArea.getMaxHeight());
+ }
+ cellArea.end();
+ area.addChild(cellArea);
+
+ // Adjust for minimum cell content height
+ if (minCellHeight > cellArea.getContentHeight()) {
+ cellArea.setHeight(minCellHeight);
+ }
+
+ // This is the allocation height of the cell (including borders
+ // and padding
+ // ALSO need to include offsets if using "separate borders"
+ height = cellArea.getHeight();
+ top = cellArea.getCurrentYPosition(); // CHECK THIS!!!
+
+ // reset absoluteHeight to beginning of row
+ // area.setHeight(cellArea.getHeight() + spaceBefore + spaceAfter);
+ // I don't think we should do this here (KL) !!!
+ // area.setHeight(cellArea.getHeight());
+ // area.setAbsoluteHeight(originalAbsoluteHeight);
+
+ return new Status(Status.OK);
+ }
+
+ /**
+ * Return the allocation height of the cell area.
+ * Note: called by TableRow.
+ * We adjust the actual allocation height of the area by the value
+ * of border separation (for separate borders) or border height
+ * adjustment for collapse style (because current scheme makes cell
+ * overestimate the allocation height).
+ */
+ public int getHeight() {
+ return cellArea.getHeight() + m_borderSeparation - borderHeight;
+ }
+
+ /**
+ * Set the final size of cell content rectangles to the actual row height
+ * and to vertically align the actual content within the cell rectangle.
+ * @param h Height of this row in the grid which is based on
+ * the allocation height of all the cells in the row, including any
+ * border separation values.
+ */
+ public void setRowHeight(int h) {
+ int delta = h - getHeight();
+ // cellArea.increaseHeight(h + borderHeight/2 - cellArea.getHeight());
+ if (bRelativeAlign) {
+ // Must get info for all cells starting in row!
+ // verticalAlign can be BEFORE or BASELINE
+ // For now just treat like "before"
+ cellArea.increaseHeight(delta);
+ } else if (delta > 0) {
+ BorderAndPadding cellBP = cellArea.getBorderAndPadding();
+ switch (verticalAlign) {
+ case DisplayAlign.CENTER:
+ // Increase cell padding before and after and change
+ // "Y" position of content rectangle
+ cellArea.shiftYPosition(delta / 2);
+ cellBP.setPaddingLength(BorderAndPadding.TOP,
+ cellBP.getPaddingTop(false)
+ + delta / 2);
+ cellBP.setPaddingLength(BorderAndPadding.BOTTOM,
+ cellBP.getPaddingBottom(false)
+ + delta - delta / 2);
+ break;
+ case DisplayAlign.AFTER:
+ // Increase cell padding before and change
+ // "Y" position of content rectangle
+ cellBP.setPaddingLength(BorderAndPadding.TOP,
+ cellBP.getPaddingTop(false) + delta);
+ cellArea.shiftYPosition(delta);
+ break;
+ case DisplayAlign.BEFORE:
+ // cellArea.increaseHeight(delta);
+ cellBP.setPaddingLength(BorderAndPadding.BOTTOM,
+ cellBP.getPaddingBottom(false)
+ + delta);
+
+ default: // OK
+ break;
+ }
+ }
+ }
+
+ /**
+ * Calculate cell border and padding, including offset of content
+ * rectangle from the theoretical grid position.
+ */
+ private void calcBorders(BorderAndPadding bp) {
+ if (this.bSepBorders) {
+ /*
+ * Easy case.
+ * Cell border is the property specified directly on cell.
+ * Offset content rect by half the border-separation value,
+ * in addition to the border and padding values. Note:
+ * border-separate should only be specified on the table object,
+ * but it inherits.
+ */
+ int iSep =
+ properties.get("border-separation.inline-progression-direction").getLength().mvalue();
+ this.startAdjust = iSep / 2 + bp.getBorderLeftWidth(false)
+ + bp.getPaddingLeft(false);
+ /*
+ * int contentOffset = iSep + bp.getBorderStartWidth(false) +
+ * bp.getPaddingStart(false);
+ */
+ this.widthAdjust = startAdjust + iSep - iSep / 2
+ + bp.getBorderRightWidth(false)
+ + bp.getPaddingRight(false);
+ // bp.getBorderEndWidth(false) + bp.getPaddingEnd(false);
+ // Offset of content rectangle in the block-progression direction
+ m_borderSeparation =
+ properties.get("border-separation.block-progression-direction").getLength().mvalue();
+ this.beforeOffset = m_borderSeparation / 2
+ + bp.getBorderTopWidth(false)
+ + bp.getPaddingTop(false);
+ // bp.getBorderBeforeWidth(false) + bp.getPaddingBefore(false);
+
+ } else {
+ // System.err.println("Collapse borders");
+ /*
+ * Hard case.
+ * Cell border is combination of other cell borders, or table
+ * border for edge cells. Also seems to border values specified
+ * on row and column FO in the table (if I read CR correclty.)
+ */
+
+ // Set up before and after borders, taking into account row
+ // and table border properties.
+ // ??? What about table-body, header,footer
+
+ /*
+ * We can't calculate before and after because we aren't sure
+ * whether this row will be the first or last in its area, due
+ * to redoing break decisions (at least in the "new" architecture.)
+ * So in the general case, we will calculate two possible values:
+ * the first/last one and the "middle" one.
+ * Example: border-before
+ * 1. If the cell is in the first row in the first table body, it
+ * will combine with the last row of the header, or with the
+ * top (before) table border if there is no header.
+ * 2. Otherwise there are two cases:
+ * a. the row is first in its (non-first) Area.
+ * The border can combine with either:
+ * i. the last row of table-header and its cells, or
+ * ii. the table before border (no table-header or it is
+ * omitted on non-first Areas).
+ * b. the row isn't first in its Area.
+ * The border combines with the border of the previous
+ * row and the cells which end in that row.
+ */
+
+ /*
+ * if-first
+ * Calculate the effective border of the cell before-border,
+ * it's parent row before-border, the last header row after-border,
+ * the after border of the cell(s) which end in the last header
+ * row.
+ */
+ /*
+ * if-not-first
+ * Calculate the effective border of the cell before-border,
+ * it's parent row before-border, the previous row after-border,
+ * the after border of the cell(s) which end in the previous
+ * row.
+ */
+
+
+ /* ivan demakov */
+ int borderStart = bp.getBorderLeftWidth(false);
+ int borderEnd = bp.getBorderRightWidth(false);
+ int borderBefore = bp.getBorderTopWidth(false);
+ int borderAfter = bp.getBorderBottomWidth(false);
+
+ this.startAdjust = borderStart / 2 + bp.getPaddingLeft(false);
+
+ this.widthAdjust = startAdjust + borderEnd / 2
+ + bp.getPaddingRight(false);
+ this.beforeOffset = borderBefore / 2 + bp.getPaddingTop(false);
+ // Half border height to fix overestimate of area size!
+ this.borderHeight = (borderBefore + borderAfter) / 2;
+ }
+ }
}
diff --git a/src/org/apache/fop/fo/flow/TableColumn.java b/src/org/apache/fop/fo/flow/TableColumn.java
index c6c6dda92..d3c05fe80 100644
--- a/src/org/apache/fop/fo/flow/TableColumn.java
+++ b/src/org/apache/fop/fo/flow/TableColumn.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo.flow;
@@ -60,97 +16,98 @@ import org.apache.fop.datatypes.*;
public class TableColumn extends FObj {
- ColorType backgroundColor;
-
- int columnWidth;
- int columnOffset;
- int numColumnsRepeated;
-
- boolean setup = false;
-
- AreaContainer areaContainer;
-
- public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new TableColumn(parent, propertyList);
- }
- }
-
- public static FObj.Maker maker() {
- return new TableColumn.Maker();
- }
-
- public TableColumn(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:table-column";
- }
-
- public int getColumnWidth() {
- return columnWidth;
- }
-
- public int getColumnNumber() {
- return 0; // not implemented yet
- }
-
- public int getNumColumnsRepeated() {
- return numColumnsRepeated;
- }
-
- public void doSetup(Area area) throws FOPException {
-
- this.numColumnsRepeated =
- this.properties.get("number-columns-repeated").getNumber().intValue();
-
- this.backgroundColor =
- this.properties.get("background-color").getColorType();
-
- this.columnWidth =
- this.properties.get("column-width").getLength().mvalue();
-
- // initialize id
- String id = this.properties.get("id").getString();
- area.getIDReferences().initializeID(id,area);
-
- setup = true;
- }
-
- public Status layout(Area area) throws FOPException {
- if (this.marker == BREAK_AFTER) {
- return new Status(Status.OK);
- }
-
- if (this.marker == START) {
- if (!setup) {
- doSetup(area);
- }
- }
-
- // KL: don't take table borders into account!
- this.areaContainer =
- new AreaContainer(propMgr.getFontState(area.getFontInfo()),
- columnOffset /*- area.getBorderLeftWidth()*/,
- /*-area.getBorderTopWidth()*/ 0, columnWidth,
- area.getContentHeight(), Position.RELATIVE);
- // area.getHeight(), Position.RELATIVE);
- areaContainer.foCreator=this; // G Seshadri
- areaContainer.setPage(area.getPage());
- areaContainer.setBorderAndPadding(propMgr.getBorderAndPadding());
- areaContainer.setBackgroundColor(this.backgroundColor);
- areaContainer.setHeight(area.getHeight());
- area.addChild(areaContainer);
-
- return new Status(Status.OK);
- }
-
- public void setColumnOffset(int columnOffset) {
- this.columnOffset = columnOffset;
- }
-
- public void setHeight(int height) {
- areaContainer.setMaxHeight(height);
- areaContainer.setHeight(height);
- }
+ ColorType backgroundColor;
+
+ int columnWidth;
+ int columnOffset;
+ int numColumnsRepeated;
+
+ boolean setup = false;
+
+ AreaContainer areaContainer;
+
+ public static class Maker extends FObj.Maker {
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new TableColumn(parent, propertyList);
+ }
+
+ }
+
+ public static FObj.Maker maker() {
+ return new TableColumn.Maker();
+ }
+
+ public TableColumn(FObj parent, PropertyList propertyList) {
+ super(parent, propertyList);
+ this.name = "fo:table-column";
+ }
+
+ public int getColumnWidth() {
+ return columnWidth;
+ }
+
+ public int getColumnNumber() {
+ return 0; // not implemented yet
+ }
+
+ public int getNumColumnsRepeated() {
+ return numColumnsRepeated;
+ }
+
+ public void doSetup(Area area) throws FOPException {
+
+ this.numColumnsRepeated =
+ this.properties.get("number-columns-repeated").getNumber().intValue();
+
+ this.backgroundColor =
+ this.properties.get("background-color").getColorType();
+
+ this.columnWidth =
+ this.properties.get("column-width").getLength().mvalue();
+
+ // initialize id
+ String id = this.properties.get("id").getString();
+ area.getIDReferences().initializeID(id, area);
+
+ setup = true;
+ }
+
+ public Status layout(Area area) throws FOPException {
+ if (this.marker == BREAK_AFTER) {
+ return new Status(Status.OK);
+ }
+
+ if (this.marker == START) {
+ if (!setup) {
+ doSetup(area);
+ }
+ }
+
+ // KL: don't take table borders into account!
+ this.areaContainer =
+ new AreaContainer(propMgr.getFontState(area.getFontInfo()),
+ columnOffset /* - area.getBorderLeftWidth() */,
+ /* -area.getBorderTopWidth() */
+ 0, columnWidth, area.getContentHeight(), Position.RELATIVE);
+ // area.getHeight(), Position.RELATIVE);
+ areaContainer.foCreator = this; // G Seshadri
+ areaContainer.setPage(area.getPage());
+ areaContainer.setBorderAndPadding(propMgr.getBorderAndPadding());
+ areaContainer.setBackgroundColor(this.backgroundColor);
+ areaContainer.setHeight(area.getHeight());
+ area.addChild(areaContainer);
+
+ return new Status(Status.OK);
+ }
+
+ public void setColumnOffset(int columnOffset) {
+ this.columnOffset = columnOffset;
+ }
+
+ public void setHeight(int height) {
+ areaContainer.setMaxHeight(height);
+ areaContainer.setHeight(height);
+ }
}
diff --git a/src/org/apache/fop/fo/flow/TableFooter.java b/src/org/apache/fop/fo/flow/TableFooter.java
index 818e208ae..0a6ebe02d 100644
--- a/src/org/apache/fop/fo/flow/TableFooter.java
+++ b/src/org/apache/fop/fo/flow/TableFooter.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo.flow;
@@ -63,31 +19,30 @@ import java.util.Vector;
import java.util.Enumeration;
public class TableFooter extends TableBody {
-
+
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new TableFooter(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new TableFooter(parent, propertyList);
+ }
+
}
- public int getYPosition()
- {
+ public int getYPosition() {
return areaContainer.getCurrentYPosition() - spaceBefore;
}
- public void setYPosition(int value)
- {
+ public void setYPosition(int value) {
areaContainer.setYPosition(value + 2 * spaceBefore);
}
public static FObj.Maker maker() {
- return new TableFooter.Maker();
+ return new TableFooter.Maker();
}
public TableFooter(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:table-footer";
+ super(parent, propertyList);
+ this.name = "fo:table-footer";
}
}
diff --git a/src/org/apache/fop/fo/flow/TableHeader.java b/src/org/apache/fop/fo/flow/TableHeader.java
index bd926ff7b..81fd7a69b 100644
--- a/src/org/apache/fop/fo/flow/TableHeader.java
+++ b/src/org/apache/fop/fo/flow/TableHeader.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo.flow;
@@ -63,21 +19,22 @@ import java.util.Vector;
import java.util.Enumeration;
public class TableHeader extends TableBody {
-
+
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new TableHeader(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new TableHeader(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new TableHeader.Maker();
+ return new TableHeader.Maker();
}
public TableHeader(FObj parent, PropertyList propertyList) {
- super(parent, propertyList);
- this.name = "fo:table-header";
+ super(parent, propertyList);
+ this.name = "fo:table-header";
}
}
diff --git a/src/org/apache/fop/fo/flow/TableRow.java b/src/org/apache/fop/fo/flow/TableRow.java
index b5eb47732..9fb0038bc 100644
--- a/src/org/apache/fop/fo/flow/TableRow.java
+++ b/src/org/apache/fop/fo/flow/TableRow.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * -- $Id$ --
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -21,14 +22,15 @@ import java.util.Enumeration;
public class TableRow extends FObj {
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent,
- PropertyList propertyList) throws FOPException {
- return new TableRow(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new TableRow(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new TableRow.Maker();
+ return new TableRow.Maker();
}
boolean setup = false;
@@ -43,7 +45,7 @@ public class TableRow extends FObj {
int widthOfCellsSoFar = 0;
int largestCellHeight = 0;
- int minHeight = 0; // force row height
+ int minHeight = 0; // force row height
Vector columns;
AreaContainer areaContainer;
@@ -54,9 +56,9 @@ public class TableRow extends FObj {
private CellArray cellArray = null;
private static class CellArray {
- public static final byte EMPTY=0;
- public static final byte CELLSTART=1;
- public static final byte CELLSPAN=2;
+ public static final byte EMPTY = 0;
+ public static final byte CELLSTART = 1;
+ public static final byte CELLSPAN = 2;
private TableCell[] cells;
private byte[] states;
@@ -66,46 +68,47 @@ public class TableRow extends FObj {
// occupied by spans from previous rows
cells = new TableCell[numColumns];
states = new byte[numColumns];
- for (int i=0; i = input value.
- */
+ /**
+ * Return column which doesn't already contain a span or a cell
+ * If past the end or no free cells after colNum, return -1
+ * Otherwise return value >= input value.
+ */
int getNextFreeCell(int colNum) {
- for (int i=colNum-1; i 0 && colNum<=cells.length) {
- return states[colNum-1];
- }
- else return -1; // probably should throw exception
+ if (colNum > 0 && colNum <= cells.length) {
+ return states[colNum - 1];
+ } else
+ return -1; // probably should throw exception
}
- /**
- * Return cell in colNum (1 based)
- */
+ /**
+ * Return cell in colNum (1 based)
+ */
TableCell getCell(int colNum) {
- if (colNum > 0 && colNum<=cells.length) {
- return cells[colNum-1];
- }
- else return null; // probably should throw exception
+ if (colNum > 0 && colNum <= cells.length) {
+ return cells[colNum - 1];
+ } else
+ return null; // probably should throw exception
}
/**
@@ -113,335 +116,337 @@ public class TableRow extends FObj {
* If any of the columns is already occupied, return false, else true
*/
boolean storeCell(TableCell cell, int colNum, int numCols) {
- boolean rslt=true;
- int index=colNum-1;
- for (int count=0; index largestCellHeight)
- largestCellHeight = h;
- }
+ /*
+ * If this cell is spanned from a previous row,
+ * and this is the last row, get the remaining height
+ * and use it to increase maxCellHeight if necessary
+ */
+ if (rowSpanMgr.isInLastRow(iColIndex)) {
+ int h = rowSpanMgr.getRemainingHeight(iColIndex);
+ if (h > largestCellHeight)
+ largestCellHeight = h;
+ }
offset += colWidth;
continue;
}
- // cell.setTableColumn(tcol);
- cell.setStartOffset(offset);
- offset += colWidth;
-
-
- int rowSpan = cell.getNumRowsSpanned();
- Status status;
- if ((status = cell.layout(areaContainer)).isIncomplete()) {
- if ((keepTogether.getType() == KeepValue.KEEP_WITH_ALWAYS) ||
- (status.getCode() == Status.AREA_FULL_NONE) ||
- rowSpan > 1) {
- // We will put this row into the next column/page
- // Note: the only time this shouldn't be honored is
- // if this row is at the top of the column area.
- // Remove spanning cells from RowSpanMgr?
- this.resetMarker();
- this.removeID(area.getIDReferences());
- return new Status(Status.AREA_FULL_NONE);
- }
- else if (status.getCode() == Status.AREA_FULL_SOME) {
- /* Row is not keep-together, cell isn't spanning
- * and part of it fits. We can break the cell and
- * the row.
- */
- someCellDidNotLayoutCompletely = true;
- }
- } //else {
- // layout was complete for a particular cell
- int h = cell.getHeight(); // allocation height of cell
- if (rowSpan > 1) { // pass cell fo or area???
- rowSpanMgr.addRowSpan(cell, iColIndex,
- cell.getNumColumnsSpanned(), h, rowSpan);
- }
- else if (h > largestCellHeight) {
- largestCellHeight = h;
- }
- // }
- } // end of loop over all columns/cells
-
- // This is in case a float was composed in the cells
- area.setMaxHeight(area.getMaxHeight() - spaceLeft +
- this.areaContainer.getMaxHeight());
-
- // Only do this for "STARTCELL", ending spans are handled separately
- // What about empty cells? Yes, we should set their height too!
- for (int iCol = 1; iCol <= columns.size(); iCol++) {
- if (cellArray.getCellType(iCol) == CellArray.CELLSTART &&
- rowSpanMgr.isSpanned(iCol)==false) {
+ // cell.setTableColumn(tcol);
+ cell.setStartOffset(offset);
+ offset += colWidth;
+
+
+ int rowSpan = cell.getNumRowsSpanned();
+ Status status;
+ if ((status = cell.layout(areaContainer)).isIncomplete()) {
+ if ((keepTogether.getType() == KeepValue.KEEP_WITH_ALWAYS)
+ || (status.getCode() == Status.AREA_FULL_NONE)
+ || rowSpan > 1) {
+ // We will put this row into the next column/page
+ // Note: the only time this shouldn't be honored is
+ // if this row is at the top of the column area.
+ // Remove spanning cells from RowSpanMgr?
+ this.resetMarker();
+ this.removeID(area.getIDReferences());
+ return new Status(Status.AREA_FULL_NONE);
+ } else if (status.getCode() == Status.AREA_FULL_SOME) {
+ /*
+ * Row is not keep-together, cell isn't spanning
+ * and part of it fits. We can break the cell and
+ * the row.
+ */
+ someCellDidNotLayoutCompletely = true;
+ }
+ } // else {
+ // layout was complete for a particular cell
+ int h = cell.getHeight(); // allocation height of cell
+ if (rowSpan > 1) { // pass cell fo or area???
+ rowSpanMgr.addRowSpan(cell, iColIndex,
+ cell.getNumColumnsSpanned(), h,
+ rowSpan);
+ } else if (h > largestCellHeight) {
+ largestCellHeight = h;
+ }
+ // }
+ } // end of loop over all columns/cells
+
+ // This is in case a float was composed in the cells
+ area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ + this.areaContainer.getMaxHeight());
+
+ // Only do this for "STARTCELL", ending spans are handled separately
+ // What about empty cells? Yes, we should set their height too!
+ for (int iCol = 1; iCol <= columns.size(); iCol++) {
+ if (cellArray.getCellType(iCol) == CellArray.CELLSTART
+ && rowSpanMgr.isSpanned(iCol) == false) {
cellArray.getCell(iCol).setRowHeight(largestCellHeight);
}
- }
-
- // Adjust spanning row information
- // ??? what if some cells are broken???
- rowSpanMgr.finishRow(largestCellHeight);
-
- area.addChild(areaContainer);
- areaContainer.setHeight(largestCellHeight);
- areaAdded = true;
- areaContainer.end();
-
- /* The method addDisplaySpace increases both the content
- * height of the parent area (table body, head or footer) and
- * also its "absolute height". So we don't need to do this
- * explicitly.
- *
- * Note: it doesn't look from the CR as though we should take
- * into account borders and padding on rows, only background.
- * The exception is perhaps if the borders are "collapsed", but
- * they should still be rendered only on cells and not on the
- * rows themselves. (Karen Lease - 01may2001)
- */
- area.addDisplaySpace(largestCellHeight +
- areaContainer.getPaddingTop() +
- areaContainer.getBorderTopWidth() +
- areaContainer.getPaddingBottom() +
- areaContainer.getBorderBottomWidth());
-
-
- // replaced by Hani Elabed 11/27/2000
- //return new Status(Status.OK);
-
- if (someCellDidNotLayoutCompletely) {
- return new Status(Status.AREA_FULL_SOME);
- } else {
- if (rowSpanMgr.hasUnfinishedSpans()) {
- // Ignore break after if row span!
- return new Status(Status.KEEP_WITH_NEXT);
- }
- if (breakAfter == BreakAfter.PAGE) {
- this.marker = BREAK_AFTER;
- return new Status(Status.FORCE_PAGE_BREAK);
- }
-
- if (breakAfter == BreakAfter.ODD_PAGE) {
- this.marker = BREAK_AFTER;
- return new Status(Status.FORCE_PAGE_BREAK_ODD);
- }
-
- if (breakAfter == BreakAfter.EVEN_PAGE) {
- this.marker = BREAK_AFTER;
- return new Status(Status.FORCE_PAGE_BREAK_EVEN);
- }
-
- if (breakAfter == BreakAfter.COLUMN) {
- this.marker = BREAK_AFTER;
- return new Status(Status.FORCE_COLUMN_BREAK);
- }
- if (keepWithNext.getType() != KeepValue.KEEP_WITH_AUTO) {
- return new Status(Status.KEEP_WITH_NEXT);
- }
- return new Status(Status.OK);
- }
+ }
+
+ // Adjust spanning row information
+ // ??? what if some cells are broken???
+ rowSpanMgr.finishRow(largestCellHeight);
+
+ area.addChild(areaContainer);
+ areaContainer.setHeight(largestCellHeight);
+ areaAdded = true;
+ areaContainer.end();
+
+ /*
+ * The method addDisplaySpace increases both the content
+ * height of the parent area (table body, head or footer) and
+ * also its "absolute height". So we don't need to do this
+ * explicitly.
+ *
+ * Note: it doesn't look from the CR as though we should take
+ * into account borders and padding on rows, only background.
+ * The exception is perhaps if the borders are "collapsed", but
+ * they should still be rendered only on cells and not on the
+ * rows themselves. (Karen Lease - 01may2001)
+ */
+ area.addDisplaySpace(largestCellHeight
+ + areaContainer.getPaddingTop()
+ + areaContainer.getBorderTopWidth()
+ + areaContainer.getPaddingBottom()
+ + areaContainer.getBorderBottomWidth());
+
+
+ // replaced by Hani Elabed 11/27/2000
+ // return new Status(Status.OK);
+
+ if (someCellDidNotLayoutCompletely) {
+ return new Status(Status.AREA_FULL_SOME);
+ } else {
+ if (rowSpanMgr.hasUnfinishedSpans()) {
+ // Ignore break after if row span!
+ return new Status(Status.KEEP_WITH_NEXT);
+ }
+ if (breakAfter == BreakAfter.PAGE) {
+ this.marker = BREAK_AFTER;
+ return new Status(Status.FORCE_PAGE_BREAK);
+ }
+
+ if (breakAfter == BreakAfter.ODD_PAGE) {
+ this.marker = BREAK_AFTER;
+ return new Status(Status.FORCE_PAGE_BREAK_ODD);
+ }
+
+ if (breakAfter == BreakAfter.EVEN_PAGE) {
+ this.marker = BREAK_AFTER;
+ return new Status(Status.FORCE_PAGE_BREAK_EVEN);
+ }
+
+ if (breakAfter == BreakAfter.COLUMN) {
+ this.marker = BREAK_AFTER;
+ return new Status(Status.FORCE_COLUMN_BREAK);
+ }
+ if (keepWithNext.getType() != KeepValue.KEEP_WITH_AUTO) {
+ return new Status(Status.KEEP_WITH_NEXT);
+ }
+ return new Status(Status.OK);
+ }
}
public int getAreaHeight() {
- return areaContainer.getHeight();
+ return areaContainer.getHeight();
}
public void removeLayout(Area area) {
- if(areaAdded)
- area.removeChild(areaContainer);
- areaAdded = false;
- this.resetMarker();
- this.removeID(area.getIDReferences());
+ if (areaAdded)
+ area.removeChild(areaContainer);
+ areaAdded = false;
+ this.resetMarker();
+ this.removeID(area.getIDReferences());
}
- public void resetMarker()
- {
- super.resetMarker();
+ public void resetMarker() {
+ super.resetMarker();
// Just reset all the states to not laid out and fix up row spans
}
/**
* Called by parent FO to initialize information about
- * cells started in previous rows which span into this row.
- * The layout operation modifies rowSpanMgr
+ * cells started in previous rows which span into this row.
+ * The layout operation modifies rowSpanMgr
*/
public void setRowSpanMgr(RowSpanMgr rowSpanMgr) {
this.rowSpanMgr = rowSpanMgr;
@@ -460,7 +465,7 @@ public class TableRow extends FObj {
// If off the end, the rest of the cells had better be
// explicitly positioned!!! (returns -1)
- TableCell cell = (TableCell) eCells.nextElement();
+ TableCell cell = (TableCell)eCells.nextElement();
int numCols = cell.getNumColumnsSpanned();
int numRows = cell.getNumRowsSpanned();
int cellColNum = cell.getColumnNumber();
@@ -472,10 +477,9 @@ public class TableRow extends FObj {
if (colNum < 1) {
// ERROR!!!
continue;
- }
- else cellColNum = colNum;
- }
- else if (cellColNum > columns.size()) {
+ } else
+ cellColNum = colNum;
+ } else if (cellColNum > columns.size()) {
// Explicit specification out of range!
// Skip it and print an ERROR MESSAGE
continue;
@@ -492,23 +496,24 @@ public class TableRow extends FObj {
if (cellColNum > colNum) {
// Cells are initialized as empty already
colNum = cellColNum;
- }
- else if (cellColNum < colNum) {
+ } else if (cellColNum < colNum) {
// MESSAGE ? cells out of order?
- colNum = cellColNum; // CR "to the letter"!
+ colNum = cellColNum; // CR "to the letter"!
}
int cellWidth = getCellWidth(cellColNum, numCols);
- cell.setWidth(cellWidth);
- colNum += numCols; // next cell in this column
+ cell.setWidth(cellWidth);
+ colNum += numCols; // next cell in this column
}
}
-
+
// ATTENTION if startCol + numCols > number of columns in table!
private int getCellWidth(int startCol, int numCols) {
int width = 0;
for (int count = 0; count < numCols; count++) {
- width += ((TableColumn) columns.elementAt(startCol+count-1)).getColumnWidth();
+ width += ((TableColumn)columns.elementAt(startCol + count
+ - 1)).getColumnWidth();
}
return width;
}
+
}
diff --git a/src/org/apache/fop/fo/flow/Wrapper.java b/src/org/apache/fop/fo/flow/Wrapper.java
index 3081f8f66..9e93439fe 100644
--- a/src/org/apache/fop/fo/flow/Wrapper.java
+++ b/src/org/apache/fop/fo/flow/Wrapper.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -13,7 +14,7 @@ import org.apache.fop.fo.properties.*;
import org.apache.fop.layout.*;
/**
- * Implementation for fo:wrapper formatting object.
+ * Implementation for fo:wrapper formatting object.
* The wrapper object serves as
* a property holder for it's children objects.
*
@@ -21,28 +22,27 @@ import org.apache.fop.layout.*;
* Properties: id
*/
public class Wrapper extends FObjMixed {
-
+
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException
- {
- return new Wrapper(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new Wrapper(parent, propertyList);
+ }
+
}
-
+
public static FObj.Maker maker() {
- return new Wrapper.Maker();
+ return new Wrapper.Maker();
+ }
+
+ public Wrapper(FObj parent, PropertyList propertyList) {
+ super(parent, propertyList);
+ // check that this occurs inside an fo:flow
}
- public Wrapper(FObj parent, PropertyList propertyList)
- {
- super(parent, propertyList);
- // check that this occurs inside an fo:flow
+ protected void addCharacters(char data[], int start, int length) {
+ FOText ft = new FOText(data, start, length, this);
+ children.addElement(ft);
}
- protected void addCharacters(char data[], int start, int length) {
- FOText ft = new FOText(data,start,length, this);
- children.addElement(ft);
- }
-
}
diff --git a/src/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java b/src/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java
index 4f6fafacb..b186bf74c 100644
--- a/src/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java
+++ b/src/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java
@@ -1,222 +1,164 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.pagination;
import org.apache.fop.fo.*;
import org.apache.fop.fo.properties.*;
-import org.apache.fop.apps.FOPException;
+import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;
-public class ConditionalPageMasterReference extends FObj
-{
-
+public class ConditionalPageMasterReference extends FObj {
+
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new ConditionalPageMasterReference(parent,propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new ConditionalPageMasterReference(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new ConditionalPageMasterReference.Maker();
+ return new ConditionalPageMasterReference.Maker();
}
private RepeatablePageMasterAlternatives repeatablePageMasterAlternatives;
-
+
private String masterName;
-
+
private int pagePosition;
private int oddOrEven;
private int blankOrNotBlank;
-
+
public ConditionalPageMasterReference(FObj parent, PropertyList propertyList)
- throws FOPException {
- super(parent, propertyList);
+ throws FOPException {
+ super(parent, propertyList);
+
+ this.name = getElementName();
+ if (getProperty("master-name") != null) {
+ setMasterName(getProperty("master-name").getString());
+ }
- this.name = getElementName();
- if (getProperty("master-name") != null) {
- setMasterName(getProperty("master-name").getString() );
- }
+ validateParent(parent);
+
+ setPagePosition(this.properties.get("page-position").getEnum());
+ setOddOrEven(this.properties.get("odd-or-even").getEnum());
+ setBlankOrNotBlank(this.properties.get("blank-or-not-blank").getEnum());
- validateParent(parent);
-
- setPagePosition( this.properties.get("page-position").getEnum() );
- setOddOrEven( this.properties.get("odd-or-even").getEnum() );
- setBlankOrNotBlank( this.properties.get("blank-or-not-blank").getEnum() );
-
}
-
- protected void setMasterName( String masterName )
- {
- this.masterName = masterName;
+
+ protected void setMasterName(String masterName) {
+ this.masterName = masterName;
}
-
+
/**
* Returns the "master-name" attribute of this page master reference
*/
- public String getMasterName()
- {
- return masterName;
+ public String getMasterName() {
+ return masterName;
+ }
+
+
+ protected boolean isValid(int currentPageNumber, boolean thisIsFirstPage,
+ boolean isEmptyPage) {
+ // page-position
+ boolean okOnPagePosition = true; // default is 'any'
+ switch (getPagePosition()) {
+ case PagePosition.FIRST:
+ if (!thisIsFirstPage)
+ okOnPagePosition = false;
+ break;
+ case PagePosition.LAST:
+ // how the hell do you know at this point?
+ MessageHandler.log("LAST PagePosition NYI");
+ okOnPagePosition = true;
+ break;
+ case PagePosition.REST:
+ if (thisIsFirstPage)
+ okOnPagePosition = false;
+ break;
+ case PagePosition.ANY:
+ okOnPagePosition = true;
+ }
+
+ // odd or even
+ boolean okOnOddOrEven = true; // default is 'any'
+ int ooe = getOddOrEven();
+ boolean isOddPage = ((currentPageNumber % 2) == 1) ? true : false;
+ if ((OddOrEven.ODD == ooe) &&!isOddPage) {
+ okOnOddOrEven = false;
+ }
+ if ((OddOrEven.EVEN == ooe) && isOddPage) {
+ okOnOddOrEven = false;
+ }
+
+ // experimental check for blank-or-not-blank
+
+ boolean okOnBlankOrNotBlank = true; // default is 'any'
+
+ int bnb = getBlankOrNotBlank();
+
+ if ((BlankOrNotBlank.BLANK == bnb) &&!isEmptyPage) {
+ okOnBlankOrNotBlank = false;
+ } else if ((BlankOrNotBlank.NOT_BLANK == bnb) && isEmptyPage) {
+ okOnBlankOrNotBlank = false;
+ }
+
+ return (okOnOddOrEven && okOnPagePosition && okOnBlankOrNotBlank);
+
}
+ protected void setPagePosition(int pagePosition) {
+ this.pagePosition = pagePosition;
+ }
+
+ protected int getPagePosition() {
+ return this.pagePosition;
+ }
+
+ protected void setOddOrEven(int oddOrEven) {
+ this.oddOrEven = oddOrEven;
+ }
+
+ protected int getOddOrEven() {
+ return this.oddOrEven;
+ }
- protected boolean isValid( int currentPageNumber, boolean thisIsFirstPage,
- boolean isEmptyPage)
- {
- // page-position
- boolean okOnPagePosition = true; // default is 'any'
- switch (getPagePosition()) {
- case PagePosition.FIRST:
- if (!thisIsFirstPage)
- okOnPagePosition = false;
- break;
- case PagePosition.LAST:
- // how the hell do you know at this point?
- MessageHandler.log( "LAST PagePosition NYI" );
- okOnPagePosition = true;
- break;
- case PagePosition.REST:
- if (thisIsFirstPage)
- okOnPagePosition = false;
- break;
- case PagePosition.ANY:
- okOnPagePosition = true;
- }
-
- // odd or even
- boolean okOnOddOrEven = true; // default is 'any'
- int ooe = getOddOrEven();
- boolean isOddPage = ((currentPageNumber % 2) == 1) ? true : false;
- if ((OddOrEven.ODD == ooe) && !isOddPage)
- {
- okOnOddOrEven = false;
- }
- if ((OddOrEven.EVEN == ooe) && isOddPage) {
- okOnOddOrEven = false;
- }
-
- // experimental check for blank-or-not-blank
-
- boolean okOnBlankOrNotBlank = true; // default is 'any'
-
- int bnb = getBlankOrNotBlank();
-
- if ((BlankOrNotBlank.BLANK == bnb) && !isEmptyPage) {
- okOnBlankOrNotBlank = false;
- }
- else if ((BlankOrNotBlank.NOT_BLANK == bnb) && isEmptyPage) {
- okOnBlankOrNotBlank = false;
- }
-
- return (okOnOddOrEven && okOnPagePosition &&
- okOnBlankOrNotBlank);
-
- }
-
- protected void setPagePosition( int pagePosition )
- {
- this.pagePosition = pagePosition;
- }
-
- protected int getPagePosition()
- {
- return this.pagePosition;
- }
-
- protected void setOddOrEven( int oddOrEven )
- {
- this.oddOrEven = oddOrEven;
- }
-
- protected int getOddOrEven()
- {
- return this.oddOrEven;
- }
-
- protected void setBlankOrNotBlank( int blankOrNotBlank )
- {
- this.blankOrNotBlank = blankOrNotBlank;
- }
-
- protected int getBlankOrNotBlank()
- {
- return this.blankOrNotBlank;
- }
-
- protected String getElementName()
- {
- return "fo:conditional-page-master-reference";
+ protected void setBlankOrNotBlank(int blankOrNotBlank) {
+ this.blankOrNotBlank = blankOrNotBlank;
}
-
-
- protected void validateParent(FObj parent)
- throws FOPException
- {
- if (parent.getName().equals("fo:repeatable-page-master-alternatives")) {
- this.repeatablePageMasterAlternatives =
- (RepeatablePageMasterAlternatives) parent;
-
- if (getMasterName() == null) {
- MessageHandler.errorln("WARNING: single-page-master-reference" +
- "does not have a master-name and so is being ignored");
- } else {
- this.repeatablePageMasterAlternatives.addConditionalPageMasterReference(this);
- }
- } else {
- throw new FOPException("fo:conditional-page-master-reference must be child "
- + "of fo:repeatable-page-master-alternatives, not "
- + parent.getName());
- }
+
+ protected int getBlankOrNotBlank() {
+ return this.blankOrNotBlank;
+ }
+
+ protected String getElementName() {
+ return "fo:conditional-page-master-reference";
}
-
+
+
+ protected void validateParent(FObj parent) throws FOPException {
+ if (parent.getName().equals("fo:repeatable-page-master-alternatives")) {
+ this.repeatablePageMasterAlternatives =
+ (RepeatablePageMasterAlternatives)parent;
+
+ if (getMasterName() == null) {
+ MessageHandler.errorln("WARNING: single-page-master-reference"
+ + "does not have a master-name and so is being ignored");
+ } else {
+ this.repeatablePageMasterAlternatives.addConditionalPageMasterReference(this);
+ }
+ } else {
+ throw new FOPException("fo:conditional-page-master-reference must be child "
+ + "of fo:repeatable-page-master-alternatives, not "
+ + parent.getName());
+ }
+ }
+
}
diff --git a/src/org/apache/fop/fo/pagination/LayoutMasterSet.java b/src/org/apache/fop/fo/pagination/LayoutMasterSet.java
index d28672ac6..1c5b85118 100644
--- a/src/org/apache/fop/fo/pagination/LayoutMasterSet.java
+++ b/src/org/apache/fop/fo/pagination/LayoutMasterSet.java
@@ -1,59 +1,16 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.pagination;
// FOP
import org.apache.fop.fo.*;
import org.apache.fop.fo.properties.*;
-import org.apache.fop.apps.FOPException;
+import org.apache.fop.apps.FOPException;
import org.apache.fop.layout.PageMaster;
// Java
@@ -62,132 +19,133 @@ import java.util.*;
public class LayoutMasterSet extends FObj {
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new LayoutMasterSet(parent,propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new LayoutMasterSet(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new LayoutMasterSet.Maker();
+ return new LayoutMasterSet.Maker();
}
private Hashtable simplePageMasters;
private Hashtable pageSequenceMasters;
private Hashtable allRegions;
-
+
private Root root;
-
- protected LayoutMasterSet(FObj parent, PropertyList propertyList)
- throws FOPException {
- super(parent, propertyList);
- this.name = "fo:layout-master-set";
-
- this.simplePageMasters = new Hashtable();
- this.pageSequenceMasters = new Hashtable();
-
- if (parent.getName().equals("fo:root")) {
- this.root = (Root)parent;
- root.setLayoutMasterSet(this);
- } else {
- throw
- new FOPException("fo:layout-master-set must be child of fo:root, not "
- + parent.getName());
- }
- allRegions = new Hashtable();
-
+
+ protected LayoutMasterSet(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ super(parent, propertyList);
+ this.name = "fo:layout-master-set";
+
+ this.simplePageMasters = new Hashtable();
+ this.pageSequenceMasters = new Hashtable();
+
+ if (parent.getName().equals("fo:root")) {
+ this.root = (Root)parent;
+ root.setLayoutMasterSet(this);
+ } else {
+ throw new FOPException("fo:layout-master-set must be child of fo:root, not "
+ + parent.getName());
+ }
+ allRegions = new Hashtable();
+
}
protected void addSimplePageMaster(SimplePageMaster simplePageMaster)
- throws FOPException {
- // check against duplication of master-name
- if (existsName(simplePageMaster.getMasterName()))
- throw new FOPException( "'master-name' (" +
- simplePageMaster.getMasterName() +
- ") must be unique " +
- "across page-masters and page-sequence-masters" );
- this.simplePageMasters.put(simplePageMaster.getMasterName(), simplePageMaster);
+ throws FOPException {
+ // check against duplication of master-name
+ if (existsName(simplePageMaster.getMasterName()))
+ throw new FOPException("'master-name' ("
+ + simplePageMaster.getMasterName()
+ + ") must be unique "
+ + "across page-masters and page-sequence-masters");
+ this.simplePageMasters.put(simplePageMaster.getMasterName(),
+ simplePageMaster);
}
protected SimplePageMaster getSimplePageMaster(String masterName) {
- return (SimplePageMaster)this.simplePageMasters.get(masterName);
+ return (SimplePageMaster)this.simplePageMasters.get(masterName);
}
- protected void addPageSequenceMaster(
- String masterName, PageSequenceMaster pageSequenceMaster)
- throws FOPException {
- // check against duplication of master-name
- if (existsName(masterName))
- throw new FOPException( "'master-name' (" +
- masterName +
- ") must be unique " +
- "across page-masters and page-sequence-masters" );
- this.pageSequenceMasters.put(masterName, pageSequenceMaster);
+ protected void addPageSequenceMaster(String masterName, PageSequenceMaster pageSequenceMaster)
+ throws FOPException {
+ // check against duplication of master-name
+ if (existsName(masterName))
+ throw new FOPException("'master-name' (" + masterName
+ + ") must be unique "
+ + "across page-masters and page-sequence-masters");
+ this.pageSequenceMasters.put(masterName, pageSequenceMaster);
}
protected PageSequenceMaster getPageSequenceMaster(String masterName) {
- return (PageSequenceMaster)this.pageSequenceMasters.get(masterName);
+ return (PageSequenceMaster)this.pageSequenceMasters.get(masterName);
+ }
+
+ private boolean existsName(String masterName) {
+ if (simplePageMasters.containsKey(masterName)
+ || pageSequenceMasters.containsKey(masterName))
+ return true;
+ else
+ return false;
}
-
- private boolean existsName( String masterName )
- {
- if (simplePageMasters.containsKey(masterName) ||
- pageSequenceMasters.containsKey(masterName))
- return true;
- else
- return false;
- }
-
- protected void resetPageMasters()
- {
- for (Enumeration e = pageSequenceMasters.elements(); e.hasMoreElements(); )
- {
- ((PageSequenceMaster)e.nextElement()).reset();
- }
-
+
+ protected void resetPageMasters() {
+ for (Enumeration e = pageSequenceMasters.elements();
+ e.hasMoreElements(); ) {
+ ((PageSequenceMaster)e.nextElement()).reset();
+ }
+
}
- protected void checkRegionNames() throws FOPException
- {
- // Section 7.33.15 check to see that if a region-name is a
- // duplicate, that it maps to the same region-class.
- for (Enumeration spm = simplePageMasters.elements(); spm.hasMoreElements(); ) {
- SimplePageMaster simplePageMaster = (SimplePageMaster)spm.nextElement();
- Hashtable spmRegions = simplePageMaster.getRegions();
- for (Enumeration e = spmRegions.elements(); e.hasMoreElements(); ) {
- Region region = (Region)e.nextElement();
- if (allRegions.containsKey(region.getRegionName())) {
- String localClass = (String)allRegions.get(region.getRegionName());
- if (!localClass.equals(region.getRegionClass())) {
- throw new FOPException("Duplicate region-names (" +
- region.getRegionName() +
- ") must map "
- + "to the same region-class ("
- + localClass
- + "!="
- + region.getRegionClass()
- + ")");
- }
- }
- allRegions.put(region.getRegionName(),region.getRegionClass());
- }
- }
+ protected void checkRegionNames() throws FOPException {
+ // Section 7.33.15 check to see that if a region-name is a
+ // duplicate, that it maps to the same region-class.
+ for (Enumeration spm = simplePageMasters.elements();
+ spm.hasMoreElements(); ) {
+ SimplePageMaster simplePageMaster =
+ (SimplePageMaster)spm.nextElement();
+ Hashtable spmRegions = simplePageMaster.getRegions();
+ for (Enumeration e = spmRegions.elements();
+ e.hasMoreElements(); ) {
+ Region region = (Region)e.nextElement();
+ if (allRegions.containsKey(region.getRegionName())) {
+ String localClass =
+ (String)allRegions.get(region.getRegionName());
+ if (!localClass.equals(region.getRegionClass())) {
+ throw new FOPException("Duplicate region-names ("
+ + region.getRegionName()
+ + ") must map "
+ + "to the same region-class ("
+ + localClass + "!="
+ + region.getRegionClass()
+ + ")");
+ }
+ }
+ allRegions.put(region.getRegionName(),
+ region.getRegionClass());
+ }
+ }
}
-
+
/**
* Checks whether or not a region name exists in this master set
* @returns true when the region name specified has a region in this LayoutMasterSet
*/
- protected boolean regionNameExists(String regionName)
- {
- boolean result = false;
- for (Enumeration e = simplePageMasters.elements(); e.hasMoreElements() ;) {
- result = ((SimplePageMaster)e.nextElement()).regionNameExists(regionName);
- if (result) {
- return result;
- }
- }
- return result;
+ protected boolean regionNameExists(String regionName) {
+ boolean result = false;
+ for (Enumeration e = simplePageMasters.elements();
+ e.hasMoreElements(); ) {
+ result =
+ ((SimplePageMaster)e.nextElement()).regionNameExists(regionName);
+ if (result) {
+ return result;
+ }
+ }
+ return result;
}
diff --git a/src/org/apache/fop/fo/pagination/PageMasterReference.java b/src/org/apache/fop/fo/pagination/PageMasterReference.java
index 3c88405bc..1cae307d3 100644
--- a/src/org/apache/fop/fo/pagination/PageMasterReference.java
+++ b/src/org/apache/fop/fo/pagination/PageMasterReference.java
@@ -1,110 +1,62 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.pagination;
import org.apache.fop.fo.*;
import org.apache.fop.fo.properties.*;
-import org.apache.fop.apps.FOPException;
+import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;
/**
* Base PageMasterReference class. Provides implementation for handling the
* master-name attribute and containment within a PageSequenceMaster
*/
-public abstract class PageMasterReference extends FObj
- implements SubSequenceSpecifier
-{
+public abstract class PageMasterReference extends FObj
+ implements SubSequenceSpecifier {
private String _masterName;
private PageSequenceMaster _pageSequenceMaster;
public PageMasterReference(FObj parent, PropertyList propertyList)
- throws FOPException
- {
- super(parent, propertyList);
- this.name = getElementName();
- if (getProperty("master-name") != null) {
- setMasterName(getProperty("master-name").getString() );
- }
- validateParent(parent);
+ throws FOPException {
+ super(parent, propertyList);
+ this.name = getElementName();
+ if (getProperty("master-name") != null) {
+ setMasterName(getProperty("master-name").getString());
+ }
+ validateParent(parent);
}
-
- protected void setMasterName( String masterName )
- {
- _masterName = masterName;
+
+ protected void setMasterName(String masterName) {
+ _masterName = masterName;
}
-
+
/**
* Returns the "master-name" attribute of this page master reference
*/
- public String getMasterName()
- {
- return _masterName;
+ public String getMasterName() {
+ return _masterName;
}
- protected void setPageSequenceMaster(PageSequenceMaster pageSequenceMaster)
- {
- _pageSequenceMaster = pageSequenceMaster;
+ protected void setPageSequenceMaster(PageSequenceMaster pageSequenceMaster) {
+ _pageSequenceMaster = pageSequenceMaster;
}
- protected PageSequenceMaster getPageSequenceMaster()
- {
- return _pageSequenceMaster;
+ protected PageSequenceMaster getPageSequenceMaster() {
+ return _pageSequenceMaster;
}
-
+
public abstract String getNextPageMaster(int currentPageNumber,
- boolean thisIsFirstPage, boolean isEmptyPage);
-
- /**
+ boolean thisIsFirstPage,
+ boolean isEmptyPage);
+
+ /**
* Gets the formating object name for this object. Subclasses must provide this.
*
* @return the element name of this reference. e.g. fo:repeatable-page-master-reference
@@ -115,28 +67,26 @@ public abstract class PageMasterReference extends FObj
* Checks that the parent is the right element. The default implementation
* checks for fo:page-sequence-master
*/
- protected void validateParent(FObj parent)
- throws FOPException
- {
- if (parent.getName().equals("fo:page-sequence-master")) {
- _pageSequenceMaster = (PageSequenceMaster)parent;
-
- if (getMasterName() == null) {
- MessageHandler.errorln("WARNING: " + getElementName() +
- " does not have a master-name and so is being ignored");
- } else {
- _pageSequenceMaster.addSubsequenceSpecifier(this);
- }
- } else {
- throw new FOPException(getElementName() + " must be" +
- "child of fo:page-sequence-master, not "
- + parent.getName());
- }
+ protected void validateParent(FObj parent) throws FOPException {
+ if (parent.getName().equals("fo:page-sequence-master")) {
+ _pageSequenceMaster = (PageSequenceMaster)parent;
+
+ if (getMasterName() == null) {
+ MessageHandler.errorln("WARNING: " + getElementName()
+ + " does not have a master-name and so is being ignored");
+ } else {
+ _pageSequenceMaster.addSubsequenceSpecifier(this);
+ }
+ } else {
+ throw new FOPException(getElementName() + " must be"
+ + "child of fo:page-sequence-master, not "
+ + parent.getName());
+ }
}
-
- public abstract void reset() ;
-
-
-
+
+ public abstract void reset();
+
+
+
}
diff --git a/src/org/apache/fop/fo/pagination/PageNumberGenerator.java b/src/org/apache/fop/fo/pagination/PageNumberGenerator.java
index d00a5c66b..26153d4e6 100644
--- a/src/org/apache/fop/fo/pagination/PageNumberGenerator.java
+++ b/src/org/apache/fop/fo/pagination/PageNumberGenerator.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -19,128 +20,134 @@ import java.util.*;
*/
public class PageNumberGenerator {
- private String format;
- private char groupingSeparator;
- private int groupingSize;
- private int letterValue;
-
- //constants
- private int DECIMAL = 1; // '0*1'
- private int LOWERALPHA = 2; // 'a'
- private int UPPERALPHA = 3; // 'A'
- private int LOWERROMAN = 4; // 'i'
- private int UPPERROMAN = 5; // 'I'
-
- // flags
- private int formatType = DECIMAL;
- private int minPadding = 0; // for decimal formats
-
- // preloaded strings of zeros
- private String zeros[] = { "", "0", "00", "000", "0000", "00000" };
-
- public PageNumberGenerator( String format,
- char groupingSeparator, int groupingSize, int letterValue ) {
- this.format = format;
- this.groupingSeparator = groupingSeparator;
- this.groupingSize = groupingSize;
- this.letterValue = letterValue;
-
- // the only accepted format strings are currently '0*1' 'a', 'A', 'i'
- // and 'I'
- int fmtLen = format.length();
- if (fmtLen == 1) {
- if (format.equals("1")) {
- formatType = DECIMAL;
- minPadding = 0;
- } else if (format.equals("a")) {
- formatType = LOWERALPHA;
- } else if (format.equals("A")) {
- formatType = UPPERALPHA;
- } else if (format.equals("i")) {
- formatType = LOWERROMAN;
- } else if (format.equals("I")) {
- formatType = UPPERROMAN;
- } else {
- // token not handled
- MessageHandler.log("'format' token not recognized; using '1'");
- formatType = DECIMAL;
- minPadding = 0;
- }
- }
- else {
- // only accepted token is '0+1'at this stage. Because of the
- // wonderful regular expression support in Java, we will resort to a
- // loop
- for (int i = 0; i < fmtLen-1; i++) {
- if (format.charAt(i) != '0') {
- MessageHandler.log("'format' token not recognized; using '1'");
- formatType = DECIMAL;
- minPadding = 0;
- } else {
- minPadding = fmtLen - 1;
- }
- }
- }
- }
-
- public String makeFormattedPageNumber(int number) {
- String pn = null;
- if (formatType == DECIMAL) {
- pn = Integer.toString(number);
- if (minPadding >= pn.length()) {
- int nz = minPadding - pn.length() + 1;
- pn = zeros[nz] + pn;
- }
- } else if ((formatType == LOWERROMAN) || (formatType == UPPERROMAN)) {
- pn = makeRoman(number);
- if (formatType == UPPERROMAN)
- pn = pn.toUpperCase();
- } else {
- // alphabetic
- pn = makeAlpha(number);
- if (formatType == UPPERALPHA)
- pn = pn.toUpperCase();
- }
- return pn;
- }
-
- private String makeRoman( int num ) {
- int arabic[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
- String roman[] = { "m", "cm", "d", "cd", "c", "xc", "l", "xl", "x",
- "ix", "v", "iv", "i" };
-
- int i = 0;
- StringBuffer romanNumber = new StringBuffer();
-
- while (num > 0) {
- while (num >= arabic[i]) {
- num = num - arabic[i];
- romanNumber.append( roman[i] );
- }
- i = i + 1;
- }
- return romanNumber.toString();
- }
-
- private String makeAlpha( int num ) {
- String letters = "abcdefghijklmnopqrstuvwxyz";
- StringBuffer alphaNumber = new StringBuffer();
-
- int base = 26;
- int rem = 0;
-
- num--;
- if (num < base) {
- alphaNumber.append(letters.charAt(num));
- } else {
- while (num >= base) {
- rem = num % base;
- alphaNumber.append(letters.charAt(rem));
- num = num / base;
- }
- alphaNumber.append(letters.charAt(num-1));
- }
- return alphaNumber.reverse().toString();
- }
+ private String format;
+ private char groupingSeparator;
+ private int groupingSize;
+ private int letterValue;
+
+ // constants
+ private int DECIMAL = 1; // '0*1'
+ private int LOWERALPHA = 2; // 'a'
+ private int UPPERALPHA = 3; // 'A'
+ private int LOWERROMAN = 4; // 'i'
+ private int UPPERROMAN = 5; // 'I'
+
+ // flags
+ private int formatType = DECIMAL;
+ private int minPadding = 0; // for decimal formats
+
+ // preloaded strings of zeros
+ private String zeros[] = {
+ "", "0", "00", "000", "0000", "00000"
+ };
+
+ public PageNumberGenerator(String format, char groupingSeparator,
+ int groupingSize, int letterValue) {
+ this.format = format;
+ this.groupingSeparator = groupingSeparator;
+ this.groupingSize = groupingSize;
+ this.letterValue = letterValue;
+
+ // the only accepted format strings are currently '0*1' 'a', 'A', 'i'
+ // and 'I'
+ int fmtLen = format.length();
+ if (fmtLen == 1) {
+ if (format.equals("1")) {
+ formatType = DECIMAL;
+ minPadding = 0;
+ } else if (format.equals("a")) {
+ formatType = LOWERALPHA;
+ } else if (format.equals("A")) {
+ formatType = UPPERALPHA;
+ } else if (format.equals("i")) {
+ formatType = LOWERROMAN;
+ } else if (format.equals("I")) {
+ formatType = UPPERROMAN;
+ } else {
+ // token not handled
+ MessageHandler.log("'format' token not recognized; using '1'");
+ formatType = DECIMAL;
+ minPadding = 0;
+ }
+ } else {
+ // only accepted token is '0+1'at this stage. Because of the
+ // wonderful regular expression support in Java, we will resort to a
+ // loop
+ for (int i = 0; i < fmtLen - 1; i++) {
+ if (format.charAt(i) != '0') {
+ MessageHandler.log("'format' token not recognized; using '1'");
+ formatType = DECIMAL;
+ minPadding = 0;
+ } else {
+ minPadding = fmtLen - 1;
+ }
+ }
+ }
+ }
+
+ public String makeFormattedPageNumber(int number) {
+ String pn = null;
+ if (formatType == DECIMAL) {
+ pn = Integer.toString(number);
+ if (minPadding >= pn.length()) {
+ int nz = minPadding - pn.length() + 1;
+ pn = zeros[nz] + pn;
+ }
+ } else if ((formatType == LOWERROMAN) || (formatType == UPPERROMAN)) {
+ pn = makeRoman(number);
+ if (formatType == UPPERROMAN)
+ pn = pn.toUpperCase();
+ } else {
+ // alphabetic
+ pn = makeAlpha(number);
+ if (formatType == UPPERALPHA)
+ pn = pn.toUpperCase();
+ }
+ return pn;
+ }
+
+ private String makeRoman(int num) {
+ int arabic[] = {
+ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
+ };
+ String roman[] = {
+ "m", "cm", "d", "cd", "c", "xc", "l", "xl", "x", "ix", "v", "iv",
+ "i"
+ };
+
+ int i = 0;
+ StringBuffer romanNumber = new StringBuffer();
+
+ while (num > 0) {
+ while (num >= arabic[i]) {
+ num = num - arabic[i];
+ romanNumber.append(roman[i]);
+ }
+ i = i + 1;
+ }
+ return romanNumber.toString();
+ }
+
+ private String makeAlpha(int num) {
+ String letters = "abcdefghijklmnopqrstuvwxyz";
+ StringBuffer alphaNumber = new StringBuffer();
+
+ int base = 26;
+ int rem = 0;
+
+ num--;
+ if (num < base) {
+ alphaNumber.append(letters.charAt(num));
+ } else {
+ while (num >= base) {
+ rem = num % base;
+ alphaNumber.append(letters.charAt(rem));
+ num = num / base;
+ }
+ alphaNumber.append(letters.charAt(num - 1));
+ }
+ return alphaNumber.reverse().toString();
+ }
+
}
diff --git a/src/org/apache/fop/fo/pagination/PageSequence.java b/src/org/apache/fop/fo/pagination/PageSequence.java
index 5faba0b27..0c9beaca2 100644
--- a/src/org/apache/fop/fo/pagination/PageSequence.java
+++ b/src/org/apache/fop/fo/pagination/PageSequence.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -37,6 +38,7 @@ public class PageSequence extends FObj {
PropertyList propertyList) throws FOPException {
return new PageSequence(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -54,10 +56,15 @@ public class PageSequence extends FObj {
//
// associations
//
- /** The parent root object */
+
+ /**
+ * The parent root object
+ */
private Root root;
- /** the set of layout masters (provided by the root object) */
+ /**
+ * the set of layout masters (provided by the root object)
+ */
private LayoutMasterSet layoutMasterSet;
// There doesn't seem to be anything in the spec requiring flows
@@ -65,10 +72,14 @@ public class PageSequence extends FObj {
// defined in the page sequence, so all we need is this one hashtable
// the set of flows includes StaticContent flows also
- /** Map of flows to their flow name (flow-name, Flow) */
+ /**
+ * Map of flows to their flow name (flow-name, Flow)
+ */
private Hashtable _flowMap;
- /** the "master-name" attribute */
+ /**
+ * the "master-name" attribute
+ */
private String masterName;
// according to communication from Paul Grosso (XSL-List,
@@ -83,28 +94,39 @@ public class PageSequence extends FObj {
private Page currentPage;
- // page number and related formatting variables
- private String ipnValue;
+ // page number and related formatting variables
+ private String ipnValue;
private int currentPageNumber = 0;
- private PageNumberGenerator pageNumberGenerator;
-
- private int forcePageCount = 0;
- private int pageCount = 0;
- private boolean isForcing = false;
-
- /** specifies page numbering type (auto|auto-even|auto-odd|explicit) */
+ private PageNumberGenerator pageNumberGenerator;
+
+ private int forcePageCount = 0;
+ private int pageCount = 0;
+ private boolean isForcing = false;
+
+ /**
+ * specifies page numbering type (auto|auto-even|auto-odd|explicit)
+ */
private int pageNumberType;
- /** used to determine whether to calculate auto, auto-even, auto-odd */
+ /**
+ * used to determine whether to calculate auto, auto-even, auto-odd
+ */
private boolean thisIsFirstPage;
- /** the current subsequence while formatting a given page sequence */
+ /**
+ * the current subsequence while formatting a given page sequence
+ */
private SubSequenceSpecifier currentSubsequence;
- /** the current index in the subsequence list */
- private int currentSubsequenceNumber = -1; // starting case is -1 so that first getNext increments to 0
+ /**
+ * the current index in the subsequence list
+ */
+ private int currentSubsequenceNumber =
+ -1; // starting case is -1 so that first getNext increments to 0
- /** the name of the current page master */
+ /**
+ * the name of the current page master
+ */
private String currentPageMasterName;
@@ -114,12 +136,11 @@ public class PageSequence extends FObj {
this.name = "fo:page-sequence";
if (parent.getName().equals("fo:root")) {
- this.root = (Root) parent;
+ this.root = (Root)parent;
this.root.addPageSequence(this);
} else {
- throw new FOPException(
- "page-sequence must be child of root, not " +
- parent.getName());
+ throw new FOPException("page-sequence must be child of root, not "
+ + parent.getName());
}
layoutMasterSet = root.getLayoutMasterSet();
@@ -129,7 +150,8 @@ public class PageSequence extends FObj {
_flowMap = new Hashtable();
- thisIsFirstPage = true; // we are now on the first page of the page sequence
+ thisIsFirstPage =
+ true; // we are now on the first page of the page sequence
ipnValue = this.properties.get("initial-page-number").getString();
if (ipnValue.equals("auto")) {
@@ -142,29 +164,28 @@ public class PageSequence extends FObj {
pageNumberType = EXPLICIT;
try {
int pageStart = new Integer(ipnValue).intValue();
- this.currentPageNumber =
- (pageStart > 0) ? pageStart - 1 : 0;
+ this.currentPageNumber = (pageStart > 0) ? pageStart - 1 : 0;
} catch (NumberFormatException nfe) {
- throw new FOPException("\""+ipnValue + "\" is not a valid value for initial-page-number");
+ throw new FOPException("\"" + ipnValue
+ + "\" is not a valid value for initial-page-number");
}
}
masterName = this.properties.get("master-name").getString();
- // get the 'format' properties
- this.pageNumberGenerator =
- new PageNumberGenerator( this.properties.get("format").getString(),
- this.properties.get("grouping-separator").getCharacter(),
- this.properties.get("grouping-size").getNumber().intValue(),
- this.properties.get("letter-value").getEnum()
+ // get the 'format' properties
+ this.pageNumberGenerator =
+ new PageNumberGenerator(this.properties.get("format").getString(),
+ this.properties.get("grouping-separator").getCharacter(),
+ this.properties.get("grouping-size").getNumber().intValue(),
+ this.properties.get("letter-value").getEnum());
- );
-
- this.forcePageCount = this.properties.get("force-page-count").getEnum();
+ this.forcePageCount =
+ this.properties.get("force-page-count").getEnum();
- //this.properties.get("country");
- //this.properties.get("language");
- //this.properties.get("id");
+ // this.properties.get("country");
+ // this.properties.get("language");
+ // this.properties.get("id");
}
public void addFlow(Flow flow) throws FOPException {
@@ -172,8 +193,9 @@ public class PageSequence extends FObj {
throw new FOPException("flow-names must be unique within an fo:page-sequence");
}
if (!this.layoutMasterSet.regionNameExists(flow.getFlowName())) {
- MessageHandler.errorln("WARNING: region-name '"+
- flow.getFlowName() + "' doesn't exist in the layout-master-set.");
+ MessageHandler.errorln("WARNING: region-name '"
+ + flow.getFlowName()
+ + "' doesn't exist in the layout-master-set.");
}
_flowMap.put(flow.getFlowName(), flow);
setIsFlowSet(true);
@@ -188,29 +210,28 @@ public class PageSequence extends FObj {
this.layoutMasterSet.resetPageMasters();
- int firstAvailPageNumber = 0;
+ int firstAvailPageNumber = 0;
do {
// makePage() moved to after the page-number computations,
// but store the page-number at this point for that method,
// since we want the 'current' current page-number...
- firstAvailPageNumber =
- this.root.getRunningPageNumberCounter();
+ firstAvailPageNumber = this.root.getRunningPageNumberCounter();
boolean tempIsFirstPage = false;
if (thisIsFirstPage) {
tempIsFirstPage = thisIsFirstPage;
if (pageNumberType == AUTO) {
this.currentPageNumber =
- this.root.getRunningPageNumberCounter();
+ this.root.getRunningPageNumberCounter();
} else if (pageNumberType == AUTO_ODD) {
this.currentPageNumber =
- this.root.getRunningPageNumberCounter();
+ this.root.getRunningPageNumberCounter();
if (this.currentPageNumber % 2 == 1) {
this.currentPageNumber++;
}
} else if (pageNumberType == AUTO_EVEN) {
this.currentPageNumber =
- this.root.getRunningPageNumberCounter();
+ this.root.getRunningPageNumberCounter();
if (this.currentPageNumber % 2 == 0) {
this.currentPageNumber++;
}
@@ -225,11 +246,11 @@ public class PageSequence extends FObj {
// compute flag for 'blank-or-not-blank'
boolean isEmptyPage = false;
- if ((status.getCode() == Status.FORCE_PAGE_BREAK_EVEN) &&
- ((currentPageNumber % 2) == 1)) {
+ if ((status.getCode() == Status.FORCE_PAGE_BREAK_EVEN)
+ && ((currentPageNumber % 2) == 1)) {
isEmptyPage = true;
- } else if ( (status.getCode() == Status.FORCE_PAGE_BREAK_ODD) &&
- ((currentPageNumber % 2) == 0)) {
+ } else if ((status.getCode() == Status.FORCE_PAGE_BREAK_ODD)
+ && ((currentPageNumber % 2) == 0)) {
isEmptyPage = true;
} else {
isEmptyPage = false;
@@ -239,28 +260,27 @@ public class PageSequence extends FObj {
tempIsFirstPage, isEmptyPage);
currentPage.setNumber(this.currentPageNumber);
- String formattedPageNumber =
- pageNumberGenerator.makeFormattedPageNumber(this.currentPageNumber);
- currentPage.setFormattedNumber(formattedPageNumber);
+ String formattedPageNumber =
+ pageNumberGenerator.makeFormattedPageNumber(this.currentPageNumber);
+ currentPage.setFormattedNumber(formattedPageNumber);
this.root.setRunningPageNumberCounter(this.currentPageNumber);
MessageHandler.log(" [" + currentPageNumber);
- if ((status.getCode() == Status.FORCE_PAGE_BREAK_EVEN) &&
- ((currentPageNumber % 2) == 1)) {
- } else if ( (status.getCode() == Status.FORCE_PAGE_BREAK_ODD) &&
- ((currentPageNumber % 2) == 0)) {
- } else {
+ if ((status.getCode() == Status.FORCE_PAGE_BREAK_EVEN)
+ && ((currentPageNumber % 2) == 1)) {}
+ else if ((status.getCode() == Status.FORCE_PAGE_BREAK_ODD)
+ && ((currentPageNumber % 2) == 0)) {}
+ else {
BodyAreaContainer bodyArea = currentPage.getBody();
bodyArea.setIDReferences(areaTree.getIDReferences());
Flow flow = getCurrentFlow(RegionBody.REGION_CLASS);
if (null == flow) {
- MessageHandler.errorln(
- "No flow found for region-body " +
- "in page-master '" +
- currentPageMasterName + "'");
+ MessageHandler.errorln("No flow found for region-body "
+ + "in page-master '"
+ + currentPageMasterName + "'");
break;
} else {
@@ -269,19 +289,18 @@ public class PageSequence extends FObj {
}
- // because of markers, do after fo:flow (likely also
- // justifiable because of spec)
- currentPage.setPageSequence(this);
+ // because of markers, do after fo:flow (likely also
+ // justifiable because of spec)
+ currentPage.setPageSequence(this);
formatStaticContent(areaTree);
MessageHandler.log("]");
areaTree.addPage(currentPage);
- this.pageCount++; // used for 'force-page-count' calculations
- } while (flowsAreIncomplete())
- ;
- // handle the 'force-page-count'
- forcePage(areaTree, firstAvailPageNumber);
-
+ this.pageCount++; // used for 'force-page-count' calculations
+ } while (flowsAreIncomplete());
+ // handle the 'force-page-count'
+ forcePage(areaTree, firstAvailPageNumber);
+
MessageHandler.logln("");
}
@@ -294,16 +313,17 @@ public class PageSequence extends FObj {
* @return a Page layout object based on the page master selected from the params
*/
private Page makePage(AreaTree areaTree, int firstAvailPageNumber,
- boolean isFirstPage, boolean isEmptyPage) throws FOPException {
+ boolean isFirstPage,
+ boolean isEmptyPage) throws FOPException {
// layout this page sequence
// while there is still stuff in the flow, ask the
// layoutMasterSet for a new page
// page number is 0-indexed
- PageMaster pageMaster =
- getNextPageMaster(masterName, firstAvailPageNumber,
- isFirstPage, isEmptyPage);
+ PageMaster pageMaster = getNextPageMaster(masterName,
+ firstAvailPageNumber,
+ isFirstPage, isEmptyPage);
// a legal alternative is to use the last sub-sequence
// specification which should be handled in getNextSubsequence. That's not done here.
@@ -321,59 +341,58 @@ public class PageSequence extends FObj {
/**
* Formats the static content of the current page
*/
- private void formatStaticContent(AreaTree areaTree)
- throws FOPException {
+ private void formatStaticContent(AreaTree areaTree) throws FOPException {
SimplePageMaster simpleMaster = getCurrentSimplePageMaster();
- if (simpleMaster.getRegion(RegionBefore.REGION_CLASS) != null &&
- (currentPage.getBefore() != null)) {
- Flow staticFlow = (Flow)_flowMap.get( simpleMaster.getRegion(
- RegionBefore.REGION_CLASS).getRegionName());
+ if (simpleMaster.getRegion(RegionBefore.REGION_CLASS) != null
+ && (currentPage.getBefore() != null)) {
+ Flow staticFlow =
+ (Flow)_flowMap.get(simpleMaster.getRegion(RegionBefore.REGION_CLASS).getRegionName());
if (staticFlow != null) {
AreaContainer beforeArea = currentPage.getBefore();
beforeArea.setIDReferences(areaTree.getIDReferences());
layoutStaticContent(staticFlow,
- simpleMaster.getRegion(
- RegionBefore.REGION_CLASS), beforeArea);
+ simpleMaster.getRegion(RegionBefore.REGION_CLASS),
+ beforeArea);
}
}
- if (simpleMaster.getRegion(RegionAfter.REGION_CLASS) != null &&
- (currentPage.getAfter() != null)) {
- Flow staticFlow = (Flow)_flowMap.get( simpleMaster.getRegion(
- RegionAfter.REGION_CLASS).getRegionName());
+ if (simpleMaster.getRegion(RegionAfter.REGION_CLASS) != null
+ && (currentPage.getAfter() != null)) {
+ Flow staticFlow =
+ (Flow)_flowMap.get(simpleMaster.getRegion(RegionAfter.REGION_CLASS).getRegionName());
if (staticFlow != null) {
AreaContainer afterArea = currentPage.getAfter();
afterArea.setIDReferences(areaTree.getIDReferences());
layoutStaticContent(staticFlow,
- simpleMaster.getRegion(
- RegionAfter.REGION_CLASS), afterArea);
+ simpleMaster.getRegion(RegionAfter.REGION_CLASS),
+ afterArea);
}
}
- if (simpleMaster.getRegion(RegionStart.REGION_CLASS) != null &&
- (currentPage.getStart() != null)) {
- Flow staticFlow = (Flow)_flowMap.get( simpleMaster.getRegion(
- RegionStart.REGION_CLASS).getRegionName());
+ if (simpleMaster.getRegion(RegionStart.REGION_CLASS) != null
+ && (currentPage.getStart() != null)) {
+ Flow staticFlow =
+ (Flow)_flowMap.get(simpleMaster.getRegion(RegionStart.REGION_CLASS).getRegionName());
if (staticFlow != null) {
AreaContainer startArea = currentPage.getStart();
startArea.setIDReferences(areaTree.getIDReferences());
layoutStaticContent(staticFlow,
- simpleMaster.getRegion(
- RegionStart.REGION_CLASS), startArea);
+ simpleMaster.getRegion(RegionStart.REGION_CLASS),
+ startArea);
}
}
- if (simpleMaster.getRegion(RegionEnd.REGION_CLASS) != null &&
- (currentPage.getEnd() != null)) {
- Flow staticFlow = (Flow)_flowMap.get( simpleMaster.getRegion(
- RegionEnd.REGION_CLASS).getRegionName());
+ if (simpleMaster.getRegion(RegionEnd.REGION_CLASS) != null
+ && (currentPage.getEnd() != null)) {
+ Flow staticFlow =
+ (Flow)_flowMap.get(simpleMaster.getRegion(RegionEnd.REGION_CLASS).getRegionName());
if (staticFlow != null) {
AreaContainer endArea = currentPage.getEnd();
endArea.setIDReferences(areaTree.getIDReferences());
layoutStaticContent(staticFlow,
- simpleMaster.getRegion(RegionEnd.REGION_CLASS)
- , endArea);
+ simpleMaster.getRegion(RegionEnd.REGION_CLASS),
+ endArea);
}
}
@@ -383,10 +402,11 @@ public class PageSequence extends FObj {
AreaContainer area) throws FOPException {
if (flow instanceof StaticContent) {
AreaContainer beforeArea = currentPage.getBefore();
- ((StaticContent) flow).layout(area, region);
+ ((StaticContent)flow).layout(area, region);
} else {
- MessageHandler.errorln("WARNING: "+region.getName() + " only supports static-content flows currently. Cannot use flow named '"+
- flow.getFlowName() + "'");
+ MessageHandler.errorln("WARNING: " + region.getName()
+ + " only supports static-content flows currently. Cannot use flow named '"
+ + flow.getFlowName() + "'");
}
}
@@ -395,13 +415,12 @@ public class PageSequence extends FObj {
* is bassed on the current state of this page sequence.
*/
// refactored from PageSequenceMaster
- private SubSequenceSpecifier getNextSubsequence(
- PageSequenceMaster master) {
- if (master.getSubSequenceSpecifierCount() >
- currentSubsequenceNumber + 1) {
+ private SubSequenceSpecifier getNextSubsequence(PageSequenceMaster master) {
+ if (master.getSubSequenceSpecifierCount()
+ > currentSubsequenceNumber + 1) {
- currentSubsequence = master.getSubSequenceSpecifier(
- currentSubsequenceNumber + 1);
+ currentSubsequence =
+ master.getSubSequenceSpecifier(currentSubsequenceNumber + 1);
currentSubsequenceNumber++;
return currentSubsequence;
} else {
@@ -414,40 +433,44 @@ public class PageSequence extends FObj {
* Returns the next simple page master for the given sequence master, page number and
* other state information
*/
- private SimplePageMaster getNextSimplePageMaster(
- PageSequenceMaster sequenceMaster, int currentPageNumber,
- boolean thisIsFirstPage, boolean isEmptyPage) {
- // handle forcing
- if (isForcing) {
- String nextPageMaster = getNextPageMasterName(sequenceMaster,
- currentPageNumber, false, true);
- return this.layoutMasterSet.getSimplePageMaster(nextPageMaster);
- }
+ private SimplePageMaster getNextSimplePageMaster(PageSequenceMaster sequenceMaster,
+ int currentPageNumber, boolean thisIsFirstPage,
+ boolean isEmptyPage) {
+ // handle forcing
+ if (isForcing) {
+ String nextPageMaster = getNextPageMasterName(sequenceMaster,
+ currentPageNumber, false, true);
+ return this.layoutMasterSet.getSimplePageMaster(nextPageMaster);
+ }
String nextPageMaster = getNextPageMasterName(sequenceMaster,
- currentPageNumber, thisIsFirstPage, isEmptyPage);
+ currentPageNumber, thisIsFirstPage, isEmptyPage);
return this.layoutMasterSet.getSimplePageMaster(nextPageMaster);
}
- private String getNextPageMasterName(
- PageSequenceMaster sequenceMaster, int currentPageNumber,
- boolean thisIsFirstPage, boolean isEmptyPage) {
+ private String getNextPageMasterName(PageSequenceMaster sequenceMaster,
+ int currentPageNumber,
+ boolean thisIsFirstPage,
+ boolean isEmptyPage) {
if (null == currentSubsequence) {
currentSubsequence = getNextSubsequence(sequenceMaster);
}
- String nextPageMaster = currentSubsequence.getNextPageMaster(
- currentPageNumber, thisIsFirstPage, isEmptyPage);
+ String nextPageMaster =
+ currentSubsequence.getNextPageMaster(currentPageNumber,
+ thisIsFirstPage,
+ isEmptyPage);
- if (null == nextPageMaster ||
- isFlowForMasterNameDone(currentPageMasterName)) {
+ if (null == nextPageMaster
+ || isFlowForMasterNameDone(currentPageMasterName)) {
SubSequenceSpecifier nextSubsequence =
- getNextSubsequence(sequenceMaster);
+ getNextSubsequence(sequenceMaster);
if (nextSubsequence == null) {
MessageHandler.errorln("\nWARNING: Page subsequences exhausted. Using previous subsequence.");
- thisIsFirstPage = true; // this becomes the first page in the new (old really) page master
+ thisIsFirstPage =
+ true; // this becomes the first page in the new (old really) page master
currentSubsequence.reset();
// we leave currentSubsequence alone
@@ -455,8 +478,10 @@ public class PageSequence extends FObj {
currentSubsequence = nextSubsequence;
}
- nextPageMaster = currentSubsequence.getNextPageMaster(
- currentPageNumber, thisIsFirstPage, isEmptyPage);
+ nextPageMaster =
+ currentSubsequence.getNextPageMaster(currentPageNumber,
+ thisIsFirstPage,
+ isEmptyPage);
}
currentPageMasterName = nextPageMaster;
@@ -465,8 +490,7 @@ public class PageSequence extends FObj {
}
private SimplePageMaster getCurrentSimplePageMaster() {
- return this.layoutMasterSet.getSimplePageMaster(
- currentPageMasterName);
+ return this.layoutMasterSet.getSimplePageMaster(currentPageMasterName);
}
private String getCurrentPageMasterName() {
@@ -475,27 +499,27 @@ public class PageSequence extends FObj {
// refactored from LayoutMasterSet
private PageMaster getNextPageMaster(String pageSequenceName,
- int currentPageNumber, boolean thisIsFirstPage,
+ int currentPageNumber,
+ boolean thisIsFirstPage,
boolean isEmptyPage) throws FOPException {
PageMaster pageMaster = null;
// see if there is a page master sequence for this master name
PageSequenceMaster sequenceMaster =
- this.layoutMasterSet.getPageSequenceMaster(
- pageSequenceName);
+ this.layoutMasterSet.getPageSequenceMaster(pageSequenceName);
if (sequenceMaster != null) {
pageMaster = getNextSimplePageMaster(sequenceMaster,
- currentPageNumber, thisIsFirstPage,
+ currentPageNumber,
+ thisIsFirstPage,
isEmptyPage).getPageMaster();
- } else { // otherwise see if there's a simple master by the given name
+ } else { // otherwise see if there's a simple master by the given name
SimplePageMaster simpleMaster =
- this.layoutMasterSet.getSimplePageMaster(
- pageSequenceName);
+ this.layoutMasterSet.getSimplePageMaster(pageSequenceName);
if (simpleMaster == null) {
- throw new FOPException(
- "'master-name' for 'fo:page-sequence'" + "matches no 'simple-page-master' or 'page-sequence-master'");
+ throw new FOPException("'master-name' for 'fo:page-sequence'"
+ + "matches no 'simple-page-master' or 'page-sequence-master'");
}
currentPageMasterName = pageSequenceName;
@@ -511,8 +535,8 @@ public class PageSequence extends FObj {
private boolean flowsAreIncomplete() {
boolean isIncomplete = false;
- for (Enumeration e = _flowMap.elements(); e.hasMoreElements();) {
- Flow flow = (Flow) e.nextElement();
+ for (Enumeration e = _flowMap.elements(); e.hasMoreElements(); ) {
+ Flow flow = (Flow)e.nextElement();
if (flow instanceof StaticContent) {
continue;
}
@@ -535,9 +559,9 @@ public class PageSequence extends FObj {
} else {
- System.out.println("flow is null. regionClass = '"+
- regionClass + "' currentSPM = "+
- getCurrentSimplePageMaster());
+ System.out.println("flow is null. regionClass = '" + regionClass
+ + "' currentSPM = "
+ + getCurrentSimplePageMaster());
return null;
}
@@ -547,11 +571,12 @@ public class PageSequence extends FObj {
private boolean isFlowForMasterNameDone(String masterName) {
// parameter is master-name of PMR; we need to locate PM
// referenced by this, and determine whether flow(s) are OK
- if (isForcing) return false;
+ if (isForcing)
+ return false;
if (masterName != null) {
SimplePageMaster spm =
- this.layoutMasterSet.getSimplePageMaster(masterName);
+ this.layoutMasterSet.getSimplePageMaster(masterName);
Region region = spm.getRegion(RegionBody.REGION_CLASS);
@@ -571,79 +596,78 @@ public class PageSequence extends FObj {
public void setIsFlowSet(boolean isFlowSet) {
this.isFlowSet = isFlowSet;
}
-
- public String getIpnValue() {
- return ipnValue;
- }
-
- public int getCurrentPageNumber() {
- return currentPageNumber;
- }
-
- private void forcePage(AreaTree areaTree, int firstAvailPageNumber) {
- boolean makePage = false;
- if (this.forcePageCount == ForcePageCount.AUTO) {
- PageSequence nextSequence =
- this.root.getSucceedingPageSequence(this);
- if (nextSequence != null) {
- if (nextSequence.getIpnValue().equals("auto")) {
- // do nothing special
- } else if (nextSequence.getIpnValue().equals("auto-odd")) {
- if (firstAvailPageNumber % 2 == 0) {
- makePage = true;
- }
- } else if (nextSequence.getIpnValue().equals("auto-even")) {
- if (firstAvailPageNumber % 2 != 0) {
- makePage = true;
- }
- } else {
- int nextSequenceStartPageNumber =
- nextSequence.getCurrentPageNumber();
- if ((nextSequenceStartPageNumber % 2 == 0) &&
- (firstAvailPageNumber % 2 == 0)) {
- makePage = true;
- } else if ((nextSequenceStartPageNumber % 2 != 0) &&
- (firstAvailPageNumber % 2 != 0)) {
- makePage = true;
- }
- }
- }
- } else if ((this.forcePageCount == ForcePageCount.EVEN) &&
- (this.pageCount % 2 != 0)) {
- makePage = true;
- } else if ((this.forcePageCount == ForcePageCount.ODD) &&
- (this.pageCount % 2 == 0)) {
- makePage = true;
- } else if ((this.forcePageCount == ForcePageCount.END_ON_EVEN) &&
- (firstAvailPageNumber % 2 == 0)) {
- makePage = true;
- } else if ((this.forcePageCount == ForcePageCount.END_ON_ODD) &&
- (firstAvailPageNumber % 2 != 0)) {
- makePage = true;
- } else if (this.forcePageCount == ForcePageCount.NO_FORCE) {
- // do nothing
- }
- if (makePage) {
- try
- {
- this.isForcing = true;
- this.currentPageNumber++;
- firstAvailPageNumber = this.currentPageNumber;
- currentPage = makePage(areaTree, firstAvailPageNumber,
- false, true);
- String formattedPageNumber =
- pageNumberGenerator.makeFormattedPageNumber(this.currentPageNumber);
- currentPage.setFormattedNumber(formattedPageNumber);
- currentPage.setPageSequence(this);
- formatStaticContent(areaTree);
- MessageHandler.log("[forced-" + firstAvailPageNumber + "]");
- areaTree.addPage(currentPage);
- this.root.setRunningPageNumberCounter(this.currentPageNumber);
- this.isForcing = false;
- }
- catch (FOPException fopex) {
- MessageHandler.log("'force-page-count' failure");
- }
- }
- }
+
+ public String getIpnValue() {
+ return ipnValue;
+ }
+
+ public int getCurrentPageNumber() {
+ return currentPageNumber;
+ }
+
+ private void forcePage(AreaTree areaTree, int firstAvailPageNumber) {
+ boolean makePage = false;
+ if (this.forcePageCount == ForcePageCount.AUTO) {
+ PageSequence nextSequence =
+ this.root.getSucceedingPageSequence(this);
+ if (nextSequence != null) {
+ if (nextSequence.getIpnValue().equals("auto")) {
+ // do nothing special
+ } else if (nextSequence.getIpnValue().equals("auto-odd")) {
+ if (firstAvailPageNumber % 2 == 0) {
+ makePage = true;
+ }
+ } else if (nextSequence.getIpnValue().equals("auto-even")) {
+ if (firstAvailPageNumber % 2 != 0) {
+ makePage = true;
+ }
+ } else {
+ int nextSequenceStartPageNumber =
+ nextSequence.getCurrentPageNumber();
+ if ((nextSequenceStartPageNumber % 2 == 0)
+ && (firstAvailPageNumber % 2 == 0)) {
+ makePage = true;
+ } else if ((nextSequenceStartPageNumber % 2 != 0)
+ && (firstAvailPageNumber % 2 != 0)) {
+ makePage = true;
+ }
+ }
+ }
+ } else if ((this.forcePageCount == ForcePageCount.EVEN)
+ && (this.pageCount % 2 != 0)) {
+ makePage = true;
+ } else if ((this.forcePageCount == ForcePageCount.ODD)
+ && (this.pageCount % 2 == 0)) {
+ makePage = true;
+ } else if ((this.forcePageCount == ForcePageCount.END_ON_EVEN)
+ && (firstAvailPageNumber % 2 == 0)) {
+ makePage = true;
+ } else if ((this.forcePageCount == ForcePageCount.END_ON_ODD)
+ && (firstAvailPageNumber % 2 != 0)) {
+ makePage = true;
+ } else if (this.forcePageCount == ForcePageCount.NO_FORCE) {
+ // do nothing
+ }
+ if (makePage) {
+ try {
+ this.isForcing = true;
+ this.currentPageNumber++;
+ firstAvailPageNumber = this.currentPageNumber;
+ currentPage = makePage(areaTree, firstAvailPageNumber, false,
+ true);
+ String formattedPageNumber =
+ pageNumberGenerator.makeFormattedPageNumber(this.currentPageNumber);
+ currentPage.setFormattedNumber(formattedPageNumber);
+ currentPage.setPageSequence(this);
+ formatStaticContent(areaTree);
+ MessageHandler.log("[forced-" + firstAvailPageNumber + "]");
+ areaTree.addPage(currentPage);
+ this.root.setRunningPageNumberCounter(this.currentPageNumber);
+ this.isForcing = false;
+ } catch (FOPException fopex) {
+ MessageHandler.log("'force-page-count' failure");
+ }
+ }
+ }
+
}
diff --git a/src/org/apache/fop/fo/pagination/PageSequenceMaster.java b/src/org/apache/fop/fo/pagination/PageSequenceMaster.java
index 182805ca7..e7598c475 100644
--- a/src/org/apache/fop/fo/pagination/PageSequenceMaster.java
+++ b/src/org/apache/fop/fo/pagination/PageSequenceMaster.java
@@ -1,138 +1,94 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.pagination;
// FOP
import org.apache.fop.fo.*;
import org.apache.fop.fo.properties.*;
import org.apache.fop.layout.PageMaster;
-import org.apache.fop.apps.FOPException;
+import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;
// Java
import java.util.*;
public class PageSequenceMaster extends FObj {
-
+
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new PageSequenceMaster(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new PageSequenceMaster(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new PageSequenceMaster.Maker();
+ return new PageSequenceMaster.Maker();
}
LayoutMasterSet layoutMasterSet;
Vector subSequenceSpecifiers;
-
+
// The terminology may be confusing. A 'page-sequence-master' consists
// of a sequence of what the XSL spec refers to as
// 'sub-sequence-specifiers'. These are, in fact, simple or complex
// references to page-masters. So the methods use the former
- // terminology ('sub-sequence-specifiers', or SSS),
+ // terminology ('sub-sequence-specifiers', or SSS),
// but the actual FO's are MasterReferences.
protected PageSequenceMaster(FObj parent, PropertyList propertyList)
- throws FOPException {
- super(parent, propertyList);
- this.name = "fo:page-sequence-master";
-
- subSequenceSpecifiers = new Vector();
-
- if (parent.getName().equals("fo:layout-master-set")) {
- this.layoutMasterSet = (LayoutMasterSet) parent;
- String pm = this.properties.get("master-name").getString();
- if (pm == null) {
- MessageHandler.errorln("WARNING: page-sequence-master does not have "
- + "a page-master-name and so is being ignored");
- } else {
- this.layoutMasterSet.addPageSequenceMaster(pm, this);
- }
- } else {
- throw new FOPException("fo:page-sequence-master must be child "
- + "of fo:layout-master-set, not "
- + parent.getName());
- }
+ throws FOPException {
+ super(parent, propertyList);
+ this.name = "fo:page-sequence-master";
+
+ subSequenceSpecifiers = new Vector();
+
+ if (parent.getName().equals("fo:layout-master-set")) {
+ this.layoutMasterSet = (LayoutMasterSet)parent;
+ String pm = this.properties.get("master-name").getString();
+ if (pm == null) {
+ MessageHandler.errorln("WARNING: page-sequence-master does not have "
+ + "a page-master-name and so is being ignored");
+ } else {
+ this.layoutMasterSet.addPageSequenceMaster(pm, this);
+ }
+ } else {
+ throw new FOPException("fo:page-sequence-master must be child "
+ + "of fo:layout-master-set, not "
+ + parent.getName());
+ }
}
-
- protected void addSubsequenceSpecifier( SubSequenceSpecifier pageMasterReference )
- {
- subSequenceSpecifiers.addElement( pageMasterReference );
+
+ protected void addSubsequenceSpecifier(SubSequenceSpecifier pageMasterReference) {
+ subSequenceSpecifiers.addElement(pageMasterReference);
}
- protected SubSequenceSpecifier getSubSequenceSpecifier(int sequenceNumber)
- {
- if (sequenceNumber >=0 && sequenceNumber < getSubSequenceSpecifierCount()) {
- return (SubSequenceSpecifier)subSequenceSpecifiers.elementAt(sequenceNumber);
- }
- return null;
-
-
+ protected SubSequenceSpecifier getSubSequenceSpecifier(int sequenceNumber) {
+ if (sequenceNumber >= 0
+ && sequenceNumber < getSubSequenceSpecifierCount()) {
+ return (SubSequenceSpecifier)subSequenceSpecifiers.elementAt(sequenceNumber);
+ }
+ return null;
+
+
}
-
- protected int getSubSequenceSpecifierCount()
- {
- return subSequenceSpecifiers.size();
+
+ protected int getSubSequenceSpecifierCount() {
+ return subSequenceSpecifiers.size();
}
-
- public void reset()
- {
- for (Enumeration e = subSequenceSpecifiers.elements(); e.hasMoreElements(); ) {
- ((SubSequenceSpecifier)e.nextElement()).reset();
- }
-
+
+ public void reset() {
+ for (Enumeration e = subSequenceSpecifiers.elements();
+ e.hasMoreElements(); ) {
+ ((SubSequenceSpecifier)e.nextElement()).reset();
+ }
+
}
-
+
}
diff --git a/src/org/apache/fop/fo/pagination/Region.java b/src/org/apache/fop/fo/pagination/Region.java
index 94d11b3e7..18c2d6d15 100644
--- a/src/org/apache/fop/fo/pagination/Region.java
+++ b/src/org/apache/fop/fo/pagination/Region.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -29,35 +30,36 @@ public abstract class Region extends FObj {
// regions may have name, or default
if (null == this.properties.get(PROP_REGION_NAME)) {
setRegionName(getDefaultRegionName());
- } else if ( this.properties.get(
- PROP_REGION_NAME).getString().equals("")) {
+ } else if (this.properties.get(PROP_REGION_NAME).getString().equals("")) {
setRegionName(getDefaultRegionName());
} else {
- setRegionName(
- this.properties.get(PROP_REGION_NAME).getString());
+ setRegionName(this.properties.get(PROP_REGION_NAME).getString());
// check that name is OK. Not very pretty.
- if (isReserved(getRegionName()) &&
- !getRegionName().equals(getDefaultRegionName())) {
- throw new FOPException(PROP_REGION_NAME + " '" +
- _regionName + "' for "+this.name + " not permitted.");
+ if (isReserved(getRegionName())
+ &&!getRegionName().equals(getDefaultRegionName())) {
+ throw new FOPException(PROP_REGION_NAME + " '" + _regionName
+ + "' for " + this.name
+ + " not permitted.");
}
}
if (parent.getName().equals("fo:simple-page-master")) {
- _layoutMaster = (SimplePageMaster) parent;
+ _layoutMaster = (SimplePageMaster)parent;
getPageMaster().addRegion(this);
} else {
- throw new FOPException(getElementName() + " must be child " +
- "of simple-page-master, not " + parent.getName());
+ throw new FOPException(getElementName() + " must be child "
+ + "of simple-page-master, not "
+ + parent.getName());
}
}
/**
* Creates a Region layout object for this pagination Region.
*/
- abstract RegionArea makeRegionArea( int allocationRectangleXPosition,
- int allocationRectangleYPosition,
- int allocationRectangleWidth, int allocationRectangleHeight);
+ abstract RegionArea makeRegionArea(int allocationRectangleXPosition,
+ int allocationRectangleYPosition,
+ int allocationRectangleWidth,
+ int allocationRectangleHeight);
/**
* Returns the default region name (xsl-region-before, xsl-region-start,
@@ -96,12 +98,12 @@ public abstract class Region extends FObj {
* @return true if the name parameter is a reserved region name
*/
protected boolean isReserved(String name) throws FOPException {
- return (name.equals("xsl-region-before") ||
- name.equals("xsl-region-start") ||
- name.equals("xsl-region-end") ||
- name.equals("xsl-region-after") ||
- name.equals("xsl-before-float-separator") ||
- name.equals("xsl-footnote-separator"));
+ return (name.equals("xsl-region-before")
+ || name.equals("xsl-region-start")
+ || name.equals("xsl-region-end")
+ || name.equals("xsl-region-after")
+ || name.equals("xsl-before-float-separator")
+ || name.equals("xsl-footnote-separator"));
}
public boolean generatesReferenceAreas() {
diff --git a/src/org/apache/fop/fo/pagination/RegionAfter.java b/src/org/apache/fop/fo/pagination/RegionAfter.java
index c5d4c9e0c..39fe22d1a 100644
--- a/src/org/apache/fop/fo/pagination/RegionAfter.java
+++ b/src/org/apache/fop/fo/pagination/RegionAfter.java
@@ -1,9 +1,10 @@
-/*-- $Id$ --
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.pagination;
// FOP
@@ -15,70 +16,68 @@ import org.apache.fop.layout.BorderAndPadding;
import org.apache.fop.layout.BackgroundProps;
public class RegionAfter extends Region {
-
+
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList) throws FOPException {
- return new RegionAfter(parent,propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new RegionAfter(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new RegionAfter.Maker();
+ return new RegionAfter.Maker();
}
public static final String REGION_CLASS = "after";
-
- private int precedence;
-
- protected RegionAfter(FObj parent, PropertyList propertyList)
- throws FOPException
- {
- super(parent, propertyList);
- precedence = this.properties.get("precedence").getEnum();
+
+ private int precedence;
+
+ protected RegionAfter(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ super(parent, propertyList);
+ precedence = this.properties.get("precedence").getEnum();
}
RegionArea makeRegionArea(int allocationRectangleXPosition,
- int allocationRectangleYPosition,
- int allocationRectangleWidth,
- int allocationRectangleHeight) {
-
-// Common Border, Padding, and Background Properties
-BorderAndPadding bap = propMgr.getBorderAndPadding();
-BackgroundProps bProps = propMgr.getBackgroundProps();
-
- //this.properties.get("clip");
- //this.properties.get("display-align");
- int extent = this.properties.get("extent").getLength().mvalue();
- //this.properties.get("overflow");
- //this.properties.get("precedence");
- //this.properties.get("region-name");
- //this.properties.get("reference-orientation");
- //this.properties.get("writing-mode");
-
- return new RegionArea(allocationRectangleXPosition,
- allocationRectangleYPosition -
- allocationRectangleHeight + extent,
- allocationRectangleWidth,extent);
+ int allocationRectangleYPosition,
+ int allocationRectangleWidth,
+ int allocationRectangleHeight) {
+
+ // Common Border, Padding, and Background Properties
+ BorderAndPadding bap = propMgr.getBorderAndPadding();
+ BackgroundProps bProps = propMgr.getBackgroundProps();
+
+ // this.properties.get("clip");
+ // this.properties.get("display-align");
+ int extent = this.properties.get("extent").getLength().mvalue();
+ // this.properties.get("overflow");
+ // this.properties.get("precedence");
+ // this.properties.get("region-name");
+ // this.properties.get("reference-orientation");
+ // this.properties.get("writing-mode");
+
+ return new RegionArea(allocationRectangleXPosition,
+ allocationRectangleYPosition
+ - allocationRectangleHeight + extent,
+ allocationRectangleWidth, extent);
}
- protected String getDefaultRegionName()
- {
- return "xsl-region-after";
+ protected String getDefaultRegionName() {
+ return "xsl-region-after";
+ }
+
+ protected String getElementName() {
+ return "fo:region-after";
}
-
- protected String getElementName()
- {
- return "fo:region-after";
+
+ public String getRegionClass() {
+ return REGION_CLASS;
}
-
- public String getRegionClass()
- {
- return REGION_CLASS;
+
+ public boolean getPrecedence() {
+ return (precedence == Precedence.TRUE ? true : false);
}
- public boolean getPrecedence()
- {
- return (precedence == Precedence.TRUE ? true : false);
- }
}
diff --git a/src/org/apache/fop/fo/pagination/RegionBefore.java b/src/org/apache/fop/fo/pagination/RegionBefore.java
index 491110d07..e2bcdcf5e 100644
--- a/src/org/apache/fop/fo/pagination/RegionBefore.java
+++ b/src/org/apache/fop/fo/pagination/RegionBefore.java
@@ -1,9 +1,10 @@
-/*-- $Id$ --
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
+ * For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.pagination;
// FOP
@@ -12,73 +13,71 @@ import org.apache.fop.fo.properties.*;
import org.apache.fop.layout.RegionArea;
import org.apache.fop.layout.BorderAndPadding;
import org.apache.fop.layout.BackgroundProps;
-import org.apache.fop.apps.FOPException;
+import org.apache.fop.apps.FOPException;
public class RegionBefore extends Region {
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList) throws FOPException {
- return new RegionBefore(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new RegionBefore(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new RegionBefore.Maker();
- }
-
+ return new RegionBefore.Maker();
+ }
+
public static final String REGION_CLASS = "before";
-
- private int precedence;
-
- protected RegionBefore(FObj parent, PropertyList propertyList)
- throws FOPException
- {
- super(parent, propertyList);
- precedence = this.properties.get("precedence").getEnum();
+
+ private int precedence;
+
+ protected RegionBefore(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ super(parent, propertyList);
+ precedence = this.properties.get("precedence").getEnum();
}
-
+
RegionArea makeRegionArea(int allocationRectangleXPosition,
- int allocationRectangleYPosition,
- int allocationRectangleWidth,
- int allocationRectangleHeight) {
-
-// Common Border, Padding, and Background Properties
-BorderAndPadding bap = propMgr.getBorderAndPadding();
-BackgroundProps bProps = propMgr.getBackgroundProps();
-
- //this.properties.get("clip");
- //this.properties.get("display-align");
- int extent = this.properties.get("extent").getLength().mvalue();
- //this.properties.get("overflow");
- //this.properties.get("precedence");
- //this.properties.get("region-name");
- //this.properties.get("reference-orientation");
- //this.properties.get("writing-mode");
-
- return new RegionArea(allocationRectangleXPosition,
- allocationRectangleYPosition,
- allocationRectangleWidth, extent);
+ int allocationRectangleYPosition,
+ int allocationRectangleWidth,
+ int allocationRectangleHeight) {
+
+ // Common Border, Padding, and Background Properties
+ BorderAndPadding bap = propMgr.getBorderAndPadding();
+ BackgroundProps bProps = propMgr.getBackgroundProps();
+
+ // this.properties.get("clip");
+ // this.properties.get("display-align");
+ int extent = this.properties.get("extent").getLength().mvalue();
+ // this.properties.get("overflow");
+ // this.properties.get("precedence");
+ // this.properties.get("region-name");
+ // this.properties.get("reference-orientation");
+ // this.properties.get("writing-mode");
+
+ return new RegionArea(allocationRectangleXPosition,
+ allocationRectangleYPosition,
+ allocationRectangleWidth, extent);
}
- protected String getDefaultRegionName()
- {
- return "xsl-region-before";
+ protected String getDefaultRegionName() {
+ return "xsl-region-before";
}
-
- protected String getElementName()
- {
- return "fo:region-before";
+
+ protected String getElementName() {
+ return "fo:region-before";
+ }
+
+ public String getRegionClass() {
+ return REGION_CLASS;
}
- public String getRegionClass()
- {
- return REGION_CLASS;
+ public boolean getPrecedence() {
+ return (precedence == Precedence.TRUE ? true : false);
}
- public boolean getPrecedence()
- {
- return (precedence == Precedence.TRUE ? true : false);
- }
}
diff --git a/src/org/apache/fop/fo/pagination/RegionBody.java b/src/org/apache/fop/fo/pagination/RegionBody.java
index 187a5957c..1eae1bb70 100644
--- a/src/org/apache/fop/fo/pagination/RegionBody.java
+++ b/src/org/apache/fop/fo/pagination/RegionBody.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -21,97 +22,98 @@ import org.apache.fop.messaging.MessageHandler;
public class RegionBody extends Region {
-
+
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList) throws FOPException {
- return new RegionBody(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new RegionBody(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new RegionBody.Maker();
- }
-
+ return new RegionBody.Maker();
+ }
+
public static final String REGION_CLASS = "body";
-
+
ColorType backgroundColor;
- protected RegionBody(FObj parent, PropertyList propertyList)
- throws FOPException
- {
- super(parent, propertyList);
+ protected RegionBody(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ super(parent, propertyList);
}
-
+
RegionArea makeRegionArea(int allocationRectangleXPosition,
- int allocationRectangleYPosition,
- int allocationRectangleWidth,
- int allocationRectangleHeight) {
-
-// Common Border, Padding, and Background Properties
-BorderAndPadding bap = propMgr.getBorderAndPadding();
-BackgroundProps bProps = propMgr.getBackgroundProps();
-
-// Common Margin Properties-Block
-MarginProps mProps = propMgr.getMarginProps();
-
- //this.properties.get("clip");
- //this.properties.get("display-align");
- //this.properties.get("region-name");
- //this.properties.get("reference-orientation");
- //this.properties.get("writing-mode");
-
- this.backgroundColor = this.properties.get(
- "background-color").getColorType();
-
- BodyRegionArea body = new BodyRegionArea(allocationRectangleXPosition + mProps.marginLeft,
- allocationRectangleYPosition - mProps.marginTop,
- allocationRectangleWidth - mProps.marginLeft -
- mProps.marginRight, allocationRectangleHeight -
- mProps.marginTop - mProps.marginBottom);
-
- int overflow = this.properties.get("overflow").getEnum();
- String columnCountAsString = this.properties.get("column-count").getString();
- int columnCount = 1;
- try
- {
- columnCount = Integer.parseInt(columnCountAsString);
- }
- catch (NumberFormatException nfe)
- {
- MessageHandler.errorln("Bad value on region body 'column-count'");
- columnCount = 1;
- }
- if ((columnCount > 1) && (overflow == Overflow.SCROLL))
- {
- // recover by setting 'column-count' to 1. This is allowed but
- // not required by the spec.
- MessageHandler.errorln("Setting 'column-count' to 1 because "
- + "'overflow' is set to 'scroll'");
- columnCount = 1;
- }
- body.setColumnCount(columnCount);
-
- int columnGap = this.properties.get("column-gap").getLength().mvalue();
- body.setColumnGap(columnGap);
-
+ int allocationRectangleYPosition,
+ int allocationRectangleWidth,
+ int allocationRectangleHeight) {
+
+ // Common Border, Padding, and Background Properties
+ BorderAndPadding bap = propMgr.getBorderAndPadding();
+ BackgroundProps bProps = propMgr.getBackgroundProps();
+
+ // Common Margin Properties-Block
+ MarginProps mProps = propMgr.getMarginProps();
+
+ // this.properties.get("clip");
+ // this.properties.get("display-align");
+ // this.properties.get("region-name");
+ // this.properties.get("reference-orientation");
+ // this.properties.get("writing-mode");
+
+ this.backgroundColor =
+ this.properties.get("background-color").getColorType();
+
+ BodyRegionArea body = new BodyRegionArea(allocationRectangleXPosition
+ + mProps.marginLeft,
+ allocationRectangleYPosition
+ - mProps.marginTop,
+ allocationRectangleWidth
+ - mProps.marginLeft
+ - mProps.marginRight,
+ allocationRectangleHeight
+ - mProps.marginTop
+ - mProps.marginBottom);
+
+ int overflow = this.properties.get("overflow").getEnum();
+ String columnCountAsString =
+ this.properties.get("column-count").getString();
+ int columnCount = 1;
+ try {
+ columnCount = Integer.parseInt(columnCountAsString);
+ } catch (NumberFormatException nfe) {
+ MessageHandler.errorln("Bad value on region body 'column-count'");
+ columnCount = 1;
+ }
+ if ((columnCount > 1) && (overflow == Overflow.SCROLL)) {
+ // recover by setting 'column-count' to 1. This is allowed but
+ // not required by the spec.
+ MessageHandler.errorln("Setting 'column-count' to 1 because "
+ + "'overflow' is set to 'scroll'");
+ columnCount = 1;
+ }
+ body.setColumnCount(columnCount);
+
+ int columnGap =
+ this.properties.get("column-gap").getLength().mvalue();
+ body.setColumnGap(columnGap);
+
body.setBackgroundColor(backgroundColor);
- return body;
+ return body;
}
-
- protected String getDefaultRegionName()
- {
- return "xsl-region-body";
+
+ protected String getDefaultRegionName() {
+ return "xsl-region-body";
}
-
- protected String getElementName()
- {
- return "fo:region-body";
+
+ protected String getElementName() {
+ return "fo:region-body";
}
- public String getRegionClass()
- {
- return REGION_CLASS;
+ public String getRegionClass() {
+ return REGION_CLASS;
}
}
diff --git a/src/org/apache/fop/fo/pagination/RegionEnd.java b/src/org/apache/fop/fo/pagination/RegionEnd.java
index 110389df4..0712af5c0 100644
--- a/src/org/apache/fop/fo/pagination/RegionEnd.java
+++ b/src/org/apache/fop/fo/pagination/RegionEnd.java
@@ -1,8 +1,8 @@
-/* $Id$
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo.pagination;
@@ -13,87 +13,86 @@ import org.apache.fop.fo.properties.*;
import org.apache.fop.layout.RegionArea;
import org.apache.fop.layout.BorderAndPadding;
import org.apache.fop.layout.BackgroundProps;
-import org.apache.fop.apps.FOPException;
+import org.apache.fop.apps.FOPException;
public class RegionEnd extends Region {
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList) throws FOPException {
- return new RegionEnd(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new RegionEnd(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new RegionEnd.Maker();
- }
-
+ return new RegionEnd.Maker();
+ }
+
public static final String REGION_CLASS = "end";
-
- protected RegionEnd(FObj parent, PropertyList propertyList)
- throws FOPException
- {
- super(parent, propertyList);
+
+ protected RegionEnd(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ super(parent, propertyList);
}
-
+
RegionArea makeRegionArea(int allocationRectangleXPosition,
- int allocationRectangleYPosition,
- int allocationRectangleWidth,
- int allocationRectangleHeight,
- boolean beforePrecedence, boolean afterPrecedence,
- int beforeHeight, int afterHeight) {
- int extent = this.properties.get("extent").getLength().mvalue();
-
- int startY = allocationRectangleYPosition;
- int startH = allocationRectangleHeight;
- if (beforePrecedence)
- {
- startY -= beforeHeight;
- startH -= beforeHeight;
- }
- if (afterPrecedence)
- startH -= afterHeight;
- return new RegionArea(allocationRectangleXPosition
- + allocationRectangleWidth - extent,
- startY, extent, startH);
+ int allocationRectangleYPosition,
+ int allocationRectangleWidth,
+ int allocationRectangleHeight,
+ boolean beforePrecedence,
+ boolean afterPrecedence, int beforeHeight,
+ int afterHeight) {
+ int extent = this.properties.get("extent").getLength().mvalue();
+
+ int startY = allocationRectangleYPosition;
+ int startH = allocationRectangleHeight;
+ if (beforePrecedence) {
+ startY -= beforeHeight;
+ startH -= beforeHeight;
+ }
+ if (afterPrecedence)
+ startH -= afterHeight;
+ return new RegionArea(allocationRectangleXPosition
+ + allocationRectangleWidth - extent, startY,
+ extent, startH);
}
RegionArea makeRegionArea(int allocationRectangleXPosition,
- int allocationRectangleYPosition,
- int allocationRectangleWidth,
- int allocationRectangleHeight) {
-
-// Common Border, Padding, and Background Properties
-BorderAndPadding bap = propMgr.getBorderAndPadding();
-BackgroundProps bProps = propMgr.getBackgroundProps();
-
- //this.properties.get("clip");
- //this.properties.get("display-align");
- int extent = this.properties.get("extent").getLength().mvalue();
- //this.properties.get("overflow");
- //this.properties.get("region-name");
- //this.properties.get("reference-orientation");
- //this.properties.get("writing-mode");
-
- return makeRegionArea(allocationRectangleXPosition,
- allocationRectangleYPosition,
- allocationRectangleWidth, extent, false, false, 0, 0);
+ int allocationRectangleYPosition,
+ int allocationRectangleWidth,
+ int allocationRectangleHeight) {
+
+ // Common Border, Padding, and Background Properties
+ BorderAndPadding bap = propMgr.getBorderAndPadding();
+ BackgroundProps bProps = propMgr.getBackgroundProps();
+
+ // this.properties.get("clip");
+ // this.properties.get("display-align");
+ int extent = this.properties.get("extent").getLength().mvalue();
+ // this.properties.get("overflow");
+ // this.properties.get("region-name");
+ // this.properties.get("reference-orientation");
+ // this.properties.get("writing-mode");
+
+ return makeRegionArea(allocationRectangleXPosition,
+ allocationRectangleYPosition,
+ allocationRectangleWidth, extent, false, false,
+ 0, 0);
}
- protected String getDefaultRegionName()
- {
- return "xsl-region-end";
+ protected String getDefaultRegionName() {
+ return "xsl-region-end";
}
-
- protected String getElementName()
- {
- return "fo:region-end";
+
+ protected String getElementName() {
+ return "fo:region-end";
}
- public String getRegionClass()
- {
- return REGION_CLASS;
+ public String getRegionClass() {
+ return REGION_CLASS;
}
}
diff --git a/src/org/apache/fop/fo/pagination/RegionStart.java b/src/org/apache/fop/fo/pagination/RegionStart.java
index a039f6684..0388340ec 100644
--- a/src/org/apache/fop/fo/pagination/RegionStart.java
+++ b/src/org/apache/fop/fo/pagination/RegionStart.java
@@ -1,6 +1,7 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
+ * For details on use and redistribution please refer to the
* LICENSE file included with these sources."
*/
@@ -12,86 +13,85 @@ import org.apache.fop.fo.properties.*;
import org.apache.fop.layout.RegionArea;
import org.apache.fop.layout.BorderAndPadding;
import org.apache.fop.layout.BackgroundProps;
-import org.apache.fop.apps.FOPException;
+import org.apache.fop.apps.FOPException;
public class RegionStart extends Region {
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList) throws FOPException {
- return new RegionStart(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new RegionStart(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new RegionStart.Maker();
- }
-
+ return new RegionStart.Maker();
+ }
+
public static final String REGION_CLASS = "start";
-
- protected RegionStart(FObj parent, PropertyList propertyList)
- throws FOPException
- {
- super(parent, propertyList);
+
+ protected RegionStart(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ super(parent, propertyList);
}
-
+
RegionArea makeRegionArea(int allocationRectangleXPosition,
- int allocationRectangleYPosition,
- int allocationRectangleWidth,
- int allocationRectangleHeight,
- boolean beforePrecedence, boolean afterPrecedence,
- int beforeHeight, int afterHeight) {
- int extent = this.properties.get("extent").getLength().mvalue();
-
- int startY = allocationRectangleYPosition;
- int startH = allocationRectangleHeight;
- if (beforePrecedence)
- {
- startY -= beforeHeight;
- startH -= beforeHeight;
- }
- if (afterPrecedence)
- startH -= afterHeight;
- return new RegionArea(allocationRectangleXPosition,
- startY, extent, startH);
+ int allocationRectangleYPosition,
+ int allocationRectangleWidth,
+ int allocationRectangleHeight,
+ boolean beforePrecedence,
+ boolean afterPrecedence, int beforeHeight,
+ int afterHeight) {
+ int extent = this.properties.get("extent").getLength().mvalue();
+
+ int startY = allocationRectangleYPosition;
+ int startH = allocationRectangleHeight;
+ if (beforePrecedence) {
+ startY -= beforeHeight;
+ startH -= beforeHeight;
+ }
+ if (afterPrecedence)
+ startH -= afterHeight;
+ return new RegionArea(allocationRectangleXPosition, startY, extent,
+ startH);
}
RegionArea makeRegionArea(int allocationRectangleXPosition,
- int allocationRectangleYPosition,
- int allocationRectangleWidth,
- int allocationRectangleHeight) {
-
-// Common Border, Padding, and Background Properties
-BorderAndPadding bap = propMgr.getBorderAndPadding();
-BackgroundProps bProps = propMgr.getBackgroundProps();
-
- //this.properties.get("clip");
- //this.properties.get("display-align");
- int extent = this.properties.get("extent").getLength().mvalue();
- //this.properties.get("overflow");
- //this.properties.get("region-name");
- //this.properties.get("reference-orientation");
- //this.properties.get("writing-mode");
-
- return makeRegionArea(allocationRectangleXPosition,
- allocationRectangleYPosition,
- allocationRectangleWidth, extent, false, false, 0, 0);
+ int allocationRectangleYPosition,
+ int allocationRectangleWidth,
+ int allocationRectangleHeight) {
+
+ // Common Border, Padding, and Background Properties
+ BorderAndPadding bap = propMgr.getBorderAndPadding();
+ BackgroundProps bProps = propMgr.getBackgroundProps();
+
+ // this.properties.get("clip");
+ // this.properties.get("display-align");
+ int extent = this.properties.get("extent").getLength().mvalue();
+ // this.properties.get("overflow");
+ // this.properties.get("region-name");
+ // this.properties.get("reference-orientation");
+ // this.properties.get("writing-mode");
+
+ return makeRegionArea(allocationRectangleXPosition,
+ allocationRectangleYPosition,
+ allocationRectangleWidth, extent, false, false,
+ 0, 0);
}
- protected String getDefaultRegionName()
- {
- return "xsl-region-start";
+ protected String getDefaultRegionName() {
+ return "xsl-region-start";
}
-
- protected String getElementName()
- {
- return "fo:region-start";
+
+ protected String getElementName() {
+ return "fo:region-start";
}
- public String getRegionClass()
- {
- return REGION_CLASS;
+ public String getRegionClass() {
+ return REGION_CLASS;
}
}
diff --git a/src/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java b/src/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java
index 9ef099b88..c7eded73f 100644
--- a/src/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java
+++ b/src/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java
@@ -1,179 +1,129 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.pagination;
import org.apache.fop.fo.*;
-import org.apache.fop.apps.FOPException;
+import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;
// Java
import java.util.Vector;
public class RepeatablePageMasterAlternatives extends FObj
- implements SubSequenceSpecifier {
-
+ implements SubSequenceSpecifier {
+
private static final int INFINITE = -1;
-
+
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new RepeatablePageMasterAlternatives(parent,propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new RepeatablePageMasterAlternatives(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new RepeatablePageMasterAlternatives.Maker();
+ return new RepeatablePageMasterAlternatives.Maker();
}
- private PageSequenceMaster pageSequenceMaster;
-
+ private PageSequenceMaster pageSequenceMaster;
+
/**
* Max times this page master can be repeated.
- * INFINITE is used for the unbounded case */
+ * INFINITE is used for the unbounded case
+ */
private int maximumRepeats;
private int numberConsumed = 0;
-
+
private Vector conditionalPageMasterRefs;
public RepeatablePageMasterAlternatives(FObj parent, PropertyList propertyList)
- throws FOPException {
- super(parent, propertyList);
- this.name = "fo:repeatable-page-master-alternatives";
-
- conditionalPageMasterRefs = new Vector();
-
- if (parent.getName().equals("fo:page-sequence-master")) {
- this.pageSequenceMaster = (PageSequenceMaster) parent;
- this.pageSequenceMaster.addSubsequenceSpecifier(this);
- } else {
- throw new FOPException("fo:repeatable-page-master-alternatives" +
- "must be child of fo:page-sequence-master, not " +
- parent.getName());
- }
-
- String mr = getProperty("maximum-repeats").getString();
- if (mr.equals("no-limit")) {
- setMaximumRepeats(INFINITE);
- }
- else {
- try {
- setMaximumRepeats( Integer.parseInt( mr ) );
- } catch (NumberFormatException nfe) {
- throw new FOPException( "Invalid number for " +
- "'maximum-repeats' property" );
- }
- }
+ throws FOPException {
+ super(parent, propertyList);
+ this.name = "fo:repeatable-page-master-alternatives";
+
+ conditionalPageMasterRefs = new Vector();
+
+ if (parent.getName().equals("fo:page-sequence-master")) {
+ this.pageSequenceMaster = (PageSequenceMaster)parent;
+ this.pageSequenceMaster.addSubsequenceSpecifier(this);
+ } else {
+ throw new FOPException("fo:repeatable-page-master-alternatives"
+ + "must be child of fo:page-sequence-master, not "
+ + parent.getName());
+ }
+
+ String mr = getProperty("maximum-repeats").getString();
+ if (mr.equals("no-limit")) {
+ setMaximumRepeats(INFINITE);
+ } else {
+ try {
+ setMaximumRepeats(Integer.parseInt(mr));
+ } catch (NumberFormatException nfe) {
+ throw new FOPException("Invalid number for "
+ + "'maximum-repeats' property");
+ }
+ }
+
+ }
+ public String getNextPageMaster(int currentPageNumber,
+ boolean thisIsFirstPage,
+ boolean isEmptyPage) {
+ String pm = null;
+
+ if (getMaximumRepeats() != INFINITE) {
+ if (numberConsumed < getMaximumRepeats()) {
+ numberConsumed++;
+ } else {
+ return null;
+ }
+ }
+
+ for (int i = 0; i < conditionalPageMasterRefs.size(); i++) {
+ ConditionalPageMasterReference cpmr =
+ (ConditionalPageMasterReference)conditionalPageMasterRefs.elementAt(i);
+
+ // 0-indexed page number
+ if (cpmr.isValid(currentPageNumber + 1, thisIsFirstPage,
+ isEmptyPage)) {
+ pm = cpmr.getMasterName();
+ break;
+ }
+ }
+ return pm;
}
-
- public String getNextPageMaster( int currentPageNumber,
- boolean thisIsFirstPage,
- boolean isEmptyPage ) {
- String pm = null;
-
- if (getMaximumRepeats() != INFINITE ) {
- if (numberConsumed < getMaximumRepeats()) {
- numberConsumed++;
- } else {
- return null;
- }
- }
-
- for (int i = 0; i < conditionalPageMasterRefs.size(); i++)
- {
- ConditionalPageMasterReference cpmr =
- (ConditionalPageMasterReference)conditionalPageMasterRefs.elementAt(i);
-
- // 0-indexed page number
- if (cpmr.isValid(currentPageNumber + 1, thisIsFirstPage,isEmptyPage))
- {
- pm = cpmr.getMasterName();
- break;
- }
- }
- return pm;
+
+ private void setMaximumRepeats(int maximumRepeats) {
+ if (maximumRepeats == INFINITE) {
+ this.maximumRepeats = maximumRepeats;
+ } else {
+ this.maximumRepeats = (maximumRepeats < 0) ? 0 : maximumRepeats;
+ }
+
+ }
+
+ private int getMaximumRepeats() {
+ return this.maximumRepeats;
}
- private void setMaximumRepeats( int maximumRepeats)
- {
- if (maximumRepeats == INFINITE) {
- this.maximumRepeats = maximumRepeats;
- }
- else {
- this.maximumRepeats =
- (maximumRepeats < 0) ? 0 : maximumRepeats;
- }
-
- }
-
- private int getMaximumRepeats()
- {
- return this.maximumRepeats;
- }
-
- public void addConditionalPageMasterReference(
- ConditionalPageMasterReference cpmr)
- {
- this.conditionalPageMasterRefs.addElement( cpmr );
- }
-
- public void reset()
- {
- this.numberConsumed = 0;
+ public void addConditionalPageMasterReference(ConditionalPageMasterReference cpmr) {
+ this.conditionalPageMasterRefs.addElement(cpmr);
}
-
- protected PageSequenceMaster getPageSequenceMaster()
- {
- return pageSequenceMaster;
+ public void reset() {
+ this.numberConsumed = 0;
}
+
+
+ protected PageSequenceMaster getPageSequenceMaster() {
+ return pageSequenceMaster;
+ }
+
}
diff --git a/src/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java b/src/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java
index 098832f66..85abf8039 100644
--- a/src/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java
+++ b/src/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java
@@ -1,139 +1,89 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fo.pagination;
import org.apache.fop.fo.*;
-import org.apache.fop.apps.FOPException;
+import org.apache.fop.apps.FOPException;
public class RepeatablePageMasterReference extends PageMasterReference
- implements SubSequenceSpecifier {
-
- private static final int INFINITE = -1;
+ implements SubSequenceSpecifier {
+
+ private static final int INFINITE = -1;
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new RepeatablePageMasterReference(parent,propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new RepeatablePageMasterReference(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new RepeatablePageMasterReference.Maker();
+ return new RepeatablePageMasterReference.Maker();
}
-
+
private PageSequenceMaster pageSequenceMaster;
-
+
private int maximumRepeats;
private int numberConsumed = 0;
public RepeatablePageMasterReference(FObj parent, PropertyList propertyList)
- throws FOPException {
- super(parent, propertyList);
-
- String mr = getProperty("maximum-repeats").getString();
- if (mr.equals("no-limit"))
- {
- setMaximumRepeats(INFINITE);
- }
- else {
- try {
- setMaximumRepeats( Integer.parseInt( mr ) );
- } catch (NumberFormatException nfe) {
- throw new FOPException( "Invalid number for " +
- "'maximum-repeats' property" );
- }
- }
+ throws FOPException {
+ super(parent, propertyList);
+
+ String mr = getProperty("maximum-repeats").getString();
+ if (mr.equals("no-limit")) {
+ setMaximumRepeats(INFINITE);
+ } else {
+ try {
+ setMaximumRepeats(Integer.parseInt(mr));
+ } catch (NumberFormatException nfe) {
+ throw new FOPException("Invalid number for "
+ + "'maximum-repeats' property");
+ }
+ }
+
+ }
+ public String getNextPageMaster(int currentPageNumber,
+ boolean thisIsFirstPage,
+ boolean isEmptyPage) {
+ String pm = getMasterName();
+
+ if (getMaximumRepeats() != INFINITE) {
+ if (numberConsumed < getMaximumRepeats()) {
+ numberConsumed++;
+ } else {
+ pm = null;
+ }
+ }
+ return pm;
+ }
+
+ private void setMaximumRepeats(int maximumRepeats) {
+ if (maximumRepeats == INFINITE) {
+ this.maximumRepeats = maximumRepeats;
+ } else {
+ this.maximumRepeats = (maximumRepeats < 0) ? 0 : maximumRepeats;
+ }
+ }
+
+ private int getMaximumRepeats() {
+ return this.maximumRepeats;
}
-
- public String getNextPageMaster( int currentPageNumber,
- boolean thisIsFirstPage,
- boolean isEmptyPage ) {
- String pm = getMasterName();
-
- if (getMaximumRepeats() != INFINITE ) {
- if (numberConsumed < getMaximumRepeats()) {
- numberConsumed++;
- } else {
- pm = null;
- }
- }
- return pm;
- }
-
- private void setMaximumRepeats( int maximumRepeats)
- {
- if (maximumRepeats == INFINITE) {
- this.maximumRepeats = maximumRepeats;
- }
- else {
- this.maximumRepeats =
- (maximumRepeats < 0) ? 0 : maximumRepeats;
- }
- }
-
- private int getMaximumRepeats()
- {
- return this.maximumRepeats;
- }
-
- protected String getElementName()
- {
- return "fo:repeatable-page-master-reference";
+
+ protected String getElementName() {
+ return "fo:repeatable-page-master-reference";
}
-
- public void reset()
- {
- this.numberConsumed = 0;
+
+ public void reset() {
+ this.numberConsumed = 0;
}
-
+
}
diff --git a/src/org/apache/fop/fo/pagination/Root.java b/src/org/apache/fop/fo/pagination/Root.java
index 9daa6da89..e98d8f1c5 100644
--- a/src/org/apache/fop/fo/pagination/Root.java
+++ b/src/org/apache/fop/fo/pagination/Root.java
@@ -1,4 +1,5 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -30,6 +31,7 @@ public class Root extends FObj {
PropertyList propertyList) throws FOPException {
return new Root(parent, propertyList);
}
+
}
public static FObj.Maker maker() {
@@ -39,7 +41,9 @@ public class Root extends FObj {
LayoutMasterSet layoutMasterSet;
Vector pageSequences;
- /** keeps count of page number from over PageSequence instances*/
+ /**
+ * keeps count of page number from over PageSequence instances
+ */
private int runningPageNumberCounter = 0;
protected Root(FObj parent,
@@ -47,10 +51,10 @@ public class Root extends FObj {
super(parent, propertyList);
this.name = "fo:root";
- //this.properties.get("media-usage");
+ // this.properties.get("media-usage");
pageSequences = new Vector();
-
+
if (parent != null) {
throw new FOPException("root must be root element");
}
@@ -64,31 +68,33 @@ public class Root extends FObj {
this.runningPageNumberCounter = count;
}
- /** @deprecated handled by addChild now
+ /**
+ * @deprecated handled by addChild now
*/
public void addPageSequence(PageSequence pageSequence) {
this.pageSequences.addElement(pageSequence);
}
- public int getPageSequenceCount() {
- return pageSequences.size();
- }
-
- /**
- * Some properties, such as 'force-page-count', require a
- * page-sequence to know about some properties of the next.
- * @returns succeeding PageSequence; null if none
- */
- public PageSequence getSucceedingPageSequence(PageSequence current) {
- int currentIndex = pageSequences.indexOf(current);
- if (currentIndex == -1) return null;
- if (currentIndex < (pageSequences.size()-1)) {
- return (PageSequence)pageSequences.elementAt(currentIndex+1);
- } else {
- return null;
- }
- }
-
+ public int getPageSequenceCount() {
+ return pageSequences.size();
+ }
+
+ /**
+ * Some properties, such as 'force-page-count', require a
+ * page-sequence to know about some properties of the next.
+ * @returns succeeding PageSequence; null if none
+ */
+ public PageSequence getSucceedingPageSequence(PageSequence current) {
+ int currentIndex = pageSequences.indexOf(current);
+ if (currentIndex == -1)
+ return null;
+ if (currentIndex < (pageSequences.size() - 1)) {
+ return (PageSequence)pageSequences.elementAt(currentIndex + 1);
+ } else {
+ return null;
+ }
+ }
+
public LayoutMasterSet getLayoutMasterSet() {
return this.layoutMasterSet;
}
@@ -98,7 +104,7 @@ public class Root extends FObj {
}
public void format(AreaTree areaTree) throws FOPException {
- // MessageHandler.errorln(" Root[" + marker + "] ");
+ // MessageHandler.errorln(" Root[" + marker + "] ");
if (layoutMasterSet == null) {
throw new FOPException("No layout master set.");
}
@@ -107,10 +113,11 @@ public class Root extends FObj {
while (e.hasMoreElements()) {
Object o = e.nextElement();
if (o instanceof PageSequence) {
- ((PageSequence) o).format(areaTree);
+ ((PageSequence)o).format(areaTree);
} else if (o instanceof ExtensionObj) {
- ((ExtensionObj) o).format(areaTree);
+ ((ExtensionObj)o).format(areaTree);
}
}
}
+
}
diff --git a/src/org/apache/fop/fo/pagination/SimplePageMaster.java b/src/org/apache/fop/fo/pagination/SimplePageMaster.java
index 2a5642d90..fed72e95c 100644
--- a/src/org/apache/fop/fo/pagination/SimplePageMaster.java
+++ b/src/org/apache/fop/fo/pagination/SimplePageMaster.java
@@ -1,7 +1,8 @@
-/*-- $Id$ --
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo.pagination;
@@ -14,174 +15,180 @@ import org.apache.fop.layout.PageMaster;
import org.apache.fop.layout.RegionArea;
import org.apache.fop.layout.BodyRegionArea;
import org.apache.fop.layout.MarginProps;
-import org.apache.fop.apps.FOPException;
+import org.apache.fop.apps.FOPException;
import java.util.*;
public class SimplePageMaster extends FObj {
-
+
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new SimplePageMaster(parent, propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new SimplePageMaster(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new SimplePageMaster.Maker();
+ return new SimplePageMaster.Maker();
}
- /** Page regions (regionClass, Region) */
+ /**
+ * Page regions (regionClass, Region)
+ */
private Hashtable _regions;
-
+
LayoutMasterSet layoutMasterSet;
PageMaster pageMaster;
String masterName;
- // before and after data as required by start and end
- boolean beforePrecedence;
- int beforeHeight;
- boolean afterPrecedence;
- int afterHeight;
-
+ // before and after data as required by start and end
+ boolean beforePrecedence;
+ int beforeHeight;
+ boolean afterPrecedence;
+ int afterHeight;
+
protected SimplePageMaster(FObj parent, PropertyList propertyList)
- throws FOPException {
- super(parent, propertyList);
- this.name = "fo:simple-page-master";
-
- if (parent.getName().equals("fo:layout-master-set")) {
- this.layoutMasterSet = (LayoutMasterSet) parent;
- masterName = this.properties.get("master-name").getString();
- if (masterName == null) {
- MessageHandler.errorln("WARNING: simple-page-master does not have "
- + "a master-name and so is being ignored");
- } else {
- this.layoutMasterSet.addSimplePageMaster(this);
- }
- } else {
- throw new FOPException("fo:simple-page-master must be child "
- + "of fo:layout-master-set, not "
- + parent.getName());
- }
- _regions = new Hashtable();
-
+ throws FOPException {
+ super(parent, propertyList);
+ this.name = "fo:simple-page-master";
+
+ if (parent.getName().equals("fo:layout-master-set")) {
+ this.layoutMasterSet = (LayoutMasterSet)parent;
+ masterName = this.properties.get("master-name").getString();
+ if (masterName == null) {
+ MessageHandler.errorln("WARNING: simple-page-master does not have "
+ + "a master-name and so is being ignored");
+ } else {
+ this.layoutMasterSet.addSimplePageMaster(this);
+ }
+ } else {
+ throw new FOPException("fo:simple-page-master must be child "
+ + "of fo:layout-master-set, not "
+ + parent.getName());
+ }
+ _regions = new Hashtable();
+
}
-
+
protected void end() {
- int pageWidth = this.properties.get("page-width").getLength().mvalue();
- int pageHeight = this.properties.get("page-height").getLength().mvalue();
- //this.properties.get("reference-orientation");
- //this.properties.get("writing-mode");
-
-// Common Margin Properties-Block
-MarginProps mProps = propMgr.getMarginProps();
-
- int contentRectangleXPosition = mProps.marginLeft;
- int contentRectangleYPosition = pageHeight - mProps.marginTop;
- int contentRectangleWidth = pageWidth - mProps.marginLeft - mProps.marginRight;
- int contentRectangleHeight = pageHeight - mProps.marginTop - mProps.marginBottom;
-
- this.pageMaster = new PageMaster(pageWidth, pageHeight);
- if (getRegion(RegionBody.REGION_CLASS) != null) {
- BodyRegionArea body =
- (BodyRegionArea)getRegion(RegionBody.REGION_CLASS).makeRegionArea(contentRectangleXPosition,
- contentRectangleYPosition,contentRectangleWidth,contentRectangleHeight);
- this.pageMaster.addBody(body);
- }
- else {
- MessageHandler.errorln("ERROR: simple-page-master must have a region of class "+RegionBody.REGION_CLASS);
- }
-
- if (getRegion(RegionBefore.REGION_CLASS) != null) {
- RegionArea before =
- getRegion(RegionBefore.REGION_CLASS).makeRegionArea(contentRectangleXPosition,
- contentRectangleYPosition,contentRectangleWidth,contentRectangleHeight);
- this.pageMaster.addBefore(before);
- beforePrecedence = ((RegionBefore)getRegion(RegionBefore.REGION_CLASS)).getPrecedence();
- beforeHeight = before.getHeight();
- }
- else {
- beforePrecedence = false;
- }
-
- if (getRegion(RegionAfter.REGION_CLASS) != null) {
- RegionArea after =
- getRegion(RegionAfter.REGION_CLASS).makeRegionArea(contentRectangleXPosition,
- contentRectangleYPosition,contentRectangleWidth,contentRectangleHeight);
- this.pageMaster.addAfter(after);
- afterPrecedence = ((RegionAfter)getRegion(RegionAfter.REGION_CLASS)).getPrecedence();
- afterHeight = after.getHeight();
- }
- else {
- afterPrecedence = false;
- }
-
- if (getRegion(RegionStart.REGION_CLASS) != null) {
- RegionArea start =
- ((RegionStart)getRegion(RegionStart.REGION_CLASS)).makeRegionArea(
- contentRectangleXPosition,
- contentRectangleYPosition,contentRectangleWidth,contentRectangleHeight,
- beforePrecedence, afterPrecedence, beforeHeight, afterHeight);
- this.pageMaster.addStart(start);
- }
-
- if (getRegion(RegionEnd.REGION_CLASS) != null) {
- RegionArea end =
- ((RegionEnd)getRegion(RegionEnd.REGION_CLASS)).makeRegionArea(
- contentRectangleXPosition,
- contentRectangleYPosition,contentRectangleWidth,contentRectangleHeight,
- beforePrecedence, afterPrecedence, beforeHeight, afterHeight);
- this.pageMaster.addEnd(end);
- }
+ int pageWidth =
+ this.properties.get("page-width").getLength().mvalue();
+ int pageHeight =
+ this.properties.get("page-height").getLength().mvalue();
+ // this.properties.get("reference-orientation");
+ // this.properties.get("writing-mode");
+
+ // Common Margin Properties-Block
+ MarginProps mProps = propMgr.getMarginProps();
+
+ int contentRectangleXPosition = mProps.marginLeft;
+ int contentRectangleYPosition = pageHeight - mProps.marginTop;
+ int contentRectangleWidth = pageWidth - mProps.marginLeft
+ - mProps.marginRight;
+ int contentRectangleHeight = pageHeight - mProps.marginTop
+ - mProps.marginBottom;
+
+ this.pageMaster = new PageMaster(pageWidth, pageHeight);
+ if (getRegion(RegionBody.REGION_CLASS) != null) {
+ BodyRegionArea body =
+ (BodyRegionArea)getRegion(RegionBody.REGION_CLASS).makeRegionArea(contentRectangleXPosition,
+ contentRectangleYPosition,
+ contentRectangleWidth,
+ contentRectangleHeight);
+ this.pageMaster.addBody(body);
+ } else {
+ MessageHandler.errorln("ERROR: simple-page-master must have a region of class "
+ + RegionBody.REGION_CLASS);
+ }
+
+ if (getRegion(RegionBefore.REGION_CLASS) != null) {
+ RegionArea before =
+ getRegion(RegionBefore.REGION_CLASS).makeRegionArea(contentRectangleXPosition,
+ contentRectangleYPosition, contentRectangleWidth,
+ contentRectangleHeight);
+ this.pageMaster.addBefore(before);
+ beforePrecedence =
+ ((RegionBefore)getRegion(RegionBefore.REGION_CLASS)).getPrecedence();
+ beforeHeight = before.getHeight();
+ } else {
+ beforePrecedence = false;
+ }
+
+ if (getRegion(RegionAfter.REGION_CLASS) != null) {
+ RegionArea after =
+ getRegion(RegionAfter.REGION_CLASS).makeRegionArea(contentRectangleXPosition,
+ contentRectangleYPosition, contentRectangleWidth,
+ contentRectangleHeight);
+ this.pageMaster.addAfter(after);
+ afterPrecedence =
+ ((RegionAfter)getRegion(RegionAfter.REGION_CLASS)).getPrecedence();
+ afterHeight = after.getHeight();
+ } else {
+ afterPrecedence = false;
+ }
+
+ if (getRegion(RegionStart.REGION_CLASS) != null) {
+ RegionArea start =
+ ((RegionStart)getRegion(RegionStart.REGION_CLASS)).makeRegionArea(contentRectangleXPosition,
+ contentRectangleYPosition, contentRectangleWidth,
+ contentRectangleHeight, beforePrecedence,
+ afterPrecedence, beforeHeight, afterHeight);
+ this.pageMaster.addStart(start);
+ }
+
+ if (getRegion(RegionEnd.REGION_CLASS) != null) {
+ RegionArea end =
+ ((RegionEnd)getRegion(RegionEnd.REGION_CLASS)).makeRegionArea(contentRectangleXPosition,
+ contentRectangleYPosition, contentRectangleWidth,
+ contentRectangleHeight, beforePrecedence,
+ afterPrecedence, beforeHeight, afterHeight);
+ this.pageMaster.addEnd(end);
+ }
}
public PageMaster getPageMaster() {
- return this.pageMaster;
+ return this.pageMaster;
}
public PageMaster getNextPageMaster() {
- return this.pageMaster;
+ return this.pageMaster;
}
- public String getMasterName()
- {
- return masterName;
+ public String getMasterName() {
+ return masterName;
}
-
-
- protected void addRegion(Region region)
- throws FOPException
- {
- if (_regions.containsKey(region.getRegionClass())) {
- throw new FOPException("Only one region of class "+region.getRegionClass()
- +" allowed within a simple-page-master.");
- }
- else {
- _regions.put(region.getRegionClass(), region);
- }
+
+
+ protected void addRegion(Region region) throws FOPException {
+ if (_regions.containsKey(region.getRegionClass())) {
+ throw new FOPException("Only one region of class "
+ + region.getRegionClass()
+ + " allowed within a simple-page-master.");
+ } else {
+ _regions.put(region.getRegionClass(), region);
+ }
}
-
- protected Region getRegion(String regionClass)
- {
- return (Region)_regions.get(regionClass);
+
+ protected Region getRegion(String regionClass) {
+ return (Region)_regions.get(regionClass);
}
- protected Hashtable getRegions()
- {
- return _regions;
+ protected Hashtable getRegions() {
+ return _regions;
}
-
- protected boolean regionNameExists(String regionName)
- {
- for (Enumeration regenum = _regions.elements(); regenum.hasMoreElements() ;) {
- Region r = (Region)regenum.nextElement();
- if (r.getRegionName().equals(regionName)) {
- return true;
- }
- }
- return false;
-
+
+ protected boolean regionNameExists(String regionName) {
+ for (Enumeration regenum = _regions.elements();
+ regenum.hasMoreElements(); ) {
+ Region r = (Region)regenum.nextElement();
+ if (r.getRegionName().equals(regionName)) {
+ return true;
+ }
+ }
+ return false;
+
}
-
+
}
diff --git a/src/org/apache/fop/fo/pagination/SinglePageMasterReference.java b/src/org/apache/fop/fo/pagination/SinglePageMasterReference.java
index 5f05b0d70..315107cf3 100644
--- a/src/org/apache/fop/fo/pagination/SinglePageMasterReference.java
+++ b/src/org/apache/fop/fo/pagination/SinglePageMasterReference.java
@@ -1,108 +1,62 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fo.pagination;
import org.apache.fop.fo.*;
-import org.apache.fop.apps.FOPException;
+import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;
public class SinglePageMasterReference extends PageMasterReference
- implements SubSequenceSpecifier {
-
+ implements SubSequenceSpecifier {
+
public static class Maker extends FObj.Maker {
- public FObj make(FObj parent, PropertyList propertyList)
- throws FOPException {
- return new SinglePageMasterReference(parent,propertyList);
- }
+ public FObj make(FObj parent,
+ PropertyList propertyList) throws FOPException {
+ return new SinglePageMasterReference(parent, propertyList);
+ }
+
}
public static FObj.Maker maker() {
- return new SinglePageMasterReference.Maker();
+ return new SinglePageMasterReference.Maker();
}
-
+
private static final int FIRST = 0;
private static final int DONE = 1;
-
+
private int state;
public SinglePageMasterReference(FObj parent, PropertyList propertyList)
- throws FOPException {
- super(parent, propertyList);
- this.state = FIRST;
-
+ throws FOPException {
+ super(parent, propertyList);
+ this.state = FIRST;
+
}
-
- public String getNextPageMaster( int currentPageNumber,
- boolean thisIsFirstPage,
- boolean isEmptyPage) {
- if (this.state == FIRST) {
- this.state = DONE;
- return getMasterName();
- }
- else {
- return null;
- }
-
+
+ public String getNextPageMaster(int currentPageNumber,
+ boolean thisIsFirstPage,
+ boolean isEmptyPage) {
+ if (this.state == FIRST) {
+ this.state = DONE;
+ return getMasterName();
+ } else {
+ return null;
+ }
+
}
- public void reset()
- {
- this.state = FIRST;
+ public void reset() {
+ this.state = FIRST;
}
-
- protected String getElementName()
- {
- return "fo:single-page-master-reference";
+
+ protected String getElementName() {
+ return "fo:single-page-master-reference";
}
-
-
+
+
}
diff --git a/src/org/apache/fop/fo/pagination/SubSequenceSpecifier.java b/src/org/apache/fop/fo/pagination/SubSequenceSpecifier.java
index 0e4828bc0..e8507fa8d 100644
--- a/src/org/apache/fop/fo/pagination/SubSequenceSpecifier.java
+++ b/src/org/apache/fop/fo/pagination/SubSequenceSpecifier.java
@@ -1,64 +1,23 @@
/*
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
-
+
package org.apache.fop.fo.pagination;
-/** Classes that implement this interface can be added to a PageSequenceMaster,
+/**
+ * Classes that implement this interface can be added to a PageSequenceMaster,
* and are capable of looking up an appropriate PageMaster.
*/
-public interface SubSequenceSpecifier
-{
- public String getNextPageMaster( int currentPageNumber,
- boolean thisIsFirstPage, boolean isEmptyPage);
+public interface SubSequenceSpecifier {
+ public String getNextPageMaster(int currentPageNumber,
+ boolean thisIsFirstPage,
+ boolean isEmptyPage);
+
/**
- * Called before a new page sequence is rendered so subsequences can reset
+ * Called before a new page sequence is rendered so subsequences can reset
* any state they keep during the formatting process.
*/
public void reset();
diff --git a/src/org/apache/fop/fonts/FontFileReader.java b/src/org/apache/fop/fonts/FontFileReader.java
index e6c7ce859..bcc2074d0 100644
--- a/src/org/apache/fop/fonts/FontFileReader.java
+++ b/src/org/apache/fop/fonts/FontFileReader.java
@@ -1,29 +1,32 @@
-/* -- $Id$ --
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fonts;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.File;
import java.io.IOException;
-/** Reads a file into an array and
- provides file like functions for array access.
-*/
+/**
+ * Reads a file into an array and
+ * provides file like functions for array access.
+ */
public class FontFileReader {
- private int fsize; // file size
- private int current; // current position in file
+ private int fsize; // file size
+ private int current; // current position in file
private byte[] file;
+
/**
* Initialisez class and reads stream. Init does not close stream
* @param stream InputStream to read from
* @param start initial size av array to read to
* @param inc if initial size isn't enough, create
- new array with size + inc
- */
+ * new array with size + inc
+ */
private void init(InputStream stream, int start,
int inc) throws java.io.IOException {
fsize = 0;
@@ -45,7 +48,7 @@ public class FontFileReader {
fsize += l;
file = tmpbuf;
- if (l < inc)// whole file read. No need to loop again
+ if (l < inc) // whole file read. No need to loop again
l = 0;
@@ -54,9 +57,9 @@ public class FontFileReader {
}
/**
- * Constructor
- * @param fileName filename to read
- */
+ * Constructor
+ * @param fileName filename to read
+ */
public FontFileReader(String fileName) throws java.io.IOException {
// Get estimates for file size and increment
@@ -67,15 +70,19 @@ public class FontFileReader {
}
- /** Set current file position to offset */
+ /**
+ * Set current file position to offset
+ */
public void seek_set(long offset) throws IOException {
if (offset > fsize || offset < 0)
- throw new java.io.EOFException("Reached EOF, file size="+
- fsize + " offset="+offset);
- current = (int) offset;
+ throw new java.io.EOFException("Reached EOF, file size=" + fsize
+ + " offset=" + offset);
+ current = (int)offset;
}
- /** Set current file position to offset */
+ /**
+ * Set current file position to offset
+ */
public void seek_add(long add) throws IOException {
seek_set(current + add);
}
@@ -84,7 +91,9 @@ public class FontFileReader {
seek_add(add);
}
- /** return current file position */
+ /**
+ * return current file position
+ */
public int getCurrentPos() {
return current;
}
@@ -94,11 +103,12 @@ public class FontFileReader {
}
- /** Read 1 byte, throws EOFException on end of file */
+ /**
+ * Read 1 byte, throws EOFException on end of file
+ */
public byte read() throws IOException {
if (current > fsize)
- throw new java.io.EOFException("Reached EOF, file size="+
- fsize);
+ throw new java.io.EOFException("Reached EOF, file size=" + fsize);
byte ret = file[current++];
return ret;
@@ -106,39 +116,47 @@ public class FontFileReader {
- /** Read 1 signed byte from InputStream */
+ /**
+ * Read 1 signed byte from InputStream
+ */
public final byte readTTFByte() throws IOException {
return read();
}
- /** Read 1 unsigned byte from InputStream */
+ /**
+ * Read 1 unsigned byte from InputStream
+ */
public final int readTTFUByte() throws IOException {
byte buf = read();
if (buf < 0)
return (int)(256 + buf);
else
- return (int) buf;
+ return (int)buf;
}
- /** Read 2 bytes signed from InputStream */
+ /**
+ * Read 2 bytes signed from InputStream
+ */
public final short readTTFShort() throws IOException {
int ret = (readTTFUByte() << 8) + readTTFUByte();
- short sret = (short) ret;
+ short sret = (short)ret;
return sret;
}
- /** Read 2 bytes unsigned from InputStream */
+ /**
+ * Read 2 bytes unsigned from InputStream
+ */
public final int readTTFUShort() throws IOException {
int ret = (readTTFUByte() << 8) + readTTFUByte();
- return (int) ret;
+ return (int)ret;
}
/**
- * Write a USHort at a given position
- */
+ * Write a USHort at a given position
+ */
public final void writeTTFUShort(int pos, int val) throws IOException {
if ((pos + 2) > fsize)
throw new java.io.EOFException("Reached EOF");
@@ -148,8 +166,10 @@ public class FontFileReader {
file[pos + 1] = b2;
}
- /** Read 2 bytes signed from InputStream at position pos
- without changing current position */
+ /**
+ * Read 2 bytes signed from InputStream at position pos
+ * without changing current position
+ */
public final short readTTFShort(long pos) throws IOException {
long cp = getCurrentPos();
seek_set(pos);
@@ -158,8 +178,10 @@ public class FontFileReader {
return ret;
}
- /** Read 2 bytes unsigned from InputStream at position pos
- without changing current position */
+ /**
+ * Read 2 bytes unsigned from InputStream at position pos
+ * without changing current position
+ */
public final int readTTFUShort(long pos) throws IOException {
long cp = getCurrentPos();
seek_set(pos);
@@ -168,17 +190,21 @@ public class FontFileReader {
return ret;
}
- /** Read 4 bytes from InputStream */
+ /**
+ * Read 4 bytes from InputStream
+ */
public final int readTTFLong() throws IOException {
- long ret = readTTFUByte();// << 8;
+ long ret = readTTFUByte(); // << 8;
ret = (ret << 8) + readTTFUByte();
ret = (ret << 8) + readTTFUByte();
ret = (ret << 8) + readTTFUByte();
- return (int) ret;
+ return (int)ret;
}
- /** Read 4 bytes from InputStream */
+ /**
+ * Read 4 bytes from InputStream
+ */
public final long readTTFULong() throws IOException {
long ret = readTTFUByte();
ret = (ret << 8) + readTTFUByte();
@@ -188,13 +214,15 @@ public class FontFileReader {
return ret;
}
- /** Read a 0 terminatet ISO-8859-1 string */
+ /**
+ * Read a 0 terminatet ISO-8859-1 string
+ */
public final String readTTFString() throws IOException {
int i = current;
while (file[i++] != 0) {
if (i > fsize)
- throw new java.io.EOFException("Reached EOF, file size="+
- fsize);
+ throw new java.io.EOFException("Reached EOF, file size="
+ + fsize);
}
byte[] tmp = new byte[i - current];
@@ -203,11 +231,12 @@ public class FontFileReader {
}
- /** Read an ISO-8859-1 string of len bytes*/
+ /**
+ * Read an ISO-8859-1 string of len bytes
+ */
public final String readTTFString(int len) throws IOException {
if ((len + current) > fsize)
- throw new java.io.EOFException("Reached EOF, file size="+
- fsize);
+ throw new java.io.EOFException("Reached EOF, file size=" + fsize);
byte[] tmp = new byte[len];
System.arraycopy(file, current, tmp, 0, len);
@@ -216,9 +245,9 @@ public class FontFileReader {
}
/**
- * Return a copy of the internal array
- * @throws IOException if out of bounds
- */
+ * Return a copy of the internal array
+ * @throws IOException if out of bounds
+ */
public byte[] getBytes(int offset,
int length) throws java.io.IOException {
if ((offset + length) > fsize)
diff --git a/src/org/apache/fop/fonts/Glyphs.java b/src/org/apache/fop/fonts/Glyphs.java
index e2510f4cd..5c167726f 100644
--- a/src/org/apache/fop/fonts/Glyphs.java
+++ b/src/org/apache/fop/fonts/Glyphs.java
@@ -1,1939 +1,504 @@
-/* -- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fonts;
public class Glyphs {
- static String notdef = ".notdef";
+ static String notdef = ".notdef";
- static String mac_glyph_names[] = {
-/* 0x00 */
- notdef,
- ".null",
- "CR",
- "space",
- "exclam",
- "quotedbl",
- "numbersign",
- "dollar",
- "percent",
- "ampersand",
- "quotesingle",
- "parenleft",
- "parenright",
- "asterisk",
- "plus",
- "comma",
-/* 0x10 */
- "hyphen",
- "period",
- "slash",
- "zero",
- "one",
- "two",
- "three",
- "four",
- "five",
- "six",
- "seven",
- "eight",
- "nine",
- "colon",
- "semicolon",
- "less",
-/* 0x20 */
- "equal",
- "greater",
- "question",
- "at",
- "A",
- "B",
- "C",
- "D",
- "E",
- "F",
- "G",
- "H",
- "I",
- "J",
- "K",
- "L",
-/* 0x30 */
- "M",
- "N",
- "O",
- "P",
- "Q",
- "R",
- "S",
- "T",
- "U",
- "V",
- "W",
- "X",
- "Y",
- "Z",
- "bracketleft",
- "backslash",
-/* 0x40 */
- "bracketright",
- "asciicircum",
- "underscore",
- "grave",
- "a",
- "b",
- "c",
- "d",
- "e",
- "f",
- "g",
- "h",
- "i",
- "j",
- "k",
- "l",
-/* 0x50 */
- "m",
- "n",
- "o",
- "p",
- "q",
- "r",
- "s",
- "t",
- "u",
- "v",
- "w",
- "x",
- "y",
- "z",
- "braceleft",
- "bar",
-/* 0x60 */
- "braceright",
- "asciitilde",
- "Adieresis",
- "Aring",
- "Ccedilla",
- "Eacute",
- "Ntilde",
- "Odieresis",
- "Udieresis",
- "aacute",
- "agrave",
- "acircumflex",
- "adieresis",
- "atilde",
- "aring",
- "ccedilla",
-/* 0x70 */
- "eacute",
- "egrave",
- "ecircumflex",
- "edieresis",
- "iacute",
- "igrave",
- "icircumflex",
- "idieresis",
- "ntilde",
- "oacute",
- "ograve",
- "ocircumflex",
- "odieresis",
- "otilde",
- "uacute",
- "ugrave",
-/* 0x80 */
- "ucircumflex",
- "udieresis",
- "dagger",
- "degree",
- "cent",
- "sterling",
- "section",
- "bullet",
- "paragraph",
- "germandbls",
- "registered",
- "copyright",
- "trademark",
- "acute",
- "dieresis",
- "notequal",
-/* 0x90 */
- "AE",
- "Oslash",
- "infinity",
- "plusminus",
- "lessequal",
- "greaterequal",
- "yen",
- "mu",
- "partialdiff",
- "Sigma",
- "Pi",
- "pi",
- "integral",
- "ordfeminine",
- "ordmasculine",
- "Omega",
-/* 0xa0 */
- "ae",
- "oslash",
- "questiondown",
- "exclamdown",
- "logicalnot",
- "radical",
- "florin",
- "approxequal",
- "Delta",
- "guillemotleft",
- "guillemotright",
- "ellipsis",
- "nbspace",
- "Agrave",
- "Atilde",
- "Otilde",
-/* 0xb0 */
- "OE",
- "oe",
- "endash",
- "emdash",
- "quotedblleft",
- "quotedblright",
- "quoteleft",
- "quoteright",
- "divide",
- "lozenge",
- "ydieresis",
- "Ydieresis",
- "fraction",
- "currency",
- "guilsinglleft",
- "guilsinglright",
-/* 0xc0 */
- "fi",
- "fl",
- "daggerdbl",
- "periodcentered",
- "quotesinglbase",
- "quotedblbase",
- "perthousand",
- "Acircumflex",
- "Ecircumflex",
- "Aacute",
- "Edieresis",
- "Egrave",
- "Iacute",
- "Icircumflex",
- "Idieresis",
- "Igrave",
-/* 0xd0 */
- "Oacute",
- "Ocircumflex",
- "applelogo",
- "Ograve",
- "Uacute",
- "Ucircumflex",
- "Ugrave",
- "dotlessi",
- "circumflex",
- "tilde",
- "macron",
- "breve",
- "dotaccent",
- "ring",
- "cedilla",
- "hungarumlaut",
-/* 0xe0 */
- "ogonek",
- "caron",
- "Lslash",
- "lslash",
- "Scaron",
- "scaron",
- "Zcaron",
- "zcaron",
- "brokenbar",
- "Eth",
- "eth",
- "Yacute",
- "yacute",
- "Thorn",
- "thorn",
- "minus",
-/* 0xf0 */
- "multiply",
- "onesuperior",
- "twosuperior",
- "threesuperior",
- "onehalf",
- "onequarter",
- "threequarters",
- "franc",
- "Gbreve",
- "gbreve",
- "Idot",
- "Scedilla",
- "scedilla",
- "Cacute",
- "cacute",
- "Ccaron",
-/* 0x100 */
- "ccaron",
- "dmacron"
- };
+ static String mac_glyph_names[] = {
+ /* 0x00 */
+ notdef, ".null", "CR", "space", "exclam", "quotedbl", "numbersign",
+ "dollar", "percent", "ampersand", "quotesingle", "parenleft",
+ "parenright", "asterisk", "plus", "comma", /* 0x10 */
+ "hyphen", "period", "slash", "zero", "one", "two", "three", "four",
+ "five", "six", "seven", "eight", "nine", "colon",
+ "semicolon", "less", /* 0x20 */
+ "equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F",
+ "G", "H", "I", "J", "K", "L", /* 0x30 */
+ "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
+ "bracketleft", "backslash", /* 0x40 */
+ "bracketright", "asciicircum", "underscore", "grave", "a", "b", "c",
+ "d", "e", "f", "g", "h", "i", "j", "k", "l",
+ /* 0x50 */
+ "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
+ "braceleft", "bar", /* 0x60 */
+ "braceright", "asciitilde", "Adieresis", "Aring", "Ccedilla",
+ "Eacute", "Ntilde", "Odieresis", "Udieresis", "aacute",
+ "agrave", "acircumflex", "adieresis", "atilde",
+ "aring", "ccedilla", /* 0x70 */
+ "eacute", "egrave", "ecircumflex", "edieresis", "iacute", "igrave",
+ "icircumflex", "idieresis", "ntilde", "oacute", "ograve",
+ "ocircumflex", "odieresis", "otilde", "uacute", "ugrave",
+ /* 0x80 */
+ "ucircumflex", "udieresis", "dagger", "degree", "cent", "sterling",
+ "section", "bullet", "paragraph", "germandbls",
+ "registered", "copyright", "trademark", "acute",
+ "dieresis", "notequal", /* 0x90 */
+ "AE", "Oslash", "infinity", "plusminus", "lessequal", "greaterequal",
+ "yen", "mu", "partialdiff", "Sigma", "Pi", "pi", "integral",
+ "ordfeminine", "ordmasculine", "Omega", /* 0xa0 */
+ "ae", "oslash", "questiondown", "exclamdown", "logicalnot",
+ "radical", "florin", "approxequal", "Delta", "guillemotleft",
+ "guillemotright", "ellipsis", "nbspace", "Agrave", "Atilde",
+ "Otilde", /* 0xb0 */
+ "OE", "oe", "endash", "emdash", "quotedblleft", "quotedblright",
+ "quoteleft", "quoteright", "divide", "lozenge", "ydieresis",
+ "Ydieresis", "fraction", "currency", "guilsinglleft",
+ "guilsinglright", /* 0xc0 */
+ "fi", "fl", "daggerdbl", "periodcentered", "quotesinglbase",
+ "quotedblbase", "perthousand", "Acircumflex", "Ecircumflex",
+ "Aacute", "Edieresis", "Egrave", "Iacute", "Icircumflex",
+ "Idieresis", "Igrave", /* 0xd0 */
+ "Oacute", "Ocircumflex", "applelogo", "Ograve", "Uacute",
+ "Ucircumflex", "Ugrave", "dotlessi", "circumflex", "tilde",
+ "macron", "breve", "dotaccent", "ring", "cedilla",
+ "hungarumlaut", /* 0xe0 */
+ "ogonek", "caron", "Lslash", "lslash", "Scaron", "scaron", "Zcaron",
+ "zcaron", "brokenbar", "Eth", "eth", "Yacute", "yacute",
+ "Thorn", "thorn", "minus", /* 0xf0 */
+ "multiply", "onesuperior", "twosuperior", "threesuperior", "onehalf",
+ "onequarter", "threequarters", "franc", "Gbreve",
+ "gbreve", "Idot", "Scedilla", "scedilla", "Cacute",
+ "cacute", "Ccaron", /* 0x100 */
+ "ccaron", "dmacron"
+ };
- static String[] tex8r = {
- // 0x00
- ".notdef",
- "dotaccent",
- "fi",
- "fl",
- "fraction",
- "hungarumlaut",
- "Lslash",
- "lslash",
- "ogonek",
- "ring",
- ".notdef",
- "breve",
- "minus",
- ".notdef",
- "Zcaron",
- "zcaron",
- // 0x10
- "caron",
- "dotlessi",
- "dotlessj",
- "ff",
- "ffi",
- "ffl",
- ".notdef",
- ".notdef",
- ".notdef",
- ".notdef",
- ".notdef",
- ".notdef",
- ".notdef",
- ".notdef",
- "grave",
- "quotesingle",
- // 0x20
- "space",
- "exclam",
- "quotedbl",
- "numbersign",
- "dollar",
- "percent",
- "ampersand",
- "quoteright",
- "parenleft",
- "parenright",
- "asterisk",
- "plus",
- "comma",
- "hyphen",
- "period",
- "slash",
- // 0x30
- "zero",
- "one",
- "two",
- "three",
- "four",
- "five",
- "six",
- "seven",
- "eight",
- "nine",
- "colon",
- "semicolon",
- "less",
- "equal",
- "greater",
- "question",
- // 0x40
- "at",
- "A",
- "B",
- "C",
- "D",
- "E",
- "F",
- "G",
- "H",
- "I",
- "J",
- "K",
- "L",
- "M",
- "N",
- "O",
- // 0x50
- "P",
- "Q",
- "R",
- "S",
- "T",
- "U",
- "V",
- "W",
- "X",
- "Y",
- "Z",
- "bracketleft",
- "backslash",
- "bracketright",
- "asciicircum",
- "underscore",
- // 0x60
- "quoteleft",
- "a",
- "b",
- "c",
- "d",
- "e",
- "f",
- "g",
- "h",
- "i",
- "j",
- "k",
- "l",
- "m",
- "n",
- "o",
- // 0x70
- "p",
- "q",
- "r",
- "s",
- "t",
- "u",
- "v",
- "w",
- "x",
- "y",
- "z",
- "braceleft",
- "bar",
- "braceright",
- "asciitilde",
- ".notdef",
- // 0x80
- "Euro",
- ".notdef",
- "quotesinglbase",
- "florin",
- "quotedblbase",
- "ellipsis",
- "dagger",
- "daggerdbl",
- "circumflex",
- "perthousand",
- "Scaron",
- "guilsinglleft",
- "OE",
- ".notdef",
- ".notdef",
- ".notdef",
- // 0x90
- ".notdef",
- ".notdef",
- ".notdef",
- "quotedblleft",
- "quotedblright",
- "bullet",
- "endash",
- "emdash",
- "tilde",
- "trademark",
- "scaron",
- "guilsinglright",
- "oe",
- ".notdef",
- ".notdef",
- "Ydieresis",
- // 0xA0
- ".notdef",
- "exclamdown",
- "cent",
- "sterling",
- "currency",
- "yen",
- "brokenbar",
- "section",
- "dieresis",
- "copyright",
- "ordfeminine",
- "guillemotleft",
- "logicalnot",
- "hyphen",
- "registered",
- "macron",
- // 0xB0
- "degree",
- "plusminus",
- "twosuperior",
- "threesuperior",
- "acute",
- "mu",
- "paragraph",
- "periodcentered",
- "cedilla",
- "onesuperior",
- "ordmasculine",
- "guillemotright",
- "onequarter",
- "onehalf",
- "threequarters",
- "questiondown",
- // 0xC0
- "Agrave",
- "Aacute",
- "Acircumflex",
- "Atilde",
- "Adieresis",
- "Aring",
- "AE",
- "Ccedilla",
- "Egrave",
- "Eacute",
- "Ecircumflex",
- "Edieresis",
- "Igrave",
- "Iacute",
- "Icircumflex",
- "Idieresis",
- // 0xD0
- "Eth",
- "Ntilde",
- "Ograve",
- "Oacute",
- "Ocircumflex",
- "Otilde",
- "Odieresis",
- "multiply",
- "Oslash",
- "Ugrave",
- "Uacute",
- "Ucircumflex",
- "Udieresis",
- "Yacute",
- "Thorn",
- "germandbls",
- // 0xE0
- "agrave",
- "aacute",
- "acircumflex",
- "atilde",
- "adieresis",
- "aring",
- "ae",
- "ccedilla",
- "egrave",
- "eacute",
- "ecircumflex",
- "edieresis",
- "igrave",
- "iacute",
- "icircumflex",
- "idieresis",
- // 0xF0
- "eth",
- "ntilde",
- "ograve",
- "oacute",
- "ocircumflex",
- "otilde",
- "odieresis",
- "divide",
- "oslash",
- "ugrave",
- "uacute",
- "ucircumflex",
- "udieresis",
- "yacute",
- "thorn",
- "ydieresis"};
+ static String[] tex8r = {
+ // 0x00
+ ".notdef", "dotaccent", "fi", "fl", "fraction", "hungarumlaut",
+ "Lslash", "lslash", "ogonek", "ring", ".notdef", "breve",
+ "minus", ".notdef", "Zcaron", "zcaron", // 0x10
+ "caron", "dotlessi", "dotlessj", "ff", "ffi", "ffl", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", "grave", "quotesingle", // 0x20
+ "space", "exclam", "quotedbl", "numbersign", "dollar", "percent",
+ "ampersand", "quoteright", "parenleft", "parenright",
+ "asterisk", "plus", "comma", "hyphen", "period", "slash",
+ // 0x30
+ "zero", "one", "two", "three", "four", "five", "six", "seven",
+ "eight", "nine", "colon", "semicolon", "less", "equal",
+ "greater", "question", // 0x40
+ "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
+ "M", "N", "O", // 0x50
+ "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft",
+ "backslash", "bracketright", "asciicircum", "underscore", // 0x60
+ "quoteleft", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
+ "l", "m", "n", "o", // 0x70
+ "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft",
+ "bar", "braceright", "asciitilde", ".notdef", // 0x80
+ "Euro", ".notdef", "quotesinglbase", "florin", "quotedblbase",
+ "ellipsis", "dagger", "daggerdbl", "circumflex",
+ "perthousand", "Scaron", "guilsinglleft", "OE", ".notdef",
+ ".notdef", ".notdef", // 0x90
+ ".notdef", ".notdef", ".notdef", "quotedblleft", "quotedblright",
+ "bullet", "endash", "emdash", "tilde", "trademark",
+ "scaron", "guilsinglright", "oe", ".notdef", ".notdef",
+ "Ydieresis", // 0xA0
+ ".notdef", "exclamdown", "cent", "sterling", "currency", "yen",
+ "brokenbar", "section", "dieresis", "copyright",
+ "ordfeminine", "guillemotleft", "logicalnot", "hyphen",
+ "registered", "macron", // 0xB0
+ "degree", "plusminus", "twosuperior", "threesuperior", "acute", "mu",
+ "paragraph", "periodcentered", "cedilla", "onesuperior",
+ "ordmasculine", "guillemotright", "onequarter", "onehalf",
+ "threequarters", "questiondown", // 0xC0
+ "Agrave", "Aacute", "Acircumflex", "Atilde", "Adieresis", "Aring",
+ "AE", "Ccedilla", "Egrave", "Eacute", "Ecircumflex",
+ "Edieresis", "Igrave", "Iacute", "Icircumflex",
+ "Idieresis", // 0xD0
+ "Eth", "Ntilde", "Ograve", "Oacute", "Ocircumflex", "Otilde",
+ "Odieresis", "multiply", "Oslash", "Ugrave", "Uacute",
+ "Ucircumflex", "Udieresis", "Yacute", "Thorn", "germandbls",
+ // 0xE0
+ "agrave", "aacute", "acircumflex", "atilde", "adieresis", "aring",
+ "ae", "ccedilla", "egrave", "eacute", "ecircumflex",
+ "edieresis", "igrave", "iacute", "icircumflex",
+ "idieresis", // 0xF0
+ "eth", "ntilde", "ograve", "oacute", "ocircumflex", "otilde",
+ "odieresis", "divide", "oslash", "ugrave", "uacute",
+ "ucircumflex", "udieresis", "yacute", "thorn", "ydieresis"
+ };
- /** The characters in WinAnsiEncoding */
+ /**
+ * The characters in WinAnsiEncoding
+ */
public static char[] winAnsiEncoding = {
- // not used until char 32
- 0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0,0,
- // 0x20
- ' ',
- '\u0021',
- '\"',
- '\u0023',
- '$',
- '%',
- '&',
- '\'',
- '(',
- ')',
- '*',
- '+',
- ',',
- '\u002d',
- '\u002e',
- '/',
- // 0x30
- '0',
- '1',
- '2',
- '3',
- '4',
- '5',
- '6',
- '7',
- '8',
- '9',
- ':',
- ';',
- '<',
- '=',
- '>',
- '?',
- '@',
- // 0x40
- 'A',
- 'B',
- 'C',
- 'D',
- 'E',
- 'F',
- 'G',
- 'H',
- 'I',
- 'J',
- 'K',
- 'L',
- 'M',
- 'N',
- 'O',
- // 0x50
- 'P',
- 'Q',
- 'R',
- 'S',
- 'T',
- 'U',
- 'V',
- 'W',
- 'X',
- 'Y',
- 'Z',
- '\u005b',
- '\\',
- '\u005d',
- '\u005e',
- '_',
- // 0x60
- '\u2018',
- 'a',
- 'b',
- 'c',
- 'd',
- 'e',
- 'f',
- 'g',
- 'h',
- 'i',
- 'j',
- 'k',
- 'l',
- 'm',
- 'n',
- 'o',
- // 0x70
- 'p',
- 'q',
- 'r',
- 's',
- 't',
- 'u',
- 'v',
- 'w',
- 'x',
- 'y',
- 'z',
- '\u007b',
- '\u007c',
- '\u007d',
- '\u007e',
- '\u2022',
- // 0x80
- '\u20ac',
- '\u2022',
- '\u201a',
- '\u0192',
- '\u201e',
- '\u2026',
- '\u2020',
- '\u2021',
- '\u02c6',
- '\u2030',
- '\u0160',
- '\u2039',
- '\u0152',
- '\u2022',
- '\u017d',
- '\u2022',
- // 0x90
- '\u2022',
- '\u2018', // quoteleft
- '\u2019', // quoteright
- '\u201c', // quotedblleft
- '\u201d', // quotedblright
- '\u2022', // bullet
- '\u2013', // endash
- '\u2014', // emdash
- '~',
- '\u2022', // bullet
- '\u0161',
- '\u203a',
- '\u0153',
- '\u2022',
- '\u017e',
- '\u0178',
- // 0xA0
- ' ',
- '\u00a1',
- '\u00a2',
- '\u00a3',
- '\u00a4',
- '\u00a5',
- '\u00a6',
- '\u00a7',
- '\u00a8',
- '\u00a9',
- '\u00aa',
- '\u00ab',
- '\u00ac',
- '\u00ad',
- '\u00ae',
- '\u00af',
- // 0xb0
- '\u00b0',
- '\u00b1',
- '\u00b2',
- '\u00b3',
- '\u00b4',
- '\u00b5', // This is hand-coded, the rest is assumption
- '\u00b6', // and *might* not be correct...
- '\u00b7',
- '\u00b8',
- '\u00b9',
- '\u00ba',
- '\u00bb',
- '\u00bc',
- '\u00bd',
- '\u00be',
- '\u00bf',
- // 0xc0
- '\u00c0',
- '\u00c1',
- '\u00c2',
- '\u00c3',
- '\u00c4',
- '\u00c5', // Aring
- '\u00c6', // AE
- '\u00c7',
- '\u00c8',
- '\u00c9',
- '\u00ca',
- '\u00cb',
- '\u00cc',
- '\u00cd',
- '\u00ce',
- '\u00cf',
- // 0xd0
- '\u00d0',
- '\u00d1',
- '\u00d2',
- '\u00d3',
- '\u00d4',
- '\u00d5',
- '\u00d6',
- '\u00d7',
- '\u00d8', // Oslash
- '\u00d9',
- '\u00da',
- '\u00db',
- '\u00dc',
- '\u00dd',
- '\u00de',
- '\u00df',
- // 0xe0
- '\u00e0',
- '\u00e1',
- '\u00e2',
- '\u00e3',
- '\u00e4',
- '\u00e5', // aring
- '\u00e6', // ae
- '\u00e7',
- '\u00e8',
- '\u00e9',
- '\u00ea',
- '\u00eb',
- '\u00ec',
- '\u00ed',
- '\u00ee',
- '\u00ef',
- // 0xf0
- '\u00f0',
- '\u00f1',
- '\u00f2',
- '\u00f3',
- '\u00f4',
- '\u00f5',
- '\u00f6',
- '\u00f7',
- '\u00f8',
- '\u00f9',
- '\u00fa',
- '\u00fb',
- '\u00fc',
- '\u00fd',
- '\u00fe',
- '\u00ff'
+ // not used until char 32
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x20
+ ' ', '!', '\"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',',
+ '-', '.', '/', // 0x30
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=',
+ '>', '?', '@', // 0x40
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
+ 'O', // 0x50
+ 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\',
+ ']', '^', '_', // 0x60
+ '?', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
+ 'n', 'o', // 0x70
+ 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}',
+ '~', '?', // 0x80
+ '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?',
+ '?', '?', // 0x90
+ '?', '?', // quoteleft
+ '?', // quoteright
+ '?', // quotedblleft
+ '?', // quotedblright
+ '?', // bullet
+ '?', // endash
+ '?', // emdash
+ '~', '?', // bullet
+ '?', '?', '?', '?', '?', '?', // 0xA0
+ ' ', '¡', '¢', '£', '¤', '¥', '¦', '§', '¨', '©', 'ª', '«', '¬', '',
+ '®', '¯', // 0xb0
+ '°', '±', '²', '³', '´',
+ 'µ', // This is hand-coded, the rest is assumption
+ '¶', // and *might* not be correct...
+ '·', '¸', '¹', 'º', '»', '¼', '½', '¾', '¿', // 0xc0
+ 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', // Aring
+ 'Æ', // AE
+ 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', // 0xd0
+ 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', '×', 'Ø', // Oslash
+ 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß', // 0xe0
+ 'à', 'á', 'â', 'ã', 'ä', 'å', // aring
+ 'æ', // ae
+ 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', // 0xf0
+ 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', '÷', 'ø', 'ù', 'ú', 'û', 'ü', 'ý',
+ 'þ', 'ÿ'
};
-
- static String[] unicode_glyphs={
- "\u0041", "A",
- "\u00C6", "AE",
- "\u01FC", "AEacute",
- "\uF7E6", "AEsmall",
- "\u00C1", "Aacute",
- "\uF7E1", "Aacutesmall",
- "\u0102", "Abreve",
- "\u00C2", "Acircumflex",
- "\uF7E2", "Acircumflexsmall",
- "\uF6C9", "Acute",
- "\uF7B4", "Acutesmall",
- "\u00C4", "Adieresis",
- "\uF7E4", "Adieresissmall",
- "\u00C0", "Agrave",
- "\uF7E0", "Agravesmall",
- "\u0391", "Alpha",
- "\u0386", "Alphatonos",
- "\u0100", "Amacron",
- "\u0104", "Aogonek",
- "\u00C5", "Aring",
- "\u01FA", "Aringacute",
- "\uF7E5", "Aringsmall",
- "\uF761", "Asmall",
- "\u00C3", "Atilde",
- "\uF7E3", "Atildesmall",
- "\u0042", "B",
- "\u0392", "Beta",
- "\uF6F4", "Brevesmall",
- "\uF762", "Bsmall",
- "\u0043", "C",
- "\u0106", "Cacute",
- "\uF6CA", "Caron",
- "\uF6F5", "Caronsmall",
- "\u010C", "Ccaron",
- "\u00C7", "Ccedilla",
- "\uF7E7", "Ccedillasmall",
- "\u0108", "Ccircumflex",
- "\u010A", "Cdotaccent",
- "\uF7B8", "Cedillasmall",
- "\u03A7", "Chi",
- "\uF6F6", "Circumflexsmall",
- "\uF763", "Csmall",
- "\u0044", "D",
- "\u010E", "Dcaron",
- "\u0110", "Dcroat",
- "\u2206", "Delta",
- "\u0394", "Delta",
- "\uF6CB", "Dieresis",
- "\uF6CC", "DieresisAcute",
- "\uF6CD", "DieresisGrave",
- "\uF7A8", "Dieresissmall",
- "\uF6F7", "Dotaccentsmall",
- "\uF764", "Dsmall",
- "\u0045", "E",
- "\u00C9", "Eacute",
- "\uF7E9", "Eacutesmall",
- "\u0114", "Ebreve",
- "\u011A", "Ecaron",
- "\u00CA", "Ecircumflex",
- "\uF7EA", "Ecircumflexsmall",
- "\u00CB", "Edieresis",
- "\uF7EB", "Edieresissmall",
- "\u0116", "Edotaccent",
- "\u00C8", "Egrave",
- "\uF7E8", "Egravesmall",
- "\u0112", "Emacron",
- "\u014A", "Eng",
- "\u0118", "Eogonek",
- "\u0395", "Epsilon",
- "\u0388", "Epsilontonos",
- "\uF765", "Esmall",
- "\u0397", "Eta",
- "\u0389", "Etatonos",
- "\u00D0", "Eth",
- "\uF7F0", "Ethsmall",
- "\u20AC", "Euro",
- "\u0046", "F",
- "\uF766", "Fsmall",
- "\u0047", "G",
- "\u0393", "Gamma",
- "\u011E", "Gbreve",
- "\u01E6", "Gcaron",
- "\u011C", "Gcircumflex",
- "\u0122", "Gcommaaccent",
- "\u0120", "Gdotaccent",
- "\uF6CE", "Grave",
- "\uF760", "Gravesmall",
- "\uF767", "Gsmall",
- "\u0048", "H",
- "\u25CF", "H18533",
- "\u25AA", "H18543",
- "\u25AB", "H18551",
- "\u25A1", "H22073",
- "\u0126", "Hbar",
- "\u0124", "Hcircumflex",
- "\uF768", "Hsmall",
- "\uF6CF", "Hungarumlaut",
- "\uF6F8", "Hungarumlautsmall",
- "\u0049", "I",
- "\u0132", "IJ",
- "\u00CD", "Iacute",
- "\uF7ED", "Iacutesmall",
- "\u012C", "Ibreve",
- "\u00CE", "Icircumflex",
- "\uF7EE", "Icircumflexsmall",
- "\u00CF", "Idieresis",
- "\uF7EF", "Idieresissmall",
- "\u0130", "Idotaccent",
- "\u2111", "Ifraktur",
- "\u00CC", "Igrave",
- "\uF7EC", "Igravesmall",
- "\u012A", "Imacron",
- "\u012E", "Iogonek",
- "\u0399", "Iota",
- "\u03AA", "Iotadieresis",
- "\u038A", "Iotatonos",
- "\uF769", "Ismall",
- "\u0128", "Itilde",
- "\u004A", "J",
- "\u0134", "Jcircumflex",
- "\uF76A", "Jsmall",
- "\u004B", "K",
- "\u039A", "Kappa",
- "\u0136", "Kcommaaccent",
- "\uF76B", "Ksmall",
- "\u004C", "L",
- "\uF6BF", "LL",
- "\u0139", "Lacute",
- "\u039B", "Lambda",
- "\u013D", "Lcaron",
- "\u013B", "Lcommaaccent",
- "\u013F", "Ldot",
- "\u0141", "Lslash",
- "\uF6F9", "Lslashsmall",
- "\uF76C", "Lsmall",
- "\u004D", "M",
- "\uF6D0", "Macron",
- "\uF7AF", "Macronsmall",
- "\uF76D", "Msmall",
- "\u039C", "Mu",
- "\u004E", "N",
- "\u0143", "Nacute",
- "\u0147", "Ncaron",
- "\u0145", "Ncommaaccent",
- "\uF76E", "Nsmall",
- "\u00D1", "Ntilde",
- "\uF7F1", "Ntildesmall",
- "\u039D", "Nu",
- "\u004F", "O",
- "\u0152", "OE",
- "\uF6FA", "OEsmall",
- "\u00D3", "Oacute",
- "\uF7F3", "Oacutesmall",
- "\u014E", "Obreve",
- "\u00D4", "Ocircumflex",
- "\uF7F4", "Ocircumflexsmall",
- "\u00D6", "Odieresis",
- "\uF7F6", "Odieresissmall",
- "\uF6FB", "Ogoneksmall",
- "\u00D2", "Ograve",
- "\uF7F2", "Ogravesmall",
- "\u01A0", "Ohorn",
- "\u0150", "Ohungarumlaut",
- "\u014C", "Omacron",
- "\u2126", "Omega",
- "\u03A9", "Omega",
- "\u038F", "Omegatonos",
- "\u039F", "Omicron",
- "\u038C", "Omicrontonos",
- "\u00D8", "Oslash",
- "\u01FE", "Oslashacute",
- "\uF7F8", "Oslashsmall",
- "\uF76F", "Osmall",
- "\u00D5", "Otilde",
- "\uF7F5", "Otildesmall",
- "\u0050", "P",
- "\u03A6", "Phi",
- "\u03A0", "Pi",
- "\u03A8", "Psi",
- "\uF770", "Psmall",
- "\u0051", "Q",
- "\uF771", "Qsmall",
- "\u0052", "R",
- "\u0154", "Racute",
- "\u0158", "Rcaron",
- "\u0156", "Rcommaaccent",
- "\u211C", "Rfraktur",
- "\u03A1", "Rho",
- "\uF6FC", "Ringsmall",
- "\uF772", "Rsmall",
- "\u0053", "S",
- "\u250C", "SF010000",
- "\u2514", "SF020000",
- "\u2510", "SF030000",
- "\u2518", "SF040000",
- "\u253C", "SF050000",
- "\u252C", "SF060000",
- "\u2534", "SF070000",
- "\u251C", "SF080000",
- "\u2524", "SF090000",
- "\u2500", "SF100000",
- "\u2502", "SF110000",
- "\u2561", "SF190000",
- "\u2562", "SF200000",
- "\u2556", "SF210000",
- "\u2555", "SF220000",
- "\u2563", "SF230000",
- "\u2551", "SF240000",
- "\u2557", "SF250000",
- "\u255D", "SF260000",
- "\u255C", "SF270000",
- "\u255B", "SF280000",
- "\u255E", "SF360000",
- "\u255F", "SF370000",
- "\u255A", "SF380000",
- "\u2554", "SF390000",
- "\u2569", "SF400000",
- "\u2566", "SF410000",
- "\u2560", "SF420000",
- "\u2550", "SF430000",
- "\u256C", "SF440000",
- "\u2567", "SF450000",
- "\u2568", "SF460000",
- "\u2564", "SF470000",
- "\u2565", "SF480000",
- "\u2559", "SF490000",
- "\u2558", "SF500000",
- "\u2552", "SF510000",
- "\u2553", "SF520000",
- "\u256B", "SF530000",
- "\u256A", "SF540000",
- "\u015A", "Sacute",
- "\u0160", "Scaron",
- "\uF6FD", "Scaronsmall",
- "\u015E", "Scedilla",
- "\uF6C1", "Scedilla",
- "\u015C", "Scircumflex",
- "\u0218", "Scommaaccent",
- "\u03A3", "Sigma",
- "\uF773", "Ssmall",
- "\u0054", "T",
- "\u03A4", "Tau",
- "\u0166", "Tbar",
- "\u0164", "Tcaron",
- "\u0162", "Tcommaaccent",
- "\u021A", "Tcommaaccent",
- "\u0398", "Theta",
- "\u00DE", "Thorn",
- "\uF7FE", "Thornsmall",
- "\uF6FE", "Tildesmall",
- "\uF774", "Tsmall",
- "\u0055", "U",
- "\u00DA", "Uacute",
- "\uF7FA", "Uacutesmall",
- "\u016C", "Ubreve",
- "\u00DB", "Ucircumflex",
- "\uF7FB", "Ucircumflexsmall",
- "\u00DC", "Udieresis",
- "\uF7FC", "Udieresissmall",
- "\u00D9", "Ugrave",
- "\uF7F9", "Ugravesmall",
- "\u01AF", "Uhorn",
- "\u0170", "Uhungarumlaut",
- "\u016A", "Umacron",
- "\u0172", "Uogonek",
- "\u03A5", "Upsilon",
- "\u03D2", "Upsilon1",
- "\u03AB", "Upsilondieresis",
- "\u038E", "Upsilontonos",
- "\u016E", "Uring",
- "\uF775", "Usmall",
- "\u0168", "Utilde",
- "\u0056", "V",
- "\uF776", "Vsmall",
- "\u0057", "W",
- "\u1E82", "Wacute",
- "\u0174", "Wcircumflex",
- "\u1E84", "Wdieresis",
- "\u1E80", "Wgrave",
- "\uF777", "Wsmall",
- "\u0058", "X",
- "\u039E", "Xi",
- "\uF778", "Xsmall",
- "\u0059", "Y",
- "\u00DD", "Yacute",
- "\uF7FD", "Yacutesmall",
- "\u0176", "Ycircumflex",
- "\u0178", "Ydieresis",
- "\uF7FF", "Ydieresissmall",
- "\u1EF2", "Ygrave",
- "\uF779", "Ysmall",
- "\u005A", "Z",
- "\u0179", "Zacute",
- "\u017D", "Zcaron",
- "\uF6FF", "Zcaronsmall",
- "\u017B", "Zdotaccent",
- "\u0396", "Zeta",
- "\uF77A", "Zsmall",
- "\u0061", "a",
- "\u00E1", "aacute",
- "\u0103", "abreve",
- "\u00E2", "acircumflex",
- "\u00B4", "acute",
- "\u0301", "acutecomb",
- "\u00E4", "adieresis",
- "\u00E6", "ae",
- "\u01FD", "aeacute",
- "\u2015", "afii00208",
- "\u0410", "afii10017",
- "\u0411", "afii10018",
- "\u0412", "afii10019",
- "\u0413", "afii10020",
- "\u0414", "afii10021",
- "\u0415", "afii10022",
- "\u0401", "afii10023",
- "\u0416", "afii10024",
- "\u0417", "afii10025",
- "\u0418", "afii10026",
- "\u0419", "afii10027",
- "\u041A", "afii10028",
- "\u041B", "afii10029",
- "\u041C", "afii10030",
- "\u041D", "afii10031",
- "\u041E", "afii10032",
- "\u041F", "afii10033",
- "\u0420", "afii10034",
- "\u0421", "afii10035",
- "\u0422", "afii10036",
- "\u0423", "afii10037",
- "\u0424", "afii10038",
- "\u0425", "afii10039",
- "\u0426", "afii10040",
- "\u0427", "afii10041",
- "\u0428", "afii10042",
- "\u0429", "afii10043",
- "\u042A", "afii10044",
- "\u042B", "afii10045",
- "\u042C", "afii10046",
- "\u042D", "afii10047",
- "\u042E", "afii10048",
- "\u042F", "afii10049",
- "\u0490", "afii10050",
- "\u0402", "afii10051",
- "\u0403", "afii10052",
- "\u0404", "afii10053",
- "\u0405", "afii10054",
- "\u0406", "afii10055",
- "\u0407", "afii10056",
- "\u0408", "afii10057",
- "\u0409", "afii10058",
- "\u040A", "afii10059",
- "\u040B", "afii10060",
- "\u040C", "afii10061",
- "\u040E", "afii10062",
- "\uF6C4", "afii10063",
- "\uF6C5", "afii10064",
- "\u0430", "afii10065",
- "\u0431", "afii10066",
- "\u0432", "afii10067",
- "\u0433", "afii10068",
- "\u0434", "afii10069",
- "\u0435", "afii10070",
- "\u0451", "afii10071",
- "\u0436", "afii10072",
- "\u0437", "afii10073",
- "\u0438", "afii10074",
- "\u0439", "afii10075",
- "\u043A", "afii10076",
- "\u043B", "afii10077",
- "\u043C", "afii10078",
- "\u043D", "afii10079",
- "\u043E", "afii10080",
- "\u043F", "afii10081",
- "\u0440", "afii10082",
- "\u0441", "afii10083",
- "\u0442", "afii10084",
- "\u0443", "afii10085",
- "\u0444", "afii10086",
- "\u0445", "afii10087",
- "\u0446", "afii10088",
- "\u0447", "afii10089",
- "\u0448", "afii10090",
- "\u0449", "afii10091",
- "\u044A", "afii10092",
- "\u044B", "afii10093",
- "\u044C", "afii10094",
- "\u044D", "afii10095",
- "\u044E", "afii10096",
- "\u044F", "afii10097",
- "\u0491", "afii10098",
- "\u0452", "afii10099",
- "\u0453", "afii10100",
- "\u0454", "afii10101",
- "\u0455", "afii10102",
- "\u0456", "afii10103",
- "\u0457", "afii10104",
- "\u0458", "afii10105",
- "\u0459", "afii10106",
- "\u045A", "afii10107",
- "\u045B", "afii10108",
- "\u045C", "afii10109",
- "\u045E", "afii10110",
- "\u040F", "afii10145",
- "\u0462", "afii10146",
- "\u0472", "afii10147",
- "\u0474", "afii10148",
- "\uF6C6", "afii10192",
- "\u045F", "afii10193",
- "\u0463", "afii10194",
- "\u0473", "afii10195",
- "\u0475", "afii10196",
- "\uF6C7", "afii10831",
- "\uF6C8", "afii10832",
- "\u04D9", "afii10846",
- "\u200E", "afii299",
- "\u200F", "afii300",
- "\u200D", "afii301",
- "\u066A", "afii57381",
- "\u060C", "afii57388",
- "\u0660", "afii57392",
- "\u0661", "afii57393",
- "\u0662", "afii57394",
- "\u0663", "afii57395",
- "\u0664", "afii57396",
- "\u0665", "afii57397",
- "\u0666", "afii57398",
- "\u0667", "afii57399",
- "\u0668", "afii57400",
- "\u0669", "afii57401",
- "\u061B", "afii57403",
- "\u061F", "afii57407",
- "\u0621", "afii57409",
- "\u0622", "afii57410",
- "\u0623", "afii57411",
- "\u0624", "afii57412",
- "\u0625", "afii57413",
- "\u0626", "afii57414",
- "\u0627", "afii57415",
- "\u0628", "afii57416",
- "\u0629", "afii57417",
- "\u062A", "afii57418",
- "\u062B", "afii57419",
- "\u062C", "afii57420",
- "\u062D", "afii57421",
- "\u062E", "afii57422",
- "\u062F", "afii57423",
- "\u0630", "afii57424",
- "\u0631", "afii57425",
- "\u0632", "afii57426",
- "\u0633", "afii57427",
- "\u0634", "afii57428",
- "\u0635", "afii57429",
- "\u0636", "afii57430",
- "\u0637", "afii57431",
- "\u0638", "afii57432",
- "\u0639", "afii57433",
- "\u063A", "afii57434",
- "\u0640", "afii57440",
- "\u0641", "afii57441",
- "\u0642", "afii57442",
- "\u0643", "afii57443",
- "\u0644", "afii57444",
- "\u0645", "afii57445",
- "\u0646", "afii57446",
- "\u0648", "afii57448",
- "\u0649", "afii57449",
- "\u064A", "afii57450",
- "\u064B", "afii57451",
- "\u064C", "afii57452",
- "\u064D", "afii57453",
- "\u064E", "afii57454",
- "\u064F", "afii57455",
- "\u0650", "afii57456",
- "\u0651", "afii57457",
- "\u0652", "afii57458",
- "\u0647", "afii57470",
- "\u06A4", "afii57505",
- "\u067E", "afii57506",
- "\u0686", "afii57507",
- "\u0698", "afii57508",
- "\u06AF", "afii57509",
- "\u0679", "afii57511",
- "\u0688", "afii57512",
- "\u0691", "afii57513",
- "\u06BA", "afii57514",
- "\u06D2", "afii57519",
- "\u06D5", "afii57534",
- "\u20AA", "afii57636",
- "\u05BE", "afii57645",
- "\u05C3", "afii57658",
- "\u05D0", "afii57664",
- "\u05D1", "afii57665",
- "\u05D2", "afii57666",
- "\u05D3", "afii57667",
- "\u05D4", "afii57668",
- "\u05D5", "afii57669",
- "\u05D6", "afii57670",
- "\u05D7", "afii57671",
- "\u05D8", "afii57672",
- "\u05D9", "afii57673",
- "\u05DA", "afii57674",
- "\u05DB", "afii57675",
- "\u05DC", "afii57676",
- "\u05DD", "afii57677",
- "\u05DE", "afii57678",
- "\u05DF", "afii57679",
- "\u05E0", "afii57680",
- "\u05E1", "afii57681",
- "\u05E2", "afii57682",
- "\u05E3", "afii57683",
- "\u05E4", "afii57684",
- "\u05E5", "afii57685",
- "\u05E6", "afii57686",
- "\u05E7", "afii57687",
- "\u05E8", "afii57688",
- "\u05E9", "afii57689",
- "\u05EA", "afii57690",
- "\uFB2A", "afii57694",
- "\uFB2B", "afii57695",
- "\uFB4B", "afii57700",
- "\uFB1F", "afii57705",
- "\u05F0", "afii57716",
- "\u05F1", "afii57717",
- "\u05F2", "afii57718",
- "\uFB35", "afii57723",
- "\u05B4", "afii57793",
- "\u05B5", "afii57794",
- "\u05B6", "afii57795",
- "\u05BB", "afii57796",
- "\u05B8", "afii57797",
- "\u05B7", "afii57798",
- "\u05B0", "afii57799",
- "\u05B2", "afii57800",
- "\u05B1", "afii57801",
- "\u05B3", "afii57802",
- "\u05C2", "afii57803",
- "\u05C1", "afii57804",
- "\u05B9", "afii57806",
- "\u05BC", "afii57807",
- "\u05BD", "afii57839",
- "\u05BF", "afii57841",
- "\u05C0", "afii57842",
- "\u02BC", "afii57929",
- "\u2105", "afii61248",
- "\u2113", "afii61289",
- "\u2116", "afii61352",
- "\u202C", "afii61573",
- "\u202D", "afii61574",
- "\u202E", "afii61575",
- "\u200C", "afii61664",
- "\u066D", "afii63167",
- "\u02BD", "afii64937",
- "\u00E0", "agrave",
- "\u2135", "aleph",
- "\u03B1", "alpha",
- "\u03AC", "alphatonos",
- "\u0101", "amacron",
- "\u0026", "ampersand",
- "\uF726", "ampersandsmall",
- "\u2220", "angle",
- "\u2329", "angleleft",
- "\u232A", "angleright",
- "\u0387", "anoteleia",
- "\u0105", "aogonek",
- "\u2248", "approxequal",
- "\u00E5", "aring",
- "\u01FB", "aringacute",
- "\u2194", "arrowboth",
- "\u21D4", "arrowdblboth",
- "\u21D3", "arrowdbldown",
- "\u21D0", "arrowdblleft",
- "\u21D2", "arrowdblright",
- "\u21D1", "arrowdblup",
- "\u2193", "arrowdown",
- "\uF8E7", "arrowhorizex",
- "\u2190", "arrowleft",
- "\u2192", "arrowright",
- "\u2191", "arrowup",
- "\u2195", "arrowupdn",
- "\u21A8", "arrowupdnbse",
- "\uF8E6", "arrowvertex",
- "\u005E", "asciicircum",
- "\u007E", "asciitilde",
- "\u002A", "asterisk",
- "\u2217", "asteriskmath",
- "\uF6E9", "asuperior",
- "\u0040", "at",
- "\u00E3", "atilde",
- "\u0062", "b",
- //"\u005C", "backslash",
- "\\", "backslash",
- "\u007C", "bar",
- "\u03B2", "beta",
- "\u2588", "block",
- "\uF8F4", "braceex",
- "\u007B", "braceleft",
- "\uF8F3", "braceleftbt",
- "\uF8F2", "braceleftmid",
- "\uF8F1", "bracelefttp",
- "\u007D", "braceright",
- "\uF8FE", "bracerightbt",
- "\uF8FD", "bracerightmid",
- "\uF8FC", "bracerighttp",
- "\u005B", "bracketleft",
- "\uF8F0", "bracketleftbt",
- "\uF8EF", "bracketleftex",
- "\uF8EE", "bracketlefttp",
- "\u005D", "bracketright",
- "\uF8FB", "bracketrightbt",
- "\uF8FA", "bracketrightex",
- "\uF8F9", "bracketrighttp",
- "\u02D8", "breve",
- "\u00A6", "brokenbar",
- "\uF6EA", "bsuperior",
- "\u2022", "bullet",
- "\u0063", "c",
- "\u0107", "cacute",
- "\u02C7", "caron",
- "\u21B5", "carriagereturn",
- "\u010D", "ccaron",
- "\u00E7", "ccedilla",
- "\u0109", "ccircumflex",
- "\u010B", "cdotaccent",
- "\u00B8", "cedilla",
- "\u00A2", "cent",
- "\uF6DF", "centinferior",
- "\uF7A2", "centoldstyle",
- "\uF6E0", "centsuperior",
- "\u03C7", "chi",
- "\u25CB", "circle",
- "\u2297", "circlemultiply",
- "\u2295", "circleplus",
- "\u02C6", "circumflex",
- "\u2663", "club",
- "\u003A", "colon",
- "\u20A1", "colonmonetary",
- "\u002C", "comma",
- "\uF6C3", "commaaccent",
- "\uF6E1", "commainferior",
- "\uF6E2", "commasuperior",
- "\u2245", "congruent",
- "\u00A9", "copyright",
- "\uF8E9", "copyrightsans",
- "\uF6D9", "copyrightserif",
- "\u00A4", "currency",
- "\uF6D1", "cyrBreve",
- "\uF6D2", "cyrFlex",
- "\uF6D4", "cyrbreve",
- "\uF6D5", "cyrflex",
- "\u0064", "d",
- "\u2020", "dagger",
- "\u2021", "daggerdbl",
- "\uF6D3", "dblGrave",
- "\uF6D6", "dblgrave",
- "\u010F", "dcaron",
- "\u0111", "dcroat",
- "\u00B0", "degree",
- "\u03B4", "delta",
- "\u2666", "diamond",
- "\u00A8", "dieresis",
- "\uF6D7", "dieresisacute",
- "\uF6D8", "dieresisgrave",
- "\u0385", "dieresistonos",
- "\u00F7", "divide",
- "\u2593", "dkshade",
- "\u2584", "dnblock",
- "\u0024", "dollar",
- "\uF6E3", "dollarinferior",
- "\uF724", "dollaroldstyle",
- "\uF6E4", "dollarsuperior",
- "\u20AB", "dong",
- "\u02D9", "dotaccent",
- "\u0323", "dotbelowcomb",
- "\u0131", "dotlessi",
- "\uF6BE", "dotlessj",
- "\u22C5", "dotmath",
- "\uF6EB", "dsuperior",
- "\u0065", "e",
- "\u00E9", "eacute",
- "\u0115", "ebreve",
- "\u011B", "ecaron",
- "\u00EA", "ecircumflex",
- "\u00EB", "edieresis",
- "\u0117", "edotaccent",
- "\u00E8", "egrave",
- "\u0038", "eight",
- "\u2088", "eightinferior",
- "\uF738", "eightoldstyle",
- "\u2078", "eightsuperior",
- "\u2208", "element",
- "\u2026", "ellipsis",
- "\u0113", "emacron",
- "\u2014", "emdash",
- "\u2205", "emptyset",
- "\u2013", "endash",
- "\u014B", "eng",
- "\u0119", "eogonek",
- "\u03B5", "epsilon",
- "\u03AD", "epsilontonos",
- "\u003D", "equal",
- "\u2261", "equivalence",
- "\u212E", "estimated",
- "\uF6EC", "esuperior",
- "\u03B7", "eta",
- "\u03AE", "etatonos",
- "\u00F0", "eth",
- "\u0021", "exclam",
- "\u203C", "exclamdbl",
- "\u00A1", "exclamdown",
- "\uF7A1", "exclamdownsmall",
- "\uF721", "exclamsmall",
- "\u2203", "existential",
- "\u0066", "f",
- "\u2640", "female",
- "\uFB00", "ff",
- "\uFB03", "ffi",
- "\uFB04", "ffl",
- "\uFB01", "fi",
- "\u2012", "figuredash",
- "\u25A0", "filledbox",
- "\u25AC", "filledrect",
- "\u0035", "five",
- "\u215D", "fiveeighths",
- "\u2085", "fiveinferior",
- "\uF735", "fiveoldstyle",
- "\u2075", "fivesuperior",
- "\uFB02", "fl",
- "\u0192", "florin",
- "\u0034", "four",
- "\u2084", "fourinferior",
- "\uF734", "fouroldstyle",
- "\u2074", "foursuperior",
- "\u2044", "fraction",
- "\u2215", "fraction",
- "\u20A3", "franc",
- "\u0067", "g",
- "\u03B3", "gamma",
- "\u011F", "gbreve",
- "\u01E7", "gcaron",
- "\u011D", "gcircumflex",
- "\u0123", "gcommaaccent",
- "\u0121", "gdotaccent",
- "\u00DF", "germandbls",
- "\u2207", "gradient",
- "\u0060", "grave",
- "\u0300", "gravecomb",
- "\u003E", "greater",
- "\u2265", "greaterequal",
- "\u00AB", "guillemotleft",
- "\u00BB", "guillemotright",
- "\u2039", "guilsinglleft",
- "\u203A", "guilsinglright",
- "\u0068", "h",
- "\u0127", "hbar",
- "\u0125", "hcircumflex",
- "\u2665", "heart",
- "\u0309", "hookabovecomb",
- "\u2302", "house",
- "\u02DD", "hungarumlaut",
- "\u002D", "hyphen",
- "\u00AD", "hyphen",
- "\uF6E5", "hypheninferior",
- "\uF6E6", "hyphensuperior",
- "\u0069", "i",
- "\u00ED", "iacute",
- "\u012D", "ibreve",
- "\u00EE", "icircumflex",
- "\u00EF", "idieresis",
- "\u00EC", "igrave",
- "\u0133", "ij",
- "\u012B", "imacron",
- "\u221E", "infinity",
- "\u222B", "integral",
- "\u2321", "integralbt",
- "\uF8F5", "integralex",
- "\u2320", "integraltp",
- "\u2229", "intersection",
- "\u25D8", "invbullet",
- "\u25D9", "invcircle",
- "\u263B", "invsmileface",
- "\u012F", "iogonek",
- "\u03B9", "iota",
- "\u03CA", "iotadieresis",
- "\u0390", "iotadieresistonos",
- "\u03AF", "iotatonos",
- "\uF6ED", "isuperior",
- "\u0129", "itilde",
- "\u006A", "j",
- "\u0135", "jcircumflex",
- "\u006B", "k",
- "\u03BA", "kappa",
- "\u0137", "kcommaaccent",
- "\u0138", "kgreenlandic",
- "\u006C", "l",
- "\u013A", "lacute",
- "\u03BB", "lambda",
- "\u013E", "lcaron",
- "\u013C", "lcommaaccent",
- "\u0140", "ldot",
- "\u003C", "less",
- "\u2264", "lessequal",
- "\u258C", "lfblock",
- "\u20A4", "lira",
- "\uF6C0", "ll",
- "\u2227", "logicaland",
- "\u00AC", "logicalnot",
- "\u2228", "logicalor",
- "\u017F", "longs",
- "\u25CA", "lozenge",
- "\u0142", "lslash",
- "\uF6EE", "lsuperior",
- "\u2591", "ltshade",
- "\u006D", "m",
- "\u00AF", "macron",
- "\u02C9", "macron",
- "\u2642", "male",
- "\u2212", "minus",
- "\u2032", "minute",
- "\uF6EF", "msuperior",
- "\u00B5", "mu",
- "\u03BC", "mu",
- "\u00D7", "multiply",
- "\u266A", "musicalnote",
- "\u266B", "musicalnotedbl",
- "\u006E", "n",
- "\u0144", "nacute",
- "\u0149", "napostrophe",
- "\u0148", "ncaron",
- "\u0146", "ncommaaccent",
- "\u0039", "nine",
- "\u2089", "nineinferior",
- "\uF739", "nineoldstyle",
- "\u2079", "ninesuperior",
- "\u2209", "notelement",
- "\u2260", "notequal",
- "\u2284", "notsubset",
- "\u207F", "nsuperior",
- "\u00F1", "ntilde",
- "\u03BD", "nu",
- "\u0023", "numbersign",
- "\u006F", "o",
- "\u00F3", "oacute",
- "\u014F", "obreve",
- "\u00F4", "ocircumflex",
- "\u00F6", "odieresis",
- "\u0153", "oe",
- "\u02DB", "ogonek",
- "\u00F2", "ograve",
- "\u01A1", "ohorn",
- "\u0151", "ohungarumlaut",
- "\u014D", "omacron",
- "\u03C9", "omega",
- "\u03D6", "omega1",
- "\u03CE", "omegatonos",
- "\u03BF", "omicron",
- "\u03CC", "omicrontonos",
- "\u0031", "one",
- "\u2024", "onedotenleader",
- "\u215B", "oneeighth",
- "\uF6DC", "onefitted",
- "\u00BD", "onehalf",
- "\u2081", "oneinferior",
- "\uF731", "oneoldstyle",
- "\u00BC", "onequarter",
- "\u00B9", "onesuperior",
- "\u2153", "onethird",
- "\u25E6", "openbullet",
- "\u00AA", "ordfeminine",
- "\u00BA", "ordmasculine",
- "\u221F", "orthogonal",
- "\u00F8", "oslash",
- "\u01FF", "oslashacute",
- "\uF6F0", "osuperior",
- "\u00F5", "otilde",
- "\u0070", "p",
- "\u00B6", "paragraph",
- "\u0028", "parenleft",
- "\uF8ED", "parenleftbt",
- "\uF8EC", "parenleftex",
- "\u208D", "parenleftinferior",
- "\u207D", "parenleftsuperior",
- "\uF8EB", "parenlefttp",
- "\u0029", "parenright",
- "\uF8F8", "parenrightbt",
- "\uF8F7", "parenrightex",
- "\u208E", "parenrightinferior",
- "\u207E", "parenrightsuperior",
- "\uF8F6", "parenrighttp",
- "\u2202", "partialdiff",
- "\u0025", "percent",
- "\u002E", "period",
- "\u00B7", "periodcentered",
- "\u2219", "periodcentered",
- "\uF6E7", "periodinferior",
- "\uF6E8", "periodsuperior",
- "\u22A5", "perpendicular",
- "\u2030", "perthousand",
- "\u20A7", "peseta",
- "\u03C6", "phi",
- "\u03D5", "phi1",
- "\u03C0", "pi",
- "\u002B", "plus",
- "\u00B1", "plusminus",
- "\u211E", "prescription",
- "\u220F", "product",
- "\u2282", "propersubset",
- "\u2283", "propersuperset",
- "\u221D", "proportional",
- "\u03C8", "psi",
- "\u0071", "q",
- "\u003F", "question",
- "\u00BF", "questiondown",
- "\uF7BF", "questiondownsmall",
- "\uF73F", "questionsmall",
- "\"", "quotedbl",
-// "\u0022", "quotedbl",
- "\u201E", "quotedblbase",
- "\u201C", "quotedblleft",
- "\u201D", "quotedblright",
- "\u2018", "quoteleft",
- "\u201B", "quotereversed",
- "\u2019", "quoteright",
- "\u201A", "quotesinglbase",
- "\u0027", "quotesingle",
- "\u0072", "r",
- "\u0155", "racute",
- "\u221A", "radical",
- "\uF8E5", "radicalex",
- "\u0159", "rcaron",
- "\u0157", "rcommaaccent",
- "\u2286", "reflexsubset",
- "\u2287", "reflexsuperset",
- "\u00AE", "registered",
- "\uF8E8", "registersans",
- "\uF6DA", "registerserif",
- "\u2310", "revlogicalnot",
- "\u03C1", "rho",
- "\u02DA", "ring",
- "\uF6F1", "rsuperior",
- "\u2590", "rtblock",
- "\uF6DD", "rupiah",
- "\u0073", "s",
- "\u015B", "sacute",
- "\u0161", "scaron",
- "\u015F", "scedilla",
- "\uF6C2", "scedilla",
- "\u015D", "scircumflex",
- "\u0219", "scommaaccent",
- "\u2033", "second",
- "\u00A7", "section",
- "\u003B", "semicolon",
- "\u0037", "seven",
- "\u215E", "seveneighths",
- "\u2087", "seveninferior",
- "\uF737", "sevenoldstyle",
- "\u2077", "sevensuperior",
- "\u2592", "shade",
- "\u03C3", "sigma",
- "\u03C2", "sigma1",
- "\u223C", "similar",
- "\u0036", "six",
- "\u2086", "sixinferior",
- "\uF736", "sixoldstyle",
- "\u2076", "sixsuperior",
- "\u002F", "slash",
- "\u263A", "smileface",
- "\u0020", "space",
- "\u00A0", "space",
- "\u2660", "spade",
- "\uF6F2", "ssuperior",
- "\u00A3", "sterling",
- "\u220B", "suchthat",
- "\u2211", "summation",
- "\u263C", "sun",
- "\u0074", "t",
- "\u03C4", "tau",
- "\u0167", "tbar",
- "\u0165", "tcaron",
- "\u0163", "tcommaaccent",
- "\u021B", "tcommaaccent",
- "\u2234", "therefore",
- "\u03B8", "theta",
- "\u03D1", "theta1",
- "\u00FE", "thorn",
- "\u0033", "three",
- "\u215C", "threeeighths",
- "\u2083", "threeinferior",
- "\uF733", "threeoldstyle",
- "\u00BE", "threequarters",
- "\uF6DE", "threequartersemdash",
- "\u00B3", "threesuperior",
- "\u02DC", "tilde",
- "\u0303", "tildecomb",
- "\u0384", "tonos",
- "\u2122", "trademark",
- "\uF8EA", "trademarksans",
- "\uF6DB", "trademarkserif",
- "\u25BC", "triagdn",
- "\u25C4", "triaglf",
- "\u25BA", "triagrt",
- "\u25B2", "triagup",
- "\uF6F3", "tsuperior",
- "\u0032", "two",
- "\u2025", "twodotenleader",
- "\u2082", "twoinferior",
- "\uF732", "twooldstyle",
- "\u00B2", "twosuperior",
- "\u2154", "twothirds",
- "\u0075", "u",
- "\u00FA", "uacute",
- "\u016D", "ubreve",
- "\u00FB", "ucircumflex",
- "\u00FC", "udieresis",
- "\u00F9", "ugrave",
- "\u01B0", "uhorn",
- "\u0171", "uhungarumlaut",
- "\u016B", "umacron",
- "\u005F", "underscore",
- "\u2017", "underscoredbl",
- "\u222A", "union",
- "\u2200", "universal",
- "\u0173", "uogonek",
- "\u2580", "upblock",
- "\u03C5", "upsilon",
- "\u03CB", "upsilondieresis",
- "\u03B0", "upsilondieresistonos",
- "\u03CD", "upsilontonos",
- "\u016F", "uring",
- "\u0169", "utilde",
- "\u0076", "v",
- "\u0077", "w",
- "\u1E83", "wacute",
- "\u0175", "wcircumflex",
- "\u1E85", "wdieresis",
- "\u2118", "weierstrass",
- "\u1E81", "wgrave",
- "\u0078", "x",
- "\u03BE", "xi",
- "\u0079", "y",
- "\u00FD", "yacute",
- "\u0177", "ycircumflex",
- "\u00FF", "ydieresis",
- "\u00A5", "yen",
- "\u1EF3", "ygrave",
- "\u007A", "z",
- "\u017A", "zacute",
- "\u017E", "zcaron",
- "\u017C", "zdotaccent",
- "\u0030", "zero",
- "\u2080", "zeroinferior",
- "\uF730", "zerooldstyle",
- "\u2070", "zerosuperior",
- "\u03B6", "zeta"};
- /** Return the glyphname from a string,
- eg, glyphToString("\\") returns "backslash"
- */
- public static String glyphToString(String name) {
- String ret="";
- int i=unicode_glyphs.length;
- for (int j=0; j", "greater",
+ "?", "greaterequal", "«", "guillemotleft", "»",
+ "guillemotright", "?", "guilsinglleft", "?", "guilsinglright",
+ "h", "h", "?", "hbar", "?", "hcircumflex", "?", "heart", "?",
+ "hookabovecomb", "?", "house", "?", "hungarumlaut", "-",
+ "hyphen", "", "hyphen", "?", "hypheninferior", "?",
+ "hyphensuperior", "i", "i", "í", "iacute", "?", "ibreve", "î",
+ "icircumflex", "ï", "idieresis", "ì", "igrave", "?", "ij", "?",
+ "imacron", "?", "infinity", "?", "integral", "?", "integralbt",
+ "?", "integralex", "?", "integraltp", "?", "intersection", "?",
+ "invbullet", "?", "invcircle", "?", "invsmileface", "?",
+ "iogonek", "?", "iota", "?", "iotadieresis", "?",
+ "iotadieresistonos", "?", "iotatonos", "?", "isuperior", "?",
+ "itilde", "j", "j", "?", "jcircumflex", "k", "k", "?", "kappa",
+ "?", "kcommaaccent", "?", "kgreenlandic", "l", "l", "?",
+ "lacute", "?", "lambda", "?", "lcaron", "?", "lcommaaccent",
+ "?", "ldot", "<", "less", "?", "lessequal", "?", "lfblock",
+ "?", "lira", "?", "ll", "?", "logicaland", "¬", "logicalnot",
+ "?", "logicalor", "?", "longs", "?", "lozenge", "?", "lslash",
+ "?", "lsuperior", "?", "ltshade", "m", "m", "¯", "macron", "?",
+ "macron", "?", "male", "?", "minus", "?", "minute", "?",
+ "msuperior", "µ", "mu", "?", "mu", "×", "multiply", "?",
+ "musicalnote", "?", "musicalnotedbl", "n", "n", "?", "nacute",
+ "?", "napostrophe", "?", "ncaron", "?", "ncommaaccent", "9",
+ "nine", "?", "nineinferior", "?", "nineoldstyle", "?",
+ "ninesuperior", "?", "notelement", "?", "notequal", "?",
+ "notsubset", "?", "nsuperior", "ñ", "ntilde", "?", "nu", "#",
+ "numbersign", "o", "o", "ó", "oacute", "?", "obreve", "ô",
+ "ocircumflex", "ö", "odieresis", "?", "oe", "?", "ogonek", "ò",
+ "ograve", "?", "ohorn", "?", "ohungarumlaut", "?", "omacron",
+ "?", "omega", "?", "omega1", "?", "omegatonos", "?", "omicron",
+ "?", "omicrontonos", "1", "one", "?", "onedotenleader", "?",
+ "oneeighth", "?", "onefitted", "½", "onehalf", "?",
+ "oneinferior", "?", "oneoldstyle", "¼", "onequarter", "¹",
+ "onesuperior", "?", "onethird", "?", "openbullet", "ª",
+ "ordfeminine", "º", "ordmasculine", "?", "orthogonal", "ø",
+ "oslash", "?", "oslashacute", "?", "osuperior", "õ", "otilde",
+ "p", "p", "¶", "paragraph", "(", "parenleft", "?",
+ "parenleftbt", "?", "parenleftex", "?", "parenleftinferior",
+ "?", "parenleftsuperior", "?", "parenlefttp", ")",
+ "parenright", "?", "parenrightbt", "?", "parenrightex", "?",
+ "parenrightinferior", "?", "parenrightsuperior", "?",
+ "parenrighttp", "?", "partialdiff", "%", "percent", ".",
+ "period", "·", "periodcentered", "?", "periodcentered", "?",
+ "periodinferior", "?", "periodsuperior", "?", "perpendicular",
+ "?", "perthousand", "?", "peseta", "?", "phi", "?", "phi1",
+ "?", "pi", "+", "plus", "±", "plusminus", "?", "prescription",
+ "?", "product", "?", "propersubset", "?", "propersuperset",
+ "?", "proportional", "?", "psi", "q", "q", "?", "question",
+ "¿", "questiondown", "?", "questiondownsmall", "?",
+ "questionsmall", "\"", "quotedbl", // """, "quotedbl",
+ "?", "quotedblbase", "?", "quotedblleft", "?", "quotedblright", "?",
+ "quoteleft", "?", "quotereversed", "?", "quoteright", "?",
+ "quotesinglbase", "'", "quotesingle", "r", "r", "?", "racute",
+ "?", "radical", "?", "radicalex", "?", "rcaron", "?",
+ "rcommaaccent", "?", "reflexsubset", "?", "reflexsuperset", "®",
+ "registered", "?", "registersans", "?", "registerserif", "?",
+ "revlogicalnot", "?", "rho", "?", "ring", "?", "rsuperior", "?",
+ "rtblock", "?", "rupiah", "s", "s", "?", "sacute", "?",
+ "scaron", "?", "scedilla", "?", "scedilla", "?", "scircumflex",
+ "?", "scommaaccent", "?", "second", "§", "section", ";",
+ "semicolon", "7", "seven", "?", "seveneighths", "?",
+ "seveninferior", "?", "sevenoldstyle", "?", "sevensuperior",
+ "?", "shade", "?", "sigma", "?", "sigma1", "?", "similar", "6",
+ "six", "?", "sixinferior", "?", "sixoldstyle", "?",
+ "sixsuperior", "/", "slash", "?", "smileface", " ", "space",
+ " ", "space", "?", "spade", "?", "ssuperior", "£", "sterling",
+ "?", "suchthat", "?", "summation", "?", "sun", "t", "t", "?",
+ "tau", "?", "tbar", "?", "tcaron", "?", "tcommaaccent", "?",
+ "tcommaaccent", "?", "therefore", "?", "theta", "?", "theta1",
+ "þ", "thorn", "3", "three", "?", "threeeighths", "?",
+ "threeinferior", "?", "threeoldstyle", "¾", "threequarters",
+ "?", "threequartersemdash", "³", "threesuperior", "?", "tilde",
+ "?", "tildecomb", "?", "tonos", "?", "trademark", "?",
+ "trademarksans", "?", "trademarkserif", "?", "triagdn", "?",
+ "triaglf", "?", "triagrt", "?", "triagup", "?", "tsuperior",
+ "2", "two", "?", "twodotenleader", "?", "twoinferior", "?",
+ "twooldstyle", "²", "twosuperior", "?", "twothirds", "u", "u",
+ "ú", "uacute", "?", "ubreve", "û", "ucircumflex", "ü",
+ "udieresis", "ù", "ugrave", "?", "uhorn", "?", "uhungarumlaut",
+ "?", "umacron", "_", "underscore", "?", "underscoredbl", "?",
+ "union", "?", "universal", "?", "uogonek", "?", "upblock", "?",
+ "upsilon", "?", "upsilondieresis", "?", "upsilondieresistonos",
+ "?", "upsilontonos", "?", "uring", "?", "utilde", "v", "v", "w",
+ "w", "?", "wacute", "?", "wcircumflex", "?", "wdieresis", "?",
+ "weierstrass", "?", "wgrave", "x", "x", "?", "xi", "y", "y",
+ "ý", "yacute", "?", "ycircumflex", "ÿ", "ydieresis", "¥", "yen",
+ "?", "ygrave", "z", "z", "?", "zacute", "?", "zcaron", "?",
+ "zdotaccent", "0", "zero", "?", "zeroinferior", "?",
+ "zerooldstyle", "?", "zerosuperior", "?", "zeta"
+ };
+
+ /**
+ * Return the glyphname from a string,
+ * eg, glyphToString("\\") returns "backslash"
+ */
+ public static String glyphToString(String name) {
+ String ret = "";
+ int i = unicode_glyphs.length;
+ for (int j = 0; j < i; j += 2) {
+ if (unicode_glyphs[j + 1].equals(name)) {
+ ret = unicode_glyphs[j];
+ j = i;
+ }
+ }
+ return ret;
+ }
+
+ /**
+ * Return the string representation of a glyphname,
+ * eg stringToGlyph("backslash") returns "\\"
+ */
+ public static String stringToGlyph(String name) {
+ String ret = "";
+ int i = unicode_glyphs.length;
+ for (int j = 0; j < i; j += 2) {
+ if (unicode_glyphs[j].equals(name)) {
+ ret = unicode_glyphs[j + 1];
+ j = i;
+ }
+ }
+ return ret;
+ }
+
}
diff --git a/src/org/apache/fop/fonts/PFMFile.java b/src/org/apache/fop/fonts/PFMFile.java
index 83c265437..cf1c7e8d7 100644
--- a/src/org/apache/fop/fonts/PFMFile.java
+++ b/src/org/apache/fop/fonts/PFMFile.java
@@ -1,9 +1,10 @@
-/*-- $Id$ --
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fonts;
import java.io.*;
@@ -16,7 +17,7 @@ import java.util.Hashtable;
*/
public class PFMFile {
- //Header stuff
+ // Header stuff
private String windowsName;
private String postscriptName;
private short dfItalic;
@@ -29,16 +30,16 @@ public class PFMFile {
private short dfFirstChar;
private short dfLastChar;
- //Extension stuff
- //---
+ // Extension stuff
+ // ---
- //Extend Text Metrics
+ // Extend Text Metrics
private int etmCapHeight;
private int etmXHeight;
private int etmLowerCaseAscent;
private int etmLowerCaseDescent;
- //Extent table
+ // Extent table
private int[] extentTable;
private Hashtable kerningTab;
@@ -47,10 +48,10 @@ public class PFMFile {
}
/**
- * Parses a PFM file
- *
- * @param inStream The stream from which to read the PFM file.
- */
+ * Parses a PFM file
+ *
+ * @param inStream The stream from which to read the PFM file.
+ */
public void load(InputStream inStream) throws IOException {
InputStream bufin = new BufferedInputStream(inStream, 1024);
bufin.mark(1024);
@@ -59,8 +60,8 @@ public class PFMFile {
long filesize = in.readInt();
bufin.reset();
- byte[] buf = new byte[(int) filesize];
- bufin.read(buf, 0, (int) filesize);
+ byte[] buf = new byte[(int)filesize];
+ bufin.read(buf, 0, (int)filesize);
bufin = new ByteArrayInputStream(buf);
in = new PFMInputStream(bufin);
@@ -69,10 +70,10 @@ public class PFMFile {
}
/**
- * Parses the header of the PFM file.
- *
- * @param inStream The stream from which to read the PFM file.
- */
+ * Parses the header of the PFM file.
+ *
+ * @param inStream The stream from which to read the PFM file.
+ */
private void loadHeader(PFMInputStream inStream) throws IOException {
inStream.skip(80);
dfItalic = inStream.readByte();
@@ -97,10 +98,10 @@ public class PFMFile {
}
/**
- * Parses the extension part of the PFM file.
- *
- * @param inStream The stream from which to read the PFM file.
- */
+ * Parses the extension part of the PFM file.
+ *
+ * @param inStream The stream from which to read the PFM file.
+ */
private void loadExtension(PFMInputStream inStream) throws IOException {
int size = inStream.readShort();
long extMetricsOffset = inStream.readInt();
@@ -134,32 +135,32 @@ public class PFMFile {
}
/**
- * Parses the kernPairs part of the pfm file
- *
- * @param inStream The stream from which to read the PFM file.
- */
+ * Parses the kernPairs part of the pfm file
+ *
+ * @param inStream The stream from which to read the PFM file.
+ */
private void loadKernPairs(PFMInputStream inStream) throws IOException {
int i = inStream.readShort();
System.out.println(i + " kerning pairs");
while (i > 0) {
- int g1 = (int) inStream.readByte();
+ int g1 = (int)inStream.readByte();
i--;
- //System.out.print ("Char no: ("+g1+", ");
+ // System.out.print ("Char no: ("+g1+", ");
- int g2 = (int) inStream.readByte();
- //System.out.print (g2+") kern");
+ int g2 = (int)inStream.readByte();
+ // System.out.print (g2+") kern");
int adj = inStream.readShort();
if (adj > 0x8000)
adj = -(0x10000 - adj);
- //System.out.println (": " + adj);
+ // System.out.println (": " + adj);
String glyph1 = Glyphs.tex8r[g1];
String glyph2 = Glyphs.tex8r[g2];
- Hashtable adjTab = (Hashtable) kerningTab.get(new Integer(g1));
+ Hashtable adjTab = (Hashtable)kerningTab.get(new Integer(g1));
if (adjTab == null)
adjTab = new Hashtable();
adjTab.put(new Integer(g2), new Integer(adj));
@@ -168,12 +169,11 @@ public class PFMFile {
}
/**
- * Parses the extended metrics part of the PFM file.
- *
- * @param inStream The stream from which to read the PFM file.
- */
- private void loadExtMetrics(PFMInputStream inStream)
- throws IOException {
+ * Parses the extended metrics part of the PFM file.
+ *
+ * @param inStream The stream from which to read the PFM file.
+ */
+ private void loadExtMetrics(PFMInputStream inStream) throws IOException {
int size = inStream.readShort();
inStream.skip(12);
etmCapHeight = inStream.readShort();
@@ -183,12 +183,11 @@ public class PFMFile {
}
/**
- * Parses the extent table of the PFM file.
- *
- * @param inStream The stream from which to read the PFM file.
- */
- private void loadExtentTable(PFMInputStream inStream)
- throws IOException {
+ * Parses the extent table of the PFM file.
+ *
+ * @param inStream The stream from which to read the PFM file.
+ */
+ private void loadExtentTable(PFMInputStream inStream) throws IOException {
extentTable = new int[dfLastChar - dfFirstChar + 1];
dfMinWidth = dfMaxWidth;
for (short i = dfFirstChar; i <= dfLastChar; i++) {
@@ -200,133 +199,133 @@ public class PFMFile {
}
/**
- * Returns the Windows name of the font.
- *
- * @return The Windows name.
- */
+ * Returns the Windows name of the font.
+ *
+ * @return The Windows name.
+ */
public String getWindowsName() {
return windowsName;
}
/**
- * Return the kerning table. The kerning table is a hastable with
- * strings with glyphnames as keys, containing hashtables as value.
- * The value hashtable contain a glyph name string key and an Integer value
- */
+ * Return the kerning table. The kerning table is a hastable with
+ * strings with glyphnames as keys, containing hashtables as value.
+ * The value hashtable contain a glyph name string key and an Integer value
+ */
public Hashtable getKerning() {
return kerningTab;
}
/**
- * Returns the Postscript name of the font.
- *
- * @return The Postscript name.
- */
+ * Returns the Postscript name of the font.
+ *
+ * @return The Postscript name.
+ */
public String getPostscriptName() {
return postscriptName;
}
/**
- * Returns the charset used for the font.
- *
- * @return The charset (0=WinAnsi).
- */
+ * Returns the charset used for the font.
+ *
+ * @return The charset (0=WinAnsi).
+ */
public short getCharSet() {
return dfCharSet;
}
/**
- * Returns the charset of the font as a string.
- *
- * @return The name of the charset.
- */
+ * Returns the charset of the font as a string.
+ *
+ * @return The name of the charset.
+ */
public String getCharSetName() {
switch (dfCharSet) {
- case 0:
- return "WinAnsi";
- case 128:
- return "Shift-JIS (Japanese)";
- default:
- return "Unknown";
+ case 0:
+ return "WinAnsi";
+ case 128:
+ return "Shift-JIS (Japanese)";
+ default:
+ return "Unknown";
}
}
/**
- * Returns the number of the character that defines
- * the first entry in the widths list.
- *
- * @return The number of the first character.
- */
+ * Returns the number of the character that defines
+ * the first entry in the widths list.
+ *
+ * @return The number of the first character.
+ */
public short getFirstChar() {
return dfFirstChar;
}
/**
- * Returns the number of the character that defines
- * the last entry in the widths list.
- *
- * @return The number of the last character.
- */
+ * Returns the number of the character that defines
+ * the last entry in the widths list.
+ *
+ * @return The number of the last character.
+ */
public short getLastChar() {
return dfLastChar;
}
/**
- * Returns the CapHeight parameter for the font (height of uppercase H).
- *
- * @return The CapHeight parameter.
- */
+ * Returns the CapHeight parameter for the font (height of uppercase H).
+ *
+ * @return The CapHeight parameter.
+ */
public int getCapHeight() {
return etmCapHeight;
}
/**
- * Returns the XHeight parameter for the font (height of lowercase x).
- *
- * @return The CapHeight parameter.
- */
+ * Returns the XHeight parameter for the font (height of lowercase x).
+ *
+ * @return The CapHeight parameter.
+ */
public int getXHeight() {
return etmXHeight;
}
/**
- * Returns the LowerCaseAscent parameter for the font (height of lowercase d).
- *
- * @return The LowerCaseAscent parameter.
- */
+ * Returns the LowerCaseAscent parameter for the font (height of lowercase d).
+ *
+ * @return The LowerCaseAscent parameter.
+ */
public int getLowerCaseAscent() {
return etmLowerCaseAscent;
}
/**
- * Returns the LowerCaseDescent parameter for the font (height of lowercase p).
- *
- * @return The LowerCaseDescent parameter.
- */
+ * Returns the LowerCaseDescent parameter for the font (height of lowercase p).
+ *
+ * @return The LowerCaseDescent parameter.
+ */
public int getLowerCaseDescent() {
return etmLowerCaseDescent;
}
/**
- * Tells whether the font has proportional character spacing.
- *
- * @return ex. true for Times, false for Courier.
- */
+ * Tells whether the font has proportional character spacing.
+ *
+ * @return ex. true for Times, false for Courier.
+ */
public boolean getIsProportional() {
return ((dfPitchAndFamily & 1) == 1);
}
/**
- * Returns the bounding box for the font.
- * Note: this value is just an approximation,
- * it does not really exist in the PFM file.
- *
- * @return The calculated Font BBox.
- */
+ * Returns the bounding box for the font.
+ * Note: this value is just an approximation,
+ * it does not really exist in the PFM file.
+ *
+ * @return The calculated Font BBox.
+ */
public int[] getFontBBox() {
int[] bbox = new int[4];
- //Just guessing....
+ // Just guessing....
if (!getIsProportional() && (dfAvgWidth == dfMaxWidth)) {
bbox[0] = -20;
} else {
@@ -339,11 +338,11 @@ public class PFMFile {
}
/**
- * Returns the characteristics flags for the font as
- * needed for a PDF font descriptor (See PDF specs).
- *
- * @return The characteristics flags.
- */
+ * Returns the characteristics flags for the font as
+ * needed for a PDF font descriptor (See PDF specs).
+ *
+ * @return The characteristics flags.
+ */
public int getFlags() {
int flags = 0;
if (!getIsProportional()) {
@@ -365,43 +364,44 @@ public class PFMFile {
}
/**
- * Returns the width of the dominant vertical stems of the font.
- * Note: this value is just an approximation,
- * it does not really exist in the PFM file.
- *
- * @return The vertical stem width.
- */
+ * Returns the width of the dominant vertical stems of the font.
+ * Note: this value is just an approximation,
+ * it does not really exist in the PFM file.
+ *
+ * @return The vertical stem width.
+ */
public int getStemV() {
- //Just guessing....
+ // Just guessing....
if (dfItalic != 0) {
- return (int) Math.round(dfMinWidth * 0.25);
+ return (int)Math.round(dfMinWidth * 0.25);
} else {
- return (int) Math.round(dfMinWidth * 0.6);
+ return (int)Math.round(dfMinWidth * 0.6);
}
}
/**
- * Returns the italic angle of the font.
- * Note: this value is just an approximation,
- * it does not really exist in the PFM file.
- *
- * @return The italic angle.
- */
+ * Returns the italic angle of the font.
+ * Note: this value is just an approximation,
+ * it does not really exist in the PFM file.
+ *
+ * @return The italic angle.
+ */
public int getItalicAngle() {
if (dfItalic != 0) {
- return -16; //Just guessing....
+ return -16; // Just guessing....
} else {
return 0;
}
}
/**
- * Returns the width of a character
- *
- * @param which The number of the character for which the width is requested.
- * @return The width of a character.
- */
+ * Returns the width of a character
+ *
+ * @param which The number of the character for which the width is requested.
+ * @return The width of a character.
+ */
public int getCharWidth(short which) {
return extentTable[which - dfFirstChar];
}
+
}
diff --git a/src/org/apache/fop/fonts/PFMInputStream.java b/src/org/apache/fop/fonts/PFMInputStream.java
index e45d5e1a5..e956070ed 100644
--- a/src/org/apache/fop/fonts/PFMInputStream.java
+++ b/src/org/apache/fop/fonts/PFMInputStream.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fonts;
import java.io.*;
@@ -64,7 +21,7 @@ public class PFMInputStream extends java.io.FilterInputStream {
/**
* Constructs a PFMInputStream based on an InputStream representing the PFM file.
- *
+ *
* @param inStream The stream from which to read the PFM file.
*/
public PFMInputStream(InputStream in) {
@@ -74,39 +31,39 @@ public class PFMInputStream extends java.io.FilterInputStream {
/**
* Parses a one byte value out of the stream.
- *
+ *
* @return The value extracted.
*/
public short readByte() throws IOException {
short s = inStream.readByte();
- //Now, we've got to trick Java into forgetting the sign
+ // Now, we've got to trick Java into forgetting the sign
int s1 = (((s & 0xF0) >>> 4) << 4) + (s & 0x0F);
return (short)s1;
}
/**
* Parses a two byte value out of the stream.
- *
+ *
* @return The value extracted.
*/
public int readShort() throws IOException {
int i = inStream.readShort();
- //Change byte order
+ // Change byte order
int high = (i & 0xFF00) >>> 8;
- int low = (i & 0x00FF) << 8;
+ int low = (i & 0x00FF) << 8;
return low + high;
}
/**
* Parses a four byte value out of the stream.
- *
+ *
* @return The value extracted.
*/
public long readInt() throws IOException {
int i = inStream.readInt();
- //Change byte order
+ // Change byte order
int i1 = (i & 0xFF000000) >>> 24;
int i2 = (i & 0x00FF0000) >>> 8;
int i3 = (i & 0x0000FF00) << 8;
@@ -116,7 +73,7 @@ public class PFMInputStream extends java.io.FilterInputStream {
/**
* Parses a zero-terminated string out of the stream.
- *
+ *
* @return The value extracted.
*/
public String readString() throws IOException {
@@ -124,9 +81,10 @@ public class PFMInputStream extends java.io.FilterInputStream {
StringBuffer buf = new StringBuffer();
int ch = reader.read();
while (ch != 0) {
- buf.append((char) ch);
- ch = reader.read();
+ buf.append((char)ch);
+ ch = reader.read();
}
return buf.toString();
}
-}
\ No newline at end of file
+
+}
diff --git a/src/org/apache/fop/fonts/TTFCmapEntry.java b/src/org/apache/fop/fonts/TTFCmapEntry.java
index b4a9c3bbc..36725a28b 100644
--- a/src/org/apache/fop/fonts/TTFCmapEntry.java
+++ b/src/org/apache/fop/fonts/TTFCmapEntry.java
@@ -1,9 +1,10 @@
-/* -- $Id$ --
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fonts;
/**
@@ -21,18 +22,18 @@ public class TTFCmapEntry {
glyphStartIndex = 0;
}
- TTFCmapEntry (int unicodeStart, int unicodeEnd, int glyphStartIndex) {
+ TTFCmapEntry(int unicodeStart, int unicodeEnd, int glyphStartIndex) {
this.unicodeStart = unicodeStart;
this.unicodeEnd = unicodeEnd;
this.glyphStartIndex = glyphStartIndex;
}
- public boolean equals (Object o) {
+ public boolean equals(Object o) {
if (o instanceof TTFCmapEntry) {
- TTFCmapEntry ce = (TTFCmapEntry) o;
- if (ce.unicodeStart == this.unicodeStart &&
- ce.unicodeEnd == this.unicodeEnd &&
- ce.glyphStartIndex == this.glyphStartIndex)
+ TTFCmapEntry ce = (TTFCmapEntry)o;
+ if (ce.unicodeStart == this.unicodeStart
+ && ce.unicodeEnd == this.unicodeEnd
+ && ce.glyphStartIndex == this.glyphStartIndex)
return true;
}
return false;
diff --git a/src/org/apache/fop/fonts/TTFDirTabEntry.java b/src/org/apache/fop/fonts/TTFDirTabEntry.java
index 9a2b0ea12..1c1e7406c 100644
--- a/src/org/apache/fop/fonts/TTFDirTabEntry.java
+++ b/src/org/apache/fop/fonts/TTFDirTabEntry.java
@@ -1,9 +1,10 @@
-/* -- $Id$ --
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fonts;
import java.io.*;
@@ -17,27 +18,30 @@ class TTFDirTabEntry {
tag = new byte[4];
}
- /** Read Dir Tab, return tag name */
+ /**
+ * Read Dir Tab, return tag name
+ */
public String read(FontFileReader in) throws IOException {
tag[0] = in.readTTFByte();
tag[1] = in.readTTFByte();
tag[2] = in.readTTFByte();
tag[3] = in.readTTFByte();
- in.skip(4); // Skip checksum
+ in.skip(4); // Skip checksum
offset = in.readTTFULong();
length = in.readTTFULong();
/*
- System.out.println ("Read dir tab [" + tag[0]+
- " "+tag[1] +
- " "+tag[2] +
- " "+tag[3] +
- "] offset: " + offset +
- " length: " + length +
- " name: " + new String(tag));
- */
+ * System.out.println ("Read dir tab [" + tag[0]+
+ * " "+tag[1] +
+ * " "+tag[2] +
+ * " "+tag[3] +
+ * "] offset: " + offset +
+ * " length: " + length +
+ * " name: " + new String(tag));
+ */
return new String(tag, "ISO-8859-1");
}
+
}
diff --git a/src/org/apache/fop/fonts/TTFFile.java b/src/org/apache/fop/fonts/TTFFile.java
index 1e72a209e..d48a1948e 100644
--- a/src/org/apache/fop/fonts/TTFFile.java
+++ b/src/org/apache/fop/fonts/TTFFile.java
@@ -1,9 +1,10 @@
-/* -- $Id$ --
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fonts;
import java.io.*;
import java.util.Enumeration;
@@ -21,25 +22,25 @@ public class TTFFile {
static final int MAX_CHAR_CODE = 255;
static final int ENC_BUF_SIZE = 1024;
- static String encoding = "WinAnsiEncoding"; // Deafult encoding
+ static String encoding = "WinAnsiEncoding"; // Deafult encoding
short firstChar = 0;
boolean is_embeddable = true;
boolean hasSerifs = true;
- Hashtable dirTabs; // Table directory
- Hashtable kerningTab; // for CIDs
- Hashtable ansiKerningTab; // For winAnsiEncoding
+ Hashtable dirTabs; // Table directory
+ Hashtable kerningTab; // for CIDs
+ Hashtable ansiKerningTab; // For winAnsiEncoding
Vector cmaps;
- Vector unicodeMapping; //
+ Vector unicodeMapping; //
- int upem; // unitsPerEm from "head" table
- int nhmtx; // Number of horizontal metrics
+ int upem; // unitsPerEm from "head" table
+ int nhmtx; // Number of horizontal metrics
int post_format;
int loca_format;
- long lastLoca = 0; // offset to last loca
- int nglyphs; // Number of glyphs in font (read from "maxp" table)
- int nmglyphs; // Used in fixWidths - remove?
+ long lastLoca = 0; // offset to last loca
+ int nglyphs; // Number of glyphs in font (read from "maxp" table)
+ int nmglyphs; // Used in fixWidths - remove?
- TTFMtxEntry mtx_tab[]; // Contains glyph data
+ TTFMtxEntry mtx_tab[]; // Contains glyph data
int[] mtx_encoded = null;
String fontName = "";
@@ -66,11 +67,13 @@ public class TTFFile {
int ansiWidth[];
Hashtable ansiIndex;
- /** Position inputstream to position indicated
- in the dirtab offset + offset */
+ /**
+ * Position inputstream to position indicated
+ * in the dirtab offset + offset
+ */
void seek_tab(FontFileReader in, String name,
long offset) throws IOException {
- TTFDirTabEntry dt = (TTFDirTabEntry) dirTabs.get(name);
+ TTFDirTabEntry dt = (TTFDirTabEntry)dirTabs.get(name);
if (dt == null) {
System.out.println("Dirtab " + name + " not found.");
return;
@@ -79,18 +82,19 @@ public class TTFFile {
in.seek_set(dt.offset + offset);
}
- /** Convert from truetype unit to pdf unit based on the
- * unitsPerEm field in the "head" table
- @param n truetype unit
- @return pdf unit
- */
+ /**
+ * Convert from truetype unit to pdf unit based on the
+ * unitsPerEm field in the "head" table
+ * @param n truetype unit
+ * @return pdf unit
+ */
int get_ttf_funit(int n) {
int ret;
if (n < 0) {
long rest1 = n % upem;
long storrest = 1000 * rest1;
long ledd2 = rest1 / storrest;
- ret = -((-1000 * n) / upem - (int) ledd2);
+ ret = -((-1000 * n) / upem - (int)ledd2);
} else {
ret = (n / upem) * 1000 + ((n % upem) * 1000) / upem;
}
@@ -98,35 +102,39 @@ public class TTFFile {
return ret;
}
- /** Read the cmap table,
- * return false if the table is not present or only unsupported
- * tables are present. Currently only unicode cmaps are supported.
- * Set the unicodeIndex in the TTFMtxEntries and fills in the
- * cmaps vector.
- */
+ /**
+ * Read the cmap table,
+ * return false if the table is not present or only unsupported
+ * tables are present. Currently only unicode cmaps are supported.
+ * Set the unicodeIndex in the TTFMtxEntries and fills in the
+ * cmaps vector.
+ */
private boolean readCMAP(FontFileReader in) throws IOException {
unicodeMapping = new Vector();
- /** Read CMAP table and correct mtx_tab.index*/
+ /**
+ * Read CMAP table and correct mtx_tab.index
+ */
int mtxPtr = 0;
seek_tab(in, "cmap", 2);
- int num_cmap = in.readTTFUShort(); // Number of cmap subtables
+ int num_cmap = in.readTTFUShort(); // Number of cmap subtables
long cmap_unioffset = 0;
- //System.out.println(num_cmap+" cmap tables");
+ // System.out.println(num_cmap+" cmap tables");
- /* Read offset for all tables
- We are only interested in the unicode table
- */
+ /*
+ * Read offset for all tables
+ * We are only interested in the unicode table
+ */
for (int i = 0; i < num_cmap; i++) {
int cmap_pid = in.readTTFUShort();
int cmap_eid = in.readTTFUShort();
long cmap_offset = in.readTTFULong();
- //System.out.println("Platform ID: "+cmap_pid+
- // " Encoding: "+cmap_eid);
+ // System.out.println("Platform ID: "+cmap_pid+
+ // " Encoding: "+cmap_eid);
if (cmap_pid == 3 && cmap_eid == 1)
cmap_unioffset = cmap_offset;
@@ -142,20 +150,20 @@ public class TTFFile {
int cmap_format = in.readTTFUShort();
int cmap_length = in.readTTFUShort();
- //System.out.println("CMAP format: "+cmap_format);
+ // System.out.println("CMAP format: "+cmap_format);
if (cmap_format == 4) {
- in.skip(2); // Skip version number
+ in.skip(2); // Skip version number
int cmap_segCountX2 = in.readTTFUShort();
int cmap_searchRange = in.readTTFUShort();
int cmap_entrySelector = in.readTTFUShort();
int cmap_rangeShift = in.readTTFUShort();
/*
- System.out.println("segCountX2 : "+cmap_segCountX2);
- System.out.println("searchRange : "+cmap_searchRange);
- System.out.println("entrySelector: "+cmap_entrySelector);
- System.out.println("rangeShift : "+cmap_rangeShift);
- */
+ * System.out.println("segCountX2 : "+cmap_segCountX2);
+ * System.out.println("searchRange : "+cmap_searchRange);
+ * System.out.println("entrySelector: "+cmap_entrySelector);
+ * System.out.println("rangeShift : "+cmap_rangeShift);
+ */
int cmap_endCounts[] = new int[cmap_segCountX2 / 2];
int cmap_startCounts[] = new int[cmap_segCountX2 / 2];
@@ -166,7 +174,7 @@ public class TTFFile {
cmap_endCounts[i] = in.readTTFUShort();
}
- in.skip(2); // Skip reservedPad
+ in.skip(2); // Skip reservedPad
for (int i = 0; i < (cmap_segCountX2 / 2); i++) {
cmap_startCounts[i] = in.readTTFUShort();
@@ -189,91 +197,86 @@ public class TTFFile {
for (int i = 0; i < cmap_startCounts.length; i++) {
/*
- System.out.println(i+ ": "+cmap_startCounts[i]+
- " - "+cmap_endCounts[i]);
- */
- for (int j = cmap_startCounts[i];
- j <= cmap_endCounts[i]; j++) {
+ * System.out.println(i+ ": "+cmap_startCounts[i]+
+ * " - "+cmap_endCounts[i]);
+ */
+ for (int j = cmap_startCounts[i]; j <= cmap_endCounts[i];
+ j++) {
// Update lastChar
if (j < 256 && j > lastChar)
- lastChar = (short) j;
+ lastChar = (short)j;
if (mtxPtr < mtx_tab.length) {
int glyphIdx;
if (cmap_rangeOffsets[i] != 0) {
- int glyphOffset = glyphIdArrayOffset +
- ((cmap_rangeOffsets[i] / 2) +
- (j - cmap_startCounts[i]) + (i) -
- cmap_segCountX2 / 2) * 2;
+ int glyphOffset =
+ glyphIdArrayOffset
+ + ((cmap_rangeOffsets[i] / 2) + (j - cmap_startCounts[i]) + (i) - cmap_segCountX2 / 2)
+ * 2;
in.seek_set(glyphOffset);
- glyphIdx = (in.readTTFUShort() +
- cmap_deltas[i]) & 0xffff;
+ glyphIdx = (in.readTTFUShort() + cmap_deltas[i])
+ & 0xffff;
- unicodeMapping.addElement(
- new UnicodeMapping(glyphIdx, j));
- mtx_tab[glyphIdx].unicodeIndex.addElement(
- new Integer(j));
+ unicodeMapping.addElement(new UnicodeMapping(glyphIdx,
+ j));
+ mtx_tab[glyphIdx].unicodeIndex.addElement(new Integer(j));
// Also add winAnsiWidth
if (false) {
int d = j;
if (j > 127)
- d = (int)
- org.apache.fop.render.pdf.CodePointMapping.map[j];
+ d = (int)org.apache.fop.render.pdf.CodePointMapping.map[j];
if (d < ansiWidth.length)
ansiWidth[d] = mtx_tab[glyphIdx].wx;
} else {
- Vector v = (Vector) ansiIndex.get(
- new Integer(j));
+ Vector v =
+ (Vector)ansiIndex.get(new Integer(j));
if (v != null) {
for (Enumeration e = v.elements();
- e.hasMoreElements();) {
+ e.hasMoreElements(); ) {
Integer aIdx =
- (Integer) e.nextElement();
+ (Integer)e.nextElement();
ansiWidth[aIdx.intValue()] =
- mtx_tab[glyphIdx].wx;
+ mtx_tab[glyphIdx].wx;
/*
- System.out.println("Added width "+
- mtx_tab[glyphIdx].wx +
- " uni: " + j +
- " ansi: " + aIdx.intValue());
- */
+ * System.out.println("Added width "+
+ * mtx_tab[glyphIdx].wx +
+ * " uni: " + j +
+ * " ansi: " + aIdx.intValue());
+ */
}
}
}
/*
- System.out.println("Idx: "+
- glyphIdx +
- " Delta: " + cmap_deltas[i]+
- " Unicode: " + j +
- " name: " +
- mtx_tab[glyphIdx].name);
- */
+ * System.out.println("Idx: "+
+ * glyphIdx +
+ * " Delta: " + cmap_deltas[i]+
+ * " Unicode: " + j +
+ * " name: " +
+ * mtx_tab[glyphIdx].name);
+ */
- }
- else {
+ } else {
glyphIdx = (j + cmap_deltas[i]) & 0xffff;
if (glyphIdx < mtx_tab.length)
- mtx_tab[glyphIdx] .unicodeIndex.addElement(
- new Integer(j));
+ mtx_tab[glyphIdx].unicodeIndex.addElement(new Integer(j));
else
- System.out.println("Glyph " +
- glyphIdx + " out of range: " +
- mtx_tab.length);
+ System.out.println("Glyph " + glyphIdx
+ + " out of range: "
+ + mtx_tab.length);
- unicodeMapping.addElement(
- new UnicodeMapping(glyphIdx, j));
+ unicodeMapping.addElement(new UnicodeMapping(glyphIdx,
+ j));
if (glyphIdx < mtx_tab.length)
- mtx_tab[glyphIdx] .unicodeIndex.addElement(
- new Integer(j));
+ mtx_tab[glyphIdx].unicodeIndex.addElement(new Integer(j));
else
- System.out.println("Glyph " +
- glyphIdx + " out of range: " +
- mtx_tab.length);
+ System.out.println("Glyph " + glyphIdx
+ + " out of range: "
+ + mtx_tab.length);
@@ -281,33 +284,32 @@ public class TTFFile {
if (false) {
int d = j;
if (j > 127)
- d = (int)
- org.apache.fop.render.pdf.CodePointMapping.map[j];
+ d = (int)org.apache.fop.render.pdf.CodePointMapping.map[j];
if (d < ansiWidth.length)
ansiWidth[d] = mtx_tab[glyphIdx].wx;
} else {
- Vector v = (Vector) ansiIndex.get(
- new Integer(j));
+ Vector v =
+ (Vector)ansiIndex.get(new Integer(j));
if (v != null) {
for (Enumeration e = v.elements();
- e.hasMoreElements();) {
+ e.hasMoreElements(); ) {
Integer aIdx =
- (Integer) e.nextElement();
+ (Integer)e.nextElement();
ansiWidth[aIdx.intValue()] =
- mtx_tab[glyphIdx].wx;
+ mtx_tab[glyphIdx].wx;
}
}
}
/*
- System.out.println("IIdx: "+
- mtxPtr +
- " Delta: " + cmap_deltas[i]+
- " Unicode: " + j +
- " name: " +
- mtx_tab[(j+cmap_deltas[i]) & 0xffff].name);
- */
+ * System.out.println("IIdx: "+
+ * mtxPtr +
+ * " Delta: " + cmap_deltas[i]+
+ * " Unicode: " + j +
+ * " name: " +
+ * mtx_tab[(j+cmap_deltas[i]) & 0xffff].name);
+ */
}
if (glyphIdx < mtx_tab.length) {
if (mtx_tab[glyphIdx].unicodeIndex.size() < 2) {
@@ -324,8 +326,8 @@ public class TTFFile {
/**
- * Print first char/last char
- */
+ * Print first char/last char
+ */
private void print_max_min() {
int min = 255;
int max = 0;
@@ -335,17 +337,18 @@ public class TTFFile {
if (mtx_tab[i].index > max)
max = mtx_tab[i].index;
}
- System.out.println("Min: "+min);
- System.out.println("Max: "+max);
+ System.out.println("Min: " + min);
+ System.out.println("Max: " + max);
}
public void readFont(FontFileReader in) throws IOException {
- readFont(in, (String) null);
+ readFont(in, (String)null);
}
- /** initialize the ansiWidths array (for winAnsiEncoding)
- * and fill with the missingwidth
- */
+ /**
+ * initialize the ansiWidths array (for winAnsiEncoding)
+ * and fill with the missingwidth
+ */
private void initAnsiWidths() {
ansiWidth = new int[256];
for (int i = 0; i < 256; i++)
@@ -357,9 +360,9 @@ public class TTFFile {
ansiIndex = new Hashtable();
for (int i = 32; i < Glyphs.winAnsiEncoding.length; i++) {
Integer ansi = new Integer(i);
- Integer uni = new Integer((int) Glyphs.winAnsiEncoding[i]);
+ Integer uni = new Integer((int)Glyphs.winAnsiEncoding[i]);
- Vector v = (Vector) ansiIndex.get(uni);
+ Vector v = (Vector)ansiIndex.get(uni);
if (v == null) {
v = new Vector();
ansiIndex.put(uni, v);
@@ -370,17 +373,17 @@ public class TTFFile {
/**
- * Read the font data
- * If the fontfile is a TrueType Collection (.ttc file)
- * The name of the font to read data for must be supplied,
- * else the name is ignored
- */
- public void readFont(FontFileReader in,
- String name) throws IOException {
-
- /* Check if TrueType collection, and that the name
- exists in the collection
- */
+ * Read the font data
+ * If the fontfile is a TrueType Collection (.ttc file)
+ * The name of the font to read data for must be supplied,
+ * else the name is ignored
+ */
+ public void readFont(FontFileReader in, String name) throws IOException {
+
+ /*
+ * Check if TrueType collection, and that the name
+ * exists in the collection
+ */
if (!checkTTC(in, name, true))
throw new IOException("Failed to read font");
@@ -397,9 +400,9 @@ public class TTFFile {
readGlyf(in);
readName(in);
readPCLT(in);
- readCMAP(in); // Read cmap table and fill in ansiwidths
- createCMaps(); // Create cmaps for bfentries
- //print_max_min();
+ readCMAP(in); // Read cmap table and fill in ansiwidths
+ createCMaps(); // Create cmaps for bfentries
+ // print_max_min();
readKerning(in);
}
@@ -409,16 +412,16 @@ public class TTFFile {
TTFCmapEntry tce = new TTFCmapEntry();
Enumeration e = unicodeMapping.elements();
- UnicodeMapping um = (UnicodeMapping) e.nextElement();
+ UnicodeMapping um = (UnicodeMapping)e.nextElement();
UnicodeMapping lastMapping = um;
tce.unicodeStart = um.uIdx;
tce.glyphStartIndex = um.gIdx;
while (e.hasMoreElements()) {
- um = (UnicodeMapping) e.nextElement();
- if (((lastMapping.uIdx + 1) != um.uIdx) ||
- ((lastMapping.gIdx + 1) != um.gIdx)) {
+ um = (UnicodeMapping)e.nextElement();
+ if (((lastMapping.uIdx + 1) != um.uIdx)
+ || ((lastMapping.gIdx + 1) != um.gIdx)) {
tce.unicodeEnd = lastMapping.uIdx;
cmaps.addElement(tce);
@@ -439,23 +442,23 @@ public class TTFFile {
System.out.println("Family name: " + familyName);
System.out.println("Subfamily name: " + subFamilyName);
System.out.println("Notice: " + notice);
- System.out.println("xHeight: " + (int) get_ttf_funit(xHeight));
- System.out.println("capheight: " + (int) get_ttf_funit(capHeight));
+ System.out.println("xHeight: " + (int)get_ttf_funit(xHeight));
+ System.out.println("capheight: " + (int)get_ttf_funit(capHeight));
int italic = (int)(italicAngle >> 16);
System.out.println("Italic: " + italic);
System.out.print("ItalicAngle: " + (short)(italicAngle / 0x10000));
if ((italicAngle % 0x10000) > 0)
- System.out.print("."+
- (short)((italicAngle % 0x10000) * 1000) / 0x10000);
+ System.out.print("."
+ + (short)((italicAngle % 0x10000) * 1000)
+ / 0x10000);
System.out.println();
System.out.println("Ascender: " + get_ttf_funit(ascender));
System.out.println("Descender: " + get_ttf_funit(descender));
- System.out.println("FontBBox: [" +
- (int) get_ttf_funit(fontBBox1) + " " +
- (int) get_ttf_funit(fontBBox2) + " " +
- (int) get_ttf_funit(fontBBox3) + " " +
- (int) get_ttf_funit(fontBBox4) + "]");
+ System.out.println("FontBBox: [" + (int)get_ttf_funit(fontBBox1)
+ + " " + (int)get_ttf_funit(fontBBox2) + " "
+ + (int)get_ttf_funit(fontBBox3) + " "
+ + (int)get_ttf_funit(fontBBox4) + "]");
}
public static void main(String[] args) {
@@ -476,31 +479,34 @@ public class TTFFile {
}
public String getWindowsName() {
- return new String(familyName + ","+subFamilyName);
+ return new String(familyName + "," + subFamilyName);
}
public String getPostscriptName() {
- if ("Regular".equals(subFamilyName) ||
- "Roman".equals(subFamilyName))
+ if ("Regular".equals(subFamilyName) || "Roman".equals(subFamilyName))
return familyName;
else
- return familyName + ","+subFamilyName;
+ return familyName + "," + subFamilyName;
}
+
public String getFamilyName() {
return familyName;
}
+
public String getCharSetName() {
return encoding;
}
+
public int getCapHeight() {
- return (int) get_ttf_funit(capHeight);
+ return (int)get_ttf_funit(capHeight);
}
+
public int getXHeight() {
- return (int) get_ttf_funit(xHeight);
+ return (int)get_ttf_funit(xHeight);
}
public int getFlags() {
- int flags = 32; // Use Adobe Standard charset
+ int flags = 32; // Use Adobe Standard charset
if (italicAngle != 0)
flags = flags | 64;
if (isFixedPitch != 0)
@@ -521,28 +527,28 @@ public class TTFFile {
// This is the correct italic angle, however only int italic
// angles are supported at the moment so this is commented out.
/*
- if ((italicAngle % 0x10000) > 0 )
- ia=ia+(comma+Short.toString((short)((short)((italicAngle % 0x10000)*1000)/0x10000)));
- */
+ * if ((italicAngle % 0x10000) > 0 )
+ * ia=ia+(comma+Short.toString((short)((short)((italicAngle % 0x10000)*1000)/0x10000)));
+ */
return ia;
}
public int[] getFontBBox() {
int[] fbb = new int[4];
- fbb[0] = (int) get_ttf_funit(fontBBox1);
- fbb[1] = (int) get_ttf_funit(fontBBox2);
- fbb[2] = (int) get_ttf_funit(fontBBox3);
- fbb[3] = (int) get_ttf_funit(fontBBox4);
+ fbb[0] = (int)get_ttf_funit(fontBBox1);
+ fbb[1] = (int)get_ttf_funit(fontBBox2);
+ fbb[2] = (int)get_ttf_funit(fontBBox3);
+ fbb[3] = (int)get_ttf_funit(fontBBox4);
return fbb;
}
public int getLowerCaseAscent() {
- return (int) get_ttf_funit(ascender);
+ return (int)get_ttf_funit(ascender);
}
public int getLowerCaseDescent() {
- return (int) get_ttf_funit(descender);
+ return (int)get_ttf_funit(descender);
}
// This is only for WinAnsiEncoding, so the last char is
@@ -558,13 +564,13 @@ public class TTFFile {
public int[] getWidths() {
int[] wx = new int[mtx_tab.length];
for (int i = 0; i < wx.length; i++)
- wx[i] = (int) get_ttf_funit(mtx_tab[i].wx);
+ wx[i] = (int)get_ttf_funit(mtx_tab[i].wx);
return wx;
}
public int getCharWidth(int idx) {
- return (int) get_ttf_funit(ansiWidth[idx]);
+ return (int)get_ttf_funit(ansiWidth[idx]);
}
public Hashtable getKerning() {
@@ -581,19 +587,19 @@ public class TTFFile {
/**
- * Read Table Directory from the current position in the
- * FontFileReader and fill the global Hashtable dirTabs
- * with the table name (String) as key and a TTFDirTabEntry
- * as value.
- */
+ * Read Table Directory from the current position in the
+ * FontFileReader and fill the global Hashtable dirTabs
+ * with the table name (String) as key and a TTFDirTabEntry
+ * as value.
+ */
protected void readDirTabs(FontFileReader in) throws IOException {
- in.skip(4); // TTF_FIXED_SIZE
+ in.skip(4); // TTF_FIXED_SIZE
int ntabs = in.readTTFUShort();
- in.skip(6); // 3xTTF_USHORT_SIZE
+ in.skip(6); // 3xTTF_USHORT_SIZE
dirTabs = new Hashtable();
TTFDirTabEntry[] pd = new TTFDirTabEntry[ntabs];
- //System.out.println("Reading " + ntabs + " dir tables");
+ // System.out.println("Reading " + ntabs + " dir tables");
for (int i = 0; i < ntabs; i++) {
pd[i] = new TTFDirTabEntry();
dirTabs.put(pd[i].read(in), pd[i]);
@@ -601,9 +607,9 @@ public class TTFFile {
}
/**
- * Read the "head" table, this reads the bounding box and
- * sets the upem (unitsPerEM) variable
- */
+ * Read the "head" table, this reads the bounding box and
+ * sets the upem (unitsPerEM) variable
+ */
protected void readFontHeader(FontFileReader in) throws IOException {
seek_tab(in, "head", 2 * 4 + 2 * 4 + 2);
upem = in.readTTFUShort();
@@ -621,52 +627,53 @@ public class TTFFile {
}
/**
- * Read the number of glyphs from the "maxp" table
- */
+ * Read the number of glyphs from the "maxp" table
+ */
protected void getNumGlyphs(FontFileReader in) throws IOException {
seek_tab(in, "maxp", 4);
nglyphs = in.readTTFUShort();
}
- /** Read the "hhea" table to find the ascender and descender and
- * size of "hmtx" table, i.e. a fixed size font might have only
- * one width
- */
+ /**
+ * Read the "hhea" table to find the ascender and descender and
+ * size of "hmtx" table, i.e. a fixed size font might have only
+ * one width
+ */
protected void readHorizontalHeader(FontFileReader in)
- throws IOException {
+ throws IOException {
seek_tab(in, "hhea", 4);
- ascender = in.readTTFShort(); // Use sTypoAscender in "OS/2" table?
- descender = in.readTTFShort(); // Use sTypoDescender in "OS/2" table?
+ ascender = in.readTTFShort(); // Use sTypoAscender in "OS/2" table?
+ descender = in.readTTFShort(); // Use sTypoDescender in "OS/2" table?
in.skip(2 + 2 + 3 * 2 + 8 * 2);
nhmtx = in.readTTFUShort();
- //System.out.println("Number of horizontal metrics: " + nhmtx);
+ // System.out.println("Number of horizontal metrics: " + nhmtx);
}
/**
- * Read "hmtx" table and put the horizontal metrics
- * in the mtx_tab array. If the number of metrics is less
- * than the number of glyphs (eg fixed size fonts), extend
- * the mtx_tab array and fill in the missing widths
- */
+ * Read "hmtx" table and put the horizontal metrics
+ * in the mtx_tab array. If the number of metrics is less
+ * than the number of glyphs (eg fixed size fonts), extend
+ * the mtx_tab array and fill in the missing widths
+ */
protected void readHorizontalMetrics(FontFileReader in)
- throws IOException {
+ throws IOException {
seek_tab(in, "hmtx", 0);
int mtx_size = (nglyphs > nhmtx) ? nglyphs : nhmtx;
mtx_tab = new TTFMtxEntry[mtx_size];
- //System.out.println("*** Widths array: \n");
+ // System.out.println("*** Widths array: \n");
for (int i = 0; i < mtx_size; i++)
mtx_tab[i] = new TTFMtxEntry();
for (int i = 0; i < nhmtx; i++) {
mtx_tab[i].wx = in.readTTFUShort();
mtx_tab[i].lsb = in.readTTFUShort();
/*
- System.out.println(" width["+i+"] = "+
- get_ttf_funit(mtx_tab[i].wx)+";");
- */
+ * System.out.println(" width["+i+"] = "+
+ * get_ttf_funit(mtx_tab[i].wx)+";");
+ */
}
if (nhmtx < mtx_size) {
@@ -681,11 +688,10 @@ public class TTFFile {
/**
- * Read the "post" table
- * containing the postscript names of the glyphs.
- */
- private final void readPostscript(FontFileReader in)
- throws IOException {
+ * Read the "post" table
+ * containing the postscript names of the glyphs.
+ */
+ private final void readPostscript(FontFileReader in) throws IOException {
String[] ps_glyphs_buf;
int i, k, l;
@@ -698,67 +704,66 @@ public class TTFFile {
in.skip(4 * 4);
- //System.out.println("Post format: "+post_format);
+ // System.out.println("Post format: "+post_format);
switch (post_format) {
- case 0x00010000:
- //System.out.println("Postscript format 1");
- for (i = 0; i < Glyphs.mac_glyph_names.length; i++) {
- mtx_tab[i].name = Glyphs.mac_glyph_names[i];
- }
- break;
- case 0x00020000:
- //System.out.println("Postscript format 2");
- int numGlyphStrings = 0;
- l = in.readTTFUShort(); // Num Glyphs
- //short minIndex=256;
- for (i = 0; i < l ; i++) { // Read indexes
- mtx_tab[i].index = in.readTTFUShort();
- //if (minIndex > mtx_tab[i].index)
- //minIndex=(short)mtx_tab[i].index;
-
- if (mtx_tab[i].index > 257)
- numGlyphStrings++;
-
- //System.out.println("Post index: "+mtx_tab[i].index);
- }
- //firstChar=minIndex;
- ps_glyphs_buf = new String[numGlyphStrings];
- //System.out.println("Reading " + numGlyphStrings +
- // " glyphnames"+
- // ", was n num glyphs="+l);
- for (i = 0; i < ps_glyphs_buf.length; i++) {
- ps_glyphs_buf[i] = in.readTTFString(in.readTTFUByte());
- }
+ case 0x00010000:
+ // System.out.println("Postscript format 1");
+ for (i = 0; i < Glyphs.mac_glyph_names.length; i++) {
+ mtx_tab[i].name = Glyphs.mac_glyph_names[i];
+ }
+ break;
+ case 0x00020000:
+ // System.out.println("Postscript format 2");
+ int numGlyphStrings = 0;
+ l = in.readTTFUShort(); // Num Glyphs
+ // short minIndex=256;
+ for (i = 0; i < l; i++) { // Read indexes
+ mtx_tab[i].index = in.readTTFUShort();
+ // if (minIndex > mtx_tab[i].index)
+ // minIndex=(short)mtx_tab[i].index;
+
+ if (mtx_tab[i].index > 257)
+ numGlyphStrings++;
+
+ // System.out.println("Post index: "+mtx_tab[i].index);
+ }
+ // firstChar=minIndex;
+ ps_glyphs_buf = new String[numGlyphStrings];
+ // System.out.println("Reading " + numGlyphStrings +
+ // " glyphnames"+
+ // ", was n num glyphs="+l);
+ for (i = 0; i < ps_glyphs_buf.length; i++) {
+ ps_glyphs_buf[i] = in.readTTFString(in.readTTFUByte());
+ }
- for (i = 0; i < l; i++) {
- if (mtx_tab[i].index < NMACGLYPHS) {
- mtx_tab[i].name =
- Glyphs.mac_glyph_names[mtx_tab[i].index];
- } else {
- k = mtx_tab[i].index - NMACGLYPHS ;
- /*
- System.out.println(k+" i="+i+" mtx="+mtx_tab.length+
- " ps="+ps_glyphs_buf.length);
- */
- mtx_tab[i].name = ps_glyphs_buf[k];
- }
+ for (i = 0; i < l; i++) {
+ if (mtx_tab[i].index < NMACGLYPHS) {
+ mtx_tab[i].name =
+ Glyphs.mac_glyph_names[mtx_tab[i].index];
+ } else {
+ k = mtx_tab[i].index - NMACGLYPHS;
+ /*
+ * System.out.println(k+" i="+i+" mtx="+mtx_tab.length+
+ * " ps="+ps_glyphs_buf.length);
+ */
+ mtx_tab[i].name = ps_glyphs_buf[k];
}
+ }
- break;
- case 0x00030000:
- // Postscript format 3 contains no glyph names
- System.out.println("Postscript format 3");
- break;
- default:
- System.out.println("Unknown Postscript format : " +
- post_format);
+ break;
+ case 0x00030000:
+ // Postscript format 3 contains no glyph names
+ System.out.println("Postscript format 3");
+ break;
+ default:
+ System.out.println("Unknown Postscript format : " + post_format);
}
}
/**
- * Read the "OS/2" table
- */
+ * Read the "OS/2" table
+ */
private final void readOS2(FontFileReader in) throws IOException {
// Check if font is embeddable
if (dirTabs.get("OS/2") != null) {
@@ -773,24 +778,24 @@ public class TTFFile {
}
/**
- * Read the "loca" table
- */
+ * Read the "loca" table
+ */
protected final void readIndexToLocation(FontFileReader in)
- throws IOException {
+ throws IOException {
seek_tab(in, "loca", 0);
- for (int i = 0; i < nglyphs ; i++) {
- mtx_tab[i].offset = (loca_format == 1 ? in.readTTFULong() :
- (in.readTTFUShort() << 1));
+ for (int i = 0; i < nglyphs; i++) {
+ mtx_tab[i].offset = (loca_format == 1 ? in.readTTFULong()
+ : (in.readTTFUShort() << 1));
}
- lastLoca = (loca_format == 1 ? in.readTTFULong() :
- (in.readTTFUShort() << 1));
+ lastLoca = (loca_format == 1 ? in.readTTFULong()
+ : (in.readTTFUShort() << 1));
}
/**
- * Read the "glyf" table to find the bounding boxes
- */
+ * Read the "glyf" table to find the bounding boxes
+ */
private final void readGlyf(FontFileReader in) throws IOException {
- TTFDirTabEntry dirTab = (TTFDirTabEntry) dirTabs.get("glyf");
+ TTFDirTabEntry dirTab = (TTFDirTabEntry)dirTabs.get("glyf");
for (int i = 0; i < (nglyphs - 1); i++) {
if (mtx_tab[i].offset != mtx_tab[i + 1].offset) {
in.seek_set(dirTab.offset + mtx_tab[i].offset);
@@ -808,10 +813,10 @@ public class TTFFile {
}
- long n = ((TTFDirTabEntry) dirTabs.get("glyf")).offset;
+ long n = ((TTFDirTabEntry)dirTabs.get("glyf")).offset;
for (int i = 0; i < nglyphs; i++) {
- if ((i + 1) >= mtx_tab.length ||
- mtx_tab[i].offset != mtx_tab[i + 1].offset) {
+ if ((i + 1) >= mtx_tab.length
+ || mtx_tab[i].offset != mtx_tab[i + 1].offset) {
in.seek_set(n + mtx_tab[i].offset);
in.skip(2);
mtx_tab[i].bbox[0] = in.readTTFShort();
@@ -824,13 +829,13 @@ public class TTFFile {
mtx_tab[i].bbox[2] = mtx_tab[0].bbox[0];
mtx_tab[i].bbox[3] = mtx_tab[0].bbox[0];
}
- //System.out.println(mtx_tab[i].toString(this));
+ // System.out.println(mtx_tab[i].toString(this));
}
}
/**
- * Read the "name" table
- */
+ * Read the "name" table
+ */
private final void readName(FontFileReader in) throws IOException {
int platform_id, encoding_id, language_id;
@@ -841,7 +846,7 @@ public class TTFFile {
i += 2 * 2;
while (n-- > 0) {
- //System.out.println("Iteration: "+n);
+ // System.out.println("Iteration: "+n);
in.seek_set(i);
platform_id = in.readTTFUShort();
encoding_id = in.readTTFUShort();
@@ -850,34 +855,33 @@ public class TTFFile {
int k = in.readTTFUShort();
int l = in.readTTFUShort();
- if (((platform_id == 1 || platform_id == 3) &&
- (encoding_id == 0 || encoding_id == 1)) &&
- (k == 1 || k == 2 || k == 0 || k == 4 || k == 6)) {
- // if (k==1 || k==2 || k==0 || k==4 || k==6) {
+ if (((platform_id == 1 || platform_id == 3) && (encoding_id == 0 || encoding_id == 1))
+ && (k == 1 || k == 2 || k == 0 || k == 4 || k == 6)) {
+ // if (k==1 || k==2 || k==0 || k==4 || k==6) {
in.seek_set(j + in.readTTFUShort());
String txt = in.readTTFString(l);
- //System.out.println(platform_id+" "+encoding_id+
- //" "+k+" "+txt);
+ // System.out.println(platform_id+" "+encoding_id+
+ // " "+k+" "+txt);
switch (k) {
- case 0:
- notice = txt;
- break;
- case 1:
- familyName = txt;
- break;
- case 2:
- subFamilyName = txt;
- break;
- case 4:
- fullName = txt;
- break;
- case 6:
- fontName = txt;
- break;
+ case 0:
+ notice = txt;
+ break;
+ case 1:
+ familyName = txt;
+ break;
+ case 2:
+ subFamilyName = txt;
+ break;
+ case 4:
+ fullName = txt;
+ break;
+ case 6:
+ fontName = txt;
+ break;
}
- if (!notice.equals("") && !fullName.equals("") &&
- !fontName.equals("") && !familyName.equals("") &&
- !subFamilyName.equals("")) {
+ if (!notice.equals("") &&!fullName.equals("")
+ &&!fontName.equals("") &&!familyName.equals("")
+ &&!subFamilyName.equals("")) {
break;
}
}
@@ -886,10 +890,10 @@ public class TTFFile {
}
/**
- * Read the "PCLT" table to find xHeight and capHeight
- */
+ * Read the "PCLT" table to find xHeight and capHeight
+ */
private final void readPCLT(FontFileReader in) throws IOException {
- TTFDirTabEntry dirTab = (TTFDirTabEntry) dirTabs.get("PCLT");
+ TTFDirTabEntry dirTab = (TTFDirTabEntry)dirTabs.get("PCLT");
if (dirTab != null) {
in.seek_set(dirTab.offset + 4 + 4 + 2);
xHeight = in.readTTFUShort();
@@ -919,17 +923,17 @@ public class TTFFile {
}
/**
- * Read the kerning table, create a table for both CIDs and
- * winAnsiEncoding
- */
+ * Read the kerning table, create a table for both CIDs and
+ * winAnsiEncoding
+ */
private final void readKerning(FontFileReader in) throws IOException {
// Read kerning
kerningTab = new Hashtable();
ansiKerningTab = new Hashtable();
- TTFDirTabEntry dirTab = (TTFDirTabEntry) dirTabs.get("kern");
+ TTFDirTabEntry dirTab = (TTFDirTabEntry)dirTabs.get("kern");
if (dirTab != null) {
seek_tab(in, "kern", 2);
- for (int n = in.readTTFUShort(); n > 0 ; n--) {
+ for (int n = in.readTTFUShort(); n > 0; n--) {
in.skip(2 * 2);
int k = in.readTTFUShort();
if (!((k & 1) != 0) || (k & 2) != 0 || (k & 4) != 0)
@@ -946,36 +950,33 @@ public class TTFFile {
if (kpx != 0) {
// CID table
Integer iObj = new Integer(i);
- Hashtable adjTab = (Hashtable) kerningTab.get(iObj);
+ Hashtable adjTab = (Hashtable)kerningTab.get(iObj);
if (adjTab == null)
adjTab = new java.util.Hashtable();
adjTab.put(new Integer(j),
- new Integer((int) get_ttf_funit(kpx)));
+ new Integer((int)get_ttf_funit(kpx)));
kerningTab.put(iObj, adjTab);
}
}
}
- //System.out.println(kerningTab.toString());
+ // System.out.println(kerningTab.toString());
// Create winAnsiEncoded kerning table
- for (Enumeration ae = kerningTab.keys();
- ae.hasMoreElements();) {
- Integer cidKey = (Integer) ae.nextElement();
+ for (Enumeration ae = kerningTab.keys(); ae.hasMoreElements(); ) {
+ Integer cidKey = (Integer)ae.nextElement();
Hashtable akpx = new Hashtable();
- Hashtable ckpx = (Hashtable) kerningTab.get(cidKey);
+ Hashtable ckpx = (Hashtable)kerningTab.get(cidKey);
- for (Enumeration aee = ckpx.keys();
- aee.hasMoreElements();) {
- Integer cidKey2 = (Integer) aee.nextElement();
- Integer kern = (Integer) ckpx.get(cidKey2);
+ for (Enumeration aee = ckpx.keys(); aee.hasMoreElements(); ) {
+ Integer cidKey2 = (Integer)aee.nextElement();
+ Integer kern = (Integer)ckpx.get(cidKey2);
- for (Enumeration uniMap = mtx_tab[cidKey2.intValue()]
- .unicodeIndex.elements();
- uniMap.hasMoreElements();) {
- Integer unicodeKey = (Integer) uniMap.nextElement();
+ for (Enumeration uniMap = mtx_tab[cidKey2.intValue()].unicodeIndex.elements();
+ uniMap.hasMoreElements(); ) {
+ Integer unicodeKey = (Integer)uniMap.nextElement();
Integer[] ansiKeys =
- unicodeToWinAnsi(unicodeKey.intValue());
+ unicodeToWinAnsi(unicodeKey.intValue());
for (int u = 0; u < ansiKeys.length; u++) {
akpx.put(ansiKeys[u], kern);
}
@@ -983,12 +984,11 @@ public class TTFFile {
}
if (akpx.size() > 0)
- for (Enumeration uniMap = mtx_tab[cidKey.intValue()]
- .unicodeIndex.elements();
- uniMap.hasMoreElements();) {
- Integer unicodeKey = (Integer) uniMap.nextElement();
+ for (Enumeration uniMap = mtx_tab[cidKey.intValue()].unicodeIndex.elements();
+ uniMap.hasMoreElements(); ) {
+ Integer unicodeKey = (Integer)uniMap.nextElement();
Integer[] ansiKeys =
- unicodeToWinAnsi(unicodeKey.intValue());
+ unicodeToWinAnsi(unicodeKey.intValue());
for (int u = 0; u < ansiKeys.length; u++) {
ansiKerningTab.put(ansiKeys[u], akpx);
}
@@ -997,20 +997,21 @@ public class TTFFile {
}
}
- /** Return a vector with TTFCmapEntry
- */
+ /**
+ * Return a vector with TTFCmapEntry
+ */
public Vector getCMaps() {
return cmaps;
}
/**
- * Check if this is a TrueType collection and that the given
- * name exists in the collection.
- * If it does, set offset in fontfile to the beginning of
- * the Table Directory for that font
- @ return true if not collection or font name present, false
- otherwise
- */
+ * Check if this is a TrueType collection and that the given
+ * name exists in the collection.
+ * If it does, set offset in fontfile to the beginning of
+ * the Table Directory for that font
+ * @ return true if not collection or font name present, false
+ * otherwise
+ */
protected final boolean checkTTC(FontFileReader in, String name,
boolean verbose) throws IOException {
String tag = in.readTTFString(4);
@@ -1020,16 +1021,16 @@ public class TTFFile {
in.skip(4);
// Read directory offsets
- int numDirectories = (int) in.readTTFULong();
- //int numDirectories=in.readTTFUShort();
+ int numDirectories = (int)in.readTTFULong();
+ // int numDirectories=in.readTTFUShort();
long[] dirOffsets = new long[numDirectories];
for (int i = 0; i < numDirectories; i++) {
dirOffsets[i] = in.readTTFULong();
}
if (verbose) {
- System.out.println("This is a TrueType collection file with"+
- numDirectories + " fonts");
+ System.out.println("This is a TrueType collection file with"
+ + numDirectories + " fonts");
System.out.println("Containing the following fonts: ");
}
// Read all the directories and name tables to check
@@ -1065,15 +1066,16 @@ public class TTFFile {
in.seek_set(dirTabOffset);
return found;
- }
- else {
+ } else {
in.seek_set(0);
return true;
}
}
- /* Helper classes, they are not very efficient, but that really
- doesn't matter... */
+ /*
+ * Helper classes, they are not very efficient, but that really
+ * doesn't matter...
+ */
private Integer[] unicodeToWinAnsi(int unicode) {
Vector ret = new Vector();
for (int i = 32; i < Glyphs.winAnsiEncoding.length; i++)
@@ -1083,12 +1085,13 @@ public class TTFFile {
ret.copyInto(itg);
return itg;
}
+
}
/**
- * Key-value helper class
- */
+ * Key-value helper class
+ */
class UnicodeMapping {
int uIdx;
int gIdx;
@@ -1096,4 +1099,5 @@ class UnicodeMapping {
this.uIdx = uIdx;
this.gIdx = gIdx;
}
+
}
diff --git a/src/org/apache/fop/fonts/TTFMtxEntry.java b/src/org/apache/fop/fonts/TTFMtxEntry.java
index 56b27e62e..286593c04 100644
--- a/src/org/apache/fop/fonts/TTFMtxEntry.java
+++ b/src/org/apache/fop/fonts/TTFMtxEntry.java
@@ -1,9 +1,10 @@
-/* -- $Id$ --
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fonts;
import java.io.*;
@@ -27,11 +28,12 @@ class TTFMtxEntry {
}
public String toString(TTFFile t) {
- return new String("Glyph "+name + " index: " + index + " bbox [ "+
- t.get_ttf_funit(bbox[0]) + " " +
- t.get_ttf_funit(bbox[1]) + " " +
- t.get_ttf_funit(bbox[2]) + " " +
- t.get_ttf_funit(bbox[3]) + "]" + "wx: "+
- t.get_ttf_funit(wx));
+ return new String("Glyph " + name + " index: " + index + " bbox [ "
+ + t.get_ttf_funit(bbox[0]) + " "
+ + t.get_ttf_funit(bbox[1]) + " "
+ + t.get_ttf_funit(bbox[2]) + " "
+ + t.get_ttf_funit(bbox[3]) + "]" + "wx: "
+ + t.get_ttf_funit(wx));
}
+
}
diff --git a/src/org/apache/fop/fonts/TTFSegEntry.java b/src/org/apache/fop/fonts/TTFSegEntry.java
index e63c024bd..f152a8b39 100644
--- a/src/org/apache/fop/fonts/TTFSegEntry.java
+++ b/src/org/apache/fop/fonts/TTFSegEntry.java
@@ -1,9 +1,10 @@
-/* -- $Id$ --
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fonts;
class TTFSegEntry {
@@ -12,6 +13,6 @@ class TTFSegEntry {
int idDelta;
int idRangeOffset;
- TTFSegEntry() {
- }
+ TTFSegEntry() {}
+
}
diff --git a/src/org/apache/fop/fonts/TTFSubSetFile.java b/src/org/apache/fop/fonts/TTFSubSetFile.java
index d8f03af0b..149f78290 100644
--- a/src/org/apache/fop/fonts/TTFSubSetFile.java
+++ b/src/org/apache/fop/fonts/TTFSubSetFile.java
@@ -1,8 +1,8 @@
-/* -- $Id$
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fonts;
@@ -21,418 +21,415 @@ import org.apache.fop.messaging.MessageHandler;
* Typography site: http://www.microsoft.com/truetype/
*/
public class TTFSubSetFile extends TTFFile {
- byte[] output = null;
- int realSize = 0;
- int currentPos = 0;
-
- /* Offsets in name table to be filled out by table.
- The offsets are to the checkSum field */
- int cvtDirOffset = 0;
- int fpgmDirOffset = 0;
- int glyfDirOffset = 0;
- int headDirOffset = 0;
- int hheaDirOffset = 0;
- int hmtxDirOffset = 0;
- int locaDirOffset = 0;
- int maxpDirOffset = 0;
- int prepDirOffset = 0;
-
- int checkSumAdjustmentOffset = 0;
- int locaOffset = 0;
-
- /**
- * Initalize the output array
- */
- private void init(int size) {
- output = new byte[size];
- realSize = 0;
- currentPos = 0;
-
- // createDirectory()
- }
-
- /**
- Create the directory table
- */
- private void createDirectory() {
- int numTables = 9;
- // Create the TrueType header
- writeByte((byte)0);
- writeByte((byte)1);
- writeByte((byte)0);
- writeByte((byte)0);
- realSize+=4;
-
- writeUShort(numTables);
- realSize += 2;
-
- // Create searchRange, entrySelector and rangeShift
- int maxPow = maxPow2(numTables);
- int searchRange = maxPow*16;
- writeUShort(searchRange);
- realSize += 2;
-
- writeUShort(maxPow);
- realSize += 2;
-
- writeUShort((numTables*16) - searchRange);
- realSize += 2;
-
- // Create space for the table entries
- writeString("cvt ");
- cvtDirOffset = currentPos;
- currentPos+=12;
- realSize+=16;
-
- writeString("fpgm");
- fpgmDirOffset = currentPos;
- currentPos+=12;
- realSize+=16;
-
- writeString("glyf");
- glyfDirOffset = currentPos;
- currentPos+=12;
- realSize+=16;
-
- writeString("head");
- headDirOffset = currentPos;
- currentPos+=12;
- realSize+=16;
-
- writeString("hhea");
- hheaDirOffset = currentPos;
- currentPos+=12;
- realSize+=16;
-
- writeString("hmtx");
- hmtxDirOffset = currentPos;
- currentPos+=12;
- realSize+=16;
-
- writeString("loca");
- locaDirOffset = currentPos;
- currentPos+=12;
- realSize+=16;
-
- writeString("maxp");
- maxpDirOffset = currentPos;
- currentPos+=12;
- realSize+=16;
-
- writeString("prep");
- prepDirOffset = currentPos;
- currentPos+=12;
- realSize+=16;
- }
-
-
- /**
- * Copy the cvt table as is from original font to subset font
- */
- private void createCvt(FontFileReader in) throws IOException {
- TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("cvt ");
- if (entry != null) {
- pad4();
- seek_tab(in, "cvt ", 0);
- System.arraycopy(in.getBytes((int)entry.offset, (int)entry.length),
- 0, output, currentPos, (int)entry.length);
-
- int checksum = getCheckSum(currentPos, (int)entry.length);
- writeULong(cvtDirOffset, checksum);
- writeULong(cvtDirOffset+4, currentPos);
- writeULong(cvtDirOffset+8, (int)entry.length);
- currentPos+=(int)entry.length;
- realSize+=(int)entry.length;
- } else {
- throw new IOException ("Can't find cvt table");
- }
- }
-
-
-
- /**
- * Copy the fpgm table as is from original font to subset font
- */
- private void createFpgm(FontFileReader in) throws IOException {
- TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("fpgm");
- if (entry != null) {
- pad4();
- seek_tab(in, "fpgm", 0);
- System.arraycopy(in.getBytes((int)entry.offset, (int)entry.length),
- 0, output, currentPos, (int)entry.length);
- int checksum = getCheckSum(currentPos, (int)entry.length);
- writeULong(fpgmDirOffset, checksum);
- writeULong(fpgmDirOffset+4, currentPos);
- writeULong(fpgmDirOffset+8, (int)entry.length);
- currentPos+=(int)entry.length;
- realSize+=(int)entry.length;
- } else {
- throw new IOException ("Can't find fpgm table");
- }
- }
-
-
-
- /**
- * Create an empty loca table without updating checksum
- */
- private void createLoca(int size) throws IOException {
- pad4();
- locaOffset = currentPos;
- writeULong(locaDirOffset+4, currentPos);
- writeULong(locaDirOffset+8, size*4+4);
- currentPos+=size*4+4;
- realSize+=size*4+4;
- }
-
-
- /**
- * Copy the maxp table as is from original font to subset font
- * and set num glyphs to size
- */
- private void createMaxp(FontFileReader in, int size) throws IOException {
- TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("maxp");
- if (entry != null) {
- pad4();
- seek_tab(in, "maxp", 0);
- System.arraycopy(in.getBytes((int)entry.offset, (int)entry.length),
- 0, output, currentPos, (int)entry.length);
- writeUShort(currentPos+4, size);
-
- int checksum = getCheckSum(currentPos, (int)entry.length);
- writeULong(maxpDirOffset, checksum);
- writeULong(maxpDirOffset+4, currentPos);
- writeULong(maxpDirOffset+8, (int)entry.length);
- currentPos+=(int)entry.length;
- realSize+=(int)entry.length;
- } else {
- throw new IOException ("Can't find maxp table");
- }
- }
-
-
- /**
- * Copy the prep table as is from original font to subset font
- */
- private void createPrep(FontFileReader in) throws IOException {
- TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("prep");
- if (entry != null) {
- pad4();
- seek_tab(in, "prep", 0);
- System.arraycopy(in.getBytes((int)entry.offset, (int)entry.length),
- 0, output, currentPos, (int)entry.length);
-
- int checksum = getCheckSum(currentPos, (int)entry.length);
- writeULong(prepDirOffset, checksum);
- writeULong(prepDirOffset+4, currentPos);
- writeULong(prepDirOffset+8, (int)entry.length);
- currentPos+=(int)entry.length;
- realSize+=(int)entry.length;
- } else {
- throw new IOException ("Can't find prep table");
- }
- }
-
-
- /**
- * Copy the hhea table as is from original font to subset font
- * and fill in size of hmtx table
- */
- private void createHhea(FontFileReader in, int size) throws IOException {
- TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("hhea");
- if (entry != null) {
- pad4();
- seek_tab(in, "hhea", 0);
- System.arraycopy(in.getBytes((int)entry.offset, (int)entry.length),
- 0, output, currentPos, (int)entry.length);
- writeUShort((int)entry.length + currentPos-2, size);
-
- int checksum = getCheckSum(currentPos, (int)entry.length);
- writeULong(hheaDirOffset, checksum);
- writeULong(hheaDirOffset+4, currentPos);
- writeULong(hheaDirOffset+8, (int)entry.length);
- currentPos+=(int)entry.length;
- realSize+=(int)entry.length;
- } else {
- throw new IOException ("Can't find hhea table");
- }
- }
-
-
- /**
- * Copy the head table as is from original font to subset font
- * and set indexToLocaFormat to long and set
- * checkSumAdjustment to 0, store offset to checkSumAdjustment
- * in checkSumAdjustmentOffset
- */
- private void createHead(FontFileReader in) throws IOException {
- TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("head");
- if (entry != null) {
- pad4();
- seek_tab(in, "head", 0);
- System.arraycopy(in.getBytes((int)entry.offset, (int)entry.length),
- 0, output, currentPos, (int)entry.length);
-
- checkSumAdjustmentOffset = currentPos + 8;
- output[currentPos+8] = 0; // Set checkSumAdjustment to 0
- output[currentPos+9] = 0;
- output[currentPos+10] = 0;
- output[currentPos+11] = 0;
- output[currentPos+50] = 0; // long locaformat
- output[currentPos+51] = 1; // long locaformat
-
- int checksum = getCheckSum(currentPos, (int)entry.length);
- writeULong(headDirOffset, checksum);
- writeULong(headDirOffset+4, currentPos);
- writeULong(headDirOffset+8, (int)entry.length);
-
- currentPos+=(int)entry.length;
- realSize+=(int)entry.length;
- } else {
- throw new IOException ("Can't find head table");
- }
- }
-
-
- /**
- * Create the glyf table and fill in loca table
- */
- private void createGlyf(FontFileReader in, Hashtable glyphs)
- throws IOException {
- TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("glyf");
- int size = 0;
- int start = 0;
- int endOffset = 0; // Store this as the last loca
- if (entry != null) {
- pad4();
- start = currentPos;
-
- for (Enumeration e = glyphs.keys(); e.hasMoreElements();) {
- int glyphLength = 0;
- Integer origIndex = (Integer)e.nextElement();
- Integer subsetIndex = (Integer)glyphs.get(origIndex);
-
- int nextOffset = 0;
- if (origIndex.intValue() >= (mtx_tab.length-1))
- nextOffset = (int)lastLoca;
- else
- nextOffset = (int)mtx_tab[origIndex.intValue()+1].offset;
+ byte[] output = null;
+ int realSize = 0;
+ int currentPos = 0;
+
+ /*
+ * Offsets in name table to be filled out by table.
+ * The offsets are to the checkSum field
+ */
+ int cvtDirOffset = 0;
+ int fpgmDirOffset = 0;
+ int glyfDirOffset = 0;
+ int headDirOffset = 0;
+ int hheaDirOffset = 0;
+ int hmtxDirOffset = 0;
+ int locaDirOffset = 0;
+ int maxpDirOffset = 0;
+ int prepDirOffset = 0;
+
+ int checkSumAdjustmentOffset = 0;
+ int locaOffset = 0;
+
+ /**
+ * Initalize the output array
+ */
+ private void init(int size) {
+ output = new byte[size];
+ realSize = 0;
+ currentPos = 0;
+
+ // createDirectory()
+ }
+
+ /**
+ * Create the directory table
+ */
+ private void createDirectory() {
+ int numTables = 9;
+ // Create the TrueType header
+ writeByte((byte)0);
+ writeByte((byte)1);
+ writeByte((byte)0);
+ writeByte((byte)0);
+ realSize += 4;
+
+ writeUShort(numTables);
+ realSize += 2;
+
+ // Create searchRange, entrySelector and rangeShift
+ int maxPow = maxPow2(numTables);
+ int searchRange = maxPow * 16;
+ writeUShort(searchRange);
+ realSize += 2;
+
+ writeUShort(maxPow);
+ realSize += 2;
+
+ writeUShort((numTables * 16) - searchRange);
+ realSize += 2;
+
+ // Create space for the table entries
+ writeString("cvt ");
+ cvtDirOffset = currentPos;
+ currentPos += 12;
+ realSize += 16;
+
+ writeString("fpgm");
+ fpgmDirOffset = currentPos;
+ currentPos += 12;
+ realSize += 16;
+
+ writeString("glyf");
+ glyfDirOffset = currentPos;
+ currentPos += 12;
+ realSize += 16;
+
+ writeString("head");
+ headDirOffset = currentPos;
+ currentPos += 12;
+ realSize += 16;
+
+ writeString("hhea");
+ hheaDirOffset = currentPos;
+ currentPos += 12;
+ realSize += 16;
+
+ writeString("hmtx");
+ hmtxDirOffset = currentPos;
+ currentPos += 12;
+ realSize += 16;
+
+ writeString("loca");
+ locaDirOffset = currentPos;
+ currentPos += 12;
+ realSize += 16;
+
+ writeString("maxp");
+ maxpDirOffset = currentPos;
+ currentPos += 12;
+ realSize += 16;
+
+ writeString("prep");
+ prepDirOffset = currentPos;
+ currentPos += 12;
+ realSize += 16;
+ }
+
+
+ /**
+ * Copy the cvt table as is from original font to subset font
+ */
+ private void createCvt(FontFileReader in) throws IOException {
+ TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("cvt ");
+ if (entry != null) {
+ pad4();
+ seek_tab(in, "cvt ", 0);
+ System.arraycopy(in.getBytes((int)entry.offset, (int)entry.length),
+ 0, output, currentPos, (int)entry.length);
+
+ int checksum = getCheckSum(currentPos, (int)entry.length);
+ writeULong(cvtDirOffset, checksum);
+ writeULong(cvtDirOffset + 4, currentPos);
+ writeULong(cvtDirOffset + 8, (int)entry.length);
+ currentPos += (int)entry.length;
+ realSize += (int)entry.length;
+ } else {
+ throw new IOException("Can't find cvt table");
+ }
+ }
+
+
+
+ /**
+ * Copy the fpgm table as is from original font to subset font
+ */
+ private void createFpgm(FontFileReader in) throws IOException {
+ TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("fpgm");
+ if (entry != null) {
+ pad4();
+ seek_tab(in, "fpgm", 0);
+ System.arraycopy(in.getBytes((int)entry.offset, (int)entry.length),
+ 0, output, currentPos, (int)entry.length);
+ int checksum = getCheckSum(currentPos, (int)entry.length);
+ writeULong(fpgmDirOffset, checksum);
+ writeULong(fpgmDirOffset + 4, currentPos);
+ writeULong(fpgmDirOffset + 8, (int)entry.length);
+ currentPos += (int)entry.length;
+ realSize += (int)entry.length;
+ } else {
+ throw new IOException("Can't find fpgm table");
+ }
+ }
+
+
+
+ /**
+ * Create an empty loca table without updating checksum
+ */
+ private void createLoca(int size) throws IOException {
+ pad4();
+ locaOffset = currentPos;
+ writeULong(locaDirOffset + 4, currentPos);
+ writeULong(locaDirOffset + 8, size * 4 + 4);
+ currentPos += size * 4 + 4;
+ realSize += size * 4 + 4;
+ }
+
+
+ /**
+ * Copy the maxp table as is from original font to subset font
+ * and set num glyphs to size
+ */
+ private void createMaxp(FontFileReader in, int size) throws IOException {
+ TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("maxp");
+ if (entry != null) {
+ pad4();
+ seek_tab(in, "maxp", 0);
+ System.arraycopy(in.getBytes((int)entry.offset, (int)entry.length),
+ 0, output, currentPos, (int)entry.length);
+ writeUShort(currentPos + 4, size);
+
+ int checksum = getCheckSum(currentPos, (int)entry.length);
+ writeULong(maxpDirOffset, checksum);
+ writeULong(maxpDirOffset + 4, currentPos);
+ writeULong(maxpDirOffset + 8, (int)entry.length);
+ currentPos += (int)entry.length;
+ realSize += (int)entry.length;
+ } else {
+ throw new IOException("Can't find maxp table");
+ }
+ }
+
+
+ /**
+ * Copy the prep table as is from original font to subset font
+ */
+ private void createPrep(FontFileReader in) throws IOException {
+ TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("prep");
+ if (entry != null) {
+ pad4();
+ seek_tab(in, "prep", 0);
+ System.arraycopy(in.getBytes((int)entry.offset, (int)entry.length),
+ 0, output, currentPos, (int)entry.length);
+
+ int checksum = getCheckSum(currentPos, (int)entry.length);
+ writeULong(prepDirOffset, checksum);
+ writeULong(prepDirOffset + 4, currentPos);
+ writeULong(prepDirOffset + 8, (int)entry.length);
+ currentPos += (int)entry.length;
+ realSize += (int)entry.length;
+ } else {
+ throw new IOException("Can't find prep table");
+ }
+ }
+
+
+ /**
+ * Copy the hhea table as is from original font to subset font
+ * and fill in size of hmtx table
+ */
+ private void createHhea(FontFileReader in, int size) throws IOException {
+ TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("hhea");
+ if (entry != null) {
+ pad4();
+ seek_tab(in, "hhea", 0);
+ System.arraycopy(in.getBytes((int)entry.offset, (int)entry.length),
+ 0, output, currentPos, (int)entry.length);
+ writeUShort((int)entry.length + currentPos - 2, size);
+
+ int checksum = getCheckSum(currentPos, (int)entry.length);
+ writeULong(hheaDirOffset, checksum);
+ writeULong(hheaDirOffset + 4, currentPos);
+ writeULong(hheaDirOffset + 8, (int)entry.length);
+ currentPos += (int)entry.length;
+ realSize += (int)entry.length;
+ } else {
+ throw new IOException("Can't find hhea table");
+ }
+ }
+
+
+ /**
+ * Copy the head table as is from original font to subset font
+ * and set indexToLocaFormat to long and set
+ * checkSumAdjustment to 0, store offset to checkSumAdjustment
+ * in checkSumAdjustmentOffset
+ */
+ private void createHead(FontFileReader in) throws IOException {
+ TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("head");
+ if (entry != null) {
+ pad4();
+ seek_tab(in, "head", 0);
+ System.arraycopy(in.getBytes((int)entry.offset, (int)entry.length),
+ 0, output, currentPos, (int)entry.length);
+
+ checkSumAdjustmentOffset = currentPos + 8;
+ output[currentPos + 8] = 0; // Set checkSumAdjustment to 0
+ output[currentPos + 9] = 0;
+ output[currentPos + 10] = 0;
+ output[currentPos + 11] = 0;
+ output[currentPos + 50] = 0; // long locaformat
+ output[currentPos + 51] = 1; // long locaformat
+
+ int checksum = getCheckSum(currentPos, (int)entry.length);
+ writeULong(headDirOffset, checksum);
+ writeULong(headDirOffset + 4, currentPos);
+ writeULong(headDirOffset + 8, (int)entry.length);
+
+ currentPos += (int)entry.length;
+ realSize += (int)entry.length;
+ } else {
+ throw new IOException("Can't find head table");
+ }
+ }
+
+
+ /**
+ * Create the glyf table and fill in loca table
+ */
+ private void createGlyf(FontFileReader in,
+ Hashtable glyphs) throws IOException {
+ TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("glyf");
+ int size = 0;
+ int start = 0;
+ int endOffset = 0; // Store this as the last loca
+ if (entry != null) {
+ pad4();
+ start = currentPos;
+
+ for (Enumeration e = glyphs.keys(); e.hasMoreElements(); ) {
+ int glyphLength = 0;
+ Integer origIndex = (Integer)e.nextElement();
+ Integer subsetIndex = (Integer)glyphs.get(origIndex);
- glyphLength = nextOffset -
- (int)mtx_tab[origIndex.intValue()].offset;
+ int nextOffset = 0;
+ if (origIndex.intValue() >= (mtx_tab.length - 1))
+ nextOffset = (int)lastLoca;
+ else
+ nextOffset =
+ (int)mtx_tab[origIndex.intValue() + 1].offset;
+
+ glyphLength = nextOffset
+ - (int)mtx_tab[origIndex.intValue()].offset;
// Copy glyph
- System.arraycopy(in.getBytes((int)entry.offset +
- (int)mtx_tab[origIndex.intValue()].offset,
- glyphLength),
- 0, output,
- currentPos,
- glyphLength);
+ System.arraycopy(in.getBytes((int)entry.offset + (int)mtx_tab[origIndex.intValue()].offset, glyphLength),
+ 0, output, currentPos, glyphLength);
// Update loca table
- writeULong(locaOffset + subsetIndex.intValue()*4,
- currentPos-start);
- if ((currentPos - start + glyphLength) > endOffset)
- endOffset = (currentPos - start + glyphLength);
-
- currentPos+=glyphLength;
- realSize+=glyphLength;
-
- }
-
- size = currentPos - start;
-
- int checksum = getCheckSum(start, size);
- writeULong(glyfDirOffset, checksum);
- writeULong(glyfDirOffset+4, start);
- writeULong(glyfDirOffset+8, size);
- currentPos+=12;
- realSize+=12;
-
- // Update loca checksum and last loca index
- writeULong(locaOffset + glyphs.size()*4,
- endOffset);
-
- checksum = getCheckSum(locaOffset, glyphs.size()*4+4);
- writeULong(locaDirOffset, checksum);
- } else {
- throw new IOException ("Can't find glyf table");
- }
- }
-
-
- /**
- * Create the hmtx table by copying metrics from original
- * font to subset font. The glyphs hashtable contains an
- * Integer key and Integer value that maps the original
- * metric (key) to the subset metric (value)
- */
- private void createHmtx(FontFileReader in, Hashtable glyphs)
- throws IOException {
- TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("hmtx");
-
- int longHorMetricSize = glyphs.size()*2;
- int leftSideBearingSize = glyphs.size()*2;
- int hmtxSize = longHorMetricSize + leftSideBearingSize;
-
- if (entry != null) {
- pad4();
- int offset = (int)entry.offset;
- for (Enumeration e = glyphs.keys(); e.hasMoreElements();) {
- Integer origIndex = (Integer)e.nextElement();
- Integer subsetIndex = (Integer)glyphs.get(origIndex);
-
- writeUShort(currentPos+subsetIndex.intValue()*4,
- mtx_tab[origIndex.intValue()].wx);
- writeUShort(currentPos+subsetIndex.intValue()*4+2,
- mtx_tab[origIndex.intValue()].lsb);
- }
-
- int checksum = getCheckSum(currentPos, hmtxSize);
- writeULong(hmtxDirOffset, checksum);
- writeULong(hmtxDirOffset+4, currentPos);
- writeULong(hmtxDirOffset+8, hmtxSize);
- currentPos+=hmtxSize;
- realSize+=hmtxSize;
- } else {
- throw new IOException ("Can't find hmtx table");
- }
- }
-
- /**
- * Returns a Vector containing the glyph itself plus all glyphs
- * that this composite glyph uses
- */
- private Vector getIncludedGlyphs(FontFileReader in,
- int glyphOffset, Integer glyphIdx)
- throws IOException {
+ writeULong(locaOffset + subsetIndex.intValue() * 4,
+ currentPos - start);
+ if ((currentPos - start + glyphLength) > endOffset)
+ endOffset = (currentPos - start + glyphLength);
+
+ currentPos += glyphLength;
+ realSize += glyphLength;
+
+ }
+
+ size = currentPos - start;
+
+ int checksum = getCheckSum(start, size);
+ writeULong(glyfDirOffset, checksum);
+ writeULong(glyfDirOffset + 4, start);
+ writeULong(glyfDirOffset + 8, size);
+ currentPos += 12;
+ realSize += 12;
+
+ // Update loca checksum and last loca index
+ writeULong(locaOffset + glyphs.size() * 4, endOffset);
+
+ checksum = getCheckSum(locaOffset, glyphs.size() * 4 + 4);
+ writeULong(locaDirOffset, checksum);
+ } else {
+ throw new IOException("Can't find glyf table");
+ }
+ }
+
+
+ /**
+ * Create the hmtx table by copying metrics from original
+ * font to subset font. The glyphs hashtable contains an
+ * Integer key and Integer value that maps the original
+ * metric (key) to the subset metric (value)
+ */
+ private void createHmtx(FontFileReader in,
+ Hashtable glyphs) throws IOException {
+ TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("hmtx");
+
+ int longHorMetricSize = glyphs.size() * 2;
+ int leftSideBearingSize = glyphs.size() * 2;
+ int hmtxSize = longHorMetricSize + leftSideBearingSize;
+
+ if (entry != null) {
+ pad4();
+ int offset = (int)entry.offset;
+ for (Enumeration e = glyphs.keys(); e.hasMoreElements(); ) {
+ Integer origIndex = (Integer)e.nextElement();
+ Integer subsetIndex = (Integer)glyphs.get(origIndex);
+
+ writeUShort(currentPos + subsetIndex.intValue() * 4,
+ mtx_tab[origIndex.intValue()].wx);
+ writeUShort(currentPos + subsetIndex.intValue() * 4 + 2,
+ mtx_tab[origIndex.intValue()].lsb);
+ }
+
+ int checksum = getCheckSum(currentPos, hmtxSize);
+ writeULong(hmtxDirOffset, checksum);
+ writeULong(hmtxDirOffset + 4, currentPos);
+ writeULong(hmtxDirOffset + 8, hmtxSize);
+ currentPos += hmtxSize;
+ realSize += hmtxSize;
+ } else {
+ throw new IOException("Can't find hmtx table");
+ }
+ }
+
+ /**
+ * Returns a Vector containing the glyph itself plus all glyphs
+ * that this composite glyph uses
+ */
+ private Vector getIncludedGlyphs(FontFileReader in, int glyphOffset,
+ Integer glyphIdx) throws IOException {
Vector ret = new Vector();
ret.addElement(glyphIdx);
- int offset = glyphOffset +
- (int)mtx_tab[glyphIdx.intValue()].offset + 10;
+ int offset = glyphOffset + (int)mtx_tab[glyphIdx.intValue()].offset
+ + 10;
Integer compositeIdx = null;
int flags = 0;
boolean moreComposites = true;
while (moreComposites) {
flags = in.readTTFUShort(offset);
- compositeIdx = new Integer(in.readTTFUShort(offset+2));
+ compositeIdx = new Integer(in.readTTFUShort(offset + 2));
ret.addElement(compositeIdx);
- offset+=4;
+ offset += 4;
if ((flags & 1) > 0) {
- // ARG_1_AND_ARG_2_ARE_WORDS
- offset+=4;
+ // ARG_1_AND_ARG_2_ARE_WORDS
+ offset += 4;
} else {
- offset+=2;
+ offset += 2;
}
if ((flags & 8) > 0)
- offset+=2; // WE_HAVE_A_SCALE
+ offset += 2; // WE_HAVE_A_SCALE
else if ((flags & 64) > 0)
- offset+=4; // WE_HAVE_AN_X_AND_Y_SCALE
+ offset += 4; // WE_HAVE_AN_X_AND_Y_SCALE
else if ((flags & 128) > 0)
- offset+=8; // WE_HAVE_A_TWO_BY_TWO
+ offset += 8; // WE_HAVE_A_TWO_BY_TWO
if ((flags & 32) > 0)
moreComposites = true;
@@ -444,15 +441,15 @@ public class TTFSubSetFile extends TTFFile {
}
- /**
- * Rewrite all compositepointers in glyphindex glyphIdx
- *
- */
+ /**
+ * Rewrite all compositepointers in glyphindex glyphIdx
+ *
+ */
private void remapComposite(FontFileReader in, Hashtable glyphs,
- int glyphOffset, Integer glyphIdx)
- throws IOException {
- int offset = glyphOffset +
- (int)mtx_tab[glyphIdx.intValue()].offset + 10;
+ int glyphOffset,
+ Integer glyphIdx) throws IOException {
+ int offset = glyphOffset + (int)mtx_tab[glyphIdx.intValue()].offset
+ + 10;
Integer compositeIdx = null;
int flags = 0;
@@ -460,36 +457,36 @@ public class TTFSubSetFile extends TTFFile {
while (moreComposites) {
flags = in.readTTFUShort(offset);
- compositeIdx = new Integer(in.readTTFUShort(offset+2));
+ compositeIdx = new Integer(in.readTTFUShort(offset + 2));
Integer newIdx = (Integer)glyphs.get(compositeIdx);
if (newIdx == null) {
- // This errormessage would look much better
- // if the fontname was printed to
- MessageHandler.error("An embedded font " +
- "contains bad glyph data. " +
- "Characters might not display " +
- "correctly.");
+ // This errormessage would look much better
+ // if the fontname was printed to
+ MessageHandler.error("An embedded font "
+ + "contains bad glyph data. "
+ + "Characters might not display "
+ + "correctly.");
moreComposites = false;
continue;
}
-
- in.writeTTFUShort(offset+2, newIdx.intValue());
- offset+=4;
+ in.writeTTFUShort(offset + 2, newIdx.intValue());
+
+ offset += 4;
if ((flags & 1) > 0) {
- // ARG_1_AND_ARG_2_ARE_WORDS
- offset+=4;
+ // ARG_1_AND_ARG_2_ARE_WORDS
+ offset += 4;
} else {
- offset+=2;
+ offset += 2;
}
- if ((flags & 8) > 0 ) {
- offset+=2; // WE_HAVE_A_SCALE
+ if ((flags & 8) > 0) {
+ offset += 2; // WE_HAVE_A_SCALE
} else if ((flags & 64) > 0) {
- offset+=4; // WE_HAVE_AN_X_AND_Y_SCALE
+ offset += 4; // WE_HAVE_AN_X_AND_Y_SCALE
} else if ((flags & 128) > 0) {
- offset+=8; // WE_HAVE_A_TWO_BY_TWO
+ offset += 8; // WE_HAVE_A_TWO_BY_TWO
}
if ((flags & 32) > 0)
@@ -500,81 +497,87 @@ public class TTFSubSetFile extends TTFFile {
}
- /**
- * Scan all the original glyphs for composite glyphs and add those glyphs
- * to the glyphmapping also rewrite the composite glyph pointers to the new
- * mapping
- */
- private void scanGlyphs(FontFileReader in, Hashtable glyphs) throws IOException {
- TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("glyf");
- Hashtable newComposites = null;
- Hashtable allComposites = new Hashtable();
+ /**
+ * Scan all the original glyphs for composite glyphs and add those glyphs
+ * to the glyphmapping also rewrite the composite glyph pointers to the new
+ * mapping
+ */
+ private void scanGlyphs(FontFileReader in,
+ Hashtable glyphs) throws IOException {
+ TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("glyf");
+ Hashtable newComposites = null;
+ Hashtable allComposites = new Hashtable();
- int newIndex = glyphs.size();
+ int newIndex = glyphs.size();
- if (entry != null) {
- while (newComposites == null || newComposites.size() > 0) {
- // Inefficient to iterate through all glyphs
- newComposites = new Hashtable();
+ if (entry != null) {
+ while (newComposites == null || newComposites.size() > 0) {
+ // Inefficient to iterate through all glyphs
+ newComposites = new Hashtable();
- for (Enumeration e = glyphs.keys(); e.hasMoreElements();) {
- Integer origIndex = (Integer)e.nextElement();
+ for (Enumeration e = glyphs.keys(); e.hasMoreElements(); ) {
+ Integer origIndex = (Integer)e.nextElement();
- if (in.readTTFShort(entry.offset +
- mtx_tab[origIndex.intValue()].offset) < 0) {
+ if (in.readTTFShort(entry.offset
+ + mtx_tab[origIndex.intValue()].offset) < 0) {
// origIndex is a composite glyph
- allComposites.put(origIndex, glyphs.get(origIndex));
- Vector composites = getIncludedGlyphs(in, (int)entry.offset,
- origIndex);
+ allComposites.put(origIndex, glyphs.get(origIndex));
+ Vector composites =
+ getIncludedGlyphs(in, (int)entry.offset,
+ origIndex);
// Iterate through all composites pointed to
// by this composite and check if they exists
// in the glyphs map, add them if not.
- for (Enumeration cps=composites.elements();
- cps.hasMoreElements();) {
-
- Integer cIdx =(Integer)cps.nextElement();
- if (glyphs.get(cIdx) == null &&
- newComposites.get(cIdx) == null) {
- newComposites.put(cIdx, new Integer(newIndex));
- newIndex++;
+ for (Enumeration cps = composites.elements();
+ cps.hasMoreElements(); ) {
+
+ Integer cIdx = (Integer)cps.nextElement();
+ if (glyphs.get(cIdx) == null
+ && newComposites.get(cIdx) == null) {
+ newComposites.put(cIdx,
+ new Integer(newIndex));
+ newIndex++;
+ }
}
}
}
- }
// Add composites to glyphs
- for (Enumeration m = newComposites.keys(); m.hasMoreElements();) {
- Integer im = (Integer)m.nextElement();
- glyphs.put(im, newComposites.get(im));
+ for (Enumeration m = newComposites.keys();
+ m.hasMoreElements(); ) {
+ Integer im = (Integer)m.nextElement();
+ glyphs.put(im, newComposites.get(im));
+ }
}
- }
- // Iterate through all composites to remap their composite index
+ // Iterate through all composites to remap their composite index
- for (Enumeration ce = allComposites.keys(); ce.hasMoreElements();) {
- remapComposite(in, glyphs, (int)entry.offset,
- (Integer)ce.nextElement());
- }
+ for (Enumeration ce = allComposites.keys();
+ ce.hasMoreElements(); ) {
+ remapComposite(in, glyphs, (int)entry.offset,
+ (Integer)ce.nextElement());
+ }
- } else {
- throw new IOException ("Can't find glyf table");
- }
- }
+ } else {
+ throw new IOException("Can't find glyf table");
+ }
+ }
- /**
- * glyphs has old index as (Integer) key and new index
- * as (Integer) value
- */
+ /**
+ * glyphs has old index as (Integer) key and new index
+ * as (Integer) value
+ */
- public byte[] readFont(FontFileReader in, String name,
- Hashtable glyphs) throws IOException {
+ public byte[] readFont(FontFileReader in, String name,
+ Hashtable glyphs) throws IOException {
- /* Check if TrueType collection, and that the name
- exists in the collection
- */
+ /*
+ * Check if TrueType collection, and that the name
+ * exists in the collection
+ */
if (!checkTTC(in, name, false))
throw new IOException("Failed to read font");
@@ -589,53 +592,48 @@ public class TTFSubSetFile extends TTFFile {
scanGlyphs(in, glyphs);
- createDirectory(); // Create the TrueType header and directory
+ createDirectory(); // Create the TrueType header and directory
createHead(in);
- createHhea(in, glyphs.size()); // Create the hhea table
- createHmtx(in, glyphs); // Create hmtx table
- createMaxp(in, glyphs.size()); // copy the maxp table
-
- try {
- createCvt(in); // copy the cvt table
- }
- catch (IOException ex) {
- // Cvt is optional (only required for OpenType (MS) fonts)
- MessageHandler.errorln("TrueType warning: "+ex.getMessage());
- }
-
- try {
- createFpgm(in); // copy fpgm table
- }
- catch (IOException ex) {
- // Fpgm is optional (only required for OpenType (MS) fonts)
- MessageHandler.errorln("TrueType warning: "+ex.getMessage());
- }
-
- try {
- createPrep(in); // copy prep table
- }
- catch (IOException ex) {
- // Prep is optional (only required for OpenType (MS) fonts)
- MessageHandler.errorln("TrueType warning: "+ex.getMessage());
- }
-
- try {
- createLoca(glyphs.size()); // create empty loca table
- }
- catch (IOException ex) {
- // Loca is optional (only required for OpenType (MS) fonts)
- MessageHandler.errorln("TrueType warning: "+ex.getMessage());
- }
-
- try {
- createGlyf(in, glyphs);
- }
- catch (IOException ex) {
- // Glyf is optional (only required for OpenType (MS) fonts)
- MessageHandler.errorln("TrueType warning: "+ex.getMessage());
- }
-
+ createHhea(in, glyphs.size()); // Create the hhea table
+ createHmtx(in, glyphs); // Create hmtx table
+ createMaxp(in, glyphs.size()); // copy the maxp table
+
+ try {
+ createCvt(in); // copy the cvt table
+ } catch (IOException ex) {
+ // Cvt is optional (only required for OpenType (MS) fonts)
+ MessageHandler.errorln("TrueType warning: " + ex.getMessage());
+ }
+
+ try {
+ createFpgm(in); // copy fpgm table
+ } catch (IOException ex) {
+ // Fpgm is optional (only required for OpenType (MS) fonts)
+ MessageHandler.errorln("TrueType warning: " + ex.getMessage());
+ }
+
+ try {
+ createPrep(in); // copy prep table
+ } catch (IOException ex) {
+ // Prep is optional (only required for OpenType (MS) fonts)
+ MessageHandler.errorln("TrueType warning: " + ex.getMessage());
+ }
+
+ try {
+ createLoca(glyphs.size()); // create empty loca table
+ } catch (IOException ex) {
+ // Loca is optional (only required for OpenType (MS) fonts)
+ MessageHandler.errorln("TrueType warning: " + ex.getMessage());
+ }
+
+ try {
+ createGlyf(in, glyphs);
+ } catch (IOException ex) {
+ // Glyf is optional (only required for OpenType (MS) fonts)
+ MessageHandler.errorln("TrueType warning: " + ex.getMessage());
+ }
+
pad4();
createCheckSumAdjustment();
@@ -643,167 +641,171 @@ public class TTFSubSetFile extends TTFFile {
System.arraycopy(output, 0, ret, 0, realSize);
return ret;
- }
-
- /**
- * writes a ISO-8859-1 string at the currentPosition
- * updates currentPosition but not realSize
- * @return number of bytes written
- */
- private int writeString(String str) {
- int length = 0;
- try {
- byte[] buf = str.getBytes("ISO-8859-1");
- System.arraycopy(buf, 0, output, currentPos, buf.length);
- length = buf.length;
- currentPos += length;
- } catch (Exception e) {
- // This should never happen!
- }
-
- return length;
- }
-
- /**
- Appends a byte to the output array,
- updates currentPost but not realSize
- */
- private void writeByte(byte b) {
- output[currentPos++] = b;
- }
-
- /**
- Appends a USHORT to the output array,
- updates currentPost but not realSize
- */
- private void writeUShort(int s) {
- byte b1 = (byte)((s >> 8) & 0xff);
- byte b2 = (byte) (s & 0xff);
- writeByte(b1);
- writeByte(b2);
- }
-
- /**
- Appends a USHORT to the output array,
- at the given position without changing currentPos
- */
- private void writeUShort(int pos, int s) {
- byte b1 = (byte)((s >> 8) & 0xff);
- byte b2 = (byte) (s & 0xff);
- output[pos] = b1;
- output[pos+1] = b2;
- }
-
- /**
- Appends a ULONG to the output array,
- updates currentPos but not realSize
- */
- private void writeULong(int s) {
- byte b1 = (byte)((s >> 24) & 0xff);
- byte b2 = (byte)((s >> 16) & 0xff);
- byte b3 = (byte)((s >> 8) & 0xff);
- byte b4 = (byte) (s & 0xff);
- writeByte(b1);
- writeByte(b2);
- writeByte(b3);
- writeByte(b4);
- }
-
- /**
- Appends a ULONG to the output array,
- at the given position without changing currentPos
- */
- private void writeULong(int pos, int s) {
- byte b1 = (byte)((s >> 24) & 0xff);
- byte b2 = (byte)((s >> 16) & 0xff);
- byte b3 = (byte)((s >> 8) & 0xff);
- byte b4 = (byte) (s & 0xff);
- output[pos] = b1;
- output[pos+1] = b2;
- output[pos+2] = b3;
- output[pos+3] = b4;
- }
-
- /** Read a signed short value at given position
- */
- private short readShort(int pos) {
- int ret = readUShort(pos);
- return (short)ret;
- }
-
- /** Read a unsigned short value at given position
- */
- private int readUShort(int pos) {
- int ret = (int)output[pos];
- if (ret < 0)
- ret+=256;
- ret = ret << 8;
- if ((int)output[pos+1] < 0) {
- ret |= (int)output[pos+1]+256;
- } else
- ret |= (int)output[pos+1];
-
- return ret;
- }
-
- /**
- * Create a padding in the fontfile to align
- * on a 4-byte boundary
- */
- private void pad4() {
- int padSize = currentPos % 4;
- for (int i = 0; i < padSize; i++) {
- output[currentPos++] = 0;
- realSize++;
- }
- }
- /**
- * Returns the maximum power of 2 <= max
- */
- private int maxPow2(int max) {
- int i=0;
- while (Math.pow(2, (double)i) < max)
- i++;
-
- return (i-1);
- }
-
- private int log2(int num) {
- return (int)(Math.log((double)num)/Math.log(2));
- }
-
-
- private int getCheckSum(int start, int size) {
- return (int)getLongCheckSum(start, size);
- }
-
- private long getLongCheckSum(int start, int size) {
- // All the tables here are aligned on four byte boundaries
- // Add remainder to size if it's not a multiple of 4
- int remainder = size % 4;
- if (remainder != 0)
- size += remainder;
-
- long sum = 0;
-
- for (int i = 0; i < size; i+=4) {
- int l = (int)(output[start+i] << 24);
- l += (int)(output[start+i+1] << 16);
- l += (int)(output[start+i+2] << 16);
- l += (int)(output[start+i+3] << 16);
- sum += l;
- if (sum > 0xffffffff)
- sum = sum - 0xffffffff;
- }
-
- return sum;
- }
-
- private void createCheckSumAdjustment() {
- long sum = getLongCheckSum(0, realSize);
- int checksum = (int)(0xb1b0afba - sum);
- writeULong(checkSumAdjustmentOffset, checksum);
- }
+ }
+
+ /**
+ * writes a ISO-8859-1 string at the currentPosition
+ * updates currentPosition but not realSize
+ * @return number of bytes written
+ */
+ private int writeString(String str) {
+ int length = 0;
+ try {
+ byte[] buf = str.getBytes("ISO-8859-1");
+ System.arraycopy(buf, 0, output, currentPos, buf.length);
+ length = buf.length;
+ currentPos += length;
+ } catch (Exception e) {
+ // This should never happen!
+ }
+
+ return length;
+ }
+
+ /**
+ * Appends a byte to the output array,
+ * updates currentPost but not realSize
+ */
+ private void writeByte(byte b) {
+ output[currentPos++] = b;
+ }
+
+ /**
+ * Appends a USHORT to the output array,
+ * updates currentPost but not realSize
+ */
+ private void writeUShort(int s) {
+ byte b1 = (byte)((s >> 8) & 0xff);
+ byte b2 = (byte)(s & 0xff);
+ writeByte(b1);
+ writeByte(b2);
+ }
+
+ /**
+ * Appends a USHORT to the output array,
+ * at the given position without changing currentPos
+ */
+ private void writeUShort(int pos, int s) {
+ byte b1 = (byte)((s >> 8) & 0xff);
+ byte b2 = (byte)(s & 0xff);
+ output[pos] = b1;
+ output[pos + 1] = b2;
+ }
+
+ /**
+ * Appends a ULONG to the output array,
+ * updates currentPos but not realSize
+ */
+ private void writeULong(int s) {
+ byte b1 = (byte)((s >> 24) & 0xff);
+ byte b2 = (byte)((s >> 16) & 0xff);
+ byte b3 = (byte)((s >> 8) & 0xff);
+ byte b4 = (byte)(s & 0xff);
+ writeByte(b1);
+ writeByte(b2);
+ writeByte(b3);
+ writeByte(b4);
+ }
+
+ /**
+ * Appends a ULONG to the output array,
+ * at the given position without changing currentPos
+ */
+ private void writeULong(int pos, int s) {
+ byte b1 = (byte)((s >> 24) & 0xff);
+ byte b2 = (byte)((s >> 16) & 0xff);
+ byte b3 = (byte)((s >> 8) & 0xff);
+ byte b4 = (byte)(s & 0xff);
+ output[pos] = b1;
+ output[pos + 1] = b2;
+ output[pos + 2] = b3;
+ output[pos + 3] = b4;
+ }
+
+ /**
+ * Read a signed short value at given position
+ */
+ private short readShort(int pos) {
+ int ret = readUShort(pos);
+ return (short)ret;
+ }
+
+ /**
+ * Read a unsigned short value at given position
+ */
+ private int readUShort(int pos) {
+ int ret = (int)output[pos];
+ if (ret < 0)
+ ret += 256;
+ ret = ret << 8;
+ if ((int)output[pos + 1] < 0) {
+ ret |= (int)output[pos + 1] + 256;
+ } else
+ ret |= (int)output[pos + 1];
+
+ return ret;
+ }
+
+ /**
+ * Create a padding in the fontfile to align
+ * on a 4-byte boundary
+ */
+ private void pad4() {
+ int padSize = currentPos % 4;
+ for (int i = 0; i < padSize; i++) {
+ output[currentPos++] = 0;
+ realSize++;
+ }
+ }
+
+ /**
+ * Returns the maximum power of 2 <= max
+ */
+ private int maxPow2(int max) {
+ int i = 0;
+ while (Math.pow(2, (double)i) < max)
+ i++;
+
+ return (i - 1);
+ }
+
+ private int log2(int num) {
+ return (int)(Math.log((double)num) / Math.log(2));
+ }
+
+
+ private int getCheckSum(int start, int size) {
+ return (int)getLongCheckSum(start, size);
+ }
+
+ private long getLongCheckSum(int start, int size) {
+ // All the tables here are aligned on four byte boundaries
+ // Add remainder to size if it's not a multiple of 4
+ int remainder = size % 4;
+ if (remainder != 0)
+ size += remainder;
+
+ long sum = 0;
+
+ for (int i = 0; i < size; i += 4) {
+ int l = (int)(output[start + i] << 24);
+ l += (int)(output[start + i + 1] << 16);
+ l += (int)(output[start + i + 2] << 16);
+ l += (int)(output[start + i + 3] << 16);
+ sum += l;
+ if (sum > 0xffffffff)
+ sum = sum - 0xffffffff;
+ }
+
+ return sum;
+ }
+
+ private void createCheckSumAdjustment() {
+ long sum = getLongCheckSum(0, realSize);
+ int checksum = (int)(0xb1b0afba - sum);
+ writeULong(checkSumAdjustmentOffset, checksum);
+ }
+
}
diff --git a/src/org/apache/fop/fonts/apps/PFMReader.java b/src/org/apache/fop/fonts/apps/PFMReader.java
index 634f03f3f..4dba53e94 100644
--- a/src/org/apache/fop/fonts/apps/PFMReader.java
+++ b/src/org/apache/fop/fonts/apps/PFMReader.java
@@ -1,9 +1,10 @@
-/*-- $Id$ --
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.fonts.apps;
import java.io.*;
@@ -25,23 +26,21 @@ import java.util.Enumeration;
public class PFMReader {
private boolean invokedStandalone = false;
- public PFMReader() {
- }
+ public PFMReader() {}
/**
- * Parse commandline arguments. put options in the Hashtable and return
- * arguments in the String array
- * the arguments: -fn Perpetua,Bold -cn PerpetuaBold per.ttf Perpetua.xml
- * returns a String[] with the per.ttf and Perpetua.xml. The hash
- * will have the (key, value) pairs: (-fn, Perpetua) and (-cn, PerpetuaBold)
- */
- private static String[] parseArguments(Hashtable options,
- String[] args) {
+ * Parse commandline arguments. put options in the Hashtable and return
+ * arguments in the String array
+ * the arguments: -fn Perpetua,Bold -cn PerpetuaBold per.ttf Perpetua.xml
+ * returns a String[] with the per.ttf and Perpetua.xml. The hash
+ * will have the (key, value) pairs: (-fn, Perpetua) and (-cn, PerpetuaBold)
+ */
+ private static String[] parseArguments(Hashtable options, String[] args) {
Vector arguments = new Vector();
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("-")) {
- if ((i + 1) < args.length && !args[i + 1].startsWith("-")) {
+ if ((i + 1) < args.length &&!args[i + 1].startsWith("-")) {
options.put(args[i], args[i + 1]);
i++;
} else {
@@ -61,32 +60,32 @@ public class PFMReader {
System.out.println(" java org.apache.fop.fonts.apps.PFMReader [options] metricfile.pfm xmlfile.xml\n");
System.out.println(" where options can be:\n");
System.out.println(" -fn \n");
- System.out.println(" default is to use the fontname in the .ttf file, but\n"+
- " you can override that name to make sure that the\n");
+ System.out.println(" default is to use the fontname in the .ttf file, but\n"
+ + " you can override that name to make sure that the\n");
System.out.println(" embedded font is used (if you're embedding fonts)\n");
System.out.println(" instead of installed fonts when viewing documents with Acrobat Reader.\n");
}
/**
- * The main method for the PFM reader tool.
- *
- * @param args Command-line arguments: [options] metricfile.pfm xmlfile.xml
- * where options can be:
- * -fn
- * default is to use the fontname in the .pfm file, but you can override
- * that name to make sure that the embedded font is used instead of installed
- * fonts when viewing documents with Acrobat Reader.
- * -cn
- * default is to use the fontname
- * -ef
- * will add the possibility to embed the font. When running fop, fop will look
- * for this file to embed it
- * -er
- * you can also include the fontfile in the fop.jar file when building fop.
- * You can use both -ef and -er. The file specified in -ef will be searched first,
- * then the -er file.
- */
+ * The main method for the PFM reader tool.
+ *
+ * @param args Command-line arguments: [options] metricfile.pfm xmlfile.xml
+ * where options can be:
+ * -fn
+ * default is to use the fontname in the .pfm file, but you can override
+ * that name to make sure that the embedded font is used instead of installed
+ * fonts when viewing documents with Acrobat Reader.
+ * -cn
+ * default is to use the fontname
+ * -ef
+ * will add the possibility to embed the font. When running fop, fop will look
+ * for this file to embed it
+ * -er
+ * you can also include the fontfile in the fop.jar file when building fop.
+ * You can use both -ef and -er. The file specified in -ef will be searched first,
+ * then the -er file.
+ */
public static void main(String[] args) {
String embFile = null;
String embResource = null;
@@ -103,29 +102,27 @@ public class PFMReader {
System.out.println();
if (options.get("-ef") != null)
- embFile = (String) options.get("-ef");
+ embFile = (String)options.get("-ef");
if (options.get("-er") != null)
- embResource = (String) options.get("-er");
+ embResource = (String)options.get("-er");
if (options.get("-fn") != null)
- fontName = (String) options.get("-fn");
+ fontName = (String)options.get("-fn");
if (options.get("-cn") != null)
- className = (String) options.get("-cn");
+ className = (String)options.get("-cn");
- if (arguments.length != 2 || options.get("-h") != null ||
- options.get("-help") != null ||
- options.get("--help") != null)
+ if (arguments.length != 2 || options.get("-h") != null
+ || options.get("-help") != null || options.get("--help") != null)
displayUsage();
else {
PFMFile pfm = app.loadPFM(arguments[0]);
if (pfm != null) {
app.preview(pfm);
- org.w3c.dom.Document doc =
- app.constructFontXML(pfm, fontName, className,
- embResource, embFile);
+ org.w3c.dom.Document doc = app.constructFontXML(pfm,
+ fontName, className, embResource, embFile);
app.writeFontXML(doc, arguments[1]);
}
@@ -134,11 +131,11 @@ public class PFMReader {
/**
- * Read a PFM file and returns it as an object.
- *
- * @param filename The filename of the PFM file.
- * @return The PFM as an object.
- */
+ * Read a PFM file and returns it as an object.
+ *
+ * @param filename The filename of the PFM file.
+ * @return The PFM as an object.
+ */
public PFMFile loadPFM(String filename) {
try {
System.out.println("Reading " + filename + "...");
@@ -154,10 +151,10 @@ public class PFMReader {
}
/**
- * Displays a preview of the PFM file on the console.
- *
- * @param pfm The PFM file to preview.
- */
+ * Displays a preview of the PFM file on the console.
+ *
+ * @param pfm The PFM file to preview.
+ */
public void preview(PFMFile pfm) {
PrintStream out = System.out;
@@ -190,20 +187,20 @@ public class PFMReader {
}
/**
- * Writes the generated DOM Document to a file.
- *
- * @param doc The DOM Document to save.
- * @param target The target filename for the XML file.
- */
+ * Writes the generated DOM Document to a file.
+ *
+ * @param doc The DOM Document to save.
+ * @param target The target filename for the XML file.
+ */
public void writeFontXML(org.w3c.dom.Document doc, String target) {
System.out.println("Writing xml font file " + target + "...");
System.out.println();
try {
- OutputFormat format = new OutputFormat(doc); //Serialize DOM
- FileWriter out = new FileWriter(target); //Writer will be a String
+ OutputFormat format = new OutputFormat(doc); // Serialize DOM
+ FileWriter out = new FileWriter(target); // Writer will be a String
XMLSerializer serial = new XMLSerializer(out, format);
- serial.asDOMSerializer(); // As a DOM Serializer
+ serial.asDOMSerializer(); // As a DOM Serializer
serial.serialize(doc.getDocumentElement());
out.close();
@@ -213,14 +210,13 @@ public class PFMReader {
}
/**
- * Generates the font metrics file from the PFM file.
- *
- * @param pfm The PFM file to generate the font metrics from.
- * @return The DOM document representing the font metrics file.
- */
+ * Generates the font metrics file from the PFM file.
+ *
+ * @param pfm The PFM file to generate the font metrics from.
+ * @return The DOM document representing the font metrics file.
+ */
public org.w3c.dom.Document constructFontXML(PFMFile pfm,
- String fontName, String className, String resource,
- String file) {
+ String fontName, String className, String resource, String file) {
System.out.println("Creating xml font file...");
System.out.println();
@@ -276,7 +272,9 @@ public class PFMReader {
Element bbox = doc.createElement("bbox");
root.appendChild(bbox);
int[] bb = pfm.getFontBBox();
- String[] names = {"left","bottom","right","top"};
+ String[] names = {
+ "left", "bottom", "right", "top"
+ };
for (int i = 0; i < 4; i++) {
el = doc.createElement(names[i]);
bbox.appendChild(el);
@@ -323,19 +321,19 @@ public class PFMReader {
// Get kerning
for (Enumeration enum = pfm.getKerning().keys();
- enum.hasMoreElements();) {
- Integer kpx1 = (Integer) enum.nextElement();
+ enum.hasMoreElements(); ) {
+ Integer kpx1 = (Integer)enum.nextElement();
el = doc.createElement("kerning");
el.setAttribute("kpx1", kpx1.toString());
root.appendChild(el);
Element el2 = null;
- Hashtable h2 = (Hashtable) pfm.getKerning().get(kpx1);
- for (Enumeration enum2 = h2.keys(); enum2.hasMoreElements();) {
- Integer kpx2 = (Integer) enum2.nextElement();
+ Hashtable h2 = (Hashtable)pfm.getKerning().get(kpx1);
+ for (Enumeration enum2 = h2.keys(); enum2.hasMoreElements(); ) {
+ Integer kpx2 = (Integer)enum2.nextElement();
el2 = doc.createElement("pair");
el2.setAttribute("kpx2", kpx2.toString());
- Integer val = (Integer) h2.get(kpx2);
+ Integer val = (Integer)h2.get(kpx2);
el2.setAttribute("kern", val.toString());
el.appendChild(el2);
}
@@ -356,6 +354,7 @@ public class PFMReader {
return esc.toString();
}
+
}
diff --git a/src/org/apache/fop/fonts/apps/TTFReader.java b/src/org/apache/fop/fonts/apps/TTFReader.java
index 61b3b01f6..5a7c47919 100644
--- a/src/org/apache/fop/fonts/apps/TTFReader.java
+++ b/src/org/apache/fop/fonts/apps/TTFReader.java
@@ -1,8 +1,8 @@
-/* -- $Id$ --
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.fonts.apps;
@@ -15,6 +15,7 @@ import org.apache.fop.fonts.*;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Enumeration;
+
/**
* A tool which reads TTF files and generates
* XML font metrics file for use in FOP.
@@ -24,23 +25,21 @@ public class TTFReader {
private boolean invokedStandalone = false;
- public TTFReader() {
- }
+ public TTFReader() {}
/**
- * Parse commandline arguments. put options in the Hashtable and return
- * arguments in the String array
- * the arguments: -fn Perpetua,Bold -cn PerpetuaBold per.ttf Perpetua.xml
- * returns a String[] with the per.ttf and Perpetua.xml. The hash
- * will have the (key, value) pairs: (-fn, Perpetua) and (-cn, PerpetuaBold)
- */
- private static String[] parseArguments(Hashtable options,
- String[] args) {
+ * Parse commandline arguments. put options in the Hashtable and return
+ * arguments in the String array
+ * the arguments: -fn Perpetua,Bold -cn PerpetuaBold per.ttf Perpetua.xml
+ * returns a String[] with the per.ttf and Perpetua.xml. The hash
+ * will have the (key, value) pairs: (-fn, Perpetua) and (-cn, PerpetuaBold)
+ */
+ private static String[] parseArguments(Hashtable options, String[] args) {
Vector arguments = new Vector();
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("-")) {
- if ((i + 1) < args.length && !args[i + 1].startsWith("-")) {
+ if ((i + 1) < args.length &&!args[i + 1].startsWith("-")) {
options.put(args[i], args[i + 1]);
i++;
} else {
@@ -73,32 +72,32 @@ public class TTFReader {
System.out.println(" from a .ttc file without this option, the fontnames");
System.out.println(" will be listed for you.");
System.out.println(" -fn \n");
- System.out.println(" default is to use the fontname in the .ttf file, but\n"+
- " you can override that name to make sure that the\n");
+ System.out.println(" default is to use the fontname in the .ttf file, but\n"
+ + " you can override that name to make sure that the\n");
System.out.println(" embedded font is used (if you're embedding fonts)\n");
System.out.println(" instead of installed fonts when viewing documents with Acrobat Reader.\n");
}
/**
- * The main method for the TTFReader tool.
- *
- * @param args Command-line arguments: [options] fontfile.ttf xmlfile.xml
- * where options can be:
- * -fn
- * default is to use the fontname in the .ttf file, but you can override
- * that name to make sure that the embedded font is used instead of installed
- * fonts when viewing documents with Acrobat Reader.
- * -cn
- * default is to use the fontname
- * -ef
- * will add the possibility to embed the font. When running fop, fop will look
- * for this file to embed it
- * -er
- * you can also include the fontfile in the fop.jar file when building fop.
- * You can use both -ef and -er. The file specified in -ef will be searched first,
- * then the -er file.
- */
+ * The main method for the TTFReader tool.
+ *
+ * @param args Command-line arguments: [options] fontfile.ttf xmlfile.xml
+ * where options can be:
+ * -fn
+ * default is to use the fontname in the .ttf file, but you can override
+ * that name to make sure that the embedded font is used instead of installed
+ * fonts when viewing documents with Acrobat Reader.
+ * -cn
+ * default is to use the fontname
+ * -ef
+ * will add the possibility to embed the font. When running fop, fop will look
+ * for this file to embed it
+ * -er
+ * you can also include the fontfile in the fop.jar file when building fop.
+ * You can use both -ef and -er. The file specified in -ef will be searched first,
+ * then the -er file.
+ */
public static void main(String[] args) {
String embFile = null;
String embResource = null;
@@ -117,36 +116,35 @@ public class TTFReader {
System.out.println();
if (options.get("-enc") != null) {
- String enc = (String) options.get("-enc");
+ String enc = (String)options.get("-enc");
if ("ansi".equals(enc))
isCid = false;
}
if (options.get("-ttcname") != null)
- ttcName = (String) options.get("-ttcname");
+ ttcName = (String)options.get("-ttcname");
if (options.get("-ef") != null)
- embFile = (String) options.get("-ef");
+ embFile = (String)options.get("-ef");
if (options.get("-er") != null)
- embResource = (String) options.get("-er");
+ embResource = (String)options.get("-er");
if (options.get("-fn") != null)
- fontName = (String) options.get("-fn");
+ fontName = (String)options.get("-fn");
if (options.get("-cn") != null)
- className = (String) options.get("-cn");
+ className = (String)options.get("-cn");
- if (arguments.length != 2 || options.get("-h") != null ||
- options.get("-help") != null ||
- options.get("--help") != null)
+ if (arguments.length != 2 || options.get("-h") != null
+ || options.get("-help") != null || options.get("--help") != null)
displayUsage();
else {
TTFFile ttf = app.loadTTF(arguments[0], ttcName);
if (ttf != null) {
- org.w3c.dom.Document doc =
- app.constructFontXML(ttf, fontName, className,
- embResource, embFile, isCid, ttcName);
+ org.w3c.dom.Document doc = app.constructFontXML(ttf,
+ fontName, className, embResource, embFile, isCid,
+ ttcName);
if (isCid)
System.out.println("Creating CID encoded metrics");
@@ -160,19 +158,19 @@ public class TTFReader {
if (ttf.isEmbeddable())
System.out.println("This font contains no embedding license restrictions");
else
- System.out.println("** Note: This font contains license retrictions for\n"+
- " embedding. This font shouldn't be embedded.");
+ System.out.println("** Note: This font contains license retrictions for\n"
+ + " embedding. This font shouldn't be embedded.");
}
}
}
/**
- * Read a TTF file and returns it as an object.
- *
- * @param filename The filename of the PFM file.
- * @return The TTF as an object.
- */
+ * Read a TTF file and returns it as an object.
+ *
+ * @param filename The filename of the PFM file.
+ * @return The TTF as an object.
+ */
public TTFFile loadTTF(String fileName, String fontName) {
TTFFile ttfFile = new TTFFile();
try {
@@ -190,20 +188,20 @@ public class TTFReader {
/**
- * Writes the generated DOM Document to a file.
- *
- * @param doc The DOM Document to save.
- * @param target The target filename for the XML file.
- */
+ * Writes the generated DOM Document to a file.
+ *
+ * @param doc The DOM Document to save.
+ * @param target The target filename for the XML file.
+ */
public void writeFontXML(org.w3c.dom.Document doc, String target) {
System.out.println("Writing xml font file " + target + "...");
System.out.println();
try {
- OutputFormat format = new OutputFormat(doc); //Serialize DOM
- FileWriter out = new FileWriter(target); //Writer will be a String
+ OutputFormat format = new OutputFormat(doc); // Serialize DOM
+ FileWriter out = new FileWriter(target); // Writer will be a String
XMLSerializer serial = new XMLSerializer(out, format);
- serial.asDOMSerializer(); // As a DOM Serializer
+ serial.asDOMSerializer(); // As a DOM Serializer
serial.serialize(doc.getDocumentElement());
out.close();
@@ -213,14 +211,14 @@ public class TTFReader {
}
/**
- * Generates the font metrics file from the TTF/TTC file.
- *
- * @param ttf The PFM file to generate the font metrics from.
- * @return The DOM document representing the font metrics file.
- */
+ * Generates the font metrics file from the TTF/TTC file.
+ *
+ * @param ttf The PFM file to generate the font metrics from.
+ * @return The DOM document representing the font metrics file.
+ */
public org.w3c.dom.Document constructFontXML(TTFFile ttf,
- String fontName, String className, String resource,
- String file, boolean isCid, String ttcName) {
+ String fontName, String className, String resource, String file,
+ boolean isCid, String ttcName) {
System.out.println("Creating xml font file...");
System.out.println();
@@ -255,28 +253,26 @@ public class TTFReader {
el = doc.createElement("cap-height");
root.appendChild(el);
- el.appendChild(
- doc.createTextNode(String.valueOf(ttf.getCapHeight())));
+ el.appendChild(doc.createTextNode(String.valueOf(ttf.getCapHeight())));
el = doc.createElement("x-height");
root.appendChild(el);
- el.appendChild(
- doc.createTextNode(String.valueOf(ttf.getXHeight())));
+ el.appendChild(doc.createTextNode(String.valueOf(ttf.getXHeight())));
el = doc.createElement("ascender");
root.appendChild(el);
- el.appendChild( doc.createTextNode(
- String.valueOf(ttf.getLowerCaseAscent())));
+ el.appendChild(doc.createTextNode(String.valueOf(ttf.getLowerCaseAscent())));
el = doc.createElement("descender");
root.appendChild(el);
- el.appendChild( doc.createTextNode(
- String.valueOf(ttf.getLowerCaseDescent())));
+ el.appendChild(doc.createTextNode(String.valueOf(ttf.getLowerCaseDescent())));
Element bbox = doc.createElement("bbox");
root.appendChild(bbox);
int[] bb = ttf.getFontBBox();
- String[] names = {"left","bottom","right","top"};
+ String[] names = {
+ "left", "bottom", "right", "top"
+ };
for (int i = 0; i < 4; i++) {
el = doc.createElement(names[i]);
bbox.appendChild(el);
@@ -322,8 +318,8 @@ public class TTFReader {
el = doc.createElement("bfranges");
mel.appendChild(el);
for (Enumeration e = ttf.getCMaps().elements();
- e.hasMoreElements();) {
- TTFCmapEntry ce = (TTFCmapEntry) e.nextElement();
+ e.hasMoreElements(); ) {
+ TTFCmapEntry ce = (TTFCmapEntry)e.nextElement();
Element el2 = doc.createElement("bf");
el.appendChild(el2);
el2.setAttribute("us", String.valueOf(ce.unicodeStart));
@@ -354,19 +350,16 @@ public class TTFReader {
el = doc.createElement("first-char");
sel.appendChild(el);
- el.appendChild(
- doc.createTextNode(String.valueOf(ttf.getFirstChar())));
+ el.appendChild(doc.createTextNode(String.valueOf(ttf.getFirstChar())));
el = doc.createElement("last-char");
sel.appendChild(el);
- el.appendChild(
- doc.createTextNode(String.valueOf(ttf.getLastChar())));
+ el.appendChild(doc.createTextNode(String.valueOf(ttf.getLastChar())));
Element widths = doc.createElement("widths");
sel.appendChild(widths);
- for (short i = ttf.getFirstChar(); i <= ttf.getLastChar();
- i++) {
+ for (short i = ttf.getFirstChar(); i <= ttf.getLastChar(); i++) {
el = doc.createElement("char");
widths.appendChild(el);
el.setAttribute("idx", String.valueOf(i));
@@ -382,7 +375,7 @@ public class TTFReader {
enum = ttf.getAnsiKerning().keys();
while (enum.hasMoreElements()) {
- Integer kpx1 = (Integer) enum.nextElement();
+ Integer kpx1 = (Integer)enum.nextElement();
el = doc.createElement("kerning");
el.setAttribute("kpx1", kpx1.toString());
@@ -391,16 +384,16 @@ public class TTFReader {
Hashtable h2;
if (isCid)
- h2 = (Hashtable) ttf.getKerning().get(kpx1);
+ h2 = (Hashtable)ttf.getKerning().get(kpx1);
else
- h2 = (Hashtable) ttf.getAnsiKerning().get(kpx1);
+ h2 = (Hashtable)ttf.getAnsiKerning().get(kpx1);
- for (Enumeration enum2 = h2.keys(); enum2.hasMoreElements();) {
- Integer kpx2 = (Integer) enum2.nextElement();
+ for (Enumeration enum2 = h2.keys(); enum2.hasMoreElements(); ) {
+ Integer kpx2 = (Integer)enum2.nextElement();
if (isCid || kpx2.intValue() < 256) {
el2 = doc.createElement("pair");
el2.setAttribute("kpx2", kpx2.toString());
- Integer val = (Integer) h2.get(kpx2);
+ Integer val = (Integer)h2.get(kpx2);
el2.setAttribute("kern", val.toString());
el.appendChild(el2);
}
@@ -416,8 +409,8 @@ public class TTFReader {
s.getChars(0, s.length(), ch, 0);
StringBuffer stb = new StringBuffer();
for (int i = 0; i < ch.length; i++)
- if (ch[i] != ' ' && ch[i] != '\r' && ch[i] != '\n' &&
- ch[i] != '\t')
+ if (ch[i] != ' ' && ch[i] != '\r' && ch[i] != '\n'
+ && ch[i] != '\t')
stb.append(ch[i]);
return stb.toString();
@@ -435,5 +428,6 @@ public class TTFReader {
return esc.toString();
}
+
}
diff --git a/src/org/apache/fop/image/AbstractFopImage.java b/src/org/apache/fop/image/AbstractFopImage.java
index c5616e1fd..9617a7ca6 100644
--- a/src/org/apache/fop/image/AbstractFopImage.java
+++ b/src/org/apache/fop/image/AbstractFopImage.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.image;
@@ -23,241 +24,255 @@ import org.apache.fop.image.analyser.ImageReader;
* @see FopImage
*/
public abstract class AbstractFopImage implements FopImage {
- /**
- * Image width (in pixel).
- */
- protected int m_width = 0;
- /**
- * Image height (in pixel).
- */
- protected int m_height = 0;
- /**
- * Image URL.
- */
- protected URL m_href = null;
- /**
- * ImageReader object (to obtain image header informations).
- */
- protected ImageReader m_imageReader = null;
- /**
- * Image color space (org.apache.fop.datatypes.ColorSpace).
- */
- protected ColorSpace m_colorSpace = null;
- /**
- * Bits per pixel.
- */
- protected int m_bitsPerPixel = 0;
- /**
- * Image data (uncompressed).
- */
- protected byte[] m_bitmaps = null;
- /**
- * Image data size.
- */
- protected int m_bitmapsSize = 0;
- /**
- * Image transparency.
- */
- protected boolean m_isTransparent = false;
- /**
- * Transparent color (org.apache.fop.pdf.PDFColor).
- */
- protected PDFColor m_transparentColor = null;
-
- /**
- * Constructor.
- * Construct a new FopImage object and initialize its default properties:
- *
- * - image width
- *
- image height
- *
- * The image data isn't kept in memory.
- * @param href image URL
- * @return a new FopImage object
- * @exception FopImageException an error occured during initialization
- */
- public AbstractFopImage(URL href) throws FopImageException {
- this.m_href = href;
- try {
- this.m_imageReader = ImageReaderFactory.Make(this.m_href.toExternalForm(), this.m_href.openStream());
- } catch (Exception e) {
- throw new FopImageException(e.getMessage());
+
+ /**
+ * Image width (in pixel).
+ */
+ protected int m_width = 0;
+
+ /**
+ * Image height (in pixel).
+ */
+ protected int m_height = 0;
+
+ /**
+ * Image URL.
+ */
+ protected URL m_href = null;
+
+ /**
+ * ImageReader object (to obtain image header informations).
+ */
+ protected ImageReader m_imageReader = null;
+
+ /**
+ * Image color space (org.apache.fop.datatypes.ColorSpace).
+ */
+ protected ColorSpace m_colorSpace = null;
+
+ /**
+ * Bits per pixel.
+ */
+ protected int m_bitsPerPixel = 0;
+
+ /**
+ * Image data (uncompressed).
+ */
+ protected byte[] m_bitmaps = null;
+
+ /**
+ * Image data size.
+ */
+ protected int m_bitmapsSize = 0;
+
+ /**
+ * Image transparency.
+ */
+ protected boolean m_isTransparent = false;
+
+ /**
+ * Transparent color (org.apache.fop.pdf.PDFColor).
+ */
+ protected PDFColor m_transparentColor = null;
+
+ /**
+ * Constructor.
+ * Construct a new FopImage object and initialize its default properties:
+ *
+ * - image width
+ *
- image height
+ *
+ * The image data isn't kept in memory.
+ * @param href image URL
+ * @return a new FopImage object
+ * @exception FopImageException an error occured during initialization
+ */
+ public AbstractFopImage(URL href) throws FopImageException {
+ this.m_href = href;
+ try {
+ this.m_imageReader =
+ ImageReaderFactory.Make(this.m_href.toExternalForm(),
+ this.m_href.openStream());
+ } catch (Exception e) {
+ throw new FopImageException(e.getMessage());
+ }
+ this.m_width = this.m_imageReader.getWidth();
+ this.m_height = this.m_imageReader.getHeight();
+ }
+
+ /**
+ * Constructor.
+ * Construct a new FopImage object and initialize its default properties:
+ *
+ * - image width
+ *
- image height
+ *
+ * The image data isn't kept in memory.
+ * @param href image URL
+ * imgReader ImageReader object
+ * @return a new FopImage object
+ * @exception FopImageException an error occured during initialization
+ */
+ public AbstractFopImage(URL href,
+ ImageReader imgReader) throws FopImageException {
+ this.m_href = href;
+ this.m_imageReader = imgReader;
+ this.m_width = this.m_imageReader.getWidth();
+ this.m_height = this.m_imageReader.getHeight();
+ }
+
+ /**
+ * Load image data and initialize its properties.
+ * Subclasses need to implement this method.
+ * @exception FopImageException an error occured during loading
+ */
+ abstract protected void loadImage() throws FopImageException;
+
+ /**
+ * Return the image URL.
+ * @return the image URL (as String)
+ */
+ public String getURL() {
+ return this.m_href.toString();
+ }
+
+ /**
+ * Return the image width.
+ * @return the image width
+ * @exception FopImageException an error occured during property retriaval
+ */
+ public int getWidth() throws FopImageException {
+ if (this.m_width == 0)
+ this.loadImage();
+
+ return this.m_width;
+ }
+
+ /**
+ * Return the image height.
+ * @return the image height
+ * @exception FopImageException an error occured during property retriaval
+ */
+ public int getHeight() throws FopImageException {
+ if (this.m_height == 0)
+ this.loadImage();
+
+ return this.m_height;
}
- this.m_width = this.m_imageReader.getWidth();
- this.m_height = this.m_imageReader.getHeight();
- }
-
- /**
- * Constructor.
- * Construct a new FopImage object and initialize its default properties:
- *
- * - image width
- *
- image height
- *
- * The image data isn't kept in memory.
- * @param href image URL
- * imgReader ImageReader object
- * @return a new FopImage object
- * @exception FopImageException an error occured during initialization
- */
- public AbstractFopImage(URL href, ImageReader imgReader)
- throws FopImageException {
- this.m_href = href;
- this.m_imageReader = imgReader;
- this.m_width = this.m_imageReader.getWidth();
- this.m_height = this.m_imageReader.getHeight();
- }
-
- /**
- * Load image data and initialize its properties.
- * Subclasses need to implement this method.
- * @exception FopImageException an error occured during loading
- */
- abstract protected void loadImage() throws FopImageException;
-
- /**
- * Return the image URL.
- * @return the image URL (as String)
- */
- public String getURL() {
- return this.m_href.toString();
- }
-
- /**
- * Return the image width.
- * @return the image width
- * @exception FopImageException an error occured during property retriaval
- */
- public int getWidth() throws FopImageException {
- if (this.m_width == 0)
- this.loadImage();
-
- return this.m_width;
- }
-
- /**
- * Return the image height.
- * @return the image height
- * @exception FopImageException an error occured during property retriaval
- */
- public int getHeight() throws FopImageException {
- if (this.m_height == 0)
- this.loadImage();
-
- return this.m_height;
- }
-
- /**
- * Return the image color space.
- * @return the image color space (org.apache.fop.datatypes.ColorSpace)
- * @exception FopImageException an error occured during property retriaval
- */
- public ColorSpace getColorSpace() throws FopImageException {
- if (this.m_colorSpace == null)
- this.loadImage();
-
- return this.m_colorSpace;
- }
-
- /**
- * Return the number of bits per pixel.
- * @return number of bits per pixel
- * @exception FopImageException an error occured during property retriaval
- */
- public int getBitsPerPixel() throws FopImageException {
- if (this.m_bitsPerPixel == 0)
- this.loadImage();
-
- return this.m_bitsPerPixel;
- }
-
- /**
- * Return the image transparency.
- * @return true if the image is transparent
- * @exception FopImageException an error occured during property retriaval
- */
- public boolean isTransparent() throws FopImageException {
- return this.m_isTransparent;
- }
-
- /**
- * Return the transparent color.
- * @return the transparent color (org.apache.fop.pdf.PDFColor)
- * @exception FopImageException an error occured during property retriaval
- */
- public PDFColor getTransparentColor() throws FopImageException {
- return this.m_transparentColor;
- }
-
- /**
- * Return the image data (uncompressed).
- * @return the image data
- * @exception FopImageException an error occured during loading
- */
- public byte[] getBitmaps() throws FopImageException {
- if (this.m_bitmaps == null)
- this.loadImage();
-
- return this.m_bitmaps;
- }
-
- /**
- * Return the image data size (uncompressed).
- * @return the image data size
- * @exception FopImageException an error occured during loading
- */
- public int getBitmapsSize() throws FopImageException {
- if (this.m_bitmapsSize == 0)
- this.loadImage();
-
- return this.m_bitmapsSize;
- }
-
- /**
- * Return the original image data (compressed).
- * @return the original image data
- * @exception FopImageException an error occured during loading
- */
- public byte[] getRessourceBytes() throws FopImageException {
- return null;
- }
-
- /**
- * Return the original image data size (compressed).
- * @return the original image data size
- * @exception FopImageException an error occured during loading
- */
- public int getRessourceBytesSize() throws FopImageException {
- return 0;
- }
-
- /**
- * Return the original image compression type.
- * @return the original image compression type (org.apache.fop.pdf.PDFFilter)
- * @exception FopImageException an error occured during loading
- */
- public PDFFilter getPDFFilter() throws FopImageException {
- return null;
- }
-
- /**
- * Free all ressource.
- */
- public void close() {
- /* For the moment, only release the bitmaps (image areas
- can share the same FopImage object)
- Thus, even if it had been called, other properties
- are still available.
- */
- //this.m_width = 0;
- //this.m_height = 0;
- //this.m_href = null;
- //this.m_colorSpace = null;
- //this.m_bitsPerPixel = 0;
- this.m_bitmaps = null;
- this.m_bitmapsSize = 0;
- //this.m_isTransparent = false;
- //this.m_transparentColor = null;
- }
+
+ /**
+ * Return the image color space.
+ * @return the image color space (org.apache.fop.datatypes.ColorSpace)
+ * @exception FopImageException an error occured during property retriaval
+ */
+ public ColorSpace getColorSpace() throws FopImageException {
+ if (this.m_colorSpace == null)
+ this.loadImage();
+
+ return this.m_colorSpace;
+ }
+
+ /**
+ * Return the number of bits per pixel.
+ * @return number of bits per pixel
+ * @exception FopImageException an error occured during property retriaval
+ */
+ public int getBitsPerPixel() throws FopImageException {
+ if (this.m_bitsPerPixel == 0)
+ this.loadImage();
+
+ return this.m_bitsPerPixel;
+ }
+
+ /**
+ * Return the image transparency.
+ * @return true if the image is transparent
+ * @exception FopImageException an error occured during property retriaval
+ */
+ public boolean isTransparent() throws FopImageException {
+ return this.m_isTransparent;
+ }
+
+ /**
+ * Return the transparent color.
+ * @return the transparent color (org.apache.fop.pdf.PDFColor)
+ * @exception FopImageException an error occured during property retriaval
+ */
+ public PDFColor getTransparentColor() throws FopImageException {
+ return this.m_transparentColor;
+ }
+
+ /**
+ * Return the image data (uncompressed).
+ * @return the image data
+ * @exception FopImageException an error occured during loading
+ */
+ public byte[] getBitmaps() throws FopImageException {
+ if (this.m_bitmaps == null)
+ this.loadImage();
+
+ return this.m_bitmaps;
+ }
+
+ /**
+ * Return the image data size (uncompressed).
+ * @return the image data size
+ * @exception FopImageException an error occured during loading
+ */
+ public int getBitmapsSize() throws FopImageException {
+ if (this.m_bitmapsSize == 0)
+ this.loadImage();
+
+ return this.m_bitmapsSize;
+ }
+
+ /**
+ * Return the original image data (compressed).
+ * @return the original image data
+ * @exception FopImageException an error occured during loading
+ */
+ public byte[] getRessourceBytes() throws FopImageException {
+ return null;
+ }
+
+ /**
+ * Return the original image data size (compressed).
+ * @return the original image data size
+ * @exception FopImageException an error occured during loading
+ */
+ public int getRessourceBytesSize() throws FopImageException {
+ return 0;
+ }
+
+ /**
+ * Return the original image compression type.
+ * @return the original image compression type (org.apache.fop.pdf.PDFFilter)
+ * @exception FopImageException an error occured during loading
+ */
+ public PDFFilter getPDFFilter() throws FopImageException {
+ return null;
+ }
+
+ /**
+ * Free all ressource.
+ */
+ public void close() {
+ /*
+ * For the moment, only release the bitmaps (image areas
+ * can share the same FopImage object)
+ * Thus, even if it had been called, other properties
+ * are still available.
+ */
+ // this.m_width = 0;
+ // this.m_height = 0;
+ // this.m_href = null;
+ // this.m_colorSpace = null;
+ // this.m_bitsPerPixel = 0;
+ this.m_bitmaps = null;
+ this.m_bitmapsSize = 0;
+ // this.m_isTransparent = false;
+ // this.m_transparentColor = null;
+ }
+
}
diff --git a/src/org/apache/fop/image/BmpImage.java b/src/org/apache/fop/image/BmpImage.java
index 158d0f227..6918d2604 100644
--- a/src/org/apache/fop/image/BmpImage.java
+++ b/src/org/apache/fop/image/BmpImage.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
/**
@@ -58,7 +14,7 @@
package org.apache.fop.image;
-//Java
+// Java
import java.net.URL;
import java.io.InputStream;
import java.io.IOException;
@@ -68,181 +24,181 @@ import org.apache.fop.datatypes.ColorSpace;
import org.apache.fop.pdf.PDFColor;
import org.apache.fop.image.analyser.ImageReader;
-public class BmpImage extends AbstractFopImage
-{
- public BmpImage(URL href) throws FopImageException {
- super(href);
- }
-
- public BmpImage(URL href, ImageReader imgReader) throws FopImageException {
- super(href, imgReader);
- }
-
- protected void loadImage() throws FopImageException
- {
- int wpos=18;
- int hpos=22; //offset positioning for w and height in bmp files
- int [] headermap = new int[54];
- int filepos = 0;
- InputStream file = null;
- byte palette[] = null;
- try
- {
- file = this.m_href.openStream();
- boolean eof=false;
- while ((!eof) && (filepos<54) )
- {
- int input =file.read();
- if (input==-1)
- eof=true;
- else
- headermap[filepos++]=input;
- }
-
- if ( headermap[28] == 4 || headermap[28] == 8 )
- {
- int palettesize = 1 << headermap[28];
- palette = new byte[palettesize * 3];
- int countr = 0;
- while ( !eof && countr < palettesize )
- {
- int count2 = 2;
- while ( !eof && count2 >= -1 )
- {
- int input = file.read();
- if ( input == -1 )
- eof = true;
- else if ( count2 >= 0 )
- {
- palette[countr * 3 + count2] = (byte)(input & 0xFF);
- }
- count2--;
- filepos++;
- }
- countr++;
- }
- }
- }
- catch (IOException e)
- {
- throw new FopImageException("Error while loading image " + this.m_href.toString() + " : " + e.getClass() + " - " + e.getMessage());
- }
- // gets h & w from headermap
- this.m_width = headermap[wpos]+headermap[wpos+1]*256+headermap[wpos+2]*256*256+headermap[wpos+3]*256*256*256;
- this.m_height = headermap[hpos]+headermap[hpos+1]*256+headermap[hpos+2]*256*256+headermap[hpos+3]*256*256*256;
-
- int imagestart =headermap[10]+headermap[11]*256+headermap[12]*256*256+headermap[13]*256*256*256;
- this.m_bitsPerPixel=headermap[28];
- this.m_colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
- int bytes;
- if ( this.m_bitsPerPixel == 1 )
- bytes = (this.m_width + 7) / 8;
- else if ( this.m_bitsPerPixel == 24 )
- bytes = this.m_width * 3;
- else if ( this.m_bitsPerPixel == 4 || this.m_bitsPerPixel == 8 )
- bytes = this.m_width / (8 / this.m_bitsPerPixel);
- else
- throw new FopImageException("Image (" + this.m_href.toString() + ") has " + this.m_bitsPerPixel + " which is not a supported BMP format.");
- if ( (bytes & 0x03) != 0 )
- {
- bytes |= 0x03;
- bytes++;
- }
-
- // Should take care of the ColorSpace and bitsPerPixel
- this.m_bitmapsSize = this.m_width * this.m_height * 3;
- this.m_bitmaps = new byte[this.m_bitmapsSize];
-
- int[] temp = new int[bytes * this.m_height];
- try
- {
- int input;
- int count=0;
- file.skip((long)(imagestart - filepos));
- while ( (input = file.read()) != -1 )
- temp[count++]=input;
- file.close();
- }
- catch (IOException e)
- {
- throw new FopImageException("Error while loading image " + this.m_href.toString() + " : " + e.getClass() + " - " + e.getMessage());
- }
-
- for ( int i = 0 ; i < this.m_height ; i++)
- {
- int x = 0;
- int j = 0;
- while ( j < bytes )
- {
- int p = temp[(this.m_height - i - 1) * bytes + j];
+public class BmpImage extends AbstractFopImage {
+ public BmpImage(URL href) throws FopImageException {
+ super(href);
+ }
- if ( this.m_bitsPerPixel == 24 && x < this.m_width )
- {
- int countr = 2;
- do
- {
- this.m_bitmaps[3 * (i * this.m_width + x) + countr] = (byte)(temp[(this.m_height - i - 1) * bytes + j] & 0xFF);
- j++;
- } while ( --countr >= 0 );
- x++;
- }
- else if ( this.m_bitsPerPixel == 1 )
- {
- for ( int countr = 0 ; countr < 8 && x < this.m_width ; countr++ )
- {
- if ( (p & 0x80) != 0 )
- {
- this.m_bitmaps[3 * (i * this.m_width + x)] = (byte)0xFF;
- this.m_bitmaps[3 * (i * this.m_width + x) + 1] = (byte)0xFF;
- this.m_bitmaps[3 * (i * this.m_width + x) + 2] = (byte)0xFF;
- }
- else
- {
- this.m_bitmaps[3 * (i * this.m_width + x)] = (byte)0;
- this.m_bitmaps[3 * (i * this.m_width + x) + 1] = (byte)0;
- this.m_bitmaps[3 * (i * this.m_width + x) + 2] = (byte)0;
- }
- p <<= 1;
- x++;
- }
- j++;
- }
- else if ( this.m_bitsPerPixel == 4 )
- {
- for ( int countr = 0 ; countr < 2 && x < this.m_width ; countr++ )
- {
- int pal = ((p & 0xF0) >> 4) * 3;
- this.m_bitmaps[3 * (i * this.m_width + x)] = palette[pal];
- this.m_bitmaps[3 * (i * this.m_width + x) + 1] = palette[pal + 1];
- this.m_bitmaps[3 * (i * this.m_width + x) + 2] = palette[pal + 2];
- p <<= 4;
- x++;
- }
- j++;
- }
- else if ( this.m_bitsPerPixel == 8 )
- {
- if ( x < this.m_width )
- {
- p *= 3;
- this.m_bitmaps[3 * (i * this.m_width + x)] = palette[p];
- this.m_bitmaps[3 * (i * this.m_width + x) + 1] = palette[p + 1];
- this.m_bitmaps[3 * (i * this.m_width + x) + 2] = palette[p + 2];
- j++;
- x++;
- }
- else
- j = bytes;
- }
- else
- j++;
- }
+ public BmpImage(URL href,
+ ImageReader imgReader) throws FopImageException {
+ super(href, imgReader);
}
- // This seems really strange to me, but I noticed that JimiImage hardcodes
- // m_bitsPerPixel to 8. If I do not do this Acrobat is unable to read the resultant PDF,
- // so we will hardcode this...
- this.m_bitsPerPixel = 8;
- }
+ protected void loadImage() throws FopImageException {
+ int wpos = 18;
+ int hpos = 22; // offset positioning for w and height in bmp files
+ int[] headermap = new int[54];
+ int filepos = 0;
+ InputStream file = null;
+ byte palette[] = null;
+ try {
+ file = this.m_href.openStream();
+ boolean eof = false;
+ while ((!eof) && (filepos < 54)) {
+ int input = file.read();
+ if (input == -1)
+ eof = true;
+ else
+ headermap[filepos++] = input;
+ }
+
+ if (headermap[28] == 4 || headermap[28] == 8) {
+ int palettesize = 1 << headermap[28];
+ palette = new byte[palettesize * 3];
+ int countr = 0;
+ while (!eof && countr < palettesize) {
+ int count2 = 2;
+ while (!eof && count2 >= -1) {
+ int input = file.read();
+ if (input == -1)
+ eof = true;
+ else if (count2 >= 0) {
+ palette[countr * 3 + count2] = (byte)(input
+ & 0xFF);
+ }
+ count2--;
+ filepos++;
+ }
+ countr++;
+ }
+ }
+ } catch (IOException e) {
+ throw new FopImageException("Error while loading image "
+ + this.m_href.toString() + " : "
+ + e.getClass() + " - "
+ + e.getMessage());
+ }
+ // gets h & w from headermap
+ this.m_width = headermap[wpos] + headermap[wpos + 1] * 256
+ + headermap[wpos + 2] * 256 * 256
+ + headermap[wpos + 3] * 256 * 256 * 256;
+ this.m_height = headermap[hpos] + headermap[hpos + 1] * 256
+ + headermap[hpos + 2] * 256 * 256
+ + headermap[hpos + 3] * 256 * 256 * 256;
+
+ int imagestart = headermap[10] + headermap[11] * 256
+ + headermap[12] * 256 * 256
+ + headermap[13] * 256 * 256 * 256;
+ this.m_bitsPerPixel = headermap[28];
+ this.m_colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
+ int bytes;
+ if (this.m_bitsPerPixel == 1)
+ bytes = (this.m_width + 7) / 8;
+ else if (this.m_bitsPerPixel == 24)
+ bytes = this.m_width * 3;
+ else if (this.m_bitsPerPixel == 4 || this.m_bitsPerPixel == 8)
+ bytes = this.m_width / (8 / this.m_bitsPerPixel);
+ else
+ throw new FopImageException("Image (" + this.m_href.toString()
+ + ") has " + this.m_bitsPerPixel
+ + " which is not a supported BMP format.");
+ if ((bytes & 0x03) != 0) {
+ bytes |= 0x03;
+ bytes++;
+ }
+
+ // Should take care of the ColorSpace and bitsPerPixel
+ this.m_bitmapsSize = this.m_width * this.m_height * 3;
+ this.m_bitmaps = new byte[this.m_bitmapsSize];
+
+ int[] temp = new int[bytes * this.m_height];
+ try {
+ int input;
+ int count = 0;
+ file.skip((long)(imagestart - filepos));
+ while ((input = file.read()) != -1)
+ temp[count++] = input;
+ file.close();
+ } catch (IOException e) {
+ throw new FopImageException("Error while loading image "
+ + this.m_href.toString() + " : "
+ + e.getClass() + " - "
+ + e.getMessage());
+ }
+
+ for (int i = 0; i < this.m_height; i++) {
+ int x = 0;
+ int j = 0;
+ while (j < bytes) {
+ int p = temp[(this.m_height - i - 1) * bytes + j];
+
+ if (this.m_bitsPerPixel == 24 && x < this.m_width) {
+ int countr = 2;
+ do {
+ this.m_bitmaps[3 * (i * this.m_width + x) + countr] =
+ (byte)(temp[(this.m_height - i - 1) * bytes + j]
+ & 0xFF);
+ j++;
+ } while (--countr >= 0);
+ x++;
+ } else if (this.m_bitsPerPixel == 1) {
+ for (int countr = 0; countr < 8 && x < this.m_width;
+ countr++) {
+ if ((p & 0x80) != 0) {
+ this.m_bitmaps[3 * (i * this.m_width + x)] =
+ (byte)0xFF;
+ this.m_bitmaps[3 * (i * this.m_width + x) + 1] =
+ (byte)0xFF;
+ this.m_bitmaps[3 * (i * this.m_width + x) + 2] =
+ (byte)0xFF;
+ } else {
+ this.m_bitmaps[3 * (i * this.m_width + x)] =
+ (byte)0;
+ this.m_bitmaps[3 * (i * this.m_width + x) + 1] =
+ (byte)0;
+ this.m_bitmaps[3 * (i * this.m_width + x) + 2] =
+ (byte)0;
+ }
+ p <<= 1;
+ x++;
+ }
+ j++;
+ } else if (this.m_bitsPerPixel == 4) {
+ for (int countr = 0; countr < 2 && x < this.m_width;
+ countr++) {
+ int pal = ((p & 0xF0) >> 4) * 3;
+ this.m_bitmaps[3 * (i * this.m_width + x)] =
+ palette[pal];
+ this.m_bitmaps[3 * (i * this.m_width + x) + 1] =
+ palette[pal + 1];
+ this.m_bitmaps[3 * (i * this.m_width + x) + 2] =
+ palette[pal + 2];
+ p <<= 4;
+ x++;
+ }
+ j++;
+ } else if (this.m_bitsPerPixel == 8) {
+ if (x < this.m_width) {
+ p *= 3;
+ this.m_bitmaps[3 * (i * this.m_width + x)] =
+ palette[p];
+ this.m_bitmaps[3 * (i * this.m_width + x) + 1] =
+ palette[p + 1];
+ this.m_bitmaps[3 * (i * this.m_width + x) + 2] =
+ palette[p + 2];
+ j++;
+ x++;
+ } else
+ j = bytes;
+ } else
+ j++;
+ }
+ }
+
+ // This seems really strange to me, but I noticed that JimiImage hardcodes
+ // m_bitsPerPixel to 8. If I do not do this Acrobat is unable to read the resultant PDF,
+ // so we will hardcode this...
+ this.m_bitsPerPixel = 8;
+ }
}
diff --git a/src/org/apache/fop/image/FopImage.java b/src/org/apache/fop/image/FopImage.java
index 79f42305d..2cbcc45c5 100644
--- a/src/org/apache/fop/image/FopImage.java
+++ b/src/org/apache/fop/image/FopImage.java
@@ -1,11 +1,12 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
-//Author: Eric SCHAEFFER
-//Description: represent an image object
+// Author: Eric SCHAEFFER
+// Description: represent an image object
package org.apache.fop.image;
@@ -14,48 +15,48 @@ import org.apache.fop.pdf.PDFColor;
import org.apache.fop.pdf.PDFFilter;
public interface FopImage {
- // Init the object.
- // If href protocol isn't file://, can load the entire image
- // and keep it in memory.
- // Should cache the input stream, and load data when needed.
-// public FopImage(URL href) throws FopImageException;
-
- // Get image general properties.
- // Methods throw exception because they can retrieve data
- // when needed.
-
- // Ressource location
- public String getURL();
-
- // image size
- public int getWidth() throws FopImageException;
- public int getHeight() throws FopImageException;
-
- // DeviceGray, DeviceRGB, or DeviceCMYK
- public ColorSpace getColorSpace() throws FopImageException;
-
- // bits per pixel
- public int getBitsPerPixel() throws FopImageException;
-
- // For transparent images
- public boolean isTransparent() throws FopImageException;
- public PDFColor getTransparentColor() throws FopImageException;
-
- // get the image bytes, and bytes properties
-
- // get uncompressed image bytes
- public byte[] getBitmaps() throws FopImageException;
-// width * (bitsPerPixel / 8) * height, no ?
- public int getBitmapsSize() throws FopImageException;
-
- // get compressed image bytes
- // I don't know if we really need it, nor if it
- // should be changed...
- public byte[] getRessourceBytes() throws FopImageException;
- public int getRessourceBytesSize() throws FopImageException;
- // return null if no corresponding PDFFilter
- public PDFFilter getPDFFilter() throws FopImageException;
-
- // release memory
- public void close();
+ // Init the object.
+ // If href protocol isn't file://, can load the entire image
+ // and keep it in memory.
+ // Should cache the input stream, and load data when needed.
+ // public FopImage(URL href) throws FopImageException;
+
+ // Get image general properties.
+ // Methods throw exception because they can retrieve data
+ // when needed.
+
+ // Ressource location
+ public String getURL();
+
+ // image size
+ public int getWidth() throws FopImageException;
+ public int getHeight() throws FopImageException;
+
+ // DeviceGray, DeviceRGB, or DeviceCMYK
+ public ColorSpace getColorSpace() throws FopImageException;
+
+ // bits per pixel
+ public int getBitsPerPixel() throws FopImageException;
+
+ // For transparent images
+ public boolean isTransparent() throws FopImageException;
+ public PDFColor getTransparentColor() throws FopImageException;
+
+ // get the image bytes, and bytes properties
+
+ // get uncompressed image bytes
+ public byte[] getBitmaps() throws FopImageException;
+ // width * (bitsPerPixel / 8) * height, no ?
+ public int getBitmapsSize() throws FopImageException;
+
+ // get compressed image bytes
+ // I don't know if we really need it, nor if it
+ // should be changed...
+ public byte[] getRessourceBytes() throws FopImageException;
+ public int getRessourceBytesSize() throws FopImageException;
+ // return null if no corresponding PDFFilter
+ public PDFFilter getPDFFilter() throws FopImageException;
+
+ // release memory
+ public void close();
}
diff --git a/src/org/apache/fop/image/FopImageConsumer.java b/src/org/apache/fop/image/FopImageConsumer.java
index 843fd7e7c..696f1bdd1 100644
--- a/src/org/apache/fop/image/FopImageConsumer.java
+++ b/src/org/apache/fop/image/FopImageConsumer.java
@@ -1,56 +1,12 @@
/*
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
-//Author: Eric SCHAEFFER
-//Description: implement ImageConsumer for FopImage classes
+// Author: Eric SCHAEFFER
+// Description: implement ImageConsumer for FopImage classes
package org.apache.fop.image;
@@ -64,121 +20,117 @@ import java.lang.reflect.Array;
// CONSUMER CLASS
public class FopImageConsumer implements ImageConsumer {
- protected int width = -1;
- protected int height = -1;
- protected Integer imageStatus = new Integer(-1);
- protected int hints = 0;
- protected Hashtable properties = null;
- protected ColorModel cm = null;
- protected ImageProducer ip = null;
-
- public FopImageConsumer(ImageProducer iprod) {
- this.ip = iprod;
- }
-
- public void imageComplete(int status) {
-/*
-MessageHandler.error("Status ");
-if (status == ImageConsumer.COMPLETESCANLINES) {
- MessageHandler.errorln("CompleteScanLines");
-} else if (status == ImageConsumer.IMAGEABORTED) {
- MessageHandler.errorln("ImageAborted");
-} else if (status == ImageConsumer.IMAGEERROR) {
- MessageHandler.errorln("ImageError");
-} else if (status == ImageConsumer.RANDOMPIXELORDER) {
- MessageHandler.errorln("RandomPixelOrder");
-} else if (status == ImageConsumer.SINGLEFRAME) {
- MessageHandler.errorln("SingleFrame");
-} else if (status == ImageConsumer.SINGLEFRAMEDONE) {
- MessageHandler.errorln("SingleFrameDone");
-} else if (status == ImageConsumer.SINGLEPASS) {
- MessageHandler.errorln("SinglePass");
-} else if (status == ImageConsumer.STATICIMAGEDONE) {
- MessageHandler.errorln("StaticImageDone");
-} else if (status == ImageConsumer.TOPDOWNLEFTRIGHT) {
- MessageHandler.errorln("TopDownLeftRight");
-}
-*/
- synchronized(this.imageStatus) {
- // Need to stop status if image done
- if (this.imageStatus.intValue() != ImageConsumer.STATICIMAGEDONE)
- this.imageStatus = new Integer(status);
- }
- }
-
- public void setColorModel(ColorModel model) {
-//MessageHandler.errorln("setColorModel: " + model);
- this.cm = model;
- }
-
- public void setDimensions(int width, int height) {
-//MessageHandler.errorln("setDimension: w=" + width + " h=" + height);
- this.width = width;
- this.height = height;
- }
-
- public void setHints(int hintflags) {
-//MessageHandler.errorln("setHints: " + hintflags);
- this.hints = hintflags;
- }
-
- public void setProperties(Hashtable props) {
-//MessageHandler.errorln("setProperties: " + props);
- this.properties = props;
- }
-
- public void setPixels(int x, int y, int w, int h,
- ColorModel model, byte[] pixels,int off,
- int scansize) {}
-
- public void setPixels(int x, int y, int w, int h,
- ColorModel model, int[] pixels, int off,
- int scansize) {}
-
- public boolean isImageReady() throws Exception {
- synchronized(this.imageStatus) {
- if (this.imageStatus.intValue() == ImageConsumer.IMAGEABORTED)
- throw new Exception("Image aborted");
- if (this.imageStatus.intValue() == ImageConsumer.IMAGEERROR)
- throw new Exception("Image error");
-
- if (this.imageStatus.intValue() == ImageConsumer.STATICIMAGEDONE)
- return true;
-
- return false;
- }
- }
-
- public int getWidth() {
- return this.width;
- }
-
- public int getHeight() {
- return this.height;
- }
-
- public ColorModel getColorModel() {
- return this.cm;
- }
-
- public int[] getImage() throws Exception {
- int tmpMap[] = new int[this.width * this.height];
- PixelGrabber pg = new PixelGrabber(
- this.ip,
- 0, 0,
- this.width, this.height,
- tmpMap,
- 0, this.width
- );
- pg.setDimensions(this.width, this.height);
- pg.setColorModel(this.cm);
- pg.setHints(this.hints);
- pg.setProperties(this.properties);
- try {
- pg.grabPixels();
- } catch (InterruptedException intex) {
- throw new Exception("Image grabbing interrupted : " + intex.getMessage());
- }
- return tmpMap;
- }
+ protected int width = -1;
+ protected int height = -1;
+ protected Integer imageStatus = new Integer(-1);
+ protected int hints = 0;
+ protected Hashtable properties = null;
+ protected ColorModel cm = null;
+ protected ImageProducer ip = null;
+
+ public FopImageConsumer(ImageProducer iprod) {
+ this.ip = iprod;
+ }
+
+ public void imageComplete(int status) {
+ /*
+ * MessageHandler.error("Status ");
+ * if (status == ImageConsumer.COMPLETESCANLINES) {
+ * MessageHandler.errorln("CompleteScanLines");
+ * } else if (status == ImageConsumer.IMAGEABORTED) {
+ * MessageHandler.errorln("ImageAborted");
+ * } else if (status == ImageConsumer.IMAGEERROR) {
+ * MessageHandler.errorln("ImageError");
+ * } else if (status == ImageConsumer.RANDOMPIXELORDER) {
+ * MessageHandler.errorln("RandomPixelOrder");
+ * } else if (status == ImageConsumer.SINGLEFRAME) {
+ * MessageHandler.errorln("SingleFrame");
+ * } else if (status == ImageConsumer.SINGLEFRAMEDONE) {
+ * MessageHandler.errorln("SingleFrameDone");
+ * } else if (status == ImageConsumer.SINGLEPASS) {
+ * MessageHandler.errorln("SinglePass");
+ * } else if (status == ImageConsumer.STATICIMAGEDONE) {
+ * MessageHandler.errorln("StaticImageDone");
+ * } else if (status == ImageConsumer.TOPDOWNLEFTRIGHT) {
+ * MessageHandler.errorln("TopDownLeftRight");
+ * }
+ */
+ synchronized (this.imageStatus) {
+ // Need to stop status if image done
+ if (this.imageStatus.intValue() != ImageConsumer.STATICIMAGEDONE)
+ this.imageStatus = new Integer(status);
+ }
+ }
+
+ public void setColorModel(ColorModel model) {
+ // MessageHandler.errorln("setColorModel: " + model);
+ this.cm = model;
+ }
+
+ public void setDimensions(int width, int height) {
+ // MessageHandler.errorln("setDimension: w=" + width + " h=" + height);
+ this.width = width;
+ this.height = height;
+ }
+
+ public void setHints(int hintflags) {
+ // MessageHandler.errorln("setHints: " + hintflags);
+ this.hints = hintflags;
+ }
+
+ public void setProperties(Hashtable props) {
+ // MessageHandler.errorln("setProperties: " + props);
+ this.properties = props;
+ }
+
+ public void setPixels(int x, int y, int w, int h, ColorModel model,
+ byte[] pixels, int off, int scansize) {}
+
+ public void setPixels(int x, int y, int w, int h, ColorModel model,
+ int[] pixels, int off, int scansize) {}
+
+ public boolean isImageReady() throws Exception {
+ synchronized (this.imageStatus) {
+ if (this.imageStatus.intValue() == ImageConsumer.IMAGEABORTED)
+ throw new Exception("Image aborted");
+ if (this.imageStatus.intValue() == ImageConsumer.IMAGEERROR)
+ throw new Exception("Image error");
+
+ if (this.imageStatus.intValue() == ImageConsumer.STATICIMAGEDONE)
+ return true;
+
+ return false;
+ }
+ }
+
+ public int getWidth() {
+ return this.width;
+ }
+
+ public int getHeight() {
+ return this.height;
+ }
+
+ public ColorModel getColorModel() {
+ return this.cm;
+ }
+
+ public int[] getImage() throws Exception {
+ int tmpMap[] = new int[this.width * this.height];
+ PixelGrabber pg = new PixelGrabber(this.ip, 0, 0, this.width,
+ this.height, tmpMap, 0,
+ this.width);
+ pg.setDimensions(this.width, this.height);
+ pg.setColorModel(this.cm);
+ pg.setHints(this.hints);
+ pg.setProperties(this.properties);
+ try {
+ pg.grabPixels();
+ } catch (InterruptedException intex) {
+ throw new Exception("Image grabbing interrupted : "
+ + intex.getMessage());
+ }
+ return tmpMap;
+ }
+
}
diff --git a/src/org/apache/fop/image/FopImageException.java b/src/org/apache/fop/image/FopImageException.java
index b7907edb7..c85ecb73d 100644
--- a/src/org/apache/fop/image/FopImageException.java
+++ b/src/org/apache/fop/image/FopImageException.java
@@ -1,11 +1,12 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
-//Author: Eric SCHAEFFER
-//Description: Image Exception
+// Author: Eric SCHAEFFER
+// Description: Image Exception
package org.apache.fop.image;
@@ -18,4 +19,5 @@ public class FopImageException extends Exception {
public FopImageException(String message) {
super(message);
}
+
}
diff --git a/src/org/apache/fop/image/FopImageFactory.java b/src/org/apache/fop/image/FopImageFactory.java
index 1d97cee3d..7255ca011 100644
--- a/src/org/apache/fop/image/FopImageFactory.java
+++ b/src/org/apache/fop/image/FopImageFactory.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -37,7 +38,7 @@ public class FopImageFactory {
* @exception FopImageException an error occured during construction
*/
public static FopImage Make(String href)
- throws MalformedURLException, FopImageException {
+ throws MalformedURLException, FopImageException {
// Get the absolute URL
URL absoluteURL = null;
@@ -51,92 +52,90 @@ public class FopImageFactory {
}
imgIS = absoluteURL.openStream();
} catch (MalformedURLException e_context) {
- throw new FopImageException("Error with image URL: " +
- e_context.getMessage());
- }
- catch (Exception e) {
+ throw new FopImageException("Error with image URL: "
+ + e_context.getMessage());
+ } catch (Exception e) {
// maybe relative
URL context_url = null;
try {
- absoluteURL = new URL(
- Configuration.getStringValue("baseDir") +
- absoluteURL.getFile());
+ absoluteURL = new URL(Configuration.getStringValue("baseDir")
+ + absoluteURL.getFile());
} catch (MalformedURLException e_context) {
// pb context url
- throw new FopImageException(
- "Invalid Image URL - error on relative URL : " +
- e_context.getMessage());
+ throw new FopImageException("Invalid Image URL - error on relative URL : "
+ + e_context.getMessage());
}
}
// check if already created
- FopImage imageObject =
- (FopImage) m_urlMap.get(absoluteURL.toString());
+ FopImage imageObject = (FopImage)m_urlMap.get(absoluteURL.toString());
if (imageObject != null)
return imageObject;
- // If not, check image type
+ // If not, check image type
ImageReader imgReader = null;
try {
if (imgIS == null) {
imgIS = absoluteURL.openStream();
}
- imgReader = ImageReaderFactory.Make(
- absoluteURL.toExternalForm(), imgIS);
+ imgReader = ImageReaderFactory.Make(absoluteURL.toExternalForm(),
+ imgIS);
} catch (Exception e) {
- throw new FopImageException(
- "Error while recovering Image Informations (" +
- absoluteURL.toString() + ") : " + e.getMessage());
+ throw new FopImageException("Error while recovering Image Informations ("
+ + absoluteURL.toString() + ") : "
+ + e.getMessage());
+ }
+ finally {
+ if (imgIS != null) {
+ try {
+ imgIS.close();
+ } catch (IOException e) {}
+ }
}
- finally { if (imgIS != null) {
- try {
- imgIS.close();
- } catch (IOException e) {}
- }
- } if (imgReader == null)
- throw new FopImageException(
- "No ImageReader for this type of image (" +
- absoluteURL.toString() + ")");
- // Associate mime-type to FopImage class
+ if (imgReader == null)
+ throw new FopImageException("No ImageReader for this type of image ("
+ + absoluteURL.toString() + ")");
+ // Associate mime-type to FopImage class
String imgMimeType = imgReader.getMimeType();
String imgClassName = null;
if ("image/gif".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.GifJpegImage";
- // imgClassName = "org.apache.fop.image.JAIImage";
+ // imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/jpeg".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.GifJpegImage";
- // imgClassName = "org.apache.fop.image.JAIImage";
+ // imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/bmp".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.BmpImage";
- // imgClassName = "org.apache.fop.image.JAIImage";
+ // imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/png".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
- // imgClassName = "org.apache.fop.image.JAIImage";
+ // imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/tga".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
- // imgClassName = "org.apache.fop.image.JAIImage";
+ // imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/tiff".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
- // imgClassName = "org.apache.fop.image.JAIImage";
+ // imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/svg+xml".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.SVGImage";
}
if (imgClassName == null)
- throw new FopImageException("Unsupported image type (" +
- absoluteURL.toString() + ") : " + imgMimeType);
+ throw new FopImageException("Unsupported image type ("
+ + absoluteURL.toString() + ") : "
+ + imgMimeType);
- // load the right image class
- // return new
+ // load the right image class
+ // return new
Object imageInstance = null;
Class imageClass = null;
try {
imageClass = Class.forName(imgClassName);
Class[] imageConstructorParameters = new Class[2];
imageConstructorParameters[0] = Class.forName("java.net.URL");
- imageConstructorParameters[1] = Class.forName("org.apache.fop.image.analyser.ImageReader");
+ imageConstructorParameters[1] =
+ Class.forName("org.apache.fop.image.analyser.ImageReader");
Constructor imageConstructor =
- imageClass.getDeclaredConstructor(
- imageConstructorParameters);
+ imageClass.getDeclaredConstructor(imageConstructorParameters);
Object[] initArgs = new Object[2];
initArgs[0] = absoluteURL;
initArgs[1] = imgReader;
@@ -149,24 +148,24 @@ public class FopImageFactory {
} else {
msg = ex.getMessage();
}
- throw new FopImageException(
- "Error creating FopImage object (" +
- absoluteURL.toString() + ") : " + msg);
- }
- catch (Exception ex) {
- throw new FopImageException(
- "Error creating FopImage object (" +
- "Error creating FopImage object (" +
- absoluteURL.toString() + ") : " + ex.getMessage());
+ throw new FopImageException("Error creating FopImage object ("
+ + absoluteURL.toString() + ") : "
+ + msg);
+ } catch (Exception ex) {
+ throw new FopImageException("Error creating FopImage object ("
+ + "Error creating FopImage object ("
+ + absoluteURL.toString() + ") : "
+ + ex.getMessage());
}
- if (! (imageInstance instanceof org.apache.fop.image.FopImage)) {
- throw new FopImageException(
- "Error creating FopImage object (" +
- absoluteURL.toString() + ") : " + "class " +
- imageClass.getName() + " doesn't implement org.apache.fop.image.FopImage interface");
+ if (!(imageInstance instanceof org.apache.fop.image.FopImage)) {
+ throw new FopImageException("Error creating FopImage object ("
+ + absoluteURL.toString() + ") : "
+ + "class " + imageClass.getName()
+ + " doesn't implement org.apache.fop.image.FopImage interface");
}
m_urlMap.put(absoluteURL.toString(), imageInstance);
- return (FopImage) imageInstance;
+ return (FopImage)imageInstance;
}
+
}
diff --git a/src/org/apache/fop/image/GifJpegImage.java b/src/org/apache/fop/image/GifJpegImage.java
index 6abf6cce8..77d591544 100644
--- a/src/org/apache/fop/image/GifJpegImage.java
+++ b/src/org/apache/fop/image/GifJpegImage.java
@@ -1,41 +1,8 @@
/*
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.image;
@@ -58,117 +25,117 @@ import org.apache.fop.image.analyser.ImageReader;
* @see FopImage
*/
public class GifJpegImage extends AbstractFopImage {
- public GifJpegImage(URL href) throws FopImageException {
- super(href);
- }
-
- public GifJpegImage(URL href, ImageReader imgReader)
- throws FopImageException {
- super(href, imgReader);
- }
+ public GifJpegImage(URL href) throws FopImageException {
+ super(href);
+ }
- protected void loadImage() throws FopImageException {
- int[] tmpMap = null;
- try {
- ImageProducer ip = (ImageProducer) this.m_href.getContent();
- FopImageConsumer consumer = new FopImageConsumer(ip);
- ip.startProduction(consumer);
+ public GifJpegImage(URL href,
+ ImageReader imgReader) throws FopImageException {
+ super(href, imgReader);
+ }
- while (! consumer.isImageReady()) {
- Thread.sleep(500);
- }
- this.m_height = consumer.getHeight();
- this.m_width = consumer.getWidth();
+ protected void loadImage() throws FopImageException {
+ int[] tmpMap = null;
+ try {
+ ImageProducer ip = (ImageProducer)this.m_href.getContent();
+ FopImageConsumer consumer = new FopImageConsumer(ip);
+ ip.startProduction(consumer);
- try {
- tmpMap = consumer.getImage();
- } catch (Exception ex) {
- throw new FopImageException(
- "Image grabbing interrupted : " +
- ex.getMessage());
- }
+ while (!consumer.isImageReady()) {
+ Thread.sleep(500);
+ }
+ this.m_height = consumer.getHeight();
+ this.m_width = consumer.getWidth();
- ColorModel cm = consumer.getColorModel();
- this.m_bitsPerPixel = 8;
- //this.m_bitsPerPixel = cm.getPixelSize();
- this.m_colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
- if (cm.hasAlpha()) {
- int transparencyType = cm.getTransparency(); // java.awt.Transparency. BITMASK or OPAQUE or TRANSLUCENT
- if (transparencyType == java.awt.Transparency.OPAQUE) {
- this.m_isTransparent = false;
- } else if (transparencyType ==
- java.awt.Transparency.BITMASK) {
- if (cm instanceof IndexColorModel) {
- this.m_isTransparent = false;
- byte[] alphas = new byte[
- ((IndexColorModel) cm).getMapSize()];
- byte[] reds = new byte[
- ((IndexColorModel) cm).getMapSize()];
- byte[] greens = new byte[
- ((IndexColorModel) cm).getMapSize()];
- byte[] blues = new byte[
- ((IndexColorModel) cm).getMapSize()];
- ((IndexColorModel) cm).getAlphas(alphas);
- ((IndexColorModel) cm).getReds(reds);
- ((IndexColorModel) cm).getGreens(greens);
- ((IndexColorModel) cm).getBlues(blues);
- for (int i = 0;
- i < ((IndexColorModel) cm).getMapSize();
- i++) {
- if ((alphas[i] & 0xFF) == 0) {
- this.m_isTransparent = true;
- this.m_transparentColor = new PDFColor(
- (int)(reds[i] & 0xFF),
- (int)(greens[i] & 0xFF),
- (int)(blues[i] & 0xFF));
- break;
- }
+ try {
+ tmpMap = consumer.getImage();
+ } catch (Exception ex) {
+ throw new FopImageException("Image grabbing interrupted : "
+ + ex.getMessage());
}
- } else {
- // TRANSLUCENT
- /*
- this.m_isTransparent = false;
- for (int i = 0; i < this.m_width * this.m_height; i++) {
- if (cm.getAlpha(tmpMap[i]) == 0) {
- this.m_isTransparent = true;
- this.m_transparentColor = new PDFColor(cm.getRed(tmpMap[i]), cm.getGreen(tmpMap[i]), cm.getBlue(tmpMap[i]));
- break;
+
+ ColorModel cm = consumer.getColorModel();
+ this.m_bitsPerPixel = 8;
+ // this.m_bitsPerPixel = cm.getPixelSize();
+ this.m_colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
+ if (cm.hasAlpha()) {
+ int transparencyType =
+ cm.getTransparency(); // java.awt.Transparency. BITMASK or OPAQUE or TRANSLUCENT
+ if (transparencyType == java.awt.Transparency.OPAQUE) {
+ this.m_isTransparent = false;
+ } else if (transparencyType
+ == java.awt.Transparency.BITMASK) {
+ if (cm instanceof IndexColorModel) {
+ this.m_isTransparent = false;
+ byte[] alphas =
+ new byte[((IndexColorModel)cm).getMapSize()];
+ byte[] reds =
+ new byte[((IndexColorModel)cm).getMapSize()];
+ byte[] greens =
+ new byte[((IndexColorModel)cm).getMapSize()];
+ byte[] blues =
+ new byte[((IndexColorModel)cm).getMapSize()];
+ ((IndexColorModel)cm).getAlphas(alphas);
+ ((IndexColorModel)cm).getReds(reds);
+ ((IndexColorModel)cm).getGreens(greens);
+ ((IndexColorModel)cm).getBlues(blues);
+ for (int i = 0;
+ i < ((IndexColorModel)cm).getMapSize(); i++) {
+ if ((alphas[i] & 0xFF) == 0) {
+ this.m_isTransparent = true;
+ this.m_transparentColor =
+ new PDFColor((int)(reds[i] & 0xFF),
+ (int)(greens[i] & 0xFF),
+ (int)(blues[i] & 0xFF));
+ break;
+ }
+ }
+ } else {
+ // TRANSLUCENT
+ /*
+ * this.m_isTransparent = false;
+ * for (int i = 0; i < this.m_width * this.m_height; i++) {
+ * if (cm.getAlpha(tmpMap[i]) == 0) {
+ * this.m_isTransparent = true;
+ * this.m_transparentColor = new PDFColor(cm.getRed(tmpMap[i]), cm.getGreen(tmpMap[i]), cm.getBlue(tmpMap[i]));
+ * break;
+ * }
+ * }
+ */
+ // use special API...
+ this.m_isTransparent = false;
+ }
+ } else {
+ this.m_isTransparent = false;
}
+ } else {
+ this.m_isTransparent = false;
}
- */
- // use special API...
- this.m_isTransparent = false;
- }
- } else {
- this.m_isTransparent = false;
+ } catch (Exception ex) {
+ throw new FopImageException("Error while loading image "
+ + this.m_href.toString() + " : "
+ + ex.getClass() + " - "
+ + ex.getMessage());
}
- } else {
- this.m_isTransparent = false;
- }
- } catch (Exception ex) {
- throw new FopImageException("Error while loading image " +
- this.m_href.toString() + " : " + ex.getClass() +
- " - " + ex.getMessage());
- }
- // Should take care of the ColorSpace and bitsPerPixel
- this.m_bitmapsSize = this.m_width * this.m_height * 3;
- this.m_bitmaps = new byte[this.m_bitmapsSize];
- for (int i = 0; i < this.m_height; i++) {
- for (int j = 0; j < this.m_width; j++) {
- int p = tmpMap[i * this.m_width + j];
- int r = (p >> 16) & 0xFF;
- int g = (p >> 8) & 0xFF;
- int b = (p) & 0xFF;
- this.m_bitmaps[3 * (i * this.m_width + j)] =
- (byte)(r & 0xFF);
- this.m_bitmaps[3 * (i * this.m_width + j) + 1] =
- (byte)(g & 0xFF);
- this.m_bitmaps[3 * (i * this.m_width + j) + 2] =
- (byte)(b & 0xFF);
- }
+ // Should take care of the ColorSpace and bitsPerPixel
+ this.m_bitmapsSize = this.m_width * this.m_height * 3;
+ this.m_bitmaps = new byte[this.m_bitmapsSize];
+ for (int i = 0; i < this.m_height; i++) {
+ for (int j = 0; j < this.m_width; j++) {
+ int p = tmpMap[i * this.m_width + j];
+ int r = (p >> 16) & 0xFF;
+ int g = (p >> 8) & 0xFF;
+ int b = (p) & 0xFF;
+ this.m_bitmaps[3 * (i * this.m_width + j)] = (byte)(r & 0xFF);
+ this.m_bitmaps[3 * (i * this.m_width + j) + 1] = (byte)(g
+ & 0xFF);
+ this.m_bitmaps[3 * (i * this.m_width + j) + 2] = (byte)(b
+ & 0xFF);
+ }
+ }
}
- }
+
}
diff --git a/src/org/apache/fop/image/ImageArea.java b/src/org/apache/fop/image/ImageArea.java
index e09afced7..509ba92d4 100644
--- a/src/org/apache/fop/image/ImageArea.java
+++ b/src/org/apache/fop/image/ImageArea.java
@@ -1,54 +1,9 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
-/* modified by JKT to integrate into 0.12.0 */
package org.apache.fop.image;
@@ -67,80 +22,75 @@ public class ImageArea extends InlineArea {
protected int align;
protected int valign;
protected FopImage image;
-
-
- public ImageArea(FontState fontState, FopImage img,
- int AllocationWidth, int width, int height,
- int startIndent, int endIndent, int align) {
- super(fontState,width,0,0,0);
- this.currentHeight = height;
- this.contentRectangleWidth = width;
- this.height = height;
- this.image = img;
- this.align = align;
-/*
- switch (align) {
- case TextAlign.START:
- xOffset = startIndent;
- break;
- case TextAlign.END:
- if (endIndent == 0)
- endIndent = AllocationWidth;
- xOffset = (endIndent - width);
- break;
- case TextAlign.JUSTIFY:
- xOffset = startIndent;
- break;
- case TextAlign.CENTER:
- if (endIndent == 0)
- endIndent = AllocationWidth;
- xOffset = startIndent + ((endIndent - startIndent) - width)/2;
- break;
- }
- */
+
+ public ImageArea(FontState fontState, FopImage img, int AllocationWidth,
+ int width, int height, int startIndent, int endIndent,
+ int align) {
+ super(fontState, width, 0, 0, 0);
+ this.currentHeight = height;
+ this.contentRectangleWidth = width;
+ this.height = height;
+ this.image = img;
+ this.align = align;
+
+ /*
+ * switch (align) {
+ * case TextAlign.START:
+ * xOffset = startIndent;
+ * break;
+ * case TextAlign.END:
+ * if (endIndent == 0)
+ * endIndent = AllocationWidth;
+ * xOffset = (endIndent - width);
+ * break;
+ * case TextAlign.JUSTIFY:
+ * xOffset = startIndent;
+ * break;
+ * case TextAlign.CENTER:
+ * if (endIndent == 0)
+ * endIndent = AllocationWidth;
+ * xOffset = startIndent + ((endIndent - startIndent) - width)/2;
+ * break;
+ * }
+ */
}
public int getXOffset() {
- return this.xOffset;
+ return this.xOffset;
}
public FopImage getImage() {
- return this.image;
+ return this.image;
}
-
+
public void render(Renderer renderer) {
- renderer.renderImageArea(this);
+ renderer.renderImageArea(this);
}
public int getImageHeight() {
- return currentHeight;
+ return currentHeight;
+ }
+
+ public void setAlign(int align) {
+ this.align = align;
+ }
+
+ public int getAlign() {
+ return this.align;
+ }
+
+ public void setVerticalAlign(int align) {
+ this.valign = align;
+ }
+
+ public int getVerticalAlign() {
+ return this.valign;
+ }
+
+ public void setStartIndent(int startIndent) {
+ xOffset = startIndent;
}
-
- public void setAlign(int align)
- {
- this.align = align;
- }
-
- public int getAlign()
- {
- return this.align;
- }
-
- public void setVerticalAlign(int align)
- {
- this.valign = align;
- }
-
- public int getVerticalAlign()
- {
- return this.valign;
- }
-
- public void setStartIndent(int startIndent)
- {
- xOffset = startIndent;
- }
diff --git a/src/org/apache/fop/image/JAIImage.java b/src/org/apache/fop/image/JAIImage.java
index e6a122db6..0e8524759 100644
--- a/src/org/apache/fop/image/JAIImage.java
+++ b/src/org/apache/fop/image/JAIImage.java
@@ -1,41 +1,8 @@
/*
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.image;
@@ -67,113 +34,118 @@ import org.apache.fop.image.analyser.ImageReader;
* @see FopImage
*/
public class JAIImage extends AbstractFopImage {
- public JAIImage(URL href) throws FopImageException {
- super(href);
- }
+ public JAIImage(URL href) throws FopImageException {
+ super(href);
+ }
- public JAIImage(URL href, ImageReader imgReader)
- throws FopImageException {
- super(href, imgReader);
- }
+ public JAIImage(URL href,
+ ImageReader imgReader) throws FopImageException {
+ super(href, imgReader);
+ }
- protected void loadImage() throws FopImageException {
- try {
- InputStream inputStream = this.m_href.openStream();
-/*
- BufferedInputStream inputStream = this.m_imageReader.getInputStream();
- inputStream.reset();
-*/
- com.sun.media.jai.codec.FileCacheSeekableStream seekableInput = new FileCacheSeekableStream(inputStream);
- RenderedOp imageOp = JAI.create("stream", seekableInput);
+ protected void loadImage() throws FopImageException {
+ try {
+ InputStream inputStream = this.m_href.openStream();
+ /*
+ * BufferedInputStream inputStream = this.m_imageReader.getInputStream();
+ * inputStream.reset();
+ */
+ com.sun.media.jai.codec.FileCacheSeekableStream seekableInput =
+ new FileCacheSeekableStream(inputStream);
+ RenderedOp imageOp = JAI.create("stream", seekableInput);
- this.m_height = imageOp.getHeight();
- this.m_width = imageOp.getWidth();
+ this.m_height = imageOp.getHeight();
+ this.m_width = imageOp.getWidth();
- ColorModel cm = imageOp.getColorModel();
- this.m_bitsPerPixel = 8;
- //this.m_bitsPerPixel = cm.getPixelSize();
- this.m_colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
+ ColorModel cm = imageOp.getColorModel();
+ this.m_bitsPerPixel = 8;
+ // this.m_bitsPerPixel = cm.getPixelSize();
+ this.m_colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
- BufferedImage imageData = imageOp.getAsBufferedImage();
- int[] tmpMap = imageData.getRGB(0, 0, this.m_width, this.m_height, null, 0, this.m_width);
+ BufferedImage imageData = imageOp.getAsBufferedImage();
+ int[] tmpMap = imageData.getRGB(0, 0, this.m_width,
+ this.m_height, null, 0,
+ this.m_width);
- if (cm.hasAlpha()) {
- int transparencyType = cm.getTransparency(); // java.awt.Transparency. BITMASK or OPAQUE or TRANSLUCENT
- if (transparencyType == java.awt.Transparency.OPAQUE) {
- this.m_isTransparent = false;
- } else if (transparencyType ==
- java.awt.Transparency.BITMASK) {
- if (cm instanceof IndexColorModel) {
- this.m_isTransparent = false;
- byte[] alphas = new byte[
- ((IndexColorModel) cm).getMapSize()];
- byte[] reds = new byte[
- ((IndexColorModel) cm).getMapSize()];
- byte[] greens = new byte[
- ((IndexColorModel) cm).getMapSize()];
- byte[] blues = new byte[
- ((IndexColorModel) cm).getMapSize()];
- ((IndexColorModel) cm).getAlphas(alphas);
- ((IndexColorModel) cm).getReds(reds);
- ((IndexColorModel) cm).getGreens(greens);
- ((IndexColorModel) cm).getBlues(blues);
- for (int i = 0;
- i < ((IndexColorModel) cm).getMapSize();
- i++) {
- if ((alphas[i] & 0xFF) == 0) {
- this.m_isTransparent = true;
- this.m_transparentColor = new PDFColor(
- (int)(reds[i] & 0xFF),
- (int)(greens[i] & 0xFF),
- (int)(blues[i] & 0xFF));
- break;
- }
- }
- } else {
- // TRANSLUCENT
-/*
- this.m_isTransparent = false;
- for (int i = 0; i < this.m_width * this.m_height; i++) {
- if (cm.getAlpha(tmpMap[i]) == 0) {
- this.m_isTransparent = true;
- this.m_transparentColor = new PDFColor(cm.getRed(tmpMap[i]), cm.getGreen(tmpMap[i]), cm.getBlue(tmpMap[i]));
- break;
+ if (cm.hasAlpha()) {
+ int transparencyType =
+ cm.getTransparency(); // java.awt.Transparency. BITMASK or OPAQUE or TRANSLUCENT
+ if (transparencyType == java.awt.Transparency.OPAQUE) {
+ this.m_isTransparent = false;
+ } else if (transparencyType
+ == java.awt.Transparency.BITMASK) {
+ if (cm instanceof IndexColorModel) {
+ this.m_isTransparent = false;
+ byte[] alphas =
+ new byte[((IndexColorModel)cm).getMapSize()];
+ byte[] reds =
+ new byte[((IndexColorModel)cm).getMapSize()];
+ byte[] greens =
+ new byte[((IndexColorModel)cm).getMapSize()];
+ byte[] blues =
+ new byte[((IndexColorModel)cm).getMapSize()];
+ ((IndexColorModel)cm).getAlphas(alphas);
+ ((IndexColorModel)cm).getReds(reds);
+ ((IndexColorModel)cm).getGreens(greens);
+ ((IndexColorModel)cm).getBlues(blues);
+ for (int i = 0;
+ i < ((IndexColorModel)cm).getMapSize(); i++) {
+ if ((alphas[i] & 0xFF) == 0) {
+ this.m_isTransparent = true;
+ this.m_transparentColor =
+ new PDFColor((int)(reds[i] & 0xFF),
+ (int)(greens[i] & 0xFF),
+ (int)(blues[i] & 0xFF));
+ break;
+ }
+ }
+ } else {
+ // TRANSLUCENT
+ /*
+ * this.m_isTransparent = false;
+ * for (int i = 0; i < this.m_width * this.m_height; i++) {
+ * if (cm.getAlpha(tmpMap[i]) == 0) {
+ * this.m_isTransparent = true;
+ * this.m_transparentColor = new PDFColor(cm.getRed(tmpMap[i]), cm.getGreen(tmpMap[i]), cm.getBlue(tmpMap[i]));
+ * break;
+ * }
+ * }
+ * // or use special API...
+ */
+ this.m_isTransparent = false;
+ }
+ } else {
+ this.m_isTransparent = false;
}
+ } else {
+ this.m_isTransparent = false;
}
- // or use special API...
-*/
- this.m_isTransparent = false;
- }
- } else {
- this.m_isTransparent = false;
- }
- } else {
- this.m_isTransparent = false;
- }
- // Should take care of the ColorSpace and bitsPerPixel
- this.m_bitmapsSize = this.m_width * this.m_height * 3;
- this.m_bitmaps = new byte[this.m_bitmapsSize];
- for (int i = 0; i < this.m_height; i++) {
- for (int j = 0; j < this.m_width; j++) {
- int p = tmpMap[i * this.m_width + j];
- int r = (p >> 16) & 0xFF;
- int g = (p >> 8) & 0xFF;
- int b = (p) & 0xFF;
- this.m_bitmaps[3 * (i * this.m_width + j)] =
- (byte)(r & 0xFF);
- this.m_bitmaps[3 * (i * this.m_width + j) + 1] =
- (byte)(g & 0xFF);
- this.m_bitmaps[3 * (i * this.m_width + j) + 2] =
- (byte)(b & 0xFF);
- }
- }
+ // Should take care of the ColorSpace and bitsPerPixel
+ this.m_bitmapsSize = this.m_width * this.m_height * 3;
+ this.m_bitmaps = new byte[this.m_bitmapsSize];
+ for (int i = 0; i < this.m_height; i++) {
+ for (int j = 0; j < this.m_width; j++) {
+ int p = tmpMap[i * this.m_width + j];
+ int r = (p >> 16) & 0xFF;
+ int g = (p >> 8) & 0xFF;
+ int b = (p) & 0xFF;
+ this.m_bitmaps[3 * (i * this.m_width + j)] = (byte)(r
+ & 0xFF);
+ this.m_bitmaps[3 * (i * this.m_width + j) + 1] = (byte)(g
+ & 0xFF);
+ this.m_bitmaps[3 * (i * this.m_width + j) + 2] = (byte)(b
+ & 0xFF);
+ }
+ }
- } catch (Exception ex) {
- throw new FopImageException("Error while loading image " +
- this.m_href.toString() + " : " + ex.getClass() +
- " - " + ex.getMessage());
+ } catch (Exception ex) {
+ throw new FopImageException("Error while loading image "
+ + this.m_href.toString() + " : "
+ + ex.getClass() + " - "
+ + ex.getMessage());
+ }
}
- }
+
}
diff --git a/src/org/apache/fop/image/JimiImage.java b/src/org/apache/fop/image/JimiImage.java
index 331ff6504..ddd2c49ea 100644
--- a/src/org/apache/fop/image/JimiImage.java
+++ b/src/org/apache/fop/image/JimiImage.java
@@ -1,41 +1,8 @@
/*
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.image;
@@ -62,128 +29,129 @@ import org.apache.fop.image.analyser.ImageReader;
* @see FopImage
*/
public class JimiImage extends AbstractFopImage {
- public JimiImage(URL href) throws FopImageException {
- super(href);
- try {
- Class c = Class.forName("com.sun.jimi.core.Jimi");
- } catch (ClassNotFoundException e) {
- throw new FopImageException("Jimi image library not available");
+ public JimiImage(URL href) throws FopImageException {
+ super(href);
+ try {
+ Class c = Class.forName("com.sun.jimi.core.Jimi");
+ } catch (ClassNotFoundException e) {
+ throw new FopImageException("Jimi image library not available");
+ }
}
- }
- public JimiImage(URL href, ImageReader imgReader) throws FopImageException {
- super(href, imgReader);
- try {
- Class c = Class.forName("com.sun.jimi.core.Jimi");
- } catch (ClassNotFoundException e) {
- throw new FopImageException("Jimi image library not available");
+ public JimiImage(URL href,
+ ImageReader imgReader) throws FopImageException {
+ super(href, imgReader);
+ try {
+ Class c = Class.forName("com.sun.jimi.core.Jimi");
+ } catch (ClassNotFoundException e) {
+ throw new FopImageException("Jimi image library not available");
+ }
}
- }
-
- protected void loadImage() throws FopImageException {
- int[] tmpMap = null;
- try {
- ImageProducer ip =
- Jimi.getImageProducer(this.m_href.openStream(),
- Jimi.SYNCHRONOUS | Jimi.IN_MEMORY);
- FopImageConsumer consumer = new FopImageConsumer(ip);
- ip.startProduction(consumer);
- while (! consumer.isImageReady()) {
- Thread.sleep(500);
- }
- this.m_height = consumer.getHeight();
- this.m_width = consumer.getWidth();
+ protected void loadImage() throws FopImageException {
+ int[] tmpMap = null;
+ try {
+ ImageProducer ip = Jimi.getImageProducer(this.m_href.openStream(),
+ Jimi.SYNCHRONOUS
+ | Jimi.IN_MEMORY);
+ FopImageConsumer consumer = new FopImageConsumer(ip);
+ ip.startProduction(consumer);
- try {
- tmpMap = consumer.getImage();
- } catch (Exception ex) {
- throw new FopImageException(
- "Image grabbing interrupted : " +
- ex.getMessage());
- }
+ while (!consumer.isImageReady()) {
+ Thread.sleep(500);
+ }
+ this.m_height = consumer.getHeight();
+ this.m_width = consumer.getWidth();
- ColorModel cm = consumer.getColorModel();
- this.m_bitsPerPixel = 8;
- //this.m_bitsPerPixel = cm.getPixelSize();
- this.m_colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
- if (cm.hasAlpha()) {
- int transparencyType = cm.getTransparency(); // java.awt.Transparency. BITMASK or OPAQUE or TRANSLUCENT
- if (transparencyType == java.awt.Transparency.OPAQUE) {
- this.m_isTransparent = false;
- } else if (transparencyType ==
- java.awt.Transparency.BITMASK) {
- if (cm instanceof IndexColorModel) {
- this.m_isTransparent = false;
- byte[] alphas = new byte[
- ((IndexColorModel) cm).getMapSize()];
- byte[] reds = new byte[
- ((IndexColorModel) cm).getMapSize()];
- byte[] greens = new byte[
- ((IndexColorModel) cm).getMapSize()];
- byte[] blues = new byte[
- ((IndexColorModel) cm).getMapSize()];
- ((IndexColorModel) cm).getAlphas(alphas);
- ((IndexColorModel) cm).getReds(reds);
- ((IndexColorModel) cm).getGreens(greens);
- ((IndexColorModel) cm).getBlues(blues);
- for (int i = 0;
- i < ((IndexColorModel) cm).getMapSize();
- i++) {
- if ((alphas[i] & 0xFF) == 0) {
- this.m_isTransparent = true;
- this.m_transparentColor = new PDFColor(
- (int)(reds[i] & 0xFF),
- (int)(greens[i] & 0xFF),
- (int)(blues[i] & 0xFF));
- break;
- }
+ try {
+ tmpMap = consumer.getImage();
+ } catch (Exception ex) {
+ throw new FopImageException("Image grabbing interrupted : "
+ + ex.getMessage());
}
- } else {
- // TRANSLUCENT
- /*
- this.m_isTransparent = false;
- for (int i = 0; i < this.m_width * this.m_height; i++) {
- if (cm.getAlpha(tmpMap[i]) == 0) {
- this.m_isTransparent = true;
- this.m_transparentColor = new PDFColor(cm.getRed(tmpMap[i]), cm.getGreen(tmpMap[i]), cm.getBlue(tmpMap[i]));
- break;
+
+ ColorModel cm = consumer.getColorModel();
+ this.m_bitsPerPixel = 8;
+ // this.m_bitsPerPixel = cm.getPixelSize();
+ this.m_colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
+ if (cm.hasAlpha()) {
+ int transparencyType =
+ cm.getTransparency(); // java.awt.Transparency. BITMASK or OPAQUE or TRANSLUCENT
+ if (transparencyType == java.awt.Transparency.OPAQUE) {
+ this.m_isTransparent = false;
+ } else if (transparencyType
+ == java.awt.Transparency.BITMASK) {
+ if (cm instanceof IndexColorModel) {
+ this.m_isTransparent = false;
+ byte[] alphas =
+ new byte[((IndexColorModel)cm).getMapSize()];
+ byte[] reds =
+ new byte[((IndexColorModel)cm).getMapSize()];
+ byte[] greens =
+ new byte[((IndexColorModel)cm).getMapSize()];
+ byte[] blues =
+ new byte[((IndexColorModel)cm).getMapSize()];
+ ((IndexColorModel)cm).getAlphas(alphas);
+ ((IndexColorModel)cm).getReds(reds);
+ ((IndexColorModel)cm).getGreens(greens);
+ ((IndexColorModel)cm).getBlues(blues);
+ for (int i = 0;
+ i < ((IndexColorModel)cm).getMapSize(); i++) {
+ if ((alphas[i] & 0xFF) == 0) {
+ this.m_isTransparent = true;
+ this.m_transparentColor =
+ new PDFColor((int)(reds[i] & 0xFF),
+ (int)(greens[i] & 0xFF),
+ (int)(blues[i] & 0xFF));
+ break;
+ }
+ }
+ } else {
+ // TRANSLUCENT
+ /*
+ * this.m_isTransparent = false;
+ * for (int i = 0; i < this.m_width * this.m_height; i++) {
+ * if (cm.getAlpha(tmpMap[i]) == 0) {
+ * this.m_isTransparent = true;
+ * this.m_transparentColor = new PDFColor(cm.getRed(tmpMap[i]), cm.getGreen(tmpMap[i]), cm.getBlue(tmpMap[i]));
+ * break;
+ * }
+ * }
+ */
+ // use special API...
+ this.m_isTransparent = false;
+ }
+ } else {
+ this.m_isTransparent = false;
}
+ } else {
+ this.m_isTransparent = false;
}
- */
- // use special API...
- this.m_isTransparent = false;
- }
- } else {
- this.m_isTransparent = false;
+ } catch (Exception ex) {
+ throw new FopImageException("Error while loading image "
+ + this.m_href.toString() + " : "
+ + ex.getClass() + " - "
+ + ex.getMessage());
}
- } else {
- this.m_isTransparent = false;
- }
- } catch (Exception ex) {
- throw new FopImageException("Error while loading image " +
- this.m_href.toString() + " : " + ex.getClass() +
- " - " + ex.getMessage());
- }
- // Should take care of the ColorSpace and bitsPerPixel
- this.m_bitmapsSize = this.m_width * this.m_height * 3;
- this.m_bitmaps = new byte[this.m_bitmapsSize];
- for (int i = 0; i < this.m_height; i++) {
- for (int j = 0; j < this.m_width; j++) {
- int p = tmpMap[i * this.m_width + j];
- int r = (p >> 16) & 0xFF;
- int g = (p >> 8) & 0xFF;
- int b = (p) & 0xFF;
- this.m_bitmaps[3 * (i * this.m_width + j)] =
- (byte)(r & 0xFF);
- this.m_bitmaps[3 * (i * this.m_width + j) + 1] =
- (byte)(g & 0xFF);
- this.m_bitmaps[3 * (i * this.m_width + j) + 2] =
- (byte)(b & 0xFF);
- }
+ // Should take care of the ColorSpace and bitsPerPixel
+ this.m_bitmapsSize = this.m_width * this.m_height * 3;
+ this.m_bitmaps = new byte[this.m_bitmapsSize];
+ for (int i = 0; i < this.m_height; i++) {
+ for (int j = 0; j < this.m_width; j++) {
+ int p = tmpMap[i * this.m_width + j];
+ int r = (p >> 16) & 0xFF;
+ int g = (p >> 8) & 0xFF;
+ int b = (p) & 0xFF;
+ this.m_bitmaps[3 * (i * this.m_width + j)] = (byte)(r & 0xFF);
+ this.m_bitmaps[3 * (i * this.m_width + j) + 1] = (byte)(g
+ & 0xFF);
+ this.m_bitmaps[3 * (i * this.m_width + j) + 2] = (byte)(b
+ & 0xFF);
+ }
+ }
}
- }
+
}
diff --git a/src/org/apache/fop/image/SVGImage.java b/src/org/apache/fop/image/SVGImage.java
index 691d5acbf..ecc08aa1a 100644
--- a/src/org/apache/fop/image/SVGImage.java
+++ b/src/org/apache/fop/image/SVGImage.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.image;
@@ -51,11 +52,12 @@ public class SVGImage extends AbstractFopImage {
protected void loadImage() throws FopImageException {
try {
- SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(SVGImage.getParserName());
+ SAXSVGDocumentFactory factory =
+ new SAXSVGDocumentFactory(SVGImage.getParserName());
doc = factory.createDocument(this.m_href.toExternalForm());
} catch (Exception e) {
- MessageHandler.errorln("ERROR LOADING EXTERNAL SVG: " +
- e.getMessage());
+ MessageHandler.errorln("ERROR LOADING EXTERNAL SVG: "
+ + e.getMessage());
}
}
@@ -64,4 +66,5 @@ public class SVGImage extends AbstractFopImage {
this.loadImage();
return doc;
}
+
}
diff --git a/src/org/apache/fop/image/analyser/AbstractImageReader.java b/src/org/apache/fop/image/analyser/AbstractImageReader.java
index d5ff4131c..aeb6e02b9 100644
--- a/src/org/apache/fop/image/analyser/AbstractImageReader.java
+++ b/src/org/apache/fop/image/analyser/AbstractImageReader.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.image.analyser;
@@ -17,33 +18,38 @@ import java.io.IOException;
* @see ImageReader
*/
public abstract class AbstractImageReader implements ImageReader {
- /**
- * Image width.
- */
- protected int width = 0;
- /**
- * Image height.
- */
- protected int height = 0;
- /**
- * Image stream.
- */
- protected BufferedInputStream imageStream = null;
-
- public abstract boolean verifySignature(String uri, BufferedInputStream fis) throws IOException;
-
- public int getHeight() {
- return this.height;
- }
-
- public int getWidth() {
- return this.width;
- }
-
- public abstract String getMimeType();
-
- public BufferedInputStream getInputStream() {
- return this.imageStream;
- }
+
+ /**
+ * Image width.
+ */
+ protected int width = 0;
+
+ /**
+ * Image height.
+ */
+ protected int height = 0;
+
+ /**
+ * Image stream.
+ */
+ protected BufferedInputStream imageStream = null;
+
+ public abstract boolean verifySignature(String uri, BufferedInputStream fis)
+ throws IOException;
+
+ public int getHeight() {
+ return this.height;
+ }
+
+ public int getWidth() {
+ return this.width;
+ }
+
+ public abstract String getMimeType();
+
+ public BufferedInputStream getInputStream() {
+ return this.imageStream;
+ }
+
}
diff --git a/src/org/apache/fop/image/analyser/BMPReader.java b/src/org/apache/fop/image/analyser/BMPReader.java
index ad4c0a131..c09a6238e 100644
--- a/src/org/apache/fop/image/analyser/BMPReader.java
+++ b/src/org/apache/fop/image/analyser/BMPReader.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.image.analyser;
@@ -16,58 +17,57 @@ import java.io.IOException;
* @version 1.0
*/
public class BMPReader extends AbstractImageReader {
- static protected final int BMP_SIG_LENGTH = 26;
+ static protected final int BMP_SIG_LENGTH = 26;
- protected byte[] header;
+ protected byte[] header;
- public boolean verifySignature(String uri, BufferedInputStream fis)
- throws IOException {
- this.imageStream = fis;
- this.setDefaultHeader();
- boolean supported = ((header[0] == (byte) 0x42) &&
- (header[1] == (byte) 0x4d));
- if (supported) {
- setDimension();
- return true;
- } else
- return false;
- }
+ public boolean verifySignature(String uri, BufferedInputStream fis)
+ throws IOException {
+ this.imageStream = fis;
+ this.setDefaultHeader();
+ boolean supported = ((header[0] == (byte)0x42)
+ && (header[1] == (byte)0x4d));
+ if (supported) {
+ setDimension();
+ return true;
+ } else
+ return false;
+ }
- public String getMimeType() {
- return "image/bmp";
- }
+ public String getMimeType() {
+ return "image/bmp";
+ }
- protected void setDimension() {
- //little endian notation
- int byte1 = header[18] & 0xff;
- int byte2 = header[19] & 0xff;
- int byte3 = header[20] & 0xff;
- int byte4 = header[21] & 0xff;
- long l = (long)((byte4 << 24) | (byte3 << 16) |
- (byte2 << 8) | byte1);
- this.width = (int)(l & 0xffffffff);
+ protected void setDimension() {
+ // little endian notation
+ int byte1 = header[18] & 0xff;
+ int byte2 = header[19] & 0xff;
+ int byte3 = header[20] & 0xff;
+ int byte4 = header[21] & 0xff;
+ long l = (long)((byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1);
+ this.width = (int)(l & 0xffffffff);
- byte1 = header[22] & 0xff;
- byte2 = header[23] & 0xff;
- byte3 = header[24] & 0xff;
- byte4 = header[25] & 0xff;
- l = (long)((byte4 << 24) | (byte3 << 16) | (byte2 << 8) |
- byte1);
- this.height = (int)(l & 0xffffffff);
- }
+ byte1 = header[22] & 0xff;
+ byte2 = header[23] & 0xff;
+ byte3 = header[24] & 0xff;
+ byte4 = header[25] & 0xff;
+ l = (long)((byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1);
+ this.height = (int)(l & 0xffffffff);
+ }
- protected void setDefaultHeader() throws IOException {
- this.header = new byte[BMP_SIG_LENGTH];
- try {
- this.imageStream.mark(BMP_SIG_LENGTH + 1);
- this.imageStream.read(header);
- this.imageStream.reset();
- } catch (IOException ex) {
- try {
- this.imageStream.reset();
- } catch (IOException exbis) {}
- throw ex;
+ protected void setDefaultHeader() throws IOException {
+ this.header = new byte[BMP_SIG_LENGTH];
+ try {
+ this.imageStream.mark(BMP_SIG_LENGTH + 1);
+ this.imageStream.read(header);
+ this.imageStream.reset();
+ } catch (IOException ex) {
+ try {
+ this.imageStream.reset();
+ } catch (IOException exbis) {}
+ throw ex;
+ }
}
- }
+
}
diff --git a/src/org/apache/fop/image/analyser/GIFReader.java b/src/org/apache/fop/image/analyser/GIFReader.java
index bb267755e..b3b8edd23 100644
--- a/src/org/apache/fop/image/analyser/GIFReader.java
+++ b/src/org/apache/fop/image/analyser/GIFReader.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.image.analyser;
@@ -16,51 +17,52 @@ import java.io.IOException;
* @version 1.0
*/
public class GIFReader extends AbstractImageReader {
- static protected final int GIF_SIG_LENGTH = 10;
- protected byte[] header;
+ static protected final int GIF_SIG_LENGTH = 10;
+ protected byte[] header;
- public boolean verifySignature(String uri, BufferedInputStream fis)
- throws IOException {
- this.imageStream = fis;
- this.setDefaultHeader();
- boolean supported = ((header[0] == 'G') && (header[1] == 'I') &&
- (header[2] == 'F') && (header[3] == '8') &&
- (header[4] == '7' || header[4] == '9') &&
- (header[5] == 'a'));
- if (supported) {
- setDimension();
- return true;
- } else
- return false;
- }
+ public boolean verifySignature(String uri, BufferedInputStream fis)
+ throws IOException {
+ this.imageStream = fis;
+ this.setDefaultHeader();
+ boolean supported = ((header[0] == 'G') && (header[1] == 'I')
+ && (header[2] == 'F') && (header[3] == '8')
+ && (header[4] == '7' || header[4] == '9')
+ && (header[5] == 'a'));
+ if (supported) {
+ setDimension();
+ return true;
+ } else
+ return false;
+ }
- public String getMimeType() {
- return "image/gif";
- }
+ public String getMimeType() {
+ return "image/gif";
+ }
- protected void setDimension() {
- //little endian notation
- int byte1 = header[6] & 0xff;
- int byte2 = header[7] & 0xff;
- this.width = ((byte2 << 8) | byte1) & 0xffff;
+ protected void setDimension() {
+ // little endian notation
+ int byte1 = header[6] & 0xff;
+ int byte2 = header[7] & 0xff;
+ this.width = ((byte2 << 8) | byte1) & 0xffff;
- byte1 = header[8] & 0xff;
- byte2 = header[9] & 0xff;
- this.height = ((byte2 << 8) | byte1) & 0xffff;
- }
+ byte1 = header[8] & 0xff;
+ byte2 = header[9] & 0xff;
+ this.height = ((byte2 << 8) | byte1) & 0xffff;
+ }
- protected void setDefaultHeader() throws IOException {
- this.header = new byte[GIF_SIG_LENGTH];
- try {
- this.imageStream.mark(GIF_SIG_LENGTH + 1);
- this.imageStream.read(header);
- this.imageStream.reset();
- } catch (IOException ex) {
- try {
- this.imageStream.reset();
- } catch (IOException exbis) {}
- throw ex;
+ protected void setDefaultHeader() throws IOException {
+ this.header = new byte[GIF_SIG_LENGTH];
+ try {
+ this.imageStream.mark(GIF_SIG_LENGTH + 1);
+ this.imageStream.read(header);
+ this.imageStream.reset();
+ } catch (IOException ex) {
+ try {
+ this.imageStream.reset();
+ } catch (IOException exbis) {}
+ throw ex;
+ }
}
- }
+
}
diff --git a/src/org/apache/fop/image/analyser/ImageReader.java b/src/org/apache/fop/image/analyser/ImageReader.java
index edf0ce96d..52f43bff4 100644
--- a/src/org/apache/fop/image/analyser/ImageReader.java
+++ b/src/org/apache/fop/image/analyser/ImageReader.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.image.analyser;
@@ -16,37 +17,38 @@ import java.io.IOException;
* @version 1.0
*/
public interface ImageReader {
- /**
- * Verify image type.
- * @param bis Image buffered input stream
- * @return true if image type is the handled one
- * @exception IOException io error
- */
- public boolean verifySignature(String uri, BufferedInputStream bis)
- throws IOException;
-
- /**
- * Return the used InputStream.
- * @return BufferedInputStream used to verify image type
- */
- public BufferedInputStream getInputStream();
-
- /**
- * Return correspondig mime type.
- * @return image mime type
- */
- public String getMimeType();
-
- /**
- * Return the image height.
- * @return image height
- */
- public int getHeight();
-
- /**
- * Return the image width.
- * @return image width
- */
- public int getWidth();
+
+ /**
+ * Verify image type.
+ * @param bis Image buffered input stream
+ * @return true if image type is the handled one
+ * @exception IOException io error
+ */
+ public boolean verifySignature(String uri, BufferedInputStream bis)
+ throws IOException;
+
+ /**
+ * Return the used InputStream.
+ * @return BufferedInputStream used to verify image type
+ */
+ public BufferedInputStream getInputStream();
+
+ /**
+ * Return correspondig mime type.
+ * @return image mime type
+ */
+ public String getMimeType();
+
+ /**
+ * Return the image height.
+ * @return image height
+ */
+ public int getHeight();
+
+ /**
+ * Return the image width.
+ * @return image width
+ */
+ public int getWidth();
}
diff --git a/src/org/apache/fop/image/analyser/ImageReaderFactory.java b/src/org/apache/fop/image/analyser/ImageReaderFactory.java
index c650c7235..e9b5ce3f0 100644
--- a/src/org/apache/fop/image/analyser/ImageReaderFactory.java
+++ b/src/org/apache/fop/image/analyser/ImageReaderFactory.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.image.analyser;
@@ -22,42 +23,43 @@ import org.apache.fop.image.FopImageException;
* @version 1.0
*/
public class ImageReaderFactory {
- static protected Vector formats = null;
-
- /**
- * ImageReader maker.
- * @param in image input stream
- * @return ImageReader object
- * @exception FopImageException an error occured during creation or
- * image type is not supported
- */
- static public ImageReader Make(String uri, InputStream in)
- throws FopImageException {
-
- // need to use a config file and remove static methods
- formats = new Vector();
- formats.addElement(new JPEGReader());
- formats.addElement(new BMPReader());
- formats.addElement(new GIFReader());
- formats.addElement(new PNGReader());
- formats.addElement(new TIFFReader());
- formats.addElement(new SVGReader());
- //
-
- ImageReader reader;
- BufferedInputStream bis = new BufferedInputStream(in);
- Enumeration itr = formats.elements();
- try {
- while (itr.hasMoreElements()) {
- reader = (ImageReader) itr.nextElement();
- if (reader.verifySignature(uri, bis)) {
- return reader;
- }
- }
- } catch (IOException ex) {
- throw new FopImageException(ex.getMessage());
- }
- return null;
- }
+ static protected Vector formats = null;
+
+ /**
+ * ImageReader maker.
+ * @param in image input stream
+ * @return ImageReader object
+ * @exception FopImageException an error occured during creation or
+ * image type is not supported
+ */
+ static public ImageReader Make(String uri,
+ InputStream in) throws FopImageException {
+
+ // need to use a config file and remove static methods
+ formats = new Vector();
+ formats.addElement(new JPEGReader());
+ formats.addElement(new BMPReader());
+ formats.addElement(new GIFReader());
+ formats.addElement(new PNGReader());
+ formats.addElement(new TIFFReader());
+ formats.addElement(new SVGReader());
+ //
+
+ ImageReader reader;
+ BufferedInputStream bis = new BufferedInputStream(in);
+ Enumeration itr = formats.elements();
+ try {
+ while (itr.hasMoreElements()) {
+ reader = (ImageReader)itr.nextElement();
+ if (reader.verifySignature(uri, bis)) {
+ return reader;
+ }
+ }
+ } catch (IOException ex) {
+ throw new FopImageException(ex.getMessage());
+ }
+ return null;
+ }
+
}
diff --git a/src/org/apache/fop/image/analyser/JPEGReader.java b/src/org/apache/fop/image/analyser/JPEGReader.java
index 5f1949288..0e1412a8b 100644
--- a/src/org/apache/fop/image/analyser/JPEGReader.java
+++ b/src/org/apache/fop/image/analyser/JPEGReader.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.image.analyser;
@@ -16,112 +17,113 @@ import java.io.IOException;
* @version 1.0
*/
public class JPEGReader extends AbstractImageReader {
- /**
- * Only SOFn and APPn markers are defined as SOFn is needed for the height and
- * width search. APPn is also defined because if the JPEG contains thumbnails
- * the dimensions of the thumnail would also be after the SOFn marker enclosed
- * inside the APPn marker. And we don't want to confuse those dimensions with
- * the image dimensions.
- */
- static protected final int MARK = 0xff; //Beginneing of a Marker
- static protected final int NULL = 0x00; //Special case for 0xff00
- static protected final int SOF1 = 0xc0; //Baseline DCT
- static protected final int SOF2 = 0xc1; //Extended Sequential DCT
- static protected final int SOF3 = 0xc2; //Progrssive DCT only PDF 1.3
- static protected final int SOFA = 0xca; //Progressice DCT only PDF 1.3
- static protected final int APP0 = 0xe0; //Application marker, JFIF
- static protected final int APPF = 0xef; //Application marker
- static protected final int SOS = 0xda; //Start of Scan
- static protected final int SOI = 0xd8; //start of Image
- static protected final int JPG_SIG_LENGTH = 2;
- protected byte[] header;
+ /**
+ * Only SOFn and APPn markers are defined as SOFn is needed for the height and
+ * width search. APPn is also defined because if the JPEG contains thumbnails
+ * the dimensions of the thumnail would also be after the SOFn marker enclosed
+ * inside the APPn marker. And we don't want to confuse those dimensions with
+ * the image dimensions.
+ */
+ static protected final int MARK = 0xff; // Beginneing of a Marker
+ static protected final int NULL = 0x00; // Special case for 0xff00
+ static protected final int SOF1 = 0xc0; // Baseline DCT
+ static protected final int SOF2 = 0xc1; // Extended Sequential DCT
+ static protected final int SOF3 = 0xc2; // Progrssive DCT only PDF 1.3
+ static protected final int SOFA = 0xca; // Progressice DCT only PDF 1.3
+ static protected final int APP0 = 0xe0; // Application marker, JFIF
+ static protected final int APPF = 0xef; // Application marker
+ static protected final int SOS = 0xda; // Start of Scan
+ static protected final int SOI = 0xd8; // start of Image
+ static protected final int JPG_SIG_LENGTH = 2;
- public boolean verifySignature(String uri, BufferedInputStream fis)
- throws IOException {
- this.imageStream = fis;
- this.setDefaultHeader();
- boolean supported = ((header[0] == (byte) 0xff) &&
- (header[1] == (byte) 0xd8));
- if (supported) {
- setDimension();
- return true;
- } else
- return false;
- }
+ protected byte[] header;
- public String getMimeType() {
- return "image/jpeg";
- }
+ public boolean verifySignature(String uri, BufferedInputStream fis)
+ throws IOException {
+ this.imageStream = fis;
+ this.setDefaultHeader();
+ boolean supported = ((header[0] == (byte)0xff)
+ && (header[1] == (byte)0xd8));
+ if (supported) {
+ setDimension();
+ return true;
+ } else
+ return false;
+ }
- protected void setDefaultHeader() throws IOException {
- this.header = new byte[JPG_SIG_LENGTH];
- try {
- this.imageStream.mark(JPG_SIG_LENGTH + 1);
- this.imageStream.read(header);
- this.imageStream.reset();
- } catch (IOException ex) {
- try {
- this.imageStream.reset();
- } catch (IOException exbis) {}
- throw ex;
+ public String getMimeType() {
+ return "image/jpeg";
}
- }
- protected void setDimension() throws IOException {
- try {
- int marker = NULL;
- long length, skipped;
- outer:
- while (imageStream.available() > 0) {
- while ((marker = imageStream.read()) != MARK) {
- ;
+ protected void setDefaultHeader() throws IOException {
+ this.header = new byte[JPG_SIG_LENGTH];
+ try {
+ this.imageStream.mark(JPG_SIG_LENGTH + 1);
+ this.imageStream.read(header);
+ this.imageStream.reset();
+ } catch (IOException ex) {
+ try {
+ this.imageStream.reset();
+ } catch (IOException exbis) {}
+ throw ex;
}
- do {
- marker = imageStream.read();
- } while (marker == MARK)
- ;
- switch (marker) {
- case SOI :
- break;
- case NULL:
- break;
- case SOF1:
- case SOF2:
- case SOF3: //SOF3 and SOFA are only supported by PDF 1.3
- case SOFA:
- this.skip(3);
- this.height = this.read2bytes();
- this.width = this.read2bytes();
- break outer;
- default:
- length = this.read2bytes();
- skipped = this.skip(length - 2);
- if (skipped != length - 2)
- throw new IOException("Skipping Error");
+ }
+
+ protected void setDimension() throws IOException {
+ try {
+ int marker = NULL;
+ long length, skipped;
+ outer:
+ while (imageStream.available() > 0) {
+ while ((marker = imageStream.read()) != MARK) {
+ ;
+ }
+ do {
+ marker = imageStream.read();
+ } while (marker == MARK);
+ switch (marker) {
+ case SOI:
+ break;
+ case NULL:
+ break;
+ case SOF1:
+ case SOF2:
+ case SOF3: // SOF3 and SOFA are only supported by PDF 1.3
+ case SOFA:
+ this.skip(3);
+ this.height = this.read2bytes();
+ this.width = this.read2bytes();
+ break outer;
+ default:
+ length = this.read2bytes();
+ skipped = this.skip(length - 2);
+ if (skipped != length - 2)
+ throw new IOException("Skipping Error");
+ }
+ }
+ } catch (IOException ioe) {
+ try {
+ this.imageStream.reset();
+ } catch (IOException exbis) {}
+ throw ioe;
}
- }
- } catch (IOException ioe) {
- try {
- this.imageStream.reset();
- } catch (IOException exbis) {}
- throw ioe;
}
- }
- protected int read2bytes() throws IOException {
- int byte1 = imageStream.read();
- int byte2 = imageStream.read();
- return (int)((byte1 << 8) | byte2);
- }
+ protected int read2bytes() throws IOException {
+ int byte1 = imageStream.read();
+ int byte2 = imageStream.read();
+ return (int)((byte1 << 8) | byte2);
+ }
- protected long skip(long n) throws IOException {
- long discarded = 0;
- while (discarded != n) {
- imageStream.read();
- discarded++;
+ protected long skip(long n) throws IOException {
+ long discarded = 0;
+ while (discarded != n) {
+ imageStream.read();
+ discarded++;
+ }
+ return discarded; // scope for exception
}
- return discarded; //scope for exception
- }
+
}
diff --git a/src/org/apache/fop/image/analyser/PNGReader.java b/src/org/apache/fop/image/analyser/PNGReader.java
index 8020cdf6a..64f175b2e 100644
--- a/src/org/apache/fop/image/analyser/PNGReader.java
+++ b/src/org/apache/fop/image/analyser/PNGReader.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.image.analyser;
@@ -16,63 +17,63 @@ import java.io.IOException;
* @version 1.0
*/
public class PNGReader extends AbstractImageReader {
- static protected final int PNG_SIG_LENGTH = 24;
- protected byte[] header;
+ static protected final int PNG_SIG_LENGTH = 24;
+ protected byte[] header;
- public boolean verifySignature(String uri, BufferedInputStream fis) throws IOException {
- this.imageStream = fis;
- this.setDefaultHeader();
- boolean supported = ((header[0] == (byte) 0x89) &&
- (header[1] == (byte) 0x50) &&
- (header[2] == (byte) 0x4e) &&
- (header[3] == (byte) 0x47) &&
- (header[4] == (byte) 0x0d) &&
- (header[5] == (byte) 0x0a) &&
- (header[6] == (byte) 0x1a) &&
- (header[7] == (byte) 0x0a));
- if (supported) {
- setDimension();
- return true;
- } else
- return false;
- }
+ public boolean verifySignature(String uri, BufferedInputStream fis)
+ throws IOException {
+ this.imageStream = fis;
+ this.setDefaultHeader();
+ boolean supported = ((header[0] == (byte)0x89)
+ && (header[1] == (byte)0x50)
+ && (header[2] == (byte)0x4e)
+ && (header[3] == (byte)0x47)
+ && (header[4] == (byte)0x0d)
+ && (header[5] == (byte)0x0a)
+ && (header[6] == (byte)0x1a)
+ && (header[7] == (byte)0x0a));
+ if (supported) {
+ setDimension();
+ return true;
+ } else
+ return false;
+ }
- public String getMimeType() {
- return "image/png";
- }
+ public String getMimeType() {
+ return "image/png";
+ }
- protected void setDimension() {
- //png is always big endian
- int byte1 = header[16] & 0xff;
- int byte2 = header[17] & 0xff;
- int byte3 = header[18] & 0xff;
- int byte4 = header[19] & 0xff;
- long l = (long)((byte1 << 24) | (byte2 << 16) |
- (byte3 << 8) | byte4);
- this.width = (int)(l);
+ protected void setDimension() {
+ // png is always big endian
+ int byte1 = header[16] & 0xff;
+ int byte2 = header[17] & 0xff;
+ int byte3 = header[18] & 0xff;
+ int byte4 = header[19] & 0xff;
+ long l = (long)((byte1 << 24) | (byte2 << 16) | (byte3 << 8) | byte4);
+ this.width = (int)(l);
- byte1 = header[20] & 0xff;
- byte2 = header[21] & 0xff;
- byte3 = header[22] & 0xff;
- byte4 = header[23] & 0xff;
- l = (long)((byte1 << 24) | (byte2 << 16) | (byte3 << 8) |
- byte4);
- this.height = (int)(l);
+ byte1 = header[20] & 0xff;
+ byte2 = header[21] & 0xff;
+ byte3 = header[22] & 0xff;
+ byte4 = header[23] & 0xff;
+ l = (long)((byte1 << 24) | (byte2 << 16) | (byte3 << 8) | byte4);
+ this.height = (int)(l);
- }
+ }
- protected void setDefaultHeader() throws IOException {
- this.header = new byte[PNG_SIG_LENGTH];
- try {
- this.imageStream.mark(PNG_SIG_LENGTH + 1);
- this.imageStream.read(header);
- this.imageStream.reset();
- } catch (IOException ex) {
- try {
- this.imageStream.reset();
- } catch (IOException exbis) {}
- throw ex;
+ protected void setDefaultHeader() throws IOException {
+ this.header = new byte[PNG_SIG_LENGTH];
+ try {
+ this.imageStream.mark(PNG_SIG_LENGTH + 1);
+ this.imageStream.read(header);
+ this.imageStream.reset();
+ } catch (IOException ex) {
+ try {
+ this.imageStream.reset();
+ } catch (IOException exbis) {}
+ throw ex;
+ }
}
- }
+
}
diff --git a/src/org/apache/fop/image/analyser/SVGReader.java b/src/org/apache/fop/image/analyser/SVGReader.java
index d196190fd..eedf04014 100644
--- a/src/org/apache/fop/image/analyser/SVGReader.java
+++ b/src/org/apache/fop/image/analyser/SVGReader.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -27,7 +28,7 @@ import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
*/
public class SVGReader extends AbstractImageReader {
public boolean verifySignature(String uri, BufferedInputStream fis)
- throws IOException {
+ throws IOException {
this.imageStream = fis;
return loadImage(uri);
}
@@ -43,20 +44,20 @@ public class SVGReader extends AbstractImageReader {
protected boolean loadImage(String uri) {
// parse document and get the size attributes of the svg element
try {
- SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(SVGImage.getParserName());
+ SAXSVGDocumentFactory factory =
+ new SAXSVGDocumentFactory(SVGImage.getParserName());
SVGDocument doc = factory.createDocument(uri, imageStream);
// should check the stream contains text data
SVGSVGElement svg = doc.getRootElement();
- this.width =
- (int) svg.getWidth().getBaseVal().getValue();
- this.height =
- (int) svg.getHeight().getBaseVal().getValue();
+ this.width = (int)svg.getWidth().getBaseVal().getValue();
+ this.height = (int)svg.getHeight().getBaseVal().getValue();
return true;
} catch (NoClassDefFoundError ncdfe) {
MessageHandler.errorln("Batik not in class path");
return false;
} catch (Exception e) {
- MessageHandler.errorln("ERROR LOADING EXTERNAL SVG: " + e.getMessage());
+ MessageHandler.errorln("ERROR LOADING EXTERNAL SVG: "
+ + e.getMessage());
// assuming any exception means this document is not svg
// or could not be loaded for some reason
return false;
diff --git a/src/org/apache/fop/image/analyser/TIFFReader.java b/src/org/apache/fop/image/analyser/TIFFReader.java
index d6b9eea16..9434ac3ff 100644
--- a/src/org/apache/fop/image/analyser/TIFFReader.java
+++ b/src/org/apache/fop/image/analyser/TIFFReader.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.image.analyser;
@@ -15,90 +16,83 @@ import java.io.IOException;
* @author Pankaj Narula, Michael Lee
* @version 1.0
*/
-public class TIFFReader extends AbstractImageReader
-{
- static protected final int TIFF_SIG_LENGTH = 8;
- protected byte[] header;
+public class TIFFReader extends AbstractImageReader {
+ static protected final int TIFF_SIG_LENGTH = 8;
+ protected byte[] header;
- public boolean verifySignature(String uri, BufferedInputStream fis ) throws IOException
- {
- this.imageStream = fis;
- this.setDefaultHeader();
- boolean supported = false;
+ public boolean verifySignature(String uri, BufferedInputStream fis)
+ throws IOException {
+ this.imageStream = fis;
+ this.setDefaultHeader();
+ boolean supported = false;
- if( header[0] == (byte) 0x49 && header[1] == (byte) 0x49 ) // first 2 bytes = II (little endian encoding)
- {
- // look for '42' in byte 3 and '0' in byte 4
- if( header[2] == 42 && header[3] == 0 )
- supported = true;
- }
+ if (header[0] == (byte)0x49
+ && header[1]
+ == (byte)0x49) // first 2 bytes = II (little endian encoding)
+ {
+ // look for '42' in byte 3 and '0' in byte 4
+ if (header[2] == 42 && header[3] == 0)
+ supported = true;
+ }
- if( header[0] == (byte) 0x4D && header[1] == (byte) 0x4D ) // first 2 bytes == MM (big endian encoding)
- {
- // look for '42' in byte 4 and '0' in byte 3
- if( header[2] == 0 && header[3] == 42 )
- supported = true;
- }
+ if (header[0] == (byte)0x4D
+ && header[1]
+ == (byte)0x4D) // first 2 bytes == MM (big endian encoding)
+ {
+ // look for '42' in byte 4 and '0' in byte 3
+ if (header[2] == 0 && header[3] == 42)
+ supported = true;
+ }
- if ( supported )
- {
- setDimension();
- return true;
- }
- else
- return false;
- }
+ if (supported) {
+ setDimension();
+ return true;
+ } else
+ return false;
+ }
- public String getMimeType()
- {
- return "image/tiff";
- }
+ public String getMimeType() {
+ return "image/tiff";
+ }
- protected void setDimension()
- {
- // currently not setting the width and height
- // these are set again by the Jimi image reader.
- // I suppose I'll do it one day to be complete. Or
- // someone else will.
- // Note: bytes 4,5,6,7 contain the byte offset in the stream of the first IFD block
- /*
- //png is always big endian
- int byte1 = header[ 16 ] & 0xff;
- int byte2 = header[ 17 ] & 0xff;
- int byte3 = header[ 18 ] & 0xff;
- int byte4 = header[ 19 ] & 0xff;
- long l = ( long ) ( ( byte1 << 24 ) | ( byte2 << 16 ) |
- ( byte3 << 8 ) | byte4 );
- this.width = ( int ) ( l );
+ protected void setDimension() {
+ // currently not setting the width and height
+ // these are set again by the Jimi image reader.
+ // I suppose I'll do it one day to be complete. Or
+ // someone else will.
+ // Note: bytes 4,5,6,7 contain the byte offset in the stream of the first IFD block
+ /*
+ * //png is always big endian
+ * int byte1 = header[ 16 ] & 0xff;
+ * int byte2 = header[ 17 ] & 0xff;
+ * int byte3 = header[ 18 ] & 0xff;
+ * int byte4 = header[ 19 ] & 0xff;
+ * long l = ( long ) ( ( byte1 << 24 ) | ( byte2 << 16 ) |
+ * ( byte3 << 8 ) | byte4 );
+ * this.width = ( int ) ( l );
+ * byte1 = header[ 20 ] & 0xff;
+ * byte2 = header[ 21 ] & 0xff;
+ * byte3 = header[ 22 ] & 0xff;
+ * byte4 = header[ 23 ] & 0xff;
+ * l = ( long ) ( ( byte1 << 24 ) | ( byte2 << 16 ) | ( byte3 << 8 ) |
+ * byte4 );
+ * this.height = ( int ) ( l );
+ */
+ }
- byte1 = header[ 20 ] & 0xff;
- byte2 = header[ 21 ] & 0xff;
- byte3 = header[ 22 ] & 0xff;
- byte4 = header[ 23 ] & 0xff;
- l = ( long ) ( ( byte1 << 24 ) | ( byte2 << 16 ) | ( byte3 << 8 ) |
- byte4 );
- this.height = ( int ) ( l );
- */
- }
+ protected void setDefaultHeader() throws IOException {
+ this.header = new byte[TIFF_SIG_LENGTH];
+ try {
+ this.imageStream.mark(TIFF_SIG_LENGTH + 1);
+ this.imageStream.read(header);
+ this.imageStream.reset();
+ } catch (IOException ex) {
+ try {
+ this.imageStream.reset();
+ } catch (IOException exbis) {}
+ throw ex;
+ }
+ }
- protected void setDefaultHeader() throws IOException
- {
- this.header = new byte[ TIFF_SIG_LENGTH ];
- try
- {
- this.imageStream.mark( TIFF_SIG_LENGTH + 1 );
- this.imageStream.read( header );
- this.imageStream.reset();
- }
- catch ( IOException ex )
- {
- try
- {
- this.imageStream.reset();
- }
- catch ( IOException exbis ) {}
- throw ex;
- }
- }
}
diff --git a/src/org/apache/fop/layout/Area.java b/src/org/apache/fop/layout/Area.java
index f022e1bd5..4ac0c935d 100644
--- a/src/org/apache/fop/layout/Area.java
+++ b/src/org/apache/fop/layout/Area.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -17,10 +18,12 @@ import java.util.Hashtable;
abstract public class Area extends Box {
- /* nominal font size and nominal font family incorporated in
- fontState */
+ /*
+ * nominal font size and nominal font family incorporated in
+ * fontState
+ */
protected FontState fontState;
- protected BorderAndPadding bp=null;
+ protected BorderAndPadding bp = null;
protected Vector children = new Vector();
@@ -49,29 +52,31 @@ abstract public class Area extends Box {
private IDReferences idReferences;
- protected Vector markers;
-
- // as defined in Section 6.1.1
- protected org.apache.fop.fo.FObj generatedBy; // corresponds to 'generated-by' trait
- protected Hashtable returnedBy;
-
- // as defined in Section 6.1.1
- protected String areaClass;
-
- // as defined in Section 4.2.2
- protected boolean isFirst = false;
- protected boolean isLast = false;
-
- /* author : Seshadri G
- ** the fo which created it */
- // This is deprecated and should be phased out in
- // favour of using 'generatedBy'
- public org.apache.fop.fo.FObj foCreator;
-
- public Area (FontState fontState) {
- setFontState(fontState);
- this.markers = new Vector();
- this.returnedBy = new Hashtable();
+ protected Vector markers;
+
+ // as defined in Section 6.1.1
+ protected org.apache.fop.fo.FObj generatedBy; // corresponds to 'generated-by' trait
+ protected Hashtable returnedBy;
+
+ // as defined in Section 6.1.1
+ protected String areaClass;
+
+ // as defined in Section 4.2.2
+ protected boolean isFirst = false;
+ protected boolean isLast = false;
+
+ /*
+ * author : Seshadri G
+ * * the fo which created it
+ */
+ // This is deprecated and should be phased out in
+ // favour of using 'generatedBy'
+ public org.apache.fop.fo.FObj foCreator;
+
+ public Area(FontState fontState) {
+ setFontState(fontState);
+ this.markers = new Vector();
+ this.returnedBy = new Hashtable();
}
/**
@@ -83,19 +88,20 @@ abstract public class Area extends Box {
* @param maxHeight the maximum block-progression dimension available
* for this Area (its allocation rectangle)
*/
- public Area (FontState fontState, int allocationWidth, int maxHeight) {
- setFontState(fontState);
+ public Area(FontState fontState, int allocationWidth, int maxHeight) {
+ setFontState(fontState);
this.allocationWidth = allocationWidth;
this.contentRectangleWidth = allocationWidth;
this.maxHeight = maxHeight;
- this.markers = new Vector();
- this.returnedBy = new Hashtable();
+ this.markers = new Vector();
+ this.returnedBy = new Hashtable();
+ }
+
+ private void setFontState(FontState fontState) {
+ // fontState.setFontInfo(this.page.getFontInfo());
+ this.fontState = fontState;
}
- private void setFontState(FontState fontState) {
- // fontState.setFontInfo(this.page.getFontInfo());
- this.fontState = fontState;
- }
public void addChild(Box child) {
this.children.addElement(child);
child.parent = this;
@@ -114,32 +120,32 @@ abstract public class Area extends Box {
public void addInlineSpace(int size) {
this.addChild(new InlineSpace(size));
- // other adjustments...
+ // other adjustments...
}
public FontInfo getFontInfo() {
return this.page.getFontInfo();
}
- public void end() {
- }
+ public void end() {}
public int getAllocationWidth() {
- /* ATTENTION: this may change your output!! (Karen Lease, 4mar2001)
- return this.allocationWidth - getPaddingLeft() - getPaddingRight()
- - getBorderLeftWidth() - getBorderRightWidth();
- */
- return this.allocationWidth ;
- }
-
- /**
- * Set the allocation width.
- * @param w The new allocation width.
- * This sets content width to the same value.
- * Currently only called during layout of Table to set the width
- * to the total width of all the columns. Note that this assumes the
- * column widths are explicitly specified.
- */
+ /*
+ * ATTENTION: this may change your output!! (Karen Lease, 4mar2001)
+ * return this.allocationWidth - getPaddingLeft() - getPaddingRight()
+ * - getBorderLeftWidth() - getBorderRightWidth();
+ */
+ return this.allocationWidth;
+ }
+
+ /**
+ * Set the allocation width.
+ * @param w The new allocation width.
+ * This sets content width to the same value.
+ * Currently only called during layout of Table to set the width
+ * to the total width of all the columns. Note that this assumes the
+ * column widths are explicitly specified.
+ */
public void setAllocationWidth(int w) {
this.allocationWidth = w;
this.contentRectangleWidth = this.allocationWidth;
@@ -154,11 +160,12 @@ abstract public class Area extends Box {
}
public int getContentWidth() {
- /* ATTENTION: this may change your output!! (Karen Lease, 4mar2001)
- return contentRectangleWidth - getPaddingLeft() - getPaddingRight()
- - getBorderLeftWidth() - getBorderRightWidth();
- */
- return contentRectangleWidth ;
+ /*
+ * ATTENTION: this may change your output!! (Karen Lease, 4mar2001)
+ * return contentRectangleWidth - getPaddingLeft() - getPaddingRight()
+ * - getBorderLeftWidth() - getBorderRightWidth();
+ */
+ return contentRectangleWidth;
}
public FontState getFontState() {
@@ -182,17 +189,17 @@ abstract public class Area extends Box {
* @return allocation height in millipoints
*/
public int getHeight() {
- return this.currentHeight + getPaddingTop() + getPaddingBottom() +
- getBorderTopWidth() + getBorderBottomWidth();
+ return this.currentHeight + getPaddingTop() + getPaddingBottom()
+ + getBorderTopWidth() + getBorderBottomWidth();
}
public int getMaxHeight() {
- // Change KDL: return max height of content rectangle
- return this.maxHeight;
- /*
- return this.maxHeight - getPaddingTop() - getPaddingBottom() -
- getBorderTopWidth() - getBorderBottomWidth();
- */
+ // Change KDL: return max height of content rectangle
+ return this.maxHeight;
+ /*
+ * return this.maxHeight - getPaddingTop() - getPaddingBottom() -
+ * getBorderTopWidth() - getBorderBottomWidth();
+ */
}
public Page getPage() {
@@ -203,39 +210,39 @@ abstract public class Area extends Box {
return this.backgroundColor;
}
- // Must handle conditionality here, depending on isLast/isFirst
+ // Must handle conditionality here, depending on isLast/isFirst
public int getPaddingTop() {
- return (bp==null? 0 : bp.getPaddingTop(false));
+ return (bp == null ? 0 : bp.getPaddingTop(false));
}
public int getPaddingLeft() {
- return(bp==null? 0 : bp.getPaddingLeft(false));
+ return (bp == null ? 0 : bp.getPaddingLeft(false));
}
public int getPaddingBottom() {
- return (bp==null? 0 : bp.getPaddingBottom(false));
+ return (bp == null ? 0 : bp.getPaddingBottom(false));
}
public int getPaddingRight() {
- return (bp==null? 0 : bp.getPaddingRight(false));
+ return (bp == null ? 0 : bp.getPaddingRight(false));
}
- // Handle border-width, including conditionality
- // For now, just pass false everywhere!
+ // Handle border-width, including conditionality
+ // For now, just pass false everywhere!
public int getBorderTopWidth() {
- return (bp==null? 0 : bp.getBorderTopWidth(false));
+ return (bp == null ? 0 : bp.getBorderTopWidth(false));
}
public int getBorderRightWidth() {
- return (bp==null? 0 : bp.getBorderRightWidth(false));
+ return (bp == null ? 0 : bp.getBorderRightWidth(false));
}
public int getBorderLeftWidth() {
- return (bp==null? 0 : bp.getBorderLeftWidth(false));
+ return (bp == null ? 0 : bp.getBorderLeftWidth(false));
}
public int getBorderBottomWidth() {
- return (bp==null? 0 : bp.getBorderBottomWidth(false));
+ return (bp == null ? 0 : bp.getBorderBottomWidth(false));
}
public int getTableCellXOffset() {
@@ -289,7 +296,7 @@ abstract public class Area extends Box {
}
public void setBorderAndPadding(BorderAndPadding bp) {
- this.bp = bp;
+ this.bp = bp;
}
/**
@@ -302,10 +309,9 @@ abstract public class Area extends Box {
return maxHeight - currentHeight;
}
- public void start() {
- }
+ public void start() {}
+
-
/**
* Set the content height to the passed value if that value is
* larger than current content height. If the new content height
@@ -315,15 +321,15 @@ abstract public class Area extends Box {
* @param height allocation height of content in millipoints
*/
public void setHeight(int height) {
- int prevHeight = currentHeight;
+ int prevHeight = currentHeight;
if (height > currentHeight) {
currentHeight = height;
- }
+ }
if (currentHeight > getMaxHeight()) {
currentHeight = getMaxHeight();
- }
- absoluteHeight += (currentHeight - prevHeight);
+ }
+ absoluteHeight += (currentHeight - prevHeight);
}
public void setMaxHeight(int height) {
@@ -346,65 +352,63 @@ abstract public class Area extends Box {
return idReferences;
}
- /* Author seshadri */
- public org.apache.fop.fo.FObj getfoCreator() {
- return this.foCreator;
- }
-
- // Function not currently used! (KLease, 16mar01)
-
- public AreaContainer getNearestAncestorAreaContainer()
- {
- Area area = this.getParent();
- while (!(area instanceof AreaContainer))
- {
- area = area.getParent();
- }
- return (AreaContainer)area;
- }
-
- public BorderAndPadding getBorderAndPadding() {
- return bp;
- }
-
- public void addMarker(Marker marker) {
- markers.addElement(marker);
- }
-
- public void addMarkers(Vector markers) {
- markers.addAll(markers);
- }
-
- public void addLineagePair(org.apache.fop.fo.FObj fo, int areaPosition) {
- returnedBy.put(fo, new Integer(areaPosition));
- }
-
- public Vector getMarkers() {
- return markers;
- }
-
- public void setGeneratedBy(org.apache.fop.fo.FObj generatedBy) {
- this.generatedBy = generatedBy;
- }
-
- public org.apache.fop.fo.FObj getGeneratedBy() {
- return generatedBy;
- }
-
- public void isFirst(boolean isFirst) {
- this.isFirst = isFirst;
- }
-
- public boolean isFirst() {
- return isFirst;
- }
-
- public void isLast(boolean isLast) {
- this.isLast = isLast;
- }
-
- public boolean isLast() {
- return isLast;
- }
-
+ /* Author seshadri */
+ public org.apache.fop.fo.FObj getfoCreator() {
+ return this.foCreator;
+ }
+
+ // Function not currently used! (KLease, 16mar01)
+
+ public AreaContainer getNearestAncestorAreaContainer() {
+ Area area = this.getParent();
+ while (!(area instanceof AreaContainer)) {
+ area = area.getParent();
+ }
+ return (AreaContainer)area;
+ }
+
+ public BorderAndPadding getBorderAndPadding() {
+ return bp;
+ }
+
+ public void addMarker(Marker marker) {
+ markers.addElement(marker);
+ }
+
+ public void addMarkers(Vector markers) {
+ markers.addAll(markers);
+ }
+
+ public void addLineagePair(org.apache.fop.fo.FObj fo, int areaPosition) {
+ returnedBy.put(fo, new Integer(areaPosition));
+ }
+
+ public Vector getMarkers() {
+ return markers;
+ }
+
+ public void setGeneratedBy(org.apache.fop.fo.FObj generatedBy) {
+ this.generatedBy = generatedBy;
+ }
+
+ public org.apache.fop.fo.FObj getGeneratedBy() {
+ return generatedBy;
+ }
+
+ public void isFirst(boolean isFirst) {
+ this.isFirst = isFirst;
+ }
+
+ public boolean isFirst() {
+ return isFirst;
+ }
+
+ public void isLast(boolean isLast) {
+ this.isLast = isLast;
+ }
+
+ public boolean isLast() {
+ return isLast;
+ }
+
}
diff --git a/src/org/apache/fop/layout/AreaClass.java b/src/org/apache/fop/layout/AreaClass.java
index 764fd6cca..7af180a90 100644
--- a/src/org/apache/fop/layout/AreaClass.java
+++ b/src/org/apache/fop/layout/AreaClass.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -9,23 +10,24 @@ package org.apache.fop.layout;
import org.apache.fop.apps.FOPException;
public class AreaClass {
- public static String UNASSIGNED = "unassigned";
+ public static String UNASSIGNED = "unassigned";
+
+ public static String XSL_NORMAL = "xsl-normal";
+ public static String XSL_ABSOLUTE = "xsl-absolute";
+ public static String XSL_FOOTNOTE = "xsl-footnote";
+ public static String XSL_SIDE_FLOAT = "xsl-side-float";
+ public static String XSL_BEFORE_FLOAT = "xsl-before-float";
+
+ // checker method
+ public static String setAreaClass(String areaClass) throws FOPException {
+ if (areaClass.equals(XSL_NORMAL) || areaClass.equals(XSL_ABSOLUTE)
+ || areaClass.equals(XSL_FOOTNOTE)
+ || areaClass.equals(XSL_SIDE_FLOAT)
+ || areaClass.equals(XSL_BEFORE_FLOAT))
+ return areaClass;
+ else
+ throw new FOPException("Unknown area class '" + areaClass + "'");
+ }
- public static String XSL_NORMAL = "xsl-normal";
- public static String XSL_ABSOLUTE = "xsl-absolute";
- public static String XSL_FOOTNOTE = "xsl-footnote";
- public static String XSL_SIDE_FLOAT = "xsl-side-float";
- public static String XSL_BEFORE_FLOAT = "xsl-before-float";
-
- // checker method
- public static String setAreaClass(String areaClass)
- throws FOPException {
- if (areaClass.equals(XSL_NORMAL) || areaClass.equals(XSL_ABSOLUTE) ||
- areaClass.equals(XSL_FOOTNOTE) || areaClass.equals(XSL_SIDE_FLOAT) ||
- areaClass.equals(XSL_BEFORE_FLOAT))
- return areaClass;
- else
- throw new FOPException("Unknown area class '" + areaClass + "'");
- }
}
diff --git a/src/org/apache/fop/layout/AreaContainer.java b/src/org/apache/fop/layout/AreaContainer.java
index e15a8ca61..53da72fda 100644
--- a/src/org/apache/fop/layout/AreaContainer.java
+++ b/src/org/apache/fop/layout/AreaContainer.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -16,22 +17,21 @@ import java.util.Enumeration;
public class AreaContainer extends Area {
- private int xPosition; // should be able to take value 'left' and 'right' too
- private int yPosition; // should be able to take value 'top' and 'bottom' too
+ private int xPosition; // should be able to take value 'left' and 'right' too
+ private int yPosition; // should be able to take value 'top' and 'bottom' too
private int position;
- // use this for identifying the general usage of the area,
- // like 'main-reference-area' or 'region-before'
- private String areaName;
-
- public AreaContainer(FontState fontState, int xPosition,
- int yPosition, int allocationWidth, int maxHeight,
- int position) {
+ // use this for identifying the general usage of the area,
+ // like 'main-reference-area' or 'region-before'
+ private String areaName;
+
+ public AreaContainer(FontState fontState, int xPosition, int yPosition,
+ int allocationWidth, int maxHeight, int position) {
super(fontState, allocationWidth, maxHeight);
this.xPosition = xPosition;
this.yPosition = yPosition;
this.position = position;
- //setIsReferenceArea(true); // Should always be true!
+ // setIsReferenceArea(true); // Should always be true!
}
public void render(Renderer renderer) {
@@ -43,8 +43,8 @@ public class AreaContainer extends Area {
}
public int getXPosition() {
- //return xPosition + getPaddingLeft() + getBorderLeftWidth();
- return xPosition ;
+ // return xPosition + getPaddingLeft() + getBorderLeftWidth();
+ return xPosition;
}
public void setXPosition(int value) {
@@ -52,8 +52,8 @@ public class AreaContainer extends Area {
}
public int getYPosition() {
- //return yPosition + getPaddingTop() + getBorderTopWidth();
- return yPosition ;
+ // return yPosition + getPaddingTop() + getBorderTopWidth();
+ return yPosition;
}
public int getCurrentYPosition() {
@@ -67,12 +67,13 @@ public class AreaContainer extends Area {
public void shiftYPosition(int value) {
yPosition += value;
}
-
- public String getAreaName() {
- return areaName;
- }
-
- public void setAreaName(String areaName) {
- this.areaName = areaName;
- }
+
+ public String getAreaName() {
+ return areaName;
+ }
+
+ public void setAreaName(String areaName) {
+ this.areaName = areaName;
+ }
+
}
diff --git a/src/org/apache/fop/layout/AreaTree.java b/src/org/apache/fop/layout/AreaTree.java
index 315230d9f..6f2bb864a 100644
--- a/src/org/apache/fop/layout/AreaTree.java
+++ b/src/org/apache/fop/layout/AreaTree.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -7,7 +8,7 @@
package org.apache.fop.layout;
// FOP
-import org.apache.fop.apps.FOPException;
+import org.apache.fop.apps.FOPException;
import org.apache.fop.fo.flow.StaticContent;
import org.apache.fop.svg.*;
import org.apache.fop.render.Renderer;
@@ -24,87 +25,90 @@ import java.util.Vector;
public class AreaTree {
- /** object containing information on available fonts, including
- metrics */
+ /**
+ * object containing information on available fonts, including
+ * metrics
+ */
FontInfo fontInfo;
-
+
/* list of all the pages */
Vector pageList = new Vector();
- /** List of root extension objects */
+ /**
+ * List of root extension objects
+ */
Vector rootExtensions = new Vector();
-
+
IDReferences idReferences = new IDReferences();
public void setFontInfo(FontInfo fontInfo) {
- this.fontInfo = fontInfo;
+ this.fontInfo = fontInfo;
}
public FontInfo getFontInfo() {
- return this.fontInfo;
+ return this.fontInfo;
}
-
+
public void addPage(Page page) {
- this.pageList.addElement(page);
+ this.pageList.addElement(page);
}
public Vector getPages() {
- return this.pageList;
+ return this.pageList;
}
- public IDReferences getIDReferences()
- {
+ public IDReferences getIDReferences() {
return idReferences;
}
- public void addExtension(ExtensionObj obj)
- {
- rootExtensions.addElement(obj);
+ public void addExtension(ExtensionObj obj) {
+ rootExtensions.addElement(obj);
}
-
- public Vector getExtensions()
- {
- return rootExtensions;
+
+ public Vector getExtensions() {
+ return rootExtensions;
}
-
- public Page getNextPage(Page current, boolean isWithinPageSequence,
- boolean isFirstCall) {
- Page nextPage = null;
- int pageIndex = 0;
- if (isFirstCall)
- pageIndex = pageList.size();
- else
- pageIndex = pageList.indexOf(current);
- if ((pageIndex + 1) < pageList.size()) {
- nextPage = (Page)pageList.elementAt(pageIndex + 1);
- if (isWithinPageSequence && !nextPage.getPageSequence().equals(current.getPageSequence())) {
- nextPage = null;
- }
- }
- return nextPage;
- }
-
- public Page getPreviousPage(Page current, boolean isWithinPageSequence,
- boolean isFirstCall) {
- Page previousPage = null;
- int pageIndex = 0;
- if (isFirstCall)
- pageIndex = pageList.size();
- else
- pageIndex = pageList.indexOf(current);
- // System.out.println("Page index = " + pageIndex);
- if ((pageIndex - 1) >= 0) {
- previousPage = (Page)pageList.elementAt(pageIndex - 1);
- PageSequence currentPS = current.getPageSequence();
- // System.out.println("Current PS = '" + currentPS + "'");
- PageSequence previousPS = previousPage.getPageSequence();
- // System.out.println("Previous PS = '" + previousPS + "'");
- if (isWithinPageSequence && !previousPS.equals(currentPS)) {
- // System.out.println("Outside page sequence");
- previousPage = null;
- }
- }
- return previousPage;
- }
+
+ public Page getNextPage(Page current, boolean isWithinPageSequence,
+ boolean isFirstCall) {
+ Page nextPage = null;
+ int pageIndex = 0;
+ if (isFirstCall)
+ pageIndex = pageList.size();
+ else
+ pageIndex = pageList.indexOf(current);
+ if ((pageIndex + 1) < pageList.size()) {
+ nextPage = (Page)pageList.elementAt(pageIndex + 1);
+ if (isWithinPageSequence
+ &&!nextPage.getPageSequence().equals(current.getPageSequence())) {
+ nextPage = null;
+ }
+ }
+ return nextPage;
+ }
+
+ public Page getPreviousPage(Page current, boolean isWithinPageSequence,
+ boolean isFirstCall) {
+ Page previousPage = null;
+ int pageIndex = 0;
+ if (isFirstCall)
+ pageIndex = pageList.size();
+ else
+ pageIndex = pageList.indexOf(current);
+ // System.out.println("Page index = " + pageIndex);
+ if ((pageIndex - 1) >= 0) {
+ previousPage = (Page)pageList.elementAt(pageIndex - 1);
+ PageSequence currentPS = current.getPageSequence();
+ // System.out.println("Current PS = '" + currentPS + "'");
+ PageSequence previousPS = previousPage.getPageSequence();
+ // System.out.println("Previous PS = '" + previousPS + "'");
+ if (isWithinPageSequence &&!previousPS.equals(currentPS)) {
+ // System.out.println("Outside page sequence");
+ previousPage = null;
+ }
+ }
+ return previousPage;
+ }
+
}
diff --git a/src/org/apache/fop/layout/BackgroundProps.java b/src/org/apache/fop/layout/BackgroundProps.java
index c7a4ec4ee..36639e236 100644
--- a/src/org/apache/fop/layout/BackgroundProps.java
+++ b/src/org/apache/fop/layout/BackgroundProps.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -12,6 +13,6 @@ package org.apache.fop.layout;
*/
public class BackgroundProps {
- public BackgroundProps() {
- }
+ public BackgroundProps() {}
+
}
diff --git a/src/org/apache/fop/layout/BlockArea.java b/src/org/apache/fop/layout/BlockArea.java
index 891a7cfde..44f6f0c22 100644
--- a/src/org/apache/fop/layout/BlockArea.java
+++ b/src/org/apache/fop/layout/BlockArea.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -54,21 +55,21 @@ public class BlockArea extends Area {
/* have any line areas been used? */
protected boolean hasLines = false;
- /*hyphenation*/
+ /* hyphenation */
protected HyphenationProps hyphProps;
protected Vector pendingFootnotes = null;
- public BlockArea(FontState fontState, int allocationWidth,
- int maxHeight, int startIndent, int endIndent,
- int textIndent, int align, int alignLastLine, int lineHeight) {
+ public BlockArea(FontState fontState, int allocationWidth, int maxHeight,
+ int startIndent, int endIndent, int textIndent,
+ int align, int alignLastLine, int lineHeight) {
super(fontState, allocationWidth, maxHeight);
this.startIndent = startIndent;
this.endIndent = endIndent;
this.textIndent = textIndent;
- this.contentRectangleWidth =
- allocationWidth - startIndent - endIndent;
+ this.contentRectangleWidth = allocationWidth - startIndent
+ - endIndent;
this.align = align;
this.alignLastLine = alignLastLine;
this.lineHeight = lineHeight;
@@ -101,8 +102,8 @@ public class BlockArea extends Area {
// add pending footnotes
if (pendingFootnotes != null) {
for (Enumeration e = pendingFootnotes.elements();
- e.hasMoreElements();) {
- FootnoteBody fb = (FootnoteBody) e.nextElement();
+ e.hasMoreElements(); ) {
+ FootnoteBody fb = (FootnoteBody)e.nextElement();
Page page = getPage();
if (!Footnote.layoutFootnote(page, fb, this)) {
page.addPendingFootnote(fb);
@@ -122,7 +123,7 @@ public class BlockArea extends Area {
* @return the line area to be used to add inlie objects
*/
public LineArea getCurrentLineArea() {
- if (currentHeight + lineHeight > maxHeight) {
+ if (currentHeight + lineHeight > maxHeight) {
return null;
}
this.currentLineArea.changeHyphenation(hyphProps);
@@ -145,9 +146,10 @@ public class BlockArea extends Area {
this.currentLineArea.align(this.align);
this.addLineArea(this.currentLineArea);
}
- this.currentLineArea =
- new LineArea(fontState, lineHeight, halfLeading,
- allocationWidth, startIndent, endIndent, currentLineArea);
+ this.currentLineArea = new LineArea(fontState, lineHeight,
+ halfLeading, allocationWidth,
+ startIndent, endIndent,
+ currentLineArea);
this.currentLineArea.changeHyphenation(hyphProps);
if (currentHeight + lineHeight > maxHeight) {
return null;
@@ -177,7 +179,9 @@ public class BlockArea extends Area {
public void start() {
currentLineArea = new LineArea(fontState, lineHeight, halfLeading,
- allocationWidth, startIndent + textIndent, endIndent, null);
+ allocationWidth,
+ startIndent + textIndent, endIndent,
+ null);
}
public int getEndIndent() {
@@ -186,15 +190,15 @@ public class BlockArea extends Area {
// KL: I think we should just return startIndent here!
public int getStartIndent() {
- //return startIndent + paddingLeft + borderWidthLeft;
- return startIndent ;
+ // return startIndent + paddingLeft + borderWidthLeft;
+ return startIndent;
}
public void setIndents(int startIndent, int endIndent) {
this.startIndent = startIndent;
this.endIndent = endIndent;
- this.contentRectangleWidth =
- allocationWidth - startIndent - endIndent;
+ this.contentRectangleWidth = allocationWidth - startIndent
+ - endIndent;
}
public int spaceLeft() {
@@ -215,4 +219,5 @@ public class BlockArea extends Area {
}
pendingFootnotes.addElement(fb);
}
+
}
diff --git a/src/org/apache/fop/layout/BodyAreaContainer.java b/src/org/apache/fop/layout/BodyAreaContainer.java
index 7aa5fde1f..9fd6122af 100644
--- a/src/org/apache/fop/layout/BodyAreaContainer.java
+++ b/src/org/apache/fop/layout/BodyAreaContainer.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -21,364 +22,354 @@ import java.util.Enumeration;
public class BodyAreaContainer extends Area {
- // dimensions for the 'region-reference-area'
- private int xPosition; // should be able to take value 'left' and 'right' too
- private int yPosition; // should be able to take value 'top' and 'bottom' too
+ // dimensions for the 'region-reference-area'
+ private int xPosition; // should be able to take value 'left' and 'right' too
+ private int yPosition; // should be able to take value 'top' and 'bottom' too
private int position;
- // the column-count and column-gap
- private int columnCount;
- private int columnGap;
-
- // the 3 primary reference areas
- private AreaContainer mainReferenceArea;
- private AreaContainer beforeFloatReferenceArea;
- private AreaContainer footnoteReferenceArea;
-
- // current heights
- private int mainRefAreaHeight;
- private int beforeFloatRefAreaHeight;
- private int footnoteRefAreaHeight;
-
- // reference area yPositions
- private int mainYPosition;
- private int beforeFloatYPosition;
- private int footnoteYPosition;
-
- // the start FO in case of rollback
- private FObj startFO;
- private boolean isNewSpanArea;
-
- // keeps track of footnote state for multiple layouts
+ // the column-count and column-gap
+ private int columnCount;
+ private int columnGap;
+
+ // the 3 primary reference areas
+ private AreaContainer mainReferenceArea;
+ private AreaContainer beforeFloatReferenceArea;
+ private AreaContainer footnoteReferenceArea;
+
+ // current heights
+ private int mainRefAreaHeight;
+ private int beforeFloatRefAreaHeight;
+ private int footnoteRefAreaHeight;
+
+ // reference area yPositions
+ private int mainYPosition;
+ private int beforeFloatYPosition;
+ private int footnoteYPosition;
+
+ // the start FO in case of rollback
+ private FObj startFO;
+ private boolean isNewSpanArea;
+
+ // keeps track of footnote state for multiple layouts
private int footnoteState = 0;
- public BodyAreaContainer(FontState fontState, int xPosition, int yPosition,
- int allocationWidth, int maxHeight, int position,
- int columnCount, int columnGap) {
- super(fontState, allocationWidth, maxHeight);
- this.xPosition = xPosition;
- this.yPosition = yPosition;
- this.position = position;
- this.columnCount = columnCount;
- this.columnGap = columnGap;
-
- // create the primary reference areas
- beforeFloatRefAreaHeight = 0;
- footnoteRefAreaHeight = 0;
- mainRefAreaHeight = maxHeight - beforeFloatRefAreaHeight - footnoteRefAreaHeight;
- beforeFloatReferenceArea = new AreaContainer(fontState, xPosition, yPosition,
- allocationWidth, beforeFloatRefAreaHeight, Position.ABSOLUTE);
- beforeFloatReferenceArea.setAreaName("before-float-reference-area");
- this.addChild(beforeFloatReferenceArea);
- mainReferenceArea = new AreaContainer(fontState, xPosition, yPosition,
- allocationWidth, mainRefAreaHeight, Position.ABSOLUTE);
- mainReferenceArea.setAreaName("main-reference-area");
- this.addChild(mainReferenceArea);
- int footnoteRefAreaYPosition = yPosition - mainRefAreaHeight;
- footnoteReferenceArea = new AreaContainer(fontState, xPosition, footnoteRefAreaYPosition,
- allocationWidth, footnoteRefAreaHeight, Position.ABSOLUTE);
- footnoteReferenceArea.setAreaName("footnote-reference-area");
- this.addChild(footnoteReferenceArea);
-
- // all padding and border-width must be 0
- //setBorderAndPadding(new BorderAndPadding());
- // setPadding(0, 0, 0, 0);
- // setBorderWidth(0, 0, 0, 0);
+ public BodyAreaContainer(FontState fontState, int xPosition,
+ int yPosition, int allocationWidth,
+ int maxHeight, int position, int columnCount,
+ int columnGap) {
+ super(fontState, allocationWidth, maxHeight);
+ this.xPosition = xPosition;
+ this.yPosition = yPosition;
+ this.position = position;
+ this.columnCount = columnCount;
+ this.columnGap = columnGap;
+
+ // create the primary reference areas
+ beforeFloatRefAreaHeight = 0;
+ footnoteRefAreaHeight = 0;
+ mainRefAreaHeight = maxHeight - beforeFloatRefAreaHeight
+ - footnoteRefAreaHeight;
+ beforeFloatReferenceArea = new AreaContainer(fontState, xPosition,
+ yPosition, allocationWidth, beforeFloatRefAreaHeight,
+ Position.ABSOLUTE);
+ beforeFloatReferenceArea.setAreaName("before-float-reference-area");
+ this.addChild(beforeFloatReferenceArea);
+ mainReferenceArea = new AreaContainer(fontState, xPosition,
+ yPosition, allocationWidth,
+ mainRefAreaHeight,
+ Position.ABSOLUTE);
+ mainReferenceArea.setAreaName("main-reference-area");
+ this.addChild(mainReferenceArea);
+ int footnoteRefAreaYPosition = yPosition - mainRefAreaHeight;
+ footnoteReferenceArea = new AreaContainer(fontState, xPosition,
+ footnoteRefAreaYPosition,
+ allocationWidth,
+ footnoteRefAreaHeight,
+ Position.ABSOLUTE);
+ footnoteReferenceArea.setAreaName("footnote-reference-area");
+ this.addChild(footnoteReferenceArea);
+
+ // all padding and border-width must be 0
+ // setBorderAndPadding(new BorderAndPadding());
+ // setPadding(0, 0, 0, 0);
+ // setBorderWidth(0, 0, 0, 0);
}
public void render(Renderer renderer) {
- renderer.renderBodyAreaContainer(this);
+ renderer.renderBodyAreaContainer(this);
}
public int getPosition() {
- return position;
+ return position;
}
public int getXPosition() {
return xPosition + getPaddingLeft() + getBorderLeftWidth();
}
- public void setXPosition(int value)
- {
- xPosition=value;
+ public void setXPosition(int value) {
+ xPosition = value;
}
public int getYPosition() {
- return yPosition + getPaddingTop() + getBorderTopWidth();
+ return yPosition + getPaddingTop() + getBorderTopWidth();
}
-
- public void setYPosition(int value)
- {
- yPosition=value;
+
+ public void setYPosition(int value) {
+ yPosition = value;
}
- public AreaContainer getMainReferenceArea()
- {
- return mainReferenceArea;
- }
+ public AreaContainer getMainReferenceArea() {
+ return mainReferenceArea;
+ }
- public AreaContainer getBeforeFloatReferenceArea()
- {
- return beforeFloatReferenceArea;
- }
+ public AreaContainer getBeforeFloatReferenceArea() {
+ return beforeFloatReferenceArea;
+ }
- public AreaContainer getFootnoteReferenceArea()
- {
- return footnoteReferenceArea;
- }
+ public AreaContainer getFootnoteReferenceArea() {
+ return footnoteReferenceArea;
+ }
public void setIDReferences(IDReferences idReferences) {
- mainReferenceArea.setIDReferences(idReferences);
+ mainReferenceArea.setIDReferences(idReferences);
}
public IDReferences getIDReferences() {
- return mainReferenceArea.getIDReferences();
+ return mainReferenceArea.getIDReferences();
+ }
+
+ /**
+ * Depending on the column-count of the next FO, determine whether
+ * a new span area needs to be constructed or not, and return the
+ * appropriate ColumnArea.
+ * The next cut of this method should also inspect the FO to see
+ * whether the area to be returned ought not to be the footnote
+ * or before-float reference area.
+ * @param fo The next formatting object
+ * @returns the next column area (possibly the current one)
+ */
+ public AreaContainer getNextArea(FObj fo) throws FOPException {
+ isNewSpanArea = false;
+
+ int span = Span.NONE;
+ if (fo instanceof Block)
+ span = ((Block)fo).getSpan();
+ else if (fo instanceof BlockContainer)
+ span = ((BlockContainer)fo).getSpan();
+
+ if (this.mainReferenceArea.getChildren().isEmpty()) {
+ if (span == Span.ALL)
+ return addSpanArea(1);
+ else
+ return addSpanArea(columnCount);
+ }
+
+ Vector spanAreas = this.mainReferenceArea.getChildren();
+ SpanArea spanArea = (SpanArea)spanAreas.elementAt(spanAreas.size()
+ - 1);
+
+ if ((span == Span.ALL) && (spanArea.getColumnCount() == 1)) {
+ // return the single column area in the same span area
+ return spanArea.getCurrentColumnArea();
+ } else if ((span == Span.NONE)
+ && (spanArea.getColumnCount() == columnCount)) {
+ // return the current column area in the same span area
+ return spanArea.getCurrentColumnArea();
+ } else if (span == Span.ALL) {
+ // create new span area with one column; return column area
+ return addSpanArea(1);
+ } else if (span == Span.NONE) {
+ // create new span area with multiple columns; return first column area
+ return addSpanArea(columnCount);
+ } else {
+ throw new FOPException("BodyAreaContainer::getNextArea(): Span attribute messed up");
+ }
+ }
+
+ /**
+ * Add a new span area with specified number of column areas.
+ * @param numColumns The number of column areas
+ * @returns AreaContainer The next column area
+ */
+ private AreaContainer addSpanArea(int numColumns) {
+ resetHeights();
+ // create span area and child column-areas, using whatever
+ // height remains after existing span areas (in the main
+ // reference area).
+ int spanAreaYPosition = getYPosition()
+ - this.mainReferenceArea.getContentHeight();
+
+ SpanArea spanArea = new SpanArea(fontState, getXPosition(),
+ spanAreaYPosition, allocationWidth,
+ getRemainingHeight(), numColumns,
+ columnGap);
+ this.mainReferenceArea.addChild(spanArea);
+ spanArea.setPage(this.getPage());
+ this.isNewSpanArea = true;
+ return spanArea.getCurrentColumnArea();
+ }
+
+ /**
+ * This almost does what getNewArea() does, without actually
+ * returning an area. These 2 methods can be reworked.
+ * @param fo The next formatting object
+ * @returns boolean True if we need to balance.
+ */
+ public boolean isBalancingRequired(FObj fo) {
+ if (this.mainReferenceArea.getChildren().isEmpty())
+ return false;
+
+ Vector spanAreas = this.mainReferenceArea.getChildren();
+ SpanArea spanArea = (SpanArea)spanAreas.elementAt(spanAreas.size()
+ - 1);
+
+ if (spanArea.isBalanced())
+ return false;
+
+ int span = Span.NONE;
+ if (fo instanceof Block)
+ span = ((Block)fo).getSpan();
+ else if (fo instanceof BlockContainer)
+ span = ((BlockContainer)fo).getSpan();
+
+ if ((span == Span.ALL) && (spanArea.getColumnCount() == 1))
+ return false;
+ else if ((span == Span.NONE)
+ && (spanArea.getColumnCount() == columnCount))
+ return false;
+ else if (span == Span.ALL)
+ return true;
+ else if (span == Span.NONE)
+ return false;
+ else
+ return false;
+ }
+
+ /**
+ * This is where the balancing algorithm lives, or gets called.
+ * Right now it's primitive: get the total content height in all
+ * columns, divide by the column count, and add a heuristic
+ * safety factor.
+ * Then the previous (unbalanced) span area is removed, and a new
+ * one added with the computed max height.
+ */
+ public void resetSpanArea() {
+ Vector spanAreas = this.mainReferenceArea.getChildren();
+ SpanArea spanArea = (SpanArea)spanAreas.elementAt(spanAreas.size()
+ - 1);
+
+ if (!spanArea.isBalanced()) {
+ // span area maintains a record of the total height of
+ // laid-out content in the previous (first) attempt
+ int newHeight = spanArea.getTotalContentHeight()
+ / spanArea.getColumnCount();
+ newHeight += 2 * 15600; // ???
+
+ this.mainReferenceArea.removeChild(spanArea);
+ resetHeights();
+ SpanArea newSpanArea = new SpanArea(fontState, getXPosition(),
+ spanArea.getYPosition(),
+ allocationWidth, newHeight,
+ spanArea.getColumnCount(),
+ columnGap);
+ this.mainReferenceArea.addChild(newSpanArea);
+ newSpanArea.setPage(this.getPage());
+ newSpanArea.setIsBalanced();
+ this.isNewSpanArea = true;
+ } else {
+ throw new IllegalStateException("Trying to balance balanced area");
+ }
+ }
+
+ /**
+ * Determine remaining height for new span area. Needs to be
+ * modified for footnote and before-float reference areas when
+ * those are supported.
+ * @returns int The remaining available height in millipoints.
+ */
+ public int getRemainingHeight() {
+ return this.mainReferenceArea.getMaxHeight()
+ - this.mainReferenceArea.getContentHeight();
+ }
+
+ /**
+ * Used by resetSpanArea() and addSpanArea() to adjust the main
+ * reference area height before creating a new span.
+ */
+ private void resetHeights() {
+ int totalHeight = 0;
+ for (Enumeration e = this.mainReferenceArea.getChildren().elements();
+ e.hasMoreElements(); ) {
+ SpanArea spanArea = (SpanArea)e.nextElement();
+ int spanContentHeight = spanArea.getMaxContentHeight();
+ int spanMaxHeight = spanArea.getMaxHeight();
+
+ totalHeight += (spanContentHeight < spanMaxHeight)
+ ? spanContentHeight : spanMaxHeight;
+ }
+ this.mainReferenceArea.setHeight(totalHeight);
+ }
+
+ /**
+ * Used in Flow when layout returns incomplete.
+ * @returns boolean Is this the last column in this span?
+ */
+ public boolean isLastColumn() {
+ Vector spanAreas = this.mainReferenceArea.getChildren();
+ SpanArea spanArea = (SpanArea)spanAreas.elementAt(spanAreas.size()
+ - 1);
+ return spanArea.isLastColumn();
+ }
+
+ /**
+ * This variable is unset by getNextArea(), is set by addSpanArea(),
+ * and may be set by resetSpanArea().
+ * @returns boolean Is the span area new or not?
+ */
+ public boolean isNewSpanArea() {
+ return isNewSpanArea;
+ }
+
+ public AreaContainer getCurrentColumnArea() {
+ Vector spanAreas = this.mainReferenceArea.getChildren();
+ SpanArea spanArea = (SpanArea)spanAreas.elementAt(spanAreas.size()
+ - 1);
+ return spanArea.getCurrentColumnArea();
}
- /**
- * Depending on the column-count of the next FO, determine whether
- * a new span area needs to be constructed or not, and return the
- * appropriate ColumnArea.
- * The next cut of this method should also inspect the FO to see
- * whether the area to be returned ought not to be the footnote
- * or before-float reference area.
- * @param fo The next formatting object
- * @returns the next column area (possibly the current one)
- */
- public AreaContainer getNextArea(FObj fo)
- throws FOPException
- {
- isNewSpanArea = false;
-
- int span = Span.NONE;
- if (fo instanceof Block)
- span = ((Block)fo).getSpan();
- else if (fo instanceof BlockContainer)
- span = ((BlockContainer)fo).getSpan();
-
- if (this.mainReferenceArea.getChildren().isEmpty())
- {
- if (span == Span.ALL)
- return addSpanArea(1);
- else
- return addSpanArea(columnCount);
- }
-
- Vector spanAreas = this.mainReferenceArea.getChildren();
- SpanArea spanArea = (SpanArea)spanAreas.elementAt(spanAreas.size()-1);
-
- if ((span == Span.ALL) && (spanArea.getColumnCount() == 1))
- {
- // return the single column area in the same span area
- return spanArea.getCurrentColumnArea();
- }
- else if ((span == Span.NONE) && (spanArea.getColumnCount() == columnCount))
- {
- // return the current column area in the same span area
- return spanArea.getCurrentColumnArea();
- }
- else if (span == Span.ALL)
- {
- // create new span area with one column; return column area
- return addSpanArea(1);
- }
- else if (span == Span.NONE)
- {
- // create new span area with multiple columns; return first column area
- return addSpanArea(columnCount);
- }
- else
- {
- throw new FOPException("BodyAreaContainer::getNextArea(): Span attribute messed up");
- }
- }
-
- /**
- * Add a new span area with specified number of column areas.
- * @param numColumns The number of column areas
- * @returns AreaContainer The next column area
- */
- private AreaContainer addSpanArea( int numColumns )
- {
- resetHeights();
- // create span area and child column-areas, using whatever
- // height remains after existing span areas (in the main
- // reference area).
- int spanAreaYPosition = getYPosition() - this.mainReferenceArea.getContentHeight();
-
- SpanArea spanArea = new SpanArea(fontState,
- getXPosition(), spanAreaYPosition,
- allocationWidth, getRemainingHeight(),
- numColumns, columnGap);
- this.mainReferenceArea.addChild(spanArea);
- spanArea.setPage(this.getPage());
- this.isNewSpanArea = true;
- return spanArea.getCurrentColumnArea();
- }
-
- /**
- * This almost does what getNewArea() does, without actually
- * returning an area. These 2 methods can be reworked.
- * @param fo The next formatting object
- * @returns boolean True if we need to balance.
- */
- public boolean isBalancingRequired(FObj fo)
- {
- if (this.mainReferenceArea.getChildren().isEmpty())
- return false;
-
- Vector spanAreas = this.mainReferenceArea.getChildren();
- SpanArea spanArea = (SpanArea)spanAreas.elementAt(spanAreas.size()-1);
-
- if (spanArea.isBalanced())
- return false;
-
- int span = Span.NONE;
- if (fo instanceof Block)
- span = ((Block)fo).getSpan();
- else if (fo instanceof BlockContainer)
- span = ((BlockContainer)fo).getSpan();
-
- if ((span == Span.ALL) && (spanArea.getColumnCount() == 1))
- return false;
- else if ((span == Span.NONE) && (spanArea.getColumnCount() == columnCount))
- return false;
- else if (span == Span.ALL)
- return true;
- else if (span == Span.NONE)
- return false;
- else
- return false;
- }
-
- /**
- * This is where the balancing algorithm lives, or gets called.
- * Right now it's primitive: get the total content height in all
- * columns, divide by the column count, and add a heuristic
- * safety factor.
- * Then the previous (unbalanced) span area is removed, and a new
- * one added with the computed max height.
- */
- public void resetSpanArea()
- {
- Vector spanAreas = this.mainReferenceArea.getChildren();
- SpanArea spanArea = (SpanArea)spanAreas.elementAt(spanAreas.size()-1);
-
- if (!spanArea.isBalanced())
- {
- // span area maintains a record of the total height of
- // laid-out content in the previous (first) attempt
- int newHeight = spanArea.getTotalContentHeight() / spanArea.getColumnCount();
- newHeight += 2*15600; // ???
-
- this.mainReferenceArea.removeChild(spanArea);
- resetHeights();
- SpanArea newSpanArea = new SpanArea(fontState,
- getXPosition(), spanArea.getYPosition(),
- allocationWidth, newHeight,
- spanArea.getColumnCount(), columnGap);
- this.mainReferenceArea.addChild(newSpanArea);
- newSpanArea.setPage(this.getPage());
- newSpanArea.setIsBalanced();
- this.isNewSpanArea = true;
- }
- else
- {
- throw new IllegalStateException("Trying to balance balanced area");
- }
- }
-
- /**
- * Determine remaining height for new span area. Needs to be
- * modified for footnote and before-float reference areas when
- * those are supported.
- * @returns int The remaining available height in millipoints.
- */
- public int getRemainingHeight()
- {
- return this.mainReferenceArea.getMaxHeight() -
- this.mainReferenceArea.getContentHeight();
- }
-
- /**
- * Used by resetSpanArea() and addSpanArea() to adjust the main
- * reference area height before creating a new span.
- */
- private void resetHeights()
- {
- int totalHeight = 0;
- for (Enumeration e = this.mainReferenceArea.getChildren().elements(); e.hasMoreElements(); )
- {
- SpanArea spanArea = (SpanArea)e.nextElement();
- int spanContentHeight = spanArea.getMaxContentHeight();
- int spanMaxHeight = spanArea.getMaxHeight();
-
- totalHeight += (spanContentHeight < spanMaxHeight) ? spanContentHeight: spanMaxHeight;
- }
- this.mainReferenceArea.setHeight(totalHeight);
- }
-
- /**
- * Used in Flow when layout returns incomplete.
- * @returns boolean Is this the last column in this span?
- */
- public boolean isLastColumn()
- {
- Vector spanAreas = this.mainReferenceArea.getChildren();
- SpanArea spanArea = (SpanArea)spanAreas.elementAt(spanAreas.size()-1);
- return spanArea.isLastColumn();
- }
-
- /**
- * This variable is unset by getNextArea(), is set by addSpanArea(),
- * and may be set by resetSpanArea().
- * @returns boolean Is the span area new or not?
- */
- public boolean isNewSpanArea()
- {
- return isNewSpanArea;
- }
-
- public AreaContainer getCurrentColumnArea()
- {
- Vector spanAreas = this.mainReferenceArea.getChildren();
- SpanArea spanArea = (SpanArea)spanAreas.elementAt(spanAreas.size()-1);
- return spanArea.getCurrentColumnArea();
- }
-
- public int getFootnoteState()
- {
+ public int getFootnoteState() {
return footnoteState;
}
- public boolean needsFootnoteAdjusting()
- {
+ public boolean needsFootnoteAdjusting() {
footnoteYPosition = footnoteReferenceArea.getYPosition();
- switch(footnoteState) {
- case 0:
- resetHeights();
- if(footnoteReferenceArea.getHeight() > 0
- && mainYPosition + mainReferenceArea.getHeight() > footnoteYPosition) {
- return true;
- }
- case 1:
+ switch (footnoteState) {
+ case 0:
+ resetHeights();
+ if (footnoteReferenceArea.getHeight() > 0
+ && mainYPosition + mainReferenceArea.getHeight()
+ > footnoteYPosition) {
+ return true;
+ }
+ case 1:
break;
}
return false;
}
- public void adjustFootnoteArea()
- {
+ public void adjustFootnoteArea() {
footnoteState++;
- if(footnoteState == 1) {
- mainReferenceArea.setMaxHeight(footnoteReferenceArea.getYPosition() - mainYPosition);
+ if (footnoteState == 1) {
+ mainReferenceArea.setMaxHeight(footnoteReferenceArea.getYPosition()
+ - mainYPosition);
footnoteYPosition = footnoteReferenceArea.getYPosition();
footnoteReferenceArea.setMaxHeight(footnoteReferenceArea.getHeight());
Vector childs = footnoteReferenceArea.getChildren();
- for(Enumeration en = childs.elements(); en.hasMoreElements(); ) {
+ for (Enumeration en = childs.elements(); en.hasMoreElements(); ) {
Object obj = en.nextElement();
- if(obj instanceof Area) {
+ if (obj instanceof Area) {
Area childArea = (Area)obj;
footnoteReferenceArea.removeChild(childArea);
}
@@ -391,12 +382,13 @@ public class BodyAreaContainer extends Area {
protected static void resetMaxHeight(Area ar, int change) {
ar.setMaxHeight(change);
Vector childs = ar.getChildren();
- for(Enumeration en = childs.elements(); en.hasMoreElements(); ) {
+ for (Enumeration en = childs.elements(); en.hasMoreElements(); ) {
Object obj = en.nextElement();
- if(obj instanceof Area) {
+ if (obj instanceof Area) {
Area childArea = (Area)obj;
resetMaxHeight(childArea, change);
}
}
}
+
}
diff --git a/src/org/apache/fop/layout/BodyRegionArea.java b/src/org/apache/fop/layout/BodyRegionArea.java
index c5677217a..98d46a873 100644
--- a/src/org/apache/fop/layout/BodyRegionArea.java
+++ b/src/org/apache/fop/layout/BodyRegionArea.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -14,34 +15,35 @@ import org.apache.fop.fo.properties.*;
public class BodyRegionArea extends RegionArea {
- // the column count and column-gap
- private int columnCount;
- private int columnGap;
-
- public BodyRegionArea(int xPosition, int yPosition, int width, int height) {
- super(xPosition, yPosition, width, height);
+ // the column count and column-gap
+ private int columnCount;
+ private int columnGap;
+
+ public BodyRegionArea(int xPosition, int yPosition, int width,
+ int height) {
+ super(xPosition, yPosition, width, height);
}
public BodyAreaContainer makeBodyAreaContainer() {
- return new BodyAreaContainer(null, xPosition, yPosition, width, height,
- Position.ABSOLUTE, columnCount, columnGap);
+ return new BodyAreaContainer(null, xPosition, yPosition, width,
+ height, Position.ABSOLUTE, columnCount,
+ columnGap);
+ }
+
+ public void setColumnCount(int columnCount) {
+ this.columnCount = columnCount;
+ }
+
+ public int getColumnCount() {
+ return columnCount;
}
-
- public void setColumnCount(int columnCount) {
- this.columnCount = columnCount;
- }
-
- public int getColumnCount()
- {
- return columnCount;
- }
-
- public void setColumnGap(int columnGap) {
- this.columnGap = columnGap;
- }
-
- public int getColumnGap()
- {
- return columnGap;
- }
+
+ public void setColumnGap(int columnGap) {
+ this.columnGap = columnGap;
+ }
+
+ public int getColumnGap() {
+ return columnGap;
+ }
+
}
diff --git a/src/org/apache/fop/layout/BorderAndPadding.java b/src/org/apache/fop/layout/BorderAndPadding.java
index 3dd3ae870..9ee8decef 100644
--- a/src/org/apache/fop/layout/BorderAndPadding.java
+++ b/src/org/apache/fop/layout/BorderAndPadding.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -11,116 +12,117 @@ import org.apache.fop.datatypes.CondLength;
public class BorderAndPadding {
- public static final int TOP=0;
- public static final int RIGHT=1;
- public static final int BOTTOM=2;
- public static final int LEFT=3;
+ public static final int TOP = 0;
+ public static final int RIGHT = 1;
+ public static final int BOTTOM = 2;
+ public static final int LEFT = 3;
- private static class ResolvedCondLength {
- int iLength; // Resolved length value
- boolean bDiscard;
+ private static class ResolvedCondLength {
+ int iLength; // Resolved length value
+ boolean bDiscard;
+
+ ResolvedCondLength(CondLength length) {
+ bDiscard = length.isDiscard();
+ iLength = length.mvalue();
+ }
+
+ }
+
+ public static class BorderInfo {
+ private int mStyle; // Enum for border style
+ private ColorType mColor; // Border color
+ private ResolvedCondLength mWidth;
+
+ BorderInfo(int style, CondLength width, ColorType color) {
+ mStyle = style;
+ mWidth = new ResolvedCondLength(width);
+ mColor = color;
+ }
+
+ }
+
+ private BorderInfo[] borderInfo = new BorderInfo[4];
+ private ResolvedCondLength[] padding = new ResolvedCondLength[4];
+
+ public BorderAndPadding() {}
+
+ public void setBorder(int side, int style, CondLength width,
+ ColorType color) {
+ borderInfo[side] = new BorderInfo(style, width, color);
+ }
+
+ public void setPadding(int side, CondLength width) {
+ padding[side] = new ResolvedCondLength(width);
+ }
+
+ public void setPaddingLength(int side, int iLength) {
+ padding[side].iLength = iLength;
+ }
+
+ public void setBorderLength(int side, int iLength) {
+ borderInfo[side].mWidth.iLength = iLength;
+ }
+
+ public int getBorderLeftWidth(boolean bDiscard) {
+ return getBorderWidth(LEFT, bDiscard);
+ }
+
+ public int getBorderRightWidth(boolean bDiscard) {
+ return getBorderWidth(RIGHT, bDiscard);
+ }
+
+ public int getBorderTopWidth(boolean bDiscard) {
+ return getBorderWidth(TOP, bDiscard);
+ }
+
+ public int getBorderBottomWidth(boolean bDiscard) {
+ return getBorderWidth(BOTTOM, bDiscard);
+ }
+
+ public int getPaddingLeft(boolean bDiscard) {
+ return getPadding(LEFT, bDiscard);
+ }
+
+ public int getPaddingRight(boolean bDiscard) {
+ return getPadding(RIGHT, bDiscard);
+ }
+
+ public int getPaddingBottom(boolean bDiscard) {
+ return getPadding(BOTTOM, bDiscard);
+ }
+
+ public int getPaddingTop(boolean bDiscard) {
+ return getPadding(TOP, bDiscard);
+ }
+
+
+ private int getBorderWidth(int side, boolean bDiscard) {
+ if ((borderInfo[side] == null)
+ || (bDiscard && borderInfo[side].mWidth.bDiscard)) {
+ return 0;
+ } else
+ return borderInfo[side].mWidth.iLength;
+ }
+
+ public ColorType getBorderColor(int side) {
+ if (borderInfo[side] != null) {
+ return borderInfo[side].mColor;
+ } else
+ return null;
+ }
+
+ public int getBorderStyle(int side) {
+ if (borderInfo[side] != null) {
+ return borderInfo[side].mStyle;
+ } else
+ return 0;
+ }
+
+ private int getPadding(int side, boolean bDiscard) {
+ if ((padding[side] == null) || (bDiscard && padding[side].bDiscard)) {
+ return 0;
+ } else
+ return padding[side].iLength;
+ }
- ResolvedCondLength(CondLength length) {
- bDiscard = length.isDiscard();
- iLength= length.mvalue();
- }
-
- }
-
- public static class BorderInfo {
- private int mStyle; // Enum for border style
- private ColorType mColor; // Border color
- private ResolvedCondLength mWidth;
-
- BorderInfo(int style, CondLength width, ColorType color) {
- mStyle = style;
- mWidth = new ResolvedCondLength(width);
- mColor = color;
- }
- }
-
- private BorderInfo[] borderInfo = new BorderInfo[4];
- private ResolvedCondLength[] padding = new ResolvedCondLength[4];
-
- public BorderAndPadding() {
- }
-
- public void setBorder(int side, int style, CondLength width, ColorType color ) {
- borderInfo[side] = new BorderInfo(style, width, color);
- }
-
- public void setPadding(int side, CondLength width ) {
- padding[side] = new ResolvedCondLength(width);
- }
-
- public void setPaddingLength(int side, int iLength ) {
- padding[side].iLength = iLength;
- }
-
- public void setBorderLength(int side, int iLength ) {
- borderInfo[side].mWidth.iLength = iLength;
- }
-
- public int getBorderLeftWidth(boolean bDiscard) {
- return getBorderWidth(LEFT, bDiscard);
- }
-
- public int getBorderRightWidth(boolean bDiscard) {
- return getBorderWidth(RIGHT, bDiscard);
- }
-
- public int getBorderTopWidth(boolean bDiscard) {
- return getBorderWidth(TOP, bDiscard);
- }
-
- public int getBorderBottomWidth(boolean bDiscard) {
- return getBorderWidth(BOTTOM, bDiscard);
- }
-
- public int getPaddingLeft(boolean bDiscard) {
- return getPadding(LEFT, bDiscard);
- }
-
- public int getPaddingRight(boolean bDiscard) {
- return getPadding(RIGHT, bDiscard);
- }
-
- public int getPaddingBottom(boolean bDiscard) {
- return getPadding(BOTTOM, bDiscard);
- }
-
- public int getPaddingTop(boolean bDiscard) {
- return getPadding(TOP, bDiscard);
- }
-
-
- private int getBorderWidth(int side, boolean bDiscard) {
- if ((borderInfo[side] == null) ||
- (bDiscard && borderInfo[side].mWidth.bDiscard)) {
- return 0;
- }
- else return borderInfo[side].mWidth.iLength;
- }
-
- public ColorType getBorderColor(int side) {
- if (borderInfo[side] != null) {
- return borderInfo[side].mColor;
- }
- else return null;
- }
-
- public int getBorderStyle(int side) {
- if (borderInfo[side] != null) {
- return borderInfo[side].mStyle;
- }
- else return 0;
- }
-
- private int getPadding(int side, boolean bDiscard) {
- if ((padding[side] == null) ||
- (bDiscard && padding[side].bDiscard)) {
- return 0;
- }
- else return padding[side].iLength;
- }
}
diff --git a/src/org/apache/fop/layout/Box.java b/src/org/apache/fop/layout/Box.java
index b9d7d501a..7f1b17e59 100644
--- a/src/org/apache/fop/layout/Box.java
+++ b/src/org/apache/fop/layout/Box.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
diff --git a/src/org/apache/fop/layout/ColumnArea.java b/src/org/apache/fop/layout/ColumnArea.java
index e5e24181b..771309f5a 100644
--- a/src/org/apache/fop/layout/ColumnArea.java
+++ b/src/org/apache/fop/layout/ColumnArea.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -16,45 +17,41 @@ import java.util.Vector;
import java.util.Enumeration;
public class ColumnArea extends AreaContainer {
-
- private int columnIndex;
- private int maxColumns;
-
+
+ private int columnIndex;
+ private int maxColumns;
+
public ColumnArea(FontState fontState, int xPosition, int yPosition,
- int allocationWidth, int maxHeight, int columnCount) {
- super(fontState, xPosition, yPosition, allocationWidth,
- maxHeight, Position.ABSOLUTE);
- this.maxColumns = columnCount;
- this.setAreaName("normal-flow-ref.-area");
+ int allocationWidth, int maxHeight, int columnCount) {
+ super(fontState, xPosition, yPosition, allocationWidth, maxHeight,
+ Position.ABSOLUTE);
+ this.maxColumns = columnCount;
+ this.setAreaName("normal-flow-ref.-area");
}
public void render(Renderer renderer) {
- renderer.renderAreaContainer(this);
+ renderer.renderAreaContainer(this);
}
- public void end() {
+ public void end() {}
+
+ public void start() {}
+
+ public int spaceLeft() {
+ return maxHeight - currentHeight;
}
- public void start() {
+ public int getColumnIndex() {
+ return columnIndex;
}
- public int spaceLeft() {
- return maxHeight - currentHeight;
+ public void setColumnIndex(int columnIndex) {
+ this.columnIndex = columnIndex;
+ }
+
+ public void incrementSpanIndex() {
+ SpanArea span = (SpanArea)this.parent;
+ span.setCurrentColumn(span.getCurrentColumn() + 1);
}
-
- public int getColumnIndex()
- {
- return columnIndex;
- }
-
- public void setColumnIndex(int columnIndex)
- {
- this.columnIndex = columnIndex;
- }
-
- public void incrementSpanIndex()
- {
- SpanArea span = (SpanArea)this.parent;
- span.setCurrentColumn(span.getCurrentColumn()+1);
- }
+
}
diff --git a/src/org/apache/fop/layout/DisplaySpace.java b/src/org/apache/fop/layout/DisplaySpace.java
index ea337373b..cbccc1863 100644
--- a/src/org/apache/fop/layout/DisplaySpace.java
+++ b/src/org/apache/fop/layout/DisplaySpace.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -9,16 +10,18 @@ package org.apache.fop.layout;
import org.apache.fop.render.Renderer;
public class DisplaySpace extends Space {
- private int size;
-
- public DisplaySpace(int size) {
- this.size = size;
- }
- public int getSize() {
- return size;
- }
+ private int size;
+
+ public DisplaySpace(int size) {
+ this.size = size;
+ }
+
+ public int getSize() {
+ return size;
+ }
public void render(Renderer renderer) {
- renderer.renderDisplaySpace(this);
+ renderer.renderDisplaySpace(this);
}
+
}
diff --git a/src/org/apache/fop/layout/ExtensionArea.java b/src/org/apache/fop/layout/ExtensionArea.java
index a0072830f..6be851b63 100644
--- a/src/org/apache/fop/layout/ExtensionArea.java
+++ b/src/org/apache/fop/layout/ExtensionArea.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -11,24 +12,21 @@ import org.apache.fop.fo.*;
import org.apache.fop.extensions.*;
import org.apache.fop.render.*;
-public class ExtensionArea extends Area
-{
+public class ExtensionArea extends Area {
private ExtensionObj _extensionObj;
-
- public ExtensionArea (ExtensionObj obj) {
- super(null);
- _extensionObj = obj;
+
+ public ExtensionArea(ExtensionObj obj) {
+ super(null);
+ _extensionObj = obj;
}
-
- public FObj getExtensionObj()
- {
- return _extensionObj;
+
+ public FObj getExtensionObj() {
+ return _extensionObj;
}
-
- public void render(Renderer renderer)
- {
- // renderer.renderExtensionArea(this);
+
+ public void render(Renderer renderer) {
+ // renderer.renderExtensionArea(this);
}
-
-
+
+
}
diff --git a/src/org/apache/fop/layout/FontDescriptor.java b/src/org/apache/fop/layout/FontDescriptor.java
index 43afb87b7..513eaacd5 100644
--- a/src/org/apache/fop/layout/FontDescriptor.java
+++ b/src/org/apache/fop/layout/FontDescriptor.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -8,23 +9,23 @@ package org.apache.fop.layout;
public interface FontDescriptor {
- //Required
- public int getAscender(); //Ascent in pdf spec
- public int getCapHeight();
- public int getDescender(); //Descent in pdf spec
- public int getFlags();
- public int[] getFontBBox();
- public String fontName(); //should be getFontName(). not?
- public int getItalicAngle();
- public int getStemV();
+ // Required
+ public int getAscender(); // Ascent in pdf spec
+ public int getCapHeight();
+ public int getDescender(); // Descent in pdf spec
+ public int getFlags();
+ public int[] getFontBBox();
+ public String fontName(); // should be getFontName(). not?
+ public int getItalicAngle();
+ public int getStemV();
- public boolean hasKerningInfo();
- public java.util.Hashtable getKerningInfo();
- public boolean isEmbeddable();
- public byte getSubType();
- public org.apache.fop.pdf.PDFStream getFontFile(int objNum);
- //Optional - but needed to calculate font-size-adjust...
- //public int getXHeight();
+ public boolean hasKerningInfo();
+ public java.util.Hashtable getKerningInfo();
+ public boolean isEmbeddable();
+ public byte getSubType();
+ public org.apache.fop.pdf.PDFStream getFontFile(int objNum);
+ // Optional - but needed to calculate font-size-adjust...
+ // public int getXHeight();
}
diff --git a/src/org/apache/fop/layout/FontInfo.java b/src/org/apache/fop/layout/FontInfo.java
index 7d55ce9f6..e54f76fcf 100644
--- a/src/org/apache/fop/layout/FontInfo.java
+++ b/src/org/apache/fop/layout/FontInfo.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -14,8 +15,8 @@ import org.apache.fop.apps.FOPException;
public class FontInfo {
Hashtable usedFonts;
- Hashtable triplets; // look up a font-triplet to find a font-name
- Hashtable fonts; // look up a font-name to get a font (that implements FontMetric at least)
+ Hashtable triplets; // look up a font-triplet to find a font-name
+ Hashtable fonts; // look up a font-name to get a font (that implements FontMetric at least)
public FontInfo() {
this.triplets = new Hashtable();
@@ -23,10 +24,12 @@ public class FontInfo {
this.usedFonts = new Hashtable();
}
- public void addFontProperties(String name, String family,
- String style, String weight) {
- /* add the given family, style and weight as a lookup for the font
- with the given name */
+ public void addFontProperties(String name, String family, String style,
+ String weight) {
+ /*
+ * add the given family, style and weight as a lookup for the font
+ * with the given name
+ */
String key = createFontKey(family, style, weight);
this.triplets.put(key, name);
@@ -45,19 +48,20 @@ public class FontInfo {
public String fontLookup(String key) throws FOPException {
- String f = (String) this.triplets.get(key);
+ String f = (String)this.triplets.get(key);
if (f == null) {
int i = key.indexOf(',');
- String s = "any"+key.substring(i);
- f = (String) this.triplets.get(s);
+ String s = "any" + key.substring(i);
+ f = (String)this.triplets.get(s);
if (f == null) {
- f = (String) this.triplets.get("any,normal,normal");
+ f = (String)this.triplets.get("any,normal,normal");
if (f == null) {
throw new FOPException("no default font defined by OutputConverter");
}
MessageHandler.errorln("WARNING: defaulted font to any,normal,normal");
}
- MessageHandler.errorln("WARNING: unknown font "+key + " so defaulted font to any");
+ MessageHandler.errorln("WARNING: unknown font " + key
+ + " so defaulted font to any");
}
usedFonts.put(f, fonts.get(f));
@@ -100,7 +104,7 @@ public class FontInfo {
public FontMetric getMetricsFor(String fontName) throws FOPException {
usedFonts.put(fontName, fonts.get(fontName));
- return (FontMetric) fonts.get(fontName);
+ return (FontMetric)fonts.get(fontName);
}
}
diff --git a/src/org/apache/fop/layout/FontMetric.java b/src/org/apache/fop/layout/FontMetric.java
index fad3f5e4b..93b60ae92 100644
--- a/src/org/apache/fop/layout/FontMetric.java
+++ b/src/org/apache/fop/layout/FontMetric.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
diff --git a/src/org/apache/fop/layout/FontState.java b/src/org/apache/fop/layout/FontState.java
index 57cb6397f..498db1000 100644
--- a/src/org/apache/fop/layout/FontState.java
+++ b/src/org/apache/fop/layout/FontState.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -12,103 +13,102 @@ import org.apache.fop.apps.FOPException;
import org.apache.fop.fo.properties.FontVariant;
public class FontState {
-
+
private FontInfo _fontInfo;
private String _fontName;
- private int _fontSize;
+ private int _fontSize;
private String _fontFamily;
private String _fontStyle;
private String _fontWeight;
- private int _fontVariant;
+ private int _fontVariant;
private FontMetric _metric;
-
+
private static Hashtable EMPTY_HASHTABLE = new Hashtable();
-
-
- public FontState(FontInfo fontInfo, String fontFamily,
- String fontStyle, String fontWeight,
- int fontSize, int fontVariant)
- throws FOPException
- {
- _fontInfo = fontInfo;
- _fontFamily = fontFamily;
- _fontStyle = fontStyle;
- _fontWeight = fontWeight;
- _fontSize = fontSize;
- _fontName = fontInfo.fontLookup(fontFamily,fontStyle,fontWeight);
- _metric = fontInfo.getMetricsFor(_fontName);
- _fontVariant = fontVariant;
+
+
+ public FontState(FontInfo fontInfo, String fontFamily, String fontStyle,
+ String fontWeight, int fontSize,
+ int fontVariant) throws FOPException {
+ _fontInfo = fontInfo;
+ _fontFamily = fontFamily;
+ _fontStyle = fontStyle;
+ _fontWeight = fontWeight;
+ _fontSize = fontSize;
+ _fontName = fontInfo.fontLookup(fontFamily, fontStyle, fontWeight);
+ _metric = fontInfo.getMetricsFor(_fontName);
+ _fontVariant = fontVariant;
}
-
+
public int getAscender() {
- return _metric.getAscender(_fontSize) / 1000;
+ return _metric.getAscender(_fontSize) / 1000;
}
-
+
public int getCapHeight() {
- return _metric.getCapHeight(_fontSize) / 1000;
+ return _metric.getCapHeight(_fontSize) / 1000;
}
-
+
public int getDescender() {
- return _metric.getDescender(_fontSize) / 1000;
+ return _metric.getDescender(_fontSize) / 1000;
}
-
+
public String getFontName() {
- return _fontName;
+ return _fontName;
}
-
+
public int getFontSize() {
- return _fontSize;
+ return _fontSize;
}
-
+
public String getFontWeight() {
- return _fontWeight;
+ return _fontWeight;
}
-
+
public String getFontFamily() {
- return _fontFamily;
+ return _fontFamily;
}
-
+
public String getFontStyle() {
- return _fontStyle;
+ return _fontStyle;
}
-
+
public int getFontVariant() {
- return _fontVariant;
+ return _fontVariant;
}
-
+
public FontInfo getFontInfo() {
- return _fontInfo;
+ return _fontInfo;
}
-
+
public int getXHeight() {
- return _metric.getXHeight(_fontSize) / 1000;
+ return _metric.getXHeight(_fontSize) / 1000;
}
-
+
public Hashtable getKerning() {
- if (_metric instanceof FontDescriptor) {
- Hashtable ret = ((FontDescriptor)_metric).getKerningInfo();
- if (ret != null) return ret;
- }
- return EMPTY_HASHTABLE;
+ if (_metric instanceof FontDescriptor) {
+ Hashtable ret = ((FontDescriptor)_metric).getKerningInfo();
+ if (ret != null)
+ return ret;
+ }
+ return EMPTY_HASHTABLE;
}
-
+
public int width(int charnum) {
- // returns width of given character number in millipoints
- return (_metric.width(charnum, _fontSize) / 1000);
+ // returns width of given character number in millipoints
+ return (_metric.width(charnum, _fontSize) / 1000);
}
-
+
/**
* Map a java character (unicode) to a font character
* Default uses CodePointMapping
*/
public char mapChar(char c) {
-
- if (_metric instanceof org.apache.fop.render.pdf.Font) {
- return ((org.apache.fop.render.pdf.Font)_metric).mapChar(c);
- }
-
- // Use default CodePointMapping
+
+ if (_metric instanceof org.apache.fop.render.pdf.Font) {
+ return ((org.apache.fop.render.pdf.Font)_metric).mapChar(c);
+ }
+
+ // Use default CodePointMapping
if (c > 127) {
char d = org.apache.fop.render.pdf.CodePointMapping.map[c];
if (d != 0) {
@@ -117,9 +117,10 @@ public class FontState {
c = '#';
}
}
-
+
return c;
}
+
}
diff --git a/src/org/apache/fop/layout/HyphenationProps.java b/src/org/apache/fop/layout/HyphenationProps.java
index 83f30a5e6..c241feb72 100644
--- a/src/org/apache/fop/layout/HyphenationProps.java
+++ b/src/org/apache/fop/layout/HyphenationProps.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -11,13 +12,13 @@ package org.apache.fop.layout;
* Public "structure" allows direct member access.
*/
public class HyphenationProps {
- public int hyphenate; // Enum true or false: store as boolean!
+ public int hyphenate; // Enum true or false: store as boolean!
public char hyphenationChar;
public int hyphenationPushCharacterCount;
public int hyphenationRemainCharacterCount;
- public String language; // Language code or enum "NONE"
- public String country; // Country code or enum "NONE"
+ public String language; // Language code or enum "NONE"
+ public String country; // Country code or enum "NONE"
+
+ public HyphenationProps() {}
- public HyphenationProps() {
- }
}
diff --git a/src/org/apache/fop/layout/LineArea.java b/src/org/apache/fop/layout/LineArea.java
index 7a1e5dde4..fd9009512 100644
--- a/src/org/apache/fop/layout/LineArea.java
+++ b/src/org/apache/fop/layout/LineArea.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -6,7 +7,7 @@
package org.apache.fop.layout;
-//fop
+// fop
import org.apache.fop.render.Renderer;
import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.layout.inline.*;
@@ -25,7 +26,7 @@ import org.apache.fop.layout.hyphenation.Hyphenation;
import org.apache.fop.layout.hyphenation.Hyphenator;
import org.apache.fop.configuration.Configuration;
-//java
+// java
import java.util.Vector;
import java.util.Enumeration;
import java.util.StringTokenizer;
@@ -44,46 +45,50 @@ public class LineArea extends Area {
private int placementOffset;
- private FontState currentFontState; // not the nominal, which is
+ private FontState currentFontState; // not the nominal, which is
// in this.fontState
private float red, green, blue;
private int wrapOption;
private int whiteSpaceCollapse;
int vAlign;
- /*hyphenation*/
+ /* hyphenation */
HyphenationProps hyphProps;
- /* the width of text that has definitely made it into the line
- area */
+ /*
+ * the width of text that has definitely made it into the line
+ * area
+ */
protected int finalWidth = 0;
- /* the position to shift a link rectangle in order to compensate for links embedded within a word*/
+ /* the position to shift a link rectangle in order to compensate for links embedded within a word */
protected int embeddedLinkStart = 0;
/* the width of the current word so far */
-// protected int wordWidth = 0;
+ // protected int wordWidth = 0;
/* values that prev (below) may take */
protected static final int NOTHING = 0;
protected static final int WHITESPACE = 1;
protected static final int TEXT = 2;
-
+
/* the character type of the previous character */
protected int prev = NOTHING;
/* the position in data[] of the start of the current word */
-// protected int wordStart;
+ // protected int wordStart;
/* the length (in characters) of the current word */
-// protected int wordLength = 0;
+ // protected int wordLength = 0;
/* width of spaces before current word */
protected int spaceWidth = 0;
- /* the inline areas that have not yet been added to the line
- because subsequent characters to come (in a different addText)
- may be part of the same word */
+ /*
+ * the inline areas that have not yet been added to the line
+ * because subsequent characters to come (in a different addText)
+ * may be part of the same word
+ */
protected Vector pendingAreas = new Vector();
/* the width of the pendingAreas */
@@ -94,20 +99,20 @@ public class LineArea extends Area {
protected boolean prevOlState = false;
protected boolean prevLTState = false;
- public LineArea(FontState fontState, int lineHeight,
- int halfLeading, int allocationWidth, int startIndent,
- int endIndent, LineArea prevLineArea) {
+ public LineArea(FontState fontState, int lineHeight, int halfLeading,
+ int allocationWidth, int startIndent, int endIndent,
+ LineArea prevLineArea) {
super(fontState);
this.currentFontState = fontState;
this.lineHeight = lineHeight;
this.nominalFontSize = fontState.getFontSize();
- this.nominalGlyphHeight =
- fontState.getAscender() - fontState.getDescender();
+ this.nominalGlyphHeight = fontState.getAscender()
+ - fontState.getDescender();
this.placementOffset = fontState.getAscender();
- this.contentRectangleWidth =
- allocationWidth - startIndent - endIndent;
+ this.contentRectangleWidth = allocationWidth - startIndent
+ - endIndent;
this.fontState = fontState;
this.allocationHeight = this.nominalGlyphHeight;
@@ -119,11 +124,11 @@ public class LineArea extends Area {
if (prevLineArea != null) {
Enumeration e = prevLineArea.pendingAreas.elements();
Box b = null;
- // There might be InlineSpaces at the beginning
- // that should not be there - eat them
+ // There might be InlineSpaces at the beginning
+ // that should not be there - eat them
boolean eatMoreSpace = true;
int eatenWidth = 0;
-
+
while (eatMoreSpace) {
if (e.hasMoreElements()) {
b = (Box)e.nextElement();
@@ -141,7 +146,7 @@ public class LineArea extends Area {
b = null;
}
}
-
+
while (b != null) {
pendingAreas.addElement(b);
if (e.hasMoreElements())
@@ -159,17 +164,17 @@ public class LineArea extends Area {
public int addPageNumberCitation(String refid, LinkSet ls) {
- /* We should add code here to handle the case where the page number doesn't fit on the current line
- */
+ /*
+ * We should add code here to handle the case where the page number doesn't fit on the current line
+ */
+
+ // Space must be alloted to the page number, so currently we give it 3 spaces
- //Space must be alloted to the page number, so currently we give it 3 spaces
-
int width = currentFontState.width(currentFontState.mapChar(' '));
- PageNumberInlineArea pia =
- new PageNumberInlineArea(currentFontState, this.red,
- this.green, this.blue, refid, width);
+ PageNumberInlineArea pia = new PageNumberInlineArea(currentFontState,
+ this.red, this.green, this.blue, refid, width);
pia.setYOffset(placementOffset);
pendingAreas.addElement(pia);
@@ -181,23 +186,24 @@ public class LineArea extends Area {
/**
- * adds text to line area
- *
- * @return int character position
- */
+ * adds text to line area
+ *
+ * @return int character position
+ */
public int addText(char odata[], int start, int end, LinkSet ls,
TextState textState) {
// this prevents an array index out of bounds
// which occurs when some text is laid out again.
- if(start == -1) return -1;
+ if (start == -1)
+ return -1;
boolean overrun = false;
int wordStart = start;
int wordLength = 0;
int wordWidth = 0;
- // With CID fonts, space isn't neccesary currentFontState.width(32)
+ // With CID fonts, space isn't neccesary currentFontState.width(32)
int whitespaceWidth = getCharWidth(' ');
-
+
char[] data = new char[odata.length];
char[] dataCopy = new char[odata.length];
System.arraycopy(odata, 0, data, 0, odata.length);
@@ -210,30 +216,29 @@ public class LineArea extends Area {
int charWidth;
/* get the character */
char c = data[i];
- if (!(isSpace(c) || (c == '\n') || (c == '\r') ||
- (c == '\t') || (c == '\u2028'))) {
- charWidth = getCharWidth(c);
- isText = true;
- // Add support for zero-width spaces
- if (charWidth <= 0 && c != '\u200B' && c != '\uFEFF')
- charWidth = whitespaceWidth;
+ if (!(isSpace(c) || (c == '\n') || (c == '\r') || (c == '\t')
+ || (c == '?'))) {
+ charWidth = getCharWidth(c);
+ isText = true;
+ // Add support for zero-width spaces
+ if (charWidth <= 0 && c != '?' && c != '?')
+ charWidth = whitespaceWidth;
} else {
if ((c == '\n') || (c == '\r') || (c == '\t'))
charWidth = whitespaceWidth;
else
charWidth = getCharWidth(c);
-
- isText = false;
+
+ isText = false;
if (prev == WHITESPACE) {
// if current & previous are WHITESPACE
- if (this.whiteSpaceCollapse ==
- WhiteSpaceCollapse.FALSE) {
+ if (this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE) {
if (isSpace(c)) {
spaceWidth += getCharWidth(c);
- } else if (c == '\n' || c == '\u2028') {
+ } else if (c == '\n' || c == '?') {
// force line break
if (spaceWidth > 0) {
InlineSpace is = new InlineSpace(spaceWidth);
@@ -244,13 +249,13 @@ public class LineArea extends Area {
finalWidth += spaceWidth;
spaceWidth = 0;
}
- return i+1;
+ return i + 1;
} else if (c == '\t') {
spaceWidth += 8 * whitespaceWidth;
}
- } else if (c == '\u2028') {
- // Line separator
- // Breaks line even if WhiteSpaceCollapse = True
+ } else if (c == '?') {
+ // Line separator
+ // Breaks line even if WhiteSpaceCollapse = True
if (spaceWidth > 0) {
InlineSpace is = new InlineSpace(spaceWidth);
is.setUnderlined(textState.getUnderlined());
@@ -260,7 +265,7 @@ public class LineArea extends Area {
finalWidth += spaceWidth;
spaceWidth = 0;
}
- return i+1;
+ return i + 1;
}
} else if (prev == TEXT) {
@@ -290,13 +295,13 @@ public class LineArea extends Area {
Enumeration e = pendingAreas.elements();
while (e.hasMoreElements()) {
- Box box = (Box) e.nextElement();
+ Box box = (Box)e.nextElement();
if (box instanceof InlineArea) {
if (ls != null) {
- Rectangle lr = new Rectangle(finalWidth, 0,
- ((InlineArea) box).
- getContentWidth(),
- fontState.getFontSize());
+ Rectangle lr =
+ new Rectangle(finalWidth, 0,
+ ((InlineArea)box).getContentWidth(),
+ fontState.getFontSize());
ls.addRect(lr, this, (InlineArea)box);
}
}
@@ -312,10 +317,10 @@ public class LineArea extends Area {
// add the current word
if (wordLength > 0) {
- // The word might contain nonbreaking
- // spaces. Split the word and add InlineSpace
- // as necessary. All spaces inside the word
- // Have a fixed width.
+ // The word might contain nonbreaking
+ // spaces. Split the word and add InlineSpace
+ // as necessary. All spaces inside the word
+ // Have a fixed width.
addSpacedWord(new String(data, wordStart, wordLength),
ls, finalWidth, 0, textState, false);
finalWidth += wordWidth;
@@ -328,53 +333,51 @@ public class LineArea extends Area {
// word we just added
prev = WHITESPACE;
- embeddedLinkStart = 0; //reset embeddedLinkStart since a space was encountered
+ embeddedLinkStart =
+ 0; // reset embeddedLinkStart since a space was encountered
spaceWidth = getCharWidth(c);
-
- /*
- here is the place for space-treatment value 'ignore':
- if (this.spaceTreatment ==
- SpaceTreatment.IGNORE) {
- // do nothing
- } else {
- spaceWidth = currentFontState.width(32);
- }
-
- */
-
- if (this.whiteSpaceCollapse ==
- WhiteSpaceCollapse.FALSE) {
- if (c == '\n' || c == '\u2028') {
+ /*
+ * here is the place for space-treatment value 'ignore':
+ * if (this.spaceTreatment ==
+ * SpaceTreatment.IGNORE) {
+ * // do nothing
+ * } else {
+ * spaceWidth = currentFontState.width(32);
+ * }
+ */
+
+
+ if (this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE) {
+ if (c == '\n' || c == '?') {
// force a line break
- return i+1;
+ return i + 1;
} else if (c == '\t') {
spaceWidth = whitespaceWidth;
}
- } else if (c == '\u2028') {
- return i+1;
+ } else if (c == '?') {
+ return i + 1;
}
} else {
// if current is WHITESPACE and no previous
- if (this.whiteSpaceCollapse ==
- WhiteSpaceCollapse.FALSE) {
+ if (this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE) {
if (isSpace(c)) {
prev = WHITESPACE;
spaceWidth = getCharWidth(c);
} else if (c == '\n') {
- // force line break
- // textdecoration not used because spaceWidth is 0
+ // force line break
+ // textdecoration not used because spaceWidth is 0
InlineSpace is = new InlineSpace(spaceWidth);
addChild(is);
- return i+1;
+ return i + 1;
} else if (c == '\t') {
- prev = WHITESPACE;
- spaceWidth = 8 * whitespaceWidth;
+ prev = WHITESPACE;
+ spaceWidth = 8 * whitespaceWidth;
}
-
+
} else {
// skip over it
wordStart++;
@@ -382,16 +385,16 @@ public class LineArea extends Area {
}
}
-
- if(isText) { // current is TEXT
+
+ if (isText) { // current is TEXT
if (prev == WHITESPACE) {
// if current is TEXT and previous WHITESPACE
wordWidth = charWidth;
- if ((finalWidth + spaceWidth + wordWidth) >
- this.getContentWidth()) {
+ if ((finalWidth + spaceWidth + wordWidth)
+ > this.getContentWidth()) {
if (overrun)
MessageHandler.error(">");
if (this.wrapOption == WrapOption.WRAP) {
@@ -404,7 +407,7 @@ public class LineArea extends Area {
} else if (prev == TEXT) {
wordLength++;
wordWidth += charWidth;
- } else { // nothing previous
+ } else { // nothing previous
prev = TEXT;
wordStart = i;
@@ -412,19 +415,21 @@ public class LineArea extends Area {
wordWidth = charWidth;
}
- if ((finalWidth + spaceWidth + pendingWidth +
- wordWidth) > this.getContentWidth()) {
+ if ((finalWidth + spaceWidth + pendingWidth + wordWidth)
+ > this.getContentWidth()) {
// BREAK MID WORD
if (canBreakMidWord()) {
- addSpacedWord(new String(data, wordStart, wordLength-1),
- ls, finalWidth + spaceWidth + embeddedLinkStart,
- spaceWidth, textState, false);
+ addSpacedWord(new String(data, wordStart, wordLength - 1),
+ ls,
+ finalWidth + spaceWidth
+ + embeddedLinkStart, spaceWidth,
+ textState, false);
finalWidth += wordWidth;
wordWidth = 0;
return i;
}
- if (wordStart == start) { // if couldn't even fit
+ if (wordStart == start) { // if couldn't even fit
// first word
overrun = true;
// if not at start of line, return word start
@@ -433,24 +438,28 @@ public class LineArea extends Area {
return wordStart;
}
} else if (this.wrapOption == WrapOption.WRAP) {
- if (hyphProps.hyphenate == Hyphenate.TRUE) {
- return this.doHyphenation(dataCopy,i,wordStart,this.getContentWidth() - (finalWidth + spaceWidth + pendingWidth));
- } else {
- return wordStart;
- }
+ if (hyphProps.hyphenate == Hyphenate.TRUE) {
+ return this.doHyphenation(dataCopy, i, wordStart,
+ this.getContentWidth()
+ - (finalWidth
+ + spaceWidth
+ + pendingWidth));
+ } else {
+ return wordStart;
+ }
}
}
}
- } // end of iteration over text
+ } // end of iteration over text
+
-
- if (prev == TEXT) {
+ if (prev == TEXT) {
if (spaceWidth > 0) {
InlineSpace pis = new InlineSpace(spaceWidth);
- // Make sure that this space doesn't occur as
- // first thing in the next line
+ // Make sure that this space doesn't occur as
+ // first thing in the next line
pis.setEatable(true);
if (prevUlState) {
pis.setUnderlined(textState.getUnderlined());
@@ -466,8 +475,8 @@ public class LineArea extends Area {
spaceWidth = 0;
}
- addSpacedWord(new String(data, wordStart, wordLength),
- ls, finalWidth + spaceWidth + embeddedLinkStart,
+ addSpacedWord(new String(data, wordStart, wordLength), ls,
+ finalWidth + spaceWidth + embeddedLinkStart,
spaceWidth, textState, true);
embeddedLinkStart += wordWidth;
@@ -480,134 +489,134 @@ public class LineArea extends Area {
}
/**
- * adds a Leader; actually the method receives the leader properties
- * and creates a leader area or an inline area which is appended to
- * the children of the containing line area.
- * leader pattern use-content is not implemented.
- */
+ * adds a Leader; actually the method receives the leader properties
+ * and creates a leader area or an inline area which is appended to
+ * the children of the containing line area.
+ * leader pattern use-content is not implemented.
+ */
public void addLeader(int leaderPattern, int leaderLengthMinimum,
int leaderLengthOptimum, int leaderLengthMaximum,
- int ruleStyle, int ruleThickness, int leaderPatternWidth,
- int leaderAlignment) {
+ int ruleStyle, int ruleThickness,
+ int leaderPatternWidth, int leaderAlignment) {
WordArea leaderPatternArea;
int leaderLength = 0;
- char dotIndex = '.'; // currentFontState.mapChar('.');
+ char dotIndex = '.'; // currentFontState.mapChar('.');
int dotWidth =
currentFontState.width(currentFontState.mapChar(dotIndex));
- char whitespaceIndex = ' ';//currentFontState.mapChar(' ');
+ char whitespaceIndex = ' '; // currentFontState.mapChar(' ');
int whitespaceWidth =
currentFontState.width(currentFontState.mapChar(whitespaceIndex));
-
- int remainingWidth =
- this.getContentWidth() - this.getCurrentXPosition();
- /** checks whether leaderLenghtOptimum fits into rest of line;
- * should never overflow, as it has been checked already in BlockArea
- * first check: use remaining width if it smaller than optimum oder maximum
- * */
- if ((remainingWidth <= leaderLengthOptimum) ||
- (remainingWidth <= leaderLengthMaximum)) {
+
+ int remainingWidth = this.getContentWidth()
+ - this.getCurrentXPosition();
+
+ /**
+ * checks whether leaderLenghtOptimum fits into rest of line;
+ * should never overflow, as it has been checked already in BlockArea
+ * first check: use remaining width if it smaller than optimum oder maximum
+ */
+ if ((remainingWidth <= leaderLengthOptimum)
+ || (remainingWidth <= leaderLengthMaximum)) {
leaderLength = remainingWidth;
- } else if ((remainingWidth > leaderLengthOptimum) &&
- ( remainingWidth > leaderLengthMaximum)) {
+ } else if ((remainingWidth > leaderLengthOptimum)
+ && (remainingWidth > leaderLengthMaximum)) {
leaderLength = leaderLengthMaximum;
- } else if ((leaderLengthOptimum > leaderLengthMaximum) &&
- (leaderLengthOptimum < remainingWidth)) {
+ } else if ((leaderLengthOptimum > leaderLengthMaximum)
+ && (leaderLengthOptimum < remainingWidth)) {
leaderLength = leaderLengthOptimum;
}
- //stop if leader-length is too small
- if (leaderLength <= 0 ) {
- return;
- }
+ // stop if leader-length is too small
+ if (leaderLength <= 0) {
+ return;
+ }
switch (leaderPattern) {
- case LeaderPattern.SPACE:
- InlineSpace spaceArea =
- new InlineSpace(leaderLength);
- pendingAreas.addElement(spaceArea);
- break;
- case LeaderPattern.RULE:
- LeaderArea leaderArea =
- new LeaderArea(fontState, red, green, blue, "",
- leaderLength, leaderPattern, ruleThickness,
- ruleStyle);
- leaderArea.setYOffset(placementOffset);
- pendingAreas.addElement(leaderArea);
- break;
- case LeaderPattern.DOTS:
- //if the width of a dot is larger than leader-pattern-width
- //ignore this property
- if (leaderPatternWidth < dotWidth) {
- leaderPatternWidth = 0;
- }
- //if value of leader-pattern-width is 'use-font-metrics' (0)
- if (leaderPatternWidth == 0) {
- pendingAreas.addElement(
- this.buildSimpleLeader(dotIndex,
- leaderLength));
- } else {
- //if leader-alignment is used, calculate space to insert before leader
- //so that all dots will be parallel.
- if (leaderAlignment == LeaderAlignment.REFERENCE_AREA) {
- int spaceBeforeLeader = this.getLeaderAlignIndent(
- leaderLength, leaderPatternWidth);
- //appending indent space leader-alignment
- //setting InlineSpace to false, so it is not used in line justification
- if (spaceBeforeLeader != 0) {
- pendingAreas.addElement(
- new InlineSpace(spaceBeforeLeader,
- false));
- pendingWidth += spaceBeforeLeader;
- //shorten leaderLength, otherwise - in case of
- //leaderLength=remaining length - it will cut off the end of
- //leaderlength
- leaderLength -= spaceBeforeLeader;
- }
+ case LeaderPattern.SPACE:
+ InlineSpace spaceArea = new InlineSpace(leaderLength);
+ pendingAreas.addElement(spaceArea);
+ break;
+ case LeaderPattern.RULE:
+ LeaderArea leaderArea = new LeaderArea(fontState, red, green,
+ blue, "", leaderLength,
+ leaderPattern,
+ ruleThickness, ruleStyle);
+ leaderArea.setYOffset(placementOffset);
+ pendingAreas.addElement(leaderArea);
+ break;
+ case LeaderPattern.DOTS:
+ // if the width of a dot is larger than leader-pattern-width
+ // ignore this property
+ if (leaderPatternWidth < dotWidth) {
+ leaderPatternWidth = 0;
+ }
+ // if value of leader-pattern-width is 'use-font-metrics' (0)
+ if (leaderPatternWidth == 0) {
+ pendingAreas.addElement(this.buildSimpleLeader(dotIndex,
+ leaderLength));
+ } else {
+ // if leader-alignment is used, calculate space to insert before leader
+ // so that all dots will be parallel.
+ if (leaderAlignment == LeaderAlignment.REFERENCE_AREA) {
+ int spaceBeforeLeader =
+ this.getLeaderAlignIndent(leaderLength,
+ leaderPatternWidth);
+ // appending indent space leader-alignment
+ // setting InlineSpace to false, so it is not used in line justification
+ if (spaceBeforeLeader != 0) {
+ pendingAreas.addElement(new InlineSpace(spaceBeforeLeader,
+ false));
+ pendingWidth += spaceBeforeLeader;
+ // shorten leaderLength, otherwise - in case of
+ // leaderLength=remaining length - it will cut off the end of
+ // leaderlength
+ leaderLength -= spaceBeforeLeader;
}
+ }
- // calculate the space to insert between the dots and create a
- //inline area with this width
- InlineSpace spaceBetweenDots =
- new InlineSpace(leaderPatternWidth - dotWidth, false);
-
- leaderPatternArea =
- new WordArea(currentFontState, this.red,
- this.green, this.blue, new String ("."),
- dotWidth);
- leaderPatternArea.setYOffset(placementOffset);
- int dotsFactor = (int) Math.floor (
- ((double) leaderLength) /
- ((double) leaderPatternWidth));
-
- //add combination of dot + space to fill leader
- //is there a way to do this in a more effective way?
- for (int i = 0; i < dotsFactor; i++) {
- pendingAreas.addElement(leaderPatternArea);
- pendingAreas.addElement(spaceBetweenDots);
- }
- //append at the end some space to fill up to leader length
- pendingAreas.addElement( new InlineSpace(leaderLength -
- dotsFactor * leaderPatternWidth));
+ // calculate the space to insert between the dots and create a
+ // inline area with this width
+ InlineSpace spaceBetweenDots =
+ new InlineSpace(leaderPatternWidth - dotWidth, false);
+
+ leaderPatternArea = new WordArea(currentFontState, this.red,
+ this.green, this.blue,
+ new String("."), dotWidth);
+ leaderPatternArea.setYOffset(placementOffset);
+ int dotsFactor =
+ (int)Math.floor(((double)leaderLength)
+ / ((double)leaderPatternWidth));
+
+ // add combination of dot + space to fill leader
+ // is there a way to do this in a more effective way?
+ for (int i = 0; i < dotsFactor; i++) {
+ pendingAreas.addElement(leaderPatternArea);
+ pendingAreas.addElement(spaceBetweenDots);
}
- break;
- //leader pattern use-content not implemented.
- case LeaderPattern.USECONTENT:
- MessageHandler.errorln(
- "leader-pattern=\"use-content\" not " + "supported by this version of Fop");
- return;
+ // append at the end some space to fill up to leader length
+ pendingAreas.addElement(new InlineSpace(leaderLength
+ - dotsFactor
+ * leaderPatternWidth));
+ }
+ break;
+ // leader pattern use-content not implemented.
+ case LeaderPattern.USECONTENT:
+ MessageHandler.errorln("leader-pattern=\"use-content\" not "
+ + "supported by this version of Fop");
+ return;
}
- //adds leader length to length of pending inline areas
+ // adds leader length to length of pending inline areas
pendingWidth += leaderLength;
- //sets prev to TEXT and makes so sure, that also blocks only
- //containing leaders are processed
+ // sets prev to TEXT and makes so sure, that also blocks only
+ // containing leaders are processed
prev = TEXT;
}
/**
- * adds pending inline areas to the line area
- * normally done, when the line area is filled and
- * added as child to the parent block area
- */
+ * adds pending inline areas to the line area
+ * normally done, when the line area is filled and
+ * added as child to the parent block area
+ */
public void addPending() {
if (spaceWidth > 0) {
addChild(new InlineSpace(spaceWidth));
@@ -617,7 +626,7 @@ public class LineArea extends Area {
Enumeration e = pendingAreas.elements();
while (e.hasMoreElements()) {
- Box box = (Box) e.nextElement();
+ Box box = (Box)e.nextElement();
addChild(box);
}
@@ -629,93 +638,89 @@ public class LineArea extends Area {
}
/**
- * aligns line area
- *
- */
+ * aligns line area
+ *
+ */
public void align(int type) {
int padding = 0;
switch (type) {
- case TextAlign.START: // left
- padding = this.getContentWidth() - finalWidth;
- endIndent += padding;
- break;
- case TextAlign.END: // right
- padding = this.getContentWidth() - finalWidth;
- startIndent += padding;
- break;
- case TextAlign.CENTER: // center
- padding = (this.getContentWidth() - finalWidth) / 2;
- startIndent += padding;
- endIndent += padding;
- break;
- case TextAlign.JUSTIFY: // justify
- // first pass - count the spaces
- int spaceCount = 0;
- Enumeration e = children.elements();
- while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
- if (b instanceof InlineSpace) {
- InlineSpace space = (InlineSpace) b;
- if (space.getResizeable()) {
- spaceCount++;
- }
+ case TextAlign.START: // left
+ padding = this.getContentWidth() - finalWidth;
+ endIndent += padding;
+ break;
+ case TextAlign.END: // right
+ padding = this.getContentWidth() - finalWidth;
+ startIndent += padding;
+ break;
+ case TextAlign.CENTER: // center
+ padding = (this.getContentWidth() - finalWidth) / 2;
+ startIndent += padding;
+ endIndent += padding;
+ break;
+ case TextAlign.JUSTIFY: // justify
+ // first pass - count the spaces
+ int spaceCount = 0;
+ Enumeration e = children.elements();
+ while (e.hasMoreElements()) {
+ Box b = (Box)e.nextElement();
+ if (b instanceof InlineSpace) {
+ InlineSpace space = (InlineSpace)b;
+ if (space.getResizeable()) {
+ spaceCount++;
}
}
- if (spaceCount > 0) {
- padding = (this.getContentWidth() - finalWidth) /
- spaceCount;
- } else { // no spaces
- padding = 0;
- }
- // second pass - add additional space
- spaceCount = 0;
- e = children.elements();
- while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
- if (b instanceof InlineSpace) {
- InlineSpace space = (InlineSpace) b;
- if (space.getResizeable()) {
- space.setSize(space.getSize() + padding);
- spaceCount++;
- }
+ }
+ if (spaceCount > 0) {
+ padding = (this.getContentWidth() - finalWidth) / spaceCount;
+ } else { // no spaces
+ padding = 0;
+ }
+ // second pass - add additional space
+ spaceCount = 0;
+ e = children.elements();
+ while (e.hasMoreElements()) {
+ Box b = (Box)e.nextElement();
+ if (b instanceof InlineSpace) {
+ InlineSpace space = (InlineSpace)b;
+ if (space.getResizeable()) {
+ space.setSize(space.getSize() + padding);
+ spaceCount++;
}
- else if (b instanceof InlineArea) {
- ((InlineArea)b).setXOffset(spaceCount * padding);
- }
-
+ } else if (b instanceof InlineArea) {
+ ((InlineArea)b).setXOffset(spaceCount * padding);
}
+
+ }
}
}
/**
* Balance (vertically) the inline areas within this line.
*/
- public void verticalAlign()
- {
+ public void verticalAlign() {
int superHeight = -this.placementOffset;
int maxHeight = this.allocationHeight;
Enumeration e = children.elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
- if(b instanceof InlineArea) {
+ Box b = (Box)e.nextElement();
+ if (b instanceof InlineArea) {
InlineArea ia = (InlineArea)b;
- if(ia instanceof WordArea) {
+ if (ia instanceof WordArea) {
ia.setYOffset(placementOffset);
}
- if(ia.getHeight() > maxHeight) {
+ if (ia.getHeight() > maxHeight) {
maxHeight = ia.getHeight();
}
int vert = ia.getVerticalAlign();
- if(vert == VerticalAlign.SUPER) {
+ if (vert == VerticalAlign.SUPER) {
int fh = fontState.getAscender();
ia.setYOffset((int)(placementOffset - (2 * fh / 3.0)));
- } else if(vert == VerticalAlign.SUB) {
+ } else if (vert == VerticalAlign.SUB) {
int fh = fontState.getAscender();
ia.setYOffset((int)(placementOffset + (2 * fh / 3.0)));
}
- } else {
- }
+ } else {}
}
// adjust the height of this line to the
// resulting alignment height.
@@ -762,7 +767,7 @@ public class LineArea extends Area {
public boolean isEmpty() {
return !(pendingAreas.size() > 0 || children.size() > 0);
-// return (prev == NOTHING);
+ // return (prev == NOTHING);
}
public Vector getPendingAreas() {
@@ -782,62 +787,63 @@ public class LineArea extends Area {
}
/**
- * sets hyphenation related traits: language, country, hyphenate, hyphenation-character
- * and minimum number of character to remain one the previous line and to be on the
- * next line.
- */
+ * sets hyphenation related traits: language, country, hyphenate, hyphenation-character
+ * and minimum number of character to remain one the previous line and to be on the
+ * next line.
+ */
public void changeHyphenation(HyphenationProps hyphProps) {
this.hyphProps = hyphProps;
}
/**
- * creates a leader as String out of the given char and the leader length
- * and wraps it in an InlineArea which is returned
- */
+ * creates a leader as String out of the given char and the leader length
+ * and wraps it in an InlineArea which is returned
+ */
private InlineArea buildSimpleLeader(char c, int leaderLength) {
int width = this.currentFontState.width(currentFontState.mapChar(c));
- if (width == 0) {
- MessageHandler.errorln("char " + c + " has width 0. Using width 100 instead.");
+ if (width == 0) {
+ MessageHandler.errorln("char " + c
+ + " has width 0. Using width 100 instead.");
width = 100;
}
- int factor = (int) Math.floor (leaderLength /
- width);
- char [] leaderChars = new char [factor];
- for (int i = 0; i < factor; i ++) {
- leaderChars[i] = c;//currentFontState.mapChar(c);
+ int factor = (int)Math.floor(leaderLength / width);
+ char[] leaderChars = new char[factor];
+ for (int i = 0; i < factor; i++) {
+ leaderChars[i] = c; // currentFontState.mapChar(c);
}
- WordArea leaderPatternArea =
- new WordArea(currentFontState, this.red, this.green,
- this.blue, new String (leaderChars), leaderLength);
+ WordArea leaderPatternArea = new WordArea(currentFontState, this.red,
+ this.green, this.blue,
+ new String(leaderChars),
+ leaderLength);
leaderPatternArea.setYOffset(placementOffset);
return leaderPatternArea;
}
/**
- * calculates the width of space which has to be inserted before the
- * start of the leader, so that all leader characters are aligned.
- * is used if property leader-align is set. At the moment only the value
- * for leader-align="reference-area" is supported.
- *
- */
- private int getLeaderAlignIndent (int leaderLength,
- int leaderPatternWidth) {
- //calculate position of used space in line area
+ * calculates the width of space which has to be inserted before the
+ * start of the leader, so that all leader characters are aligned.
+ * is used if property leader-align is set. At the moment only the value
+ * for leader-align="reference-area" is supported.
+ *
+ */
+ private int getLeaderAlignIndent(int leaderLength,
+ int leaderPatternWidth) {
+ // calculate position of used space in line area
double position = getCurrentXPosition();
- //calculate factor of next leader pattern cycle
- double nextRepeatedLeaderPatternCycle =
- Math.ceil(position / leaderPatternWidth);
- //calculate difference between start of next leader
- //pattern cycle and already used space
- double difference = (leaderPatternWidth *
- nextRepeatedLeaderPatternCycle) - position;
- return (int) difference;
+ // calculate factor of next leader pattern cycle
+ double nextRepeatedLeaderPatternCycle = Math.ceil(position
+ / leaderPatternWidth);
+ // calculate difference between start of next leader
+ // pattern cycle and already used space
+ double difference =
+ (leaderPatternWidth * nextRepeatedLeaderPatternCycle) - position;
+ return (int)difference;
}
/**
- * calculates the used space in this line area
- */
+ * calculates the used space in this line area
+ */
private int getCurrentXPosition() {
return finalWidth + spaceWidth + startIndent + pendingWidth;
}
@@ -845,218 +851,239 @@ public class LineArea extends Area {
/**
* extracts a complete word from the character data
*/
- private String getHyphenationWord (char [] characters, int wordStart) {
+ private String getHyphenationWord(char[] characters, int wordStart) {
boolean wordendFound = false;
int counter = 0;
- char [] newWord = new char [100]; //create a buffer
- while ((!wordendFound) && ((wordStart + counter) < characters.length)) {
- char tk = characters[wordStart+counter];
- if (Character.isLetter(tk)) {
- newWord[counter] = tk;
- counter++;
- } else {
- wordendFound = true;
- }
+ char[] newWord = new char[100]; // create a buffer
+ while ((!wordendFound)
+ && ((wordStart + counter) < characters.length)) {
+ char tk = characters[wordStart + counter];
+ if (Character.isLetter(tk)) {
+ newWord[counter] = tk;
+ counter++;
+ } else {
+ wordendFound = true;
+ }
}
- return new String (newWord,0,counter);
+ return new String(newWord, 0, counter);
}
- /** extracts word for hyphenation and calls hyphenation package,
- * handles cases of inword punctuation and quotation marks at the beginning
- * of words, but not in a internationalized way
+ /**
+ * extracts word for hyphenation and calls hyphenation package,
+ * handles cases of inword punctuation and quotation marks at the beginning
+ * of words, but not in a internationalized way
*/
- public int doHyphenation (char [] characters, int position, int wordStart, int remainingWidth) {
- //check whether the language property has been set
+ public int doHyphenation(char[] characters, int position, int wordStart,
+ int remainingWidth) {
+ // check whether the language property has been set
if (this.hyphProps.language.equalsIgnoreCase("none")) {
- MessageHandler.errorln("if property 'hyphenate' is used, a language must be specified");
- return wordStart;
+ MessageHandler.errorln("if property 'hyphenate' is used, a language must be specified");
+ return wordStart;
}
- /** remaining part string of hyphenation */
+ /**
+ * remaining part string of hyphenation
+ */
StringBuffer remainingString = new StringBuffer();
- /** for words with some inword punctuation like / or - */
+ /**
+ * for words with some inword punctuation like / or -
+ */
StringBuffer preString = null;
- /** char before the word, probably whitespace */
- char startChar = ' ' ;//characters[wordStart-1];
+ /**
+ * char before the word, probably whitespace
+ */
+ char startChar = ' '; // characters[wordStart-1];
- /** in word punctuation character */
+ /**
+ * in word punctuation character
+ */
char inwordPunctuation;
- /** the complete word handed to the hyphenator */
+ /**
+ * the complete word handed to the hyphenator
+ */
String wordToHyphenate;
- //width of hyphenation character
- int hyphCharWidth = this.currentFontState.width(currentFontState.mapChar(this.hyphProps.hyphenationChar));
+ // width of hyphenation character
+ int hyphCharWidth =
+ this.currentFontState.width(currentFontState.mapChar(this.hyphProps.hyphenationChar));
remainingWidth -= hyphCharWidth;
- //handles ' or " at the beginning of the word
- if (characters[wordStart] == '"' || characters[wordStart] == '\'' ) {
+ // handles ' or " at the beginning of the word
+ if (characters[wordStart] == '"' || characters[wordStart] == '\'') {
remainingString.append(characters[wordStart]);
- //extracts whole word from string
- wordToHyphenate = getHyphenationWord(characters,wordStart+1);
+ // extracts whole word from string
+ wordToHyphenate = getHyphenationWord(characters, wordStart + 1);
} else {
- wordToHyphenate = getHyphenationWord(characters,wordStart);
+ wordToHyphenate = getHyphenationWord(characters, wordStart);
}
- //if the extracted word is smaller than the remaining width
- //we have a non letter character inside the word. at the moment
- //we will only handle hard hyphens and slashes
- if (getWordWidth(wordToHyphenate)< remainingWidth) {
- inwordPunctuation = characters[wordStart+wordToHyphenate.length()];
- if (inwordPunctuation == '-' ||
- inwordPunctuation == '/' ) {
+ // if the extracted word is smaller than the remaining width
+ // we have a non letter character inside the word. at the moment
+ // we will only handle hard hyphens and slashes
+ if (getWordWidth(wordToHyphenate) < remainingWidth) {
+ inwordPunctuation =
+ characters[wordStart + wordToHyphenate.length()];
+ if (inwordPunctuation == '-' || inwordPunctuation == '/') {
preString = new StringBuffer(wordToHyphenate);
preString = preString.append(inwordPunctuation);
- wordToHyphenate = getHyphenationWord(characters,wordStart+wordToHyphenate.length()+1);
- remainingWidth -= (getWordWidth(wordToHyphenate) +
- this.currentFontState.width(currentFontState.mapChar(inwordPunctuation)));
+ wordToHyphenate =
+ getHyphenationWord(characters,
+ wordStart + wordToHyphenate.length()
+ + 1);
+ remainingWidth -=
+ (getWordWidth(wordToHyphenate)
+ + this.currentFontState.width(currentFontState.mapChar(inwordPunctuation)));
}
}
- //are there any hyphenation points
- Hyphenation hyph = Hyphenator.hyphenate(hyphProps.language,
- hyphProps.country, wordToHyphenate,hyphProps.hyphenationRemainCharacterCount,hyphProps.hyphenationPushCharacterCount);
- //no hyphenation points and no inword non letter character
+ // are there any hyphenation points
+ Hyphenation hyph =
+ Hyphenator.hyphenate(hyphProps.language, hyphProps.country,
+ wordToHyphenate,
+ hyphProps.hyphenationRemainCharacterCount,
+ hyphProps.hyphenationPushCharacterCount);
+ // no hyphenation points and no inword non letter character
if (hyph == null && preString == null) {
if (remainingString.length() > 0) {
- return wordStart-1;
+ return wordStart - 1;
} else {
return wordStart;
}
- //no hyphenation points, but a inword non-letter character
- } else if (hyph == null && preString != null){
+ // no hyphenation points, but a inword non-letter character
+ } else if (hyph == null && preString != null) {
remainingString.append(preString);
- //is.addMapWord(startChar,remainingString);
- this.addWord(startChar,remainingString);
+ // is.addMapWord(startChar,remainingString);
+ this.addWord(startChar, remainingString);
return wordStart + remainingString.length();
- //hyphenation points and no inword non-letter character
- } else if (hyph != null && preString == null) {
- int index = getFinalHyphenationPoint(hyph,remainingWidth);
+ // hyphenation points and no inword non-letter character
+ } else if (hyph != null && preString == null) {
+ int index = getFinalHyphenationPoint(hyph, remainingWidth);
if (index != -1) {
remainingString.append(hyph.getPreHyphenText(index));
remainingString.append(this.hyphProps.hyphenationChar);
- //is.addMapWord(startChar,remainingString);
- this.addWord(startChar,remainingString);
- return wordStart + remainingString.length()-1;
+ // is.addMapWord(startChar,remainingString);
+ this.addWord(startChar, remainingString);
+ return wordStart + remainingString.length() - 1;
}
- //hyphenation points and a inword non letter character
+ // hyphenation points and a inword non letter character
} else if (hyph != null && preString != null) {
- int index = getFinalHyphenationPoint(hyph,remainingWidth);
+ int index = getFinalHyphenationPoint(hyph, remainingWidth);
if (index != -1) {
- remainingString.append(preString.append(hyph.getPreHyphenText(index)));
- remainingString.append(this.hyphProps.hyphenationChar);
- //is.addMapWord(startChar,remainingString);
- this.addWord(startChar,remainingString);
- return wordStart + remainingString.length()-1;
+ remainingString.append(preString.append(hyph.getPreHyphenText(index)));
+ remainingString.append(this.hyphProps.hyphenationChar);
+ // is.addMapWord(startChar,remainingString);
+ this.addWord(startChar, remainingString);
+ return wordStart + remainingString.length() - 1;
} else {
- remainingString.append(preString) ;
- //is.addMapWord(startChar,remainingString);
- this.addWord(startChar,remainingString);
- return wordStart + remainingString.length();
+ remainingString.append(preString);
+ // is.addMapWord(startChar,remainingString);
+ this.addWord(startChar, remainingString);
+ return wordStart + remainingString.length();
}
}
return wordStart;
}
- /**
- * Calculates the wordwidth of a string by first mapping the
- * characteers in the string to glyphs in the current fontstate.
- */
+ /**
+ * Calculates the wordwidth of a string by first mapping the
+ * characteers in the string to glyphs in the current fontstate.
+ */
private int getWordWidth(String word) {
return getWordWidth(word, true);
}
-
- /** calculates the wordWidth using the actual fontstate
- @param doMap if true, map the charaters in the string to glyphs in
- the current fontstate before calculating width. If false,
- assume that it's already done.
- */
- private int getWordWidth (String word, boolean doMap) {
+
+ /**
+ * calculates the wordWidth using the actual fontstate
+ * @param doMap if true, map the charaters in the string to glyphs in
+ * the current fontstate before calculating width. If false,
+ * assume that it's already done.
+ */
+ private int getWordWidth(String word, boolean doMap) {
if (word == null)
return 0;
int wordLength = word.length();
int width = 0;
- char [] characters = new char [wordLength];
- word.getChars(0,wordLength,characters,0);
+ char[] characters = new char[wordLength];
+ word.getChars(0, wordLength, characters, 0);
char currentChar;
for (int i = 0; i < wordLength; i++) {
if (doMap)
currentChar = currentFontState.mapChar(characters[i]);
else
- currentChar=characters[i];
-
+ currentChar = characters[i];
+
width += getCharWidth(currentChar);
}
return width;
}
- public int getRemainingWidth()
- {
+ public int getRemainingWidth() {
return this.getContentWidth() - this.getCurrentXPosition();
}
- public void setLinkSet(LinkSet ls)
- {
- }
+ public void setLinkSet(LinkSet ls) {}
- public void addInlineArea(Area box)
- {
+ public void addInlineArea(Area box) {
addPending();
addChild(box);
prev = TEXT;
finalWidth += box.getContentWidth();
}
- public void addInlineSpace(InlineSpace is, int spaceWidth)
- {
+ public void addInlineSpace(InlineSpace is, int spaceWidth) {
addChild(is);
finalWidth += spaceWidth;
-// spaceWidth = 0;
+ // spaceWidth = 0;
}
- /** adds a single character to the line area tree*/
- public int addCharacter (char data, LinkSet ls, boolean ul) {
+ /**
+ * adds a single character to the line area tree
+ */
+ public int addCharacter(char data, LinkSet ls, boolean ul) {
WordArea ia = null;
- int remainingWidth =
- this.getContentWidth() - this.getCurrentXPosition();
- int width = this.currentFontState.width(currentFontState.mapChar(data));
- //if it doesn't fit, return
+ int remainingWidth = this.getContentWidth()
+ - this.getCurrentXPosition();
+ int width =
+ this.currentFontState.width(currentFontState.mapChar(data));
+ // if it doesn't fit, return
if (width > remainingWidth) {
- return org.apache.fop.fo.flow.Character.DOESNOT_FIT;
+ return org.apache.fop.fo.flow.Character.DOESNOT_FIT;
} else {
- //if whitespace-collapse == true, discard character
- if (Character.isSpaceChar(data) && whiteSpaceCollapse == WhiteSpaceCollapse.TRUE) {
+ // if whitespace-collapse == true, discard character
+ if (Character.isSpaceChar(data)
+ && whiteSpaceCollapse == WhiteSpaceCollapse.TRUE) {
+ return org.apache.fop.fo.flow.Character.OK;
+ }
+ // create new InlineArea
+ ia = new WordArea(currentFontState, this.red, this.green,
+ this.blue, new Character(data).toString(),
+ width);
+ ia.setYOffset(placementOffset);
+ ia.setUnderlined(ul);
+ pendingAreas.addElement(ia);
+ if (Character.isSpaceChar(data)) {
+ this.spaceWidth = +width;
+ prev = LineArea.WHITESPACE;
+ } else {
+ pendingWidth += width;
+ prev = LineArea.TEXT;
+ }
return org.apache.fop.fo.flow.Character.OK;
- }
- //create new InlineArea
- ia = new WordArea(currentFontState,
- this.red, this.green, this.blue,
- new Character(data).toString(),width);
- ia.setYOffset(placementOffset);
- ia.setUnderlined(ul);
- pendingAreas.addElement(ia);
- if (Character.isSpaceChar(data)) {
- this.spaceWidth =+ width;
- prev = LineArea.WHITESPACE;
- } else {
- pendingWidth += width;
- prev = LineArea.TEXT;
- }
- return org.apache.fop.fo.flow.Character.OK;
}
}
- /**
- * Same as addWord except that characters in wordBuf is mapped
- * to the current fontstate's encoding
- */
- private void addMapWord (char startChar, StringBuffer wordBuf) {
- StringBuffer mapBuf = new StringBuffer (wordBuf.length());
+ /**
+ * Same as addWord except that characters in wordBuf is mapped
+ * to the current fontstate's encoding
+ */
+ private void addMapWord(char startChar, StringBuffer wordBuf) {
+ StringBuffer mapBuf = new StringBuffer(wordBuf.length());
for (int i = 0; i < wordBuf.length(); i++) {
mapBuf.append(currentFontState.mapChar(wordBuf.charAt(i)));
}
@@ -1064,45 +1091,49 @@ public class LineArea extends Area {
addWord(startChar, mapBuf);
}
- /** adds a InlineArea containing the String startChar+wordBuf to the line area children. */
- private void addWord (char startChar, StringBuffer wordBuf) {
- String word = (wordBuf != null) ? wordBuf.toString() : "";
+ /**
+ * adds a InlineArea containing the String startChar+wordBuf to the line area children.
+ */
+ private void addWord(char startChar, StringBuffer wordBuf) {
+ String word = (wordBuf != null) ? wordBuf.toString() : "";
WordArea hia;
int startCharWidth = getCharWidth(startChar);
if (isAnySpace(startChar)) {
this.addChild(new InlineSpace(startCharWidth));
} else {
- hia = new WordArea(currentFontState,
- this.red, this.green, this.blue,
- new Character(startChar).toString(),1);
+ hia = new WordArea(currentFontState, this.red, this.green,
+ this.blue,
+ new Character(startChar).toString(), 1);
hia.setYOffset(placementOffset);
this.addChild(hia);
}
int wordWidth = this.getWordWidth(word);
- hia = new WordArea(currentFontState,
- this.red, this.green, this.blue,
- word,word.length());
+ hia = new WordArea(currentFontState, this.red, this.green, this.blue,
+ word, word.length());
hia.setYOffset(placementOffset);
this.addChild(hia);
- //calculate the space needed
- finalWidth += startCharWidth + wordWidth ;
+ // calculate the space needed
+ finalWidth += startCharWidth + wordWidth;
}
- /** extracts from a hyphenated word the best (most greedy) fit */
- private int getFinalHyphenationPoint(Hyphenation hyph, int remainingWidth) {
- int [] hyphenationPoints = hyph.getHyphenationPoints();
+ /**
+ * extracts from a hyphenated word the best (most greedy) fit
+ */
+ private int getFinalHyphenationPoint(Hyphenation hyph,
+ int remainingWidth) {
+ int[] hyphenationPoints = hyph.getHyphenationPoints();
int numberOfHyphenationPoints = hyphenationPoints.length;
int index = -1;
String wordBegin = "";
int wordBeginWidth = 0;
- for (int i = 0;i < numberOfHyphenationPoints; i++){
+ for (int i = 0; i < numberOfHyphenationPoints; i++) {
wordBegin = hyph.getPreHyphenText(i);
- if (this.getWordWidth(wordBegin) > remainingWidth){
+ if (this.getWordWidth(wordBegin) > remainingWidth) {
break;
}
index = i;
@@ -1110,127 +1141,142 @@ public class LineArea extends Area {
return index;
}
- /**
- * Checks if it's legal to break a word in the middle
- * based on the current language property.
- @return true if legal to break word in the middle
- */
+ /**
+ * Checks if it's legal to break a word in the middle
+ * based on the current language property.
+ * @return true if legal to break word in the middle
+ */
private boolean canBreakMidWord() {
boolean ret = false;
- if (hyphProps != null && hyphProps.language != null &&
- !hyphProps.language.equals("NONE")) {
+ if (hyphProps != null && hyphProps.language != null
+ &&!hyphProps.language.equals("NONE")) {
String lang = hyphProps.language.toLowerCase();
- if ("zh".equals(lang) || "ja".equals(lang) ||
- "ko".equals(lang) || "vi".equals(lang))
+ if ("zh".equals(lang) || "ja".equals(lang) || "ko".equals(lang)
+ || "vi".equals(lang))
ret = true;
}
return ret;
}
- /**
- * Helper method for getting the width of a unicode char
- * from the current fontstate.
- * This also performs some guessing on widths on various
- * versions of space that might not exists in the font.
- */
+ /**
+ * Helper method for getting the width of a unicode char
+ * from the current fontstate.
+ * This also performs some guessing on widths on various
+ * versions of space that might not exists in the font.
+ */
private int getCharWidth(char c) {
- int width =
- currentFontState.width(currentFontState.mapChar(c));
+ int width = currentFontState.width(currentFontState.mapChar(c));
if (width <= 0) {
- // Estimate the width of spaces not represented in
- // the font
+ // Estimate the width of spaces not represented in
+ // the font
int em = currentFontState.width(currentFontState.mapChar('m'));
int en = currentFontState.width(currentFontState.mapChar('n'));
- if (em <= 0) em = 500*currentFontState.getFontSize();
- if (en <= 0) en = em-10;
-
- if (c == ' ') width = em;
- if (c == '\u2000') width = en;
- if (c == '\u2001') width = em;
- if (c == '\u2002') width = em/2;
- if (c == '\u2003') width = currentFontState.getFontSize();
- if (c == '\u2004') width = em/3;
- if (c == '\u2005') width = em/4;
- if (c == '\u2006') width = em/6;
- if (c == '\u2007') width = getCharWidth(' ');
- if (c == '\u2008') width = getCharWidth('.');
- if (c == '\u2009') width = em/5;
- if (c == '\u200A') width = 5;
- if (c == '\u200B') width = 100;
- if (c == '\u00A0') width = getCharWidth(' ');
- if (c == '\u202F') width = getCharWidth(' ')/2;
- if (c == '\u3000') width = getCharWidth(' ')*2;
+ if (em <= 0)
+ em = 500 * currentFontState.getFontSize();
+ if (en <= 0)
+ en = em - 10;
+
+ if (c == ' ')
+ width = em;
+ if (c == '?')
+ width = en;
+ if (c == '?')
+ width = em;
+ if (c == '?')
+ width = em / 2;
+ if (c == '?')
+ width = currentFontState.getFontSize();
+ if (c == '?')
+ width = em / 3;
+ if (c == '?')
+ width = em / 4;
+ if (c == '?')
+ width = em / 6;
+ if (c == '?')
+ width = getCharWidth(' ');
+ if (c == '?')
+ width = getCharWidth('.');
+ if (c == '?')
+ width = em / 5;
+ if (c == '?')
+ width = 5;
+ if (c == '?')
+ width = 100;
+ if (c == ' ')
+ width = getCharWidth(' ');
+ if (c == '?')
+ width = getCharWidth(' ') / 2;
+ if (c == '?')
+ width = getCharWidth(' ') * 2;
if ((c == '\n') || (c == '\r') || (c == '\t'))
width = getCharWidth(' ');
}
-
+
return width;
}
-
- /** Helper method to determine if the character is a
- space with normal behaviour. Normal behaviour means that
- it's not non-breaking
- */
+
+ /**
+ * Helper method to determine if the character is a
+ * space with normal behaviour. Normal behaviour means that
+ * it's not non-breaking
+ */
private boolean isSpace(char c) {
- if (c == ' ' ||
- c == '\u2000' || // en quad
- c == '\u2001' || // em quad
- c == '\u2002' || // en space
- c == '\u2003' || // em space
- c == '\u2004' || // three-per-em space
- c == '\u2005' || // four--per-em space
- c == '\u2006' || // six-per-em space
- c == '\u2007' || // figure space
- c == '\u2008' || // punctuation space
- c == '\u2009' || // thin space
- c == '\u200A' || // hair space
- c == '\u200B') // zero width space
+ if (c == ' ' || c == '?' || // en quad
+ c == '?' || // em quad
+ c == '?' || // en space
+ c == '?' || // em space
+ c == '?' || // three-per-em space
+ c == '?' || // four--per-em space
+ c == '?' || // six-per-em space
+ c == '?' || // figure space
+ c == '?' || // punctuation space
+ c == '?' || // thin space
+ c == '?' || // hair space
+ c == '?') // zero width space
return true;
else
return false;
}
- /** Method to determine if the character is a nonbreaking
- space.
- */
+ /**
+ * Method to determine if the character is a nonbreaking
+ * space.
+ */
private boolean isNBSP(char c) {
- if (c == '\u00A0' ||
- c == '\u202F' || // narrow no-break space
- c == '\u3000' || // ideographic space
- c == '\uFEFF') { // zero width no-break space
+ if (c == ' ' || c == '?' || // narrow no-break space
+ c == '?' || // ideographic space
+ c == '?') { // zero width no-break space
return true;
} else
return false;
}
- /**
- @return true if the character represents any kind of space
- */
+ /**
+ * @return true if the character represents any kind of space
+ */
private boolean isAnySpace(char c) {
boolean ret = (isSpace(c) || isNBSP(c));
return ret;
}
- /**
- * Add a word that might contain non-breaking spaces.
- * Split the word into WordArea and InlineSpace and add it.
- * If addToPending is true, add to pending areas.
- */
- private void addSpacedWord(String word, LinkSet ls,
- int startw, int spacew, TextState textState,
+ /**
+ * Add a word that might contain non-breaking spaces.
+ * Split the word into WordArea and InlineSpace and add it.
+ * If addToPending is true, add to pending areas.
+ */
+ private void addSpacedWord(String word, LinkSet ls, int startw,
+ int spacew, TextState textState,
boolean addToPending) {
- StringTokenizer st = new StringTokenizer(word,
- "\u00A0\u202F\u3000\uFEFF",
- true);
+ StringTokenizer st = new StringTokenizer(word, " ???", true);
int extraw = 0;
while (st.hasMoreTokens()) {
String currentWord = st.nextToken();
- if (currentWord.length() == 1 &&
- (isNBSP(currentWord.charAt(0)))) {
- // Add an InlineSpace
+ if (currentWord.length() == 1
+ && (isNBSP(currentWord.charAt(0)))) {
+ // Add an InlineSpace
int spaceWidth = getCharWidth(currentWord.charAt(0));
if (spaceWidth > 0) {
InlineSpace is = new InlineSpace(spaceWidth);
@@ -1253,8 +1299,8 @@ public class LineArea extends Area {
}
}
} else {
- WordArea ia = new WordArea(currentFontState,
- this.red, this.green, this.blue,
+ WordArea ia = new WordArea(currentFontState, this.red,
+ this.green, this.blue,
currentWord,
getWordWidth(currentWord));
ia.setYOffset(placementOffset);
@@ -1265,7 +1311,7 @@ public class LineArea extends Area {
ia.setLineThrough(textState.getLineThrough());
prevLTState = textState.getLineThrough();
ia.setVerticalAlign(vAlign);
-
+
if (addToPending) {
pendingAreas.addElement(ia);
pendingWidth += getWordWidth(currentWord);
@@ -1273,7 +1319,7 @@ public class LineArea extends Area {
addChild(ia);
}
if (ls != null) {
- Rectangle lr = new Rectangle(startw+extraw, spacew,
+ Rectangle lr = new Rectangle(startw + extraw, spacew,
ia.getContentWidth(),
fontState.getFontSize());
ls.addRect(lr, this, ia);
@@ -1281,5 +1327,6 @@ public class LineArea extends Area {
}
}
}
+
}
diff --git a/src/org/apache/fop/layout/LinkSet.java b/src/org/apache/fop/layout/LinkSet.java
index 276178053..30d58ca8d 100644
--- a/src/org/apache/fop/layout/LinkSet.java
+++ b/src/org/apache/fop/layout/LinkSet.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -13,13 +14,13 @@ import java.awt.Rectangle;
import org.apache.fop.layout.inline.InlineArea;
-import org.apache.fop.fo.properties.WrapOption; // for enumerated
+import org.apache.fop.fo.properties.WrapOption; // for enumerated
// values
// import org.apache.fop.fo.properties.WhiteSpaceCollapse; // for
// enumerated values
-import org.apache.fop.fo.properties.TextAlign; // for enumerated
+import org.apache.fop.fo.properties.TextAlign; // for enumerated
// values
-import org.apache.fop.fo.properties.TextAlignLast; // for enumerated
+import org.apache.fop.fo.properties.TextAlignLast; // for enumerated
// values
/**
@@ -28,16 +29,20 @@ import org.apache.fop.fo.properties.TextAlignLast; // for enumerated
*/
public class LinkSet {
- /** the destination of the links */
+ /**
+ * the destination of the links
+ */
String destination;
- /** the set of rectangles */
+ /**
+ * the set of rectangles
+ */
Vector rects = new Vector();
private int xoffset = 0;
private int yoffset = 0;
- /* the maximum Y offset value encountered for this LinkSet*/
+ /* the maximum Y offset value encountered for this LinkSet */
private int maxY = 0;
protected int startIndent;
@@ -47,8 +52,8 @@ public class LinkSet {
private Area area;
- public final static int INTERNAL = 0, // represents internal link
- EXTERNAL = 1; // represents external link
+ public final static int INTERNAL = 0, // represents internal link
+ EXTERNAL = 1; // represents external link
// property required for alignment adjustments
int contentRectangleWidth = 0;
@@ -59,8 +64,10 @@ public class LinkSet {
this.linkType = linkType;
}
- public void addRect(Rectangle r, LineArea lineArea, InlineArea inlineArea) {
- LinkedRectangle linkedRectangle = new LinkedRectangle(r, lineArea, inlineArea);
+ public void addRect(Rectangle r, LineArea lineArea,
+ InlineArea inlineArea) {
+ LinkedRectangle linkedRectangle = new LinkedRectangle(r, lineArea,
+ inlineArea);
linkedRectangle.setY(this.yoffset);
if (this.yoffset > maxY) {
maxY = this.yoffset;
@@ -82,14 +89,13 @@ public class LinkSet {
public void applyAreaContainerOffsets(AreaContainer ac, Area area) {
int height = area.getAbsoluteHeight();
- BlockArea ba = (BlockArea) area;
+ BlockArea ba = (BlockArea)area;
Enumeration re = rects.elements();
while (re.hasMoreElements()) {
- LinkedRectangle r = (LinkedRectangle) re.nextElement();
- r.setX(r.getX() + ac.getXPosition() +
- area.getTableCellXOffset());
- r.setY(ac.getYPosition() - height + (maxY - r.getY()) -
- ba.getHalfLeading());
+ LinkedRectangle r = (LinkedRectangle)re.nextElement();
+ r.setX(r.getX() + ac.getXPosition() + area.getTableCellXOffset());
+ r.setY(ac.getYPosition() - height + (maxY - r.getY())
+ - ba.getHalfLeading());
}
}
@@ -100,11 +106,11 @@ public class LinkSet {
return;
LinkedRectangle curRect =
- new LinkedRectangle((LinkedRectangle) rects.elementAt(0));
+ new LinkedRectangle((LinkedRectangle)rects.elementAt(0));
Vector nv = new Vector();
for (int ri = 1; ri < numRects; ri++) {
- LinkedRectangle r = (LinkedRectangle) rects.elementAt(ri);
+ LinkedRectangle r = (LinkedRectangle)rects.elementAt(ri);
// yes, I'm really happy with comparing refs...
if (r.getLineArea() == curRect.getLineArea()) {
@@ -124,10 +130,9 @@ public class LinkSet {
public void align() {
Enumeration re = rects.elements();
while (re.hasMoreElements()) {
- LinkedRectangle r = (LinkedRectangle) re.nextElement();
- r.setX(r.getX() +
- r.getLineArea().getStartIndent() +
- r.getInlineArea().getXOffset());
+ LinkedRectangle r = (LinkedRectangle)re.nextElement();
+ r.setX(r.getX() + r.getLineArea().getStartIndent()
+ + r.getInlineArea().getXOffset());
}
}
@@ -154,4 +159,5 @@ public class LinkSet {
public int getLinkType() {
return linkType;
}
+
}
diff --git a/src/org/apache/fop/layout/LinkedRectangle.java b/src/org/apache/fop/layout/LinkedRectangle.java
index b60f9fcd3..cca659596 100644
--- a/src/org/apache/fop/layout/LinkedRectangle.java
+++ b/src/org/apache/fop/layout/LinkedRectangle.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -19,81 +20,88 @@ import org.apache.fop.layout.inline.InlineArea;
*/
public class LinkedRectangle {
- /** the linked Rectangle */
+ /**
+ * the linked Rectangle
+ */
protected Rectangle link;
- /** the associated LineArea */
+ /**
+ * the associated LineArea
+ */
protected LineArea lineArea;
- /** the associated InlineArea */
+ /**
+ * the associated InlineArea
+ */
protected InlineArea inlineArea;
- public LinkedRectangle(Rectangle link, LineArea lineArea, InlineArea inlineArea) {
- this.link = link;
- this.lineArea = lineArea;
- this.inlineArea = inlineArea;
+ public LinkedRectangle(Rectangle link, LineArea lineArea,
+ InlineArea inlineArea) {
+ this.link = link;
+ this.lineArea = lineArea;
+ this.inlineArea = inlineArea;
}
-
+
public LinkedRectangle(LinkedRectangle lr) {
- this.link = new Rectangle( lr.getRectangle() );
- this.lineArea = lr.getLineArea();
- this.inlineArea = lr.getInlineArea();
+ this.link = new Rectangle(lr.getRectangle());
+ this.lineArea = lr.getLineArea();
+ this.inlineArea = lr.getInlineArea();
}
public void setRectangle(Rectangle link) {
- this.link = link;
+ this.link = link;
}
public Rectangle getRectangle() {
- return this.link;
+ return this.link;
}
public LineArea getLineArea() {
- return this.lineArea;
+ return this.lineArea;
}
-
+
public void setLineArea(LineArea lineArea) {
- this.lineArea = lineArea;
+ this.lineArea = lineArea;
}
public InlineArea getInlineArea() {
- return this.inlineArea;
+ return this.inlineArea;
}
-
+
public void setLineArea(InlineArea inlineArea) {
- this.inlineArea = inlineArea;
+ this.inlineArea = inlineArea;
}
-
+
public void setX(int x) {
- this.link.x = x;
+ this.link.x = x;
}
public void setY(int y) {
- this.link.y = y;
+ this.link.y = y;
}
public void setWidth(int width) {
- this.link.width = width;
+ this.link.width = width;
}
public void setHeight(int height) {
- this.link.height = height;
+ this.link.height = height;
}
public int getX() {
- return this.link.x;
+ return this.link.x;
}
public int getY() {
- return this.link.y;
+ return this.link.y;
}
public int getWidth() {
- return this.link.width;
+ return this.link.width;
}
public int getHeight() {
- return this.link.height;
+ return this.link.height;
}
}
diff --git a/src/org/apache/fop/layout/MarginProps.java b/src/org/apache/fop/layout/MarginProps.java
index 4b31be890..2d8bfcf32 100644
--- a/src/org/apache/fop/layout/MarginProps.java
+++ b/src/org/apache/fop/layout/MarginProps.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -11,15 +12,15 @@ package org.apache.fop.layout;
* Public "structure" allows direct member access.
*/
public class MarginProps {
- public int marginTop;
- public int marginBottom;
- public int marginLeft;
- public int marginRight;
- public int spaceBefore;
- public int spaceAfter;
- public int startIndent;
- public int endIndent;
+ public int marginTop;
+ public int marginBottom;
+ public int marginLeft;
+ public int marginRight;
+ public int spaceBefore;
+ public int spaceAfter;
+ public int startIndent;
+ public int endIndent;
+
+ public MarginProps() {}
- public MarginProps() {
- }
}
diff --git a/src/org/apache/fop/layout/Page.java b/src/org/apache/fop/layout/Page.java
index 0b837317f..c83a86bec 100644
--- a/src/org/apache/fop/layout/Page.java
+++ b/src/org/apache/fop/layout/Page.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -27,143 +28,143 @@ public class Page {
private AreaContainer after;
private AreaContainer start;
private AreaContainer end;
-
+
private AreaTree areaTree;
- private PageSequence pageSequence;
-
+ private PageSequence pageSequence;
+
protected int pageNumber = 0;
- protected String formattedPageNumber;
-
+ protected String formattedPageNumber;
+
protected Vector linkSets = new Vector();
private Vector idList = new Vector();
private Vector footnotes = null;
- private Vector markers = null;
-
+ private Vector markers = null;
+
Page(AreaTree areaTree, int height, int width) {
- this.areaTree = areaTree;
- this.height = height;
- this.width = width;
- markers = new Vector();
- }
-
- public void setPageSequence(PageSequence pageSequence) {
- this.pageSequence = pageSequence;
- }
-
- public PageSequence getPageSequence() {
- return pageSequence;
- }
-
- public AreaTree getAreaTree() {
- return areaTree;
- }
-
+ this.areaTree = areaTree;
+ this.height = height;
+ this.width = width;
+ markers = new Vector();
+ }
+
+ public void setPageSequence(PageSequence pageSequence) {
+ this.pageSequence = pageSequence;
+ }
+
+ public PageSequence getPageSequence() {
+ return pageSequence;
+ }
+
+ public AreaTree getAreaTree() {
+ return areaTree;
+ }
+
public void setNumber(int number) {
- this.pageNumber = number;
+ this.pageNumber = number;
}
public int getNumber() {
- return this.pageNumber;
+ return this.pageNumber;
+ }
+
+ public void setFormattedNumber(String number) {
+ this.formattedPageNumber = number;
}
- public void setFormattedNumber(String number) {
- this.formattedPageNumber = number;
- }
-
public String getFormattedNumber() {
- return this.formattedPageNumber;
+ return this.formattedPageNumber;
}
void addAfter(AreaContainer area) {
- this.after = area;
- area.setPage(this);
+ this.after = area;
+ area.setPage(this);
}
void addBefore(AreaContainer area) {
- this.before = area;
- area.setPage(this);
+ this.before = area;
+ area.setPage(this);
}
- /**
- * Ensure that page is set not only on B.A.C. but also on the
- * three top-level reference areas.
- * @param area The region-body area container (special)
- */
+ /**
+ * Ensure that page is set not only on B.A.C. but also on the
+ * three top-level reference areas.
+ * @param area The region-body area container (special)
+ */
public void addBody(BodyAreaContainer area) {
- this.body = area;
- area.setPage(this);
- ((BodyAreaContainer)area).getMainReferenceArea().setPage(this);
- ((BodyAreaContainer)area).getBeforeFloatReferenceArea().setPage(this);
- ((BodyAreaContainer)area).getFootnoteReferenceArea().setPage(this);
+ this.body = area;
+ area.setPage(this);
+ ((BodyAreaContainer)area).getMainReferenceArea().setPage(this);
+ ((BodyAreaContainer)area).getBeforeFloatReferenceArea().setPage(this);
+ ((BodyAreaContainer)area).getFootnoteReferenceArea().setPage(this);
}
-
+
void addEnd(AreaContainer area) {
- this.end = area;
- area.setPage(this);
+ this.end = area;
+ area.setPage(this);
}
void addStart(AreaContainer area) {
- this.start = area;
- area.setPage(this);
+ this.start = area;
+ area.setPage(this);
}
public void render(Renderer renderer) {
- renderer.renderPage(this);
+ renderer.renderPage(this);
}
public AreaContainer getAfter() {
- return this.after;
+ return this.after;
}
public AreaContainer getBefore() {
- return this.before;
+ return this.before;
}
public AreaContainer getStart() {
- return this.start;
+ return this.start;
}
public AreaContainer getEnd() {
- return this.end;
+ return this.end;
}
public BodyAreaContainer getBody() {
- return this.body;
+ return this.body;
}
public int getHeight() {
- return this.height;
+ return this.height;
}
public int getWidth() {
- return this.width;
+ return this.width;
}
public FontInfo getFontInfo() {
- return this.areaTree.getFontInfo();
+ return this.areaTree.getFontInfo();
}
public void addLinkSet(LinkSet linkSet) {
- this.linkSets.addElement(linkSet);
+ this.linkSets.addElement(linkSet);
}
public Vector getLinkSets() {
- return this.linkSets;
+ return this.linkSets;
}
public boolean hasLinks() {
- return (!this.linkSets.isEmpty());
+ return (!this.linkSets.isEmpty());
}
- public void addToIDList(String id){
+ public void addToIDList(String id) {
idList.addElement(id);
}
- public Vector getIDList(){
+ public Vector getIDList() {
return idList;
}
@@ -173,29 +174,31 @@ public class Page {
public void setPendingFootnotes(Vector v) {
footnotes = v;
- if(footnotes != null) {
- for(Enumeration e = footnotes.elements(); e.hasMoreElements(); ) {
+ if (footnotes != null) {
+ for (Enumeration e = footnotes.elements();
+ e.hasMoreElements(); ) {
FootnoteBody fb = (FootnoteBody)e.nextElement();
- if(!Footnote.layoutFootnote(this, fb, null)) {
+ if (!Footnote.layoutFootnote(this, fb, null)) {
// footnotes are too large to fit on empty page
}
}
- footnotes = null;
- }
+ footnotes = null;
+ }
}
public void addPendingFootnote(FootnoteBody fb) {
- if(footnotes == null) {
+ if (footnotes == null) {
footnotes = new Vector();
}
footnotes.addElement(fb);
}
-
- public void registerMarker(Marker marker) {
- markers.addElement(marker);
- }
-
- public Vector getMarkers() {
- return this.markers;
- }
+
+ public void registerMarker(Marker marker) {
+ markers.addElement(marker);
+ }
+
+ public Vector getMarkers() {
+ return this.markers;
+ }
+
}
diff --git a/src/org/apache/fop/layout/PageMaster.java b/src/org/apache/fop/layout/PageMaster.java
index 591fb369d..7034bf238 100644
--- a/src/org/apache/fop/layout/PageMaster.java
+++ b/src/org/apache/fop/layout/PageMaster.java
@@ -1,16 +1,17 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
-
+
package org.apache.fop.layout;
public class PageMaster {
private int width;
private int height;
-
+
private BodyRegionArea body;
private RegionArea before;
private RegionArea after;
@@ -18,56 +19,57 @@ public class PageMaster {
private RegionArea end;
public PageMaster(int pageWidth, int pageHeight) {
- this.width = pageWidth;
- this.height = pageHeight;
+ this.width = pageWidth;
+ this.height = pageHeight;
}
public void addAfter(RegionArea region) {
- this.after = region;
+ this.after = region;
}
public void addBefore(RegionArea region) {
- this.before = region;
+ this.before = region;
}
public void addBody(BodyRegionArea region) {
- this.body = region;
+ this.body = region;
}
public void addEnd(RegionArea region) {
- this.end = region;
+ this.end = region;
}
-
+
public void addStart(RegionArea region) {
- this.start = region;
+ this.start = region;
}
public int getHeight() {
- return this.height;
+ return this.height;
}
public int getWidth() {
- return this.width;
+ return this.width;
}
public Page makePage(AreaTree areaTree) {
- Page p = new Page(areaTree, this.height, this.width);
- if (this.body != null) {
- p.addBody(body.makeBodyAreaContainer());
- }
- if (this.before != null) {
- p.addBefore(before.makeAreaContainer());
- }
- if (this.after != null) {
- p.addAfter(after.makeAreaContainer());
- }
- if (this.start != null) {
- p.addStart(start.makeAreaContainer());
- }
- if (this.end != null) {
- p.addEnd(end.makeAreaContainer());
- }
-
- return p;
+ Page p = new Page(areaTree, this.height, this.width);
+ if (this.body != null) {
+ p.addBody(body.makeBodyAreaContainer());
+ }
+ if (this.before != null) {
+ p.addBefore(before.makeAreaContainer());
+ }
+ if (this.after != null) {
+ p.addAfter(after.makeAreaContainer());
+ }
+ if (this.start != null) {
+ p.addStart(start.makeAreaContainer());
+ }
+ if (this.end != null) {
+ p.addEnd(end.makeAreaContainer());
+ }
+
+ return p;
}
+
}
diff --git a/src/org/apache/fop/layout/RegionArea.java b/src/org/apache/fop/layout/RegionArea.java
index 52221d7d6..7e7465448 100644
--- a/src/org/apache/fop/layout/RegionArea.java
+++ b/src/org/apache/fop/layout/RegionArea.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -15,27 +16,31 @@ public class RegionArea {
protected int yPosition;
protected int width;
protected int height;
-
+
protected ColorType backgroundColor;
public RegionArea(int xPosition, int yPosition, int width, int height) {
- this.xPosition = xPosition;
- this.yPosition = yPosition;
- this.width = width;
- this.height = height;
+ this.xPosition = xPosition;
+ this.yPosition = yPosition;
+ this.width = width;
+ this.height = height;
}
public AreaContainer makeAreaContainer() {
- return new AreaContainer(null, xPosition, yPosition, width, height, Position.ABSOLUTE);
+ return new AreaContainer(null, xPosition, yPosition, width, height,
+ Position.ABSOLUTE);
}
public ColorType getBackgroundColor() {
- return this.backgroundColor;
+ return this.backgroundColor;
}
public void setBackgroundColor(ColorType bgColor) {
- this.backgroundColor = bgColor;
+ this.backgroundColor = bgColor;
+ }
+
+ public int getHeight() {
+ return height;
}
- public int getHeight() { return height; }
}
diff --git a/src/org/apache/fop/layout/Space.java b/src/org/apache/fop/layout/Space.java
index 8e61d9118..d49b4be4a 100644
--- a/src/org/apache/fop/layout/Space.java
+++ b/src/org/apache/fop/layout/Space.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -6,5 +7,4 @@
package org.apache.fop.layout;
-abstract public class Space extends Box {
-}
+abstract public class Space extends Box {}
diff --git a/src/org/apache/fop/layout/SpanArea.java b/src/org/apache/fop/layout/SpanArea.java
index 6cf6cd6f0..6ba58db1b 100644
--- a/src/org/apache/fop/layout/SpanArea.java
+++ b/src/org/apache/fop/layout/SpanArea.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -16,116 +17,108 @@ import java.util.Vector;
import java.util.Enumeration;
public class SpanArea extends AreaContainer {
-
- private int columnCount;
- private int currentColumn = 1;
- private int columnGap = 0;
-
- // has the area been balanced?
- private boolean isBalanced = false;
-
+
+ private int columnCount;
+ private int currentColumn = 1;
+ private int columnGap = 0;
+
+ // has the area been balanced?
+ private boolean isBalanced = false;
+
public SpanArea(FontState fontState, int xPosition, int yPosition,
- int allocationWidth, int maxHeight,
- int columnCount, int columnGap) {
- super(fontState, xPosition, yPosition, allocationWidth,
- maxHeight, Position.ABSOLUTE);
-
- this.contentRectangleWidth = allocationWidth;
- this.columnCount = columnCount;
- this.columnGap = columnGap;
-
- int columnWidth =
- (allocationWidth - columnGap*(columnCount-1)) / columnCount;
- for (int columnIndex = 0; columnIndex < columnCount; columnIndex++)
- {
- int colXPosition = (xPosition + columnIndex*(columnWidth + columnGap));
- int colYPosition = yPosition;
- ColumnArea colArea = new ColumnArea(fontState, colXPosition, colYPosition,
- columnWidth, maxHeight, columnCount);
- addChild(colArea);
- colArea.setColumnIndex(columnIndex+1);
- }
+ int allocationWidth, int maxHeight, int columnCount,
+ int columnGap) {
+ super(fontState, xPosition, yPosition, allocationWidth, maxHeight,
+ Position.ABSOLUTE);
+
+ this.contentRectangleWidth = allocationWidth;
+ this.columnCount = columnCount;
+ this.columnGap = columnGap;
+
+ int columnWidth = (allocationWidth - columnGap * (columnCount - 1))
+ / columnCount;
+ for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
+ int colXPosition = (xPosition
+ + columnIndex * (columnWidth + columnGap));
+ int colYPosition = yPosition;
+ ColumnArea colArea = new ColumnArea(fontState, colXPosition,
+ colYPosition, columnWidth,
+ maxHeight, columnCount);
+ addChild(colArea);
+ colArea.setColumnIndex(columnIndex + 1);
+ }
}
public void render(Renderer renderer) {
- renderer.renderSpanArea(this);
+ renderer.renderSpanArea(this);
}
- public void end() {
+ public void end() {}
+
+ public void start() {}
+
+ public int spaceLeft() {
+ return maxHeight - currentHeight;
}
- public void start() {
+ public int getColumnCount() {
+ return columnCount;
}
- public int spaceLeft() {
- return maxHeight - currentHeight;
+ public int getCurrentColumn() {
+ return currentColumn;
+ }
+
+ public void setCurrentColumn(int currentColumn) {
+ if (currentColumn <= columnCount)
+ this.currentColumn = currentColumn;
+ else
+ this.currentColumn = columnCount;
+ }
+
+ public AreaContainer getCurrentColumnArea() {
+ return (AreaContainer)getChildren().elementAt(currentColumn - 1);
}
-
- public int getColumnCount()
- {
- return columnCount;
- }
-
- public int getCurrentColumn()
- {
- return currentColumn;
- }
-
- public void setCurrentColumn(int currentColumn)
- {
- if (currentColumn <= columnCount)
- this.currentColumn = currentColumn;
- else
- this.currentColumn = columnCount;
- }
-
- public AreaContainer getCurrentColumnArea()
- {
- return (AreaContainer)getChildren().elementAt(currentColumn-1);
- }
-
- public boolean isBalanced()
- {
- return isBalanced;
- }
-
- public void setIsBalanced()
- {
- this.isBalanced = true;
- }
-
- public int getTotalContentHeight()
- {
- int totalContentHeight = 0;
- for (Enumeration e = getChildren().elements(); e.hasMoreElements(); )
- {
- totalContentHeight += ((AreaContainer)e.nextElement()).getContentHeight();
- }
- return totalContentHeight;
- }
-
- public int getMaxContentHeight()
- {
- int maxContentHeight = 0;
- for (Enumeration e = getChildren().elements(); e.hasMoreElements(); )
- {
- AreaContainer nextElm = (AreaContainer)e.nextElement();
- if (nextElm.getContentHeight() > maxContentHeight)
- maxContentHeight = nextElm.getContentHeight();
- }
- return maxContentHeight;
- }
-
+
+ public boolean isBalanced() {
+ return isBalanced;
+ }
+
+ public void setIsBalanced() {
+ this.isBalanced = true;
+ }
+
+ public int getTotalContentHeight() {
+ int totalContentHeight = 0;
+ for (Enumeration e = getChildren().elements();
+ e.hasMoreElements(); ) {
+ totalContentHeight +=
+ ((AreaContainer)e.nextElement()).getContentHeight();
+ }
+ return totalContentHeight;
+ }
+
+ public int getMaxContentHeight() {
+ int maxContentHeight = 0;
+ for (Enumeration e = getChildren().elements();
+ e.hasMoreElements(); ) {
+ AreaContainer nextElm = (AreaContainer)e.nextElement();
+ if (nextElm.getContentHeight() > maxContentHeight)
+ maxContentHeight = nextElm.getContentHeight();
+ }
+ return maxContentHeight;
+ }
+
public void setPage(Page page) {
- this.page = page;
- for (Enumeration e = getChildren().elements(); e.hasMoreElements(); )
- {
- ((AreaContainer)e.nextElement()).setPage(page);
- }
+ this.page = page;
+ for (Enumeration e = getChildren().elements();
+ e.hasMoreElements(); ) {
+ ((AreaContainer)e.nextElement()).setPage(page);
+ }
}
-
- public boolean isLastColumn()
- {
- return (currentColumn == columnCount);
- }
+
+ public boolean isLastColumn() {
+ return (currentColumn == columnCount);
+ }
+
}
diff --git a/src/org/apache/fop/layout/TextState.java b/src/org/apache/fop/layout/TextState.java
index 5f5c16e9e..3774facf0 100644
--- a/src/org/apache/fop/layout/TextState.java
+++ b/src/org/apache/fop/layout/TextState.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -13,31 +14,30 @@ import org.apache.fop.apps.FOPException;
*
*/
public class TextState {
-
+
protected boolean underlined;
protected boolean overlined;
protected boolean linethrough;
- public TextState() throws FOPException {
- }
+ public TextState() throws FOPException {}
/**
* @return true if text should be underlined
- */
+ */
public boolean getUnderlined() {
return underlined;
}
/**
* set text as underlined
- */
+ */
public void setUnderlined(boolean ul) {
this.underlined = ul;
}
/**
* @return true if text should be overlined
- */
+ */
public boolean getOverlined() {
return overlined;
}
diff --git a/src/org/apache/fop/layout/hyphenation/ByteVector.java b/src/org/apache/fop/layout/hyphenation/ByteVector.java
index a617ce920..66ce5fa9b 100644
--- a/src/org/apache/fop/layout/hyphenation/ByteVector.java
+++ b/src/org/apache/fop/layout/hyphenation/ByteVector.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -14,100 +15,99 @@ import java.io.Serializable;
*
* @author Carlos Villegas
*/
-public class ByteVector implements Serializable
-{
- /** Capacity increment size */
- private final static int DEFAULT_BLOCK_SIZE=2048;
- private int BLOCK_SIZE;
-
- /** The encapsulated array */
- private byte[] array;
-
- /** Points to next free item */
- private int n;
-
- public ByteVector()
- {
- this(DEFAULT_BLOCK_SIZE);
- }
-
- public ByteVector(int capacity)
- {
- if ( capacity > 0 )
+public class ByteVector implements Serializable {
+
+ /**
+ * Capacity increment size
+ */
+ private final static int DEFAULT_BLOCK_SIZE = 2048;
+ private int BLOCK_SIZE;
+
+ /**
+ * The encapsulated array
+ */
+ private byte[] array;
+
+ /**
+ * Points to next free item
+ */
+ private int n;
+
+ public ByteVector() {
+ this(DEFAULT_BLOCK_SIZE);
+ }
+
+ public ByteVector(int capacity) {
+ if (capacity > 0)
BLOCK_SIZE = capacity;
- else
+ else
BLOCK_SIZE = DEFAULT_BLOCK_SIZE;
- array = new byte[BLOCK_SIZE];
- n = 0;
- }
-
- public ByteVector(byte[] a)
- {
- BLOCK_SIZE = DEFAULT_BLOCK_SIZE;
- array = a;
- n = 0;
- }
-
- public ByteVector(byte[] a, int capacity)
- {
- if ( capacity > 0 )
+ array = new byte[BLOCK_SIZE];
+ n = 0;
+ }
+
+ public ByteVector(byte[] a) {
+ BLOCK_SIZE = DEFAULT_BLOCK_SIZE;
+ array = a;
+ n = 0;
+ }
+
+ public ByteVector(byte[] a, int capacity) {
+ if (capacity > 0)
BLOCK_SIZE = capacity;
- else
+ else
BLOCK_SIZE = DEFAULT_BLOCK_SIZE;
- array = a;
- n = 0;
- }
-
- public byte[] getArray()
- {
- return array;
- }
-
- /** return number of items in array */
- public int length()
- {
- return n;
- }
-
- /** returns current capacity of array */
- public int capacity()
- {
- return array.length;
- }
-
- public void put(int index, byte val)
- {
- array[index] = val;
- }
-
- public byte get(int index)
- {
- return array[index];
- }
-
- /**
- * This is to implement memory allocation in the array. Like malloc().
- */
- public int alloc(int size)
- {
- int index = n;
- int len = array.length;
- if ( n+size >= len ) {
- byte[] aux = new byte[len+BLOCK_SIZE];
+ array = a;
+ n = 0;
+ }
+
+ public byte[] getArray() {
+ return array;
+ }
+
+ /**
+ * return number of items in array
+ */
+ public int length() {
+ return n;
+ }
+
+ /**
+ * returns current capacity of array
+ */
+ public int capacity() {
+ return array.length;
+ }
+
+ public void put(int index, byte val) {
+ array[index] = val;
+ }
+
+ public byte get(int index) {
+ return array[index];
+ }
+
+ /**
+ * This is to implement memory allocation in the array. Like malloc().
+ */
+ public int alloc(int size) {
+ int index = n;
+ int len = array.length;
+ if (n + size >= len) {
+ byte[] aux = new byte[len + BLOCK_SIZE];
System.arraycopy(array, 0, aux, 0, len);
array = aux;
- }
- n += size;
- return index;
- }
-
- public void trimToSize()
- {
- if ( n < array.length ) {
+ }
+ n += size;
+ return index;
+ }
+
+ public void trimToSize() {
+ if (n < array.length) {
byte[] aux = new byte[n];
System.arraycopy(array, 0, aux, 0, n);
array = aux;
- }
- }
-
+ }
+ }
+
}
diff --git a/src/org/apache/fop/layout/hyphenation/CharVector.java b/src/org/apache/fop/layout/hyphenation/CharVector.java
index 551adf094..e2993a0b6 100644
--- a/src/org/apache/fop/layout/hyphenation/CharVector.java
+++ b/src/org/apache/fop/layout/hyphenation/CharVector.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -14,110 +15,109 @@ import java.io.Serializable;
*
* @author Carlos Villegas
*/
-public class CharVector implements Cloneable, Serializable
-
-{
- /** Capacity increment size */
- private final static int DEFAULT_BLOCK_SIZE=2048;
- private int BLOCK_SIZE;
-
- /** The encapsulated array */
- private char[] array;
-
- /** Points to next free item */
- private int n;
-
- public CharVector()
- {
- this(DEFAULT_BLOCK_SIZE);
- }
-
- public CharVector(int capacity)
- {
- if ( capacity > 0 )
+public class CharVector implements Cloneable, Serializable {
+
+ /**
+ * Capacity increment size
+ */
+ private final static int DEFAULT_BLOCK_SIZE = 2048;
+ private int BLOCK_SIZE;
+
+ /**
+ * The encapsulated array
+ */
+ private char[] array;
+
+ /**
+ * Points to next free item
+ */
+ private int n;
+
+ public CharVector() {
+ this(DEFAULT_BLOCK_SIZE);
+ }
+
+ public CharVector(int capacity) {
+ if (capacity > 0)
BLOCK_SIZE = capacity;
- else
+ else
BLOCK_SIZE = DEFAULT_BLOCK_SIZE;
- array = new char[BLOCK_SIZE];
- n = 0;
- }
-
- public CharVector(char[] a)
- {
- BLOCK_SIZE = DEFAULT_BLOCK_SIZE;
- array = a;
- n = a.length;
- }
-
- public CharVector(char[] a, int capacity)
- {
- if ( capacity > 0 )
+ array = new char[BLOCK_SIZE];
+ n = 0;
+ }
+
+ public CharVector(char[] a) {
+ BLOCK_SIZE = DEFAULT_BLOCK_SIZE;
+ array = a;
+ n = a.length;
+ }
+
+ public CharVector(char[] a, int capacity) {
+ if (capacity > 0)
BLOCK_SIZE = capacity;
- else
+ else
BLOCK_SIZE = DEFAULT_BLOCK_SIZE;
- array = a;
- n = a.length;
- }
-
- /** Reset Vector but don't resize or clear elements */
- public void clear()
- {
- n = 0;
- }
-
- public Object clone()
- {
- CharVector cv = new CharVector((char[])array.clone(), BLOCK_SIZE);
- cv.n = this.n;
- return cv;
- }
-
- public char[] getArray()
- {
- return array;
- }
-
- /** return number of items in array */
- public int length()
- {
- return n;
- }
-
- /** returns current capacity of array */
- public int capacity()
- {
- return array.length;
- }
-
- public void put(int index, char val)
- {
- array[index] = val;
- }
-
- public char get(int index)
- {
- return array[index];
- }
-
- public int alloc(int size)
- {
- int index = n;
- int len = array.length;
- if ( n+size >= len ) {
- char[] aux = new char[len+BLOCK_SIZE];
+ array = a;
+ n = a.length;
+ }
+
+ /**
+ * Reset Vector but don't resize or clear elements
+ */
+ public void clear() {
+ n = 0;
+ }
+
+ public Object clone() {
+ CharVector cv = new CharVector((char[])array.clone(), BLOCK_SIZE);
+ cv.n = this.n;
+ return cv;
+ }
+
+ public char[] getArray() {
+ return array;
+ }
+
+ /**
+ * return number of items in array
+ */
+ public int length() {
+ return n;
+ }
+
+ /**
+ * returns current capacity of array
+ */
+ public int capacity() {
+ return array.length;
+ }
+
+ public void put(int index, char val) {
+ array[index] = val;
+ }
+
+ public char get(int index) {
+ return array[index];
+ }
+
+ public int alloc(int size) {
+ int index = n;
+ int len = array.length;
+ if (n + size >= len) {
+ char[] aux = new char[len + BLOCK_SIZE];
System.arraycopy(array, 0, aux, 0, len);
array = aux;
- }
- n += size;
- return index;
- }
-
- public void trimToSize()
- {
- if ( n < array.length ) {
+ }
+ n += size;
+ return index;
+ }
+
+ public void trimToSize() {
+ if (n < array.length) {
char[] aux = new char[n];
System.arraycopy(array, 0, aux, 0, n);
array = aux;
- }
- }
+ }
+ }
+
}
diff --git a/src/org/apache/fop/layout/hyphenation/Hyphen.java b/src/org/apache/fop/layout/hyphenation/Hyphen.java
index fdfed8b88..d93c3dd85 100644
--- a/src/org/apache/fop/layout/hyphenation/Hyphen.java
+++ b/src/org/apache/fop/layout/hyphenation/Hyphen.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -21,37 +22,35 @@ import java.io.Serializable;
* @author Carlos Villegas
*/
-public class Hyphen implements Serializable
-{
- public String preBreak;
- public String noBreak;
- public String postBreak;
-
- Hyphen(String pre, String no, String post)
- {
- preBreak = pre;
- noBreak = no;
- postBreak = post;
- }
-
- Hyphen(String pre)
- {
- preBreak = pre;
- noBreak = null;
- postBreak = null;
- }
-
- public String toString()
- {
- if ( noBreak == null && postBreak == null && preBreak != null && preBreak.equals("-") )
+public class Hyphen implements Serializable {
+ public String preBreak;
+ public String noBreak;
+ public String postBreak;
+
+ Hyphen(String pre, String no, String post) {
+ preBreak = pre;
+ noBreak = no;
+ postBreak = post;
+ }
+
+ Hyphen(String pre) {
+ preBreak = pre;
+ noBreak = null;
+ postBreak = null;
+ }
+
+ public String toString() {
+ if (noBreak == null && postBreak == null && preBreak != null
+ && preBreak.equals("-"))
return "-";
- StringBuffer res = new StringBuffer("{");
- res.append(preBreak);
- res.append("}{");
- res.append(postBreak);
- res.append("}{");
- res.append(noBreak);
- res.append('}');
- return res.toString();
- }
+ StringBuffer res = new StringBuffer("{");
+ res.append(preBreak);
+ res.append("}{");
+ res.append(postBreak);
+ res.append("}{");
+ res.append(noBreak);
+ res.append('}');
+ return res.toString();
+ }
+
}
diff --git a/src/org/apache/fop/layout/hyphenation/Hyphenation.java b/src/org/apache/fop/layout/hyphenation/Hyphenation.java
index 1685eddf2..016091a4c 100644
--- a/src/org/apache/fop/layout/hyphenation/Hyphenation.java
+++ b/src/org/apache/fop/layout/hyphenation/Hyphenation.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -17,34 +18,46 @@ public class Hyphenation {
int[] hyphenPoints;
String word;
- /** number of hyphenation points in word */
+ /**
+ * number of hyphenation points in word
+ */
int len;
- /** rawWord as made of alternating strings and {@link Hyphen Hyphen}
- * instances */
+ /**
+ * rawWord as made of alternating strings and {@link Hyphen Hyphen}
+ * instances
+ */
Hyphenation(String word, int[] points) {
this.word = word;
hyphenPoints = points;
len = points.length;
}
- /** @return the number of hyphenation points in the word */
+ /**
+ * @return the number of hyphenation points in the word
+ */
public int length() {
return len;
}
- /** @return the pre-break text, not including the hyphen character */
+ /**
+ * @return the pre-break text, not including the hyphen character
+ */
public String getPreHyphenText(int index) {
return word.substring(0, hyphenPoints[index]);
}
- /** @return the post-break text */
+ /**
+ * @return the post-break text
+ */
public String getPostHyphenText(int index) {
return word.substring(hyphenPoints[index]);
}
- /** @return the hyphenation points */
- public int [] getHyphenationPoints() {
+ /**
+ * @return the hyphenation points
+ */
+ public int[] getHyphenationPoints() {
return hyphenPoints;
}
@@ -58,4 +71,5 @@ public class Hyphenation {
str.append(word.substring(start));
return str.toString();
}
+
}
diff --git a/src/org/apache/fop/layout/hyphenation/HyphenationException.java b/src/org/apache/fop/layout/hyphenation/HyphenationException.java
index 1457b3033..442673512 100644
--- a/src/org/apache/fop/layout/hyphenation/HyphenationException.java
+++ b/src/org/apache/fop/layout/hyphenation/HyphenationException.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -11,8 +12,8 @@ package org.apache.fop.layout.hyphenation;
*/
public class HyphenationException extends Exception {
- public HyphenationException(String msg)
- {
- super(msg);
- }
+ public HyphenationException(String msg) {
+ super(msg);
+ }
+
}
diff --git a/src/org/apache/fop/layout/hyphenation/HyphenationTree.java b/src/org/apache/fop/layout/hyphenation/HyphenationTree.java
index 0145e9469..d2c0f16bf 100644
--- a/src/org/apache/fop/layout/hyphenation/HyphenationTree.java
+++ b/src/org/apache/fop/layout/hyphenation/HyphenationTree.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -17,472 +18,478 @@ import java.util.Hashtable;
*
* @author Carlos Villegas
*/
-public class HyphenationTree extends TernaryTree
- implements PatternConsumer, Serializable
-{
-
- /** value space: stores the inteletter values */
- protected ByteVector vspace;
- /** This map stores hyphenation exceptions */
- protected Hashtable stoplist;
- /** This map stores the character classes */
- protected TernaryTree classmap;
- /** Temporary map to store interletter values on pattern loading. */
- private transient TernaryTree ivalues;
-
- public HyphenationTree()
- {
- stoplist = new Hashtable(23); // usually a small table
- classmap = new TernaryTree();
- vspace = new ByteVector();
- vspace.alloc(1); // this reserves index 0, which we don't use
- }
-
- /**
- * Packs the values by storing them in 4 bits, two values into a byte
- * Values range is from 0 to 9. We use zero as terminator,
- * so we'll add 1 to the value.
- * @param values a string of digits from '0' to '9' representing the
- * interletter values.
- * @return the index into the vspace array where the packed values
- * are stored.
- */
- protected int packValues(String values)
- {
- int i, n = values.length();
- int m = (n & 1) == 1 ? (n>>1)+2 : (n>>1)+1;
- int offset = vspace.alloc(m);
- byte[] va = vspace.getArray();
- for(i=0; i>1;
+public class HyphenationTree extends TernaryTree implements PatternConsumer,
+ Serializable {
+
+ /**
+ * value space: stores the inteletter values
+ */
+ protected ByteVector vspace;
+
+ /**
+ * This map stores hyphenation exceptions
+ */
+ protected Hashtable stoplist;
+
+ /**
+ * This map stores the character classes
+ */
+ protected TernaryTree classmap;
+
+ /**
+ * Temporary map to store interletter values on pattern loading.
+ */
+ private transient TernaryTree ivalues;
+
+ public HyphenationTree() {
+ stoplist = new Hashtable(23); // usually a small table
+ classmap = new TernaryTree();
+ vspace = new ByteVector();
+ vspace.alloc(1); // this reserves index 0, which we don't use
+ }
+
+ /**
+ * Packs the values by storing them in 4 bits, two values into a byte
+ * Values range is from 0 to 9. We use zero as terminator,
+ * so we'll add 1 to the value.
+ * @param values a string of digits from '0' to '9' representing the
+ * interletter values.
+ * @return the index into the vspace array where the packed values
+ * are stored.
+ */
+ protected int packValues(String values) {
+ int i, n = values.length();
+ int m = (n & 1) == 1 ? (n >> 1) + 2 : (n >> 1) + 1;
+ int offset = vspace.alloc(m);
+ byte[] va = vspace.getArray();
+ for (i = 0; i < n; i++) {
+ int j = i >> 1;
byte v = (byte)((values.charAt(i) - '0' + 1) & 0x0f);
- if ( (i&1) == 1 )
- va[j+offset] = (byte)( va[j+offset] | v );
+ if ((i & 1) == 1)
+ va[j + offset] = (byte)(va[j + offset] | v);
else
- va[j+offset] = (byte)(v << 4); // big endian
- }
- va[m-1+offset] = 0; // terminator
- return offset;
- }
-
- protected String unpackValues(int k)
- {
- StringBuffer buf = new StringBuffer();
- byte v = vspace.get(k++);
- while( v != 0 ) {
- char c = (char)((v >>> 4) -1 + '0');
+ va[j + offset] = (byte)(v << 4); // big endian
+ }
+ va[m - 1 + offset] = 0; // terminator
+ return offset;
+ }
+
+ protected String unpackValues(int k) {
+ StringBuffer buf = new StringBuffer();
+ byte v = vspace.get(k++);
+ while (v != 0) {
+ char c = (char)((v >>> 4) - 1 + '0');
buf.append(c);
c = (char)(v & 0x0f);
- if ( c == 0 ) break;
+ if (c == 0)
+ break;
c = (char)(c - 1 + '0');
buf.append(c);
v = vspace.get(k++);
- }
- return buf.toString();
- }
-
- /**
- * Read hyphenation patterns from an XML file.
- */
- public void loadPatterns(String filename)
- throws HyphenationException
- {
- PatternParser pp = new PatternParser(this);
- ivalues = new TernaryTree();
-
- pp.parse(filename);
-
- // patterns/values should be now in the tree
- // let's optimize a bit
- trimToSize();
- vspace.trimToSize();
- classmap.trimToSize();
-
- // get rid of the auxiliary map
- ivalues = null;
- }
-
- public String findPattern(String pat)
- {
- int k = super.find(pat);
- if ( k >= 0 )
+ }
+ return buf.toString();
+ }
+
+ /**
+ * Read hyphenation patterns from an XML file.
+ */
+ public void loadPatterns(String filename) throws HyphenationException {
+ PatternParser pp = new PatternParser(this);
+ ivalues = new TernaryTree();
+
+ pp.parse(filename);
+
+ // patterns/values should be now in the tree
+ // let's optimize a bit
+ trimToSize();
+ vspace.trimToSize();
+ classmap.trimToSize();
+
+ // get rid of the auxiliary map
+ ivalues = null;
+ }
+
+ public String findPattern(String pat) {
+ int k = super.find(pat);
+ if (k >= 0)
return unpackValues(k);
- return "";
- }
-
- /**
- * String compare, returns 0 if equal or
- * t is a substring of s
- */
- protected int hstrcmp(char[] s, int si, char[] t, int ti)
- {
- for ( ; s[si] == t[ti]; si++, ti++)
+ return "";
+ }
+
+ /**
+ * String compare, returns 0 if equal or
+ * t is a substring of s
+ */
+ protected int hstrcmp(char[] s, int si, char[] t, int ti) {
+ for (; s[si] == t[ti]; si++, ti++)
if (s[si] == 0)
- return 0;
- if ( t[ti] == 0 )
+ return 0;
+ if (t[ti] == 0)
return 0;
- return s[si] - t[ti];
- }
-
- protected byte[] getValues(int k)
- {
- StringBuffer buf = new StringBuffer();
- byte v = vspace.get(k++);
- while( v != 0 ) {
+ return s[si] - t[ti];
+ }
+
+ protected byte[] getValues(int k) {
+ StringBuffer buf = new StringBuffer();
+ byte v = vspace.get(k++);
+ while (v != 0) {
char c = (char)((v >>> 4) - 1);
buf.append(c);
c = (char)(v & 0x0f);
- if ( c == 0 ) break;
+ if (c == 0)
+ break;
c = (char)(c - 1);
buf.append(c);
v = vspace.get(k++);
- }
- byte[] res = new byte[buf.length()];
- for(int i=0;iSearch for all possible partial matches of word starting
- * at index an update interletter values. In other words, it
- * does something like:
- *
- * for(i=0; i
- * But it is done in an efficient way since the patterns are
- * stored in a ternary tree. In fact, this is the whole purpose
- * of having the tree: doing this search without having to test
- * every single pattern. The number of patterns for languages
- * such as English range from 4000 to 10000. Thus, doing thousands
- * of string comparisons for each word to hyphenate would be
- * really slow without the tree. The tradeoff is memory, but
- * using a ternary tree instead of a trie, almost halves the
- * the memory used by Lout or TeX. It's also faster than using
- * a hash table
- * @param word null terminated word to match
- * @param index start index from word
- * @param il interletter values array to update
- */
- protected void searchPatterns(char[] word, int index, byte[] il)
- {
- byte[] values;
- int i=index;
- char p, q;
- char sp = word[i];
- p = root;
-
- while( p > 0 && p < sc.length){
+ return res;
+ }
+
+ /**
+ * Search for all possible partial matches of word starting
+ * at index an update interletter values. In other words, it
+ * does something like:
+ *
+ * for(i=0; i
+ * But it is done in an efficient way since the patterns are
+ * stored in a ternary tree. In fact, this is the whole purpose
+ * of having the tree: doing this search without having to test
+ * every single pattern. The number of patterns for languages
+ * such as English range from 4000 to 10000. Thus, doing thousands
+ * of string comparisons for each word to hyphenate would be
+ * really slow without the tree. The tradeoff is memory, but
+ * using a ternary tree instead of a trie, almost halves the
+ * the memory used by Lout or TeX. It's also faster than using
+ * a hash table
+ * @param word null terminated word to match
+ * @param index start index from word
+ * @param il interletter values array to update
+ */
+ protected void searchPatterns(char[] word, int index, byte[] il) {
+ byte[] values;
+ int i = index;
+ char p, q;
+ char sp = word[i];
+ p = root;
+
+ while (p > 0 && p < sc.length) {
if (sc[p] == 0xFFFF) {
- if ( hstrcmp(word, i, kv.getArray(), lo[p]) == 0 ) {
- values = getValues(eq[p]); // data pointer is in eq[]
- int j=index;
- for(int k=0; k il[j] )
- il[j] = values[k];
- j++;
- }
- }
- return;
+ if (hstrcmp(word, i, kv.getArray(), lo[p]) == 0) {
+ values = getValues(eq[p]); // data pointer is in eq[]
+ int j = index;
+ for (int k = 0; k < values.length; k++) {
+ if (j < il.length && values[k] > il[j])
+ il[j] = values[k];
+ j++;
+ }
+ }
+ return;
}
int d = sp - sc[p];
- if ( d == 0 ) {
- if ( sp == 0 ) {
+ if (d == 0) {
+ if (sp == 0) {
break;
}
- sp = word[++i];
- p = eq[p];
- q = p;
-
- // look for a pattern ending at this position by searching for
- // the null char ( splitchar == 0 )
- while ( q > 0 && q < sc.length ) {
- if ( sc[q] == 0xFFFF ) {// stop at compressed branch
- break;
- }
- if ( sc[q] == 0 ) {
- values = getValues(eq[q]);
- int j=index;
- for(int k=0; k il[j] ) {
- il[j] = values[k];
- }
- j++;
- }
- break;
- } else {
- q = lo[q];
- /** actually the code should be:
- q = sc[q] < 0 ? hi[q] : lo[q];
- but java chars are unsigned
- */
- }
- }
+ sp = word[++i];
+ p = eq[p];
+ q = p;
+
+ // look for a pattern ending at this position by searching for
+ // the null char ( splitchar == 0 )
+ while (q > 0 && q < sc.length) {
+ if (sc[q] == 0xFFFF) { // stop at compressed branch
+ break;
+ }
+ if (sc[q] == 0) {
+ values = getValues(eq[q]);
+ int j = index;
+ for (int k = 0; k < values.length; k++) {
+ if (j < il.length && values[k] > il[j]) {
+ il[j] = values[k];
+ }
+ j++;
+ }
+ break;
+ } else {
+ q = lo[q];
+
+ /**
+ * actually the code should be:
+ * q = sc[q] < 0 ? hi[q] : lo[q];
+ * but java chars are unsigned
+ */
+ }
+ }
} else
- p = d < 0 ? lo[p] : hi[p];
- }
- }
-
- /**
- * Hyphenate word and return a Hyphenation object.
- * @param word the word to be hyphenated
- * @param remainCharCount Minimum number of characters allowed
- * before the hyphenation point.
- * @param pushCharCount Minimum number of characters allowed after
- * the hyphenation point.
- * @return a {@link Hyphenation Hyphenation} object representing
- * the hyphenated word or null if word is not hyphenated.
- */
- public Hyphenation hyphenate(String word, int remainCharCount, int pushCharCount)
- {
- char[] w = word.toCharArray();
- return hyphenate(w, 0, w.length, remainCharCount, pushCharCount);
- }
-
- /**
- * Hyphenate word and return an array of hyphenation points.
- * @param w char array that contains the word
- * @param offset Offset to first character in word
- * @param len Length of word
- * @param remainCharCount Minimum number of characters allowed
- * before the hyphenation point.
- * @param pushCharCount Minimum number of characters allowed after
- * the hyphenation point.
- * @return a {@link Hyphenation Hyphenation} object representing
- * the hyphenated word or null if word is not hyphenated.
- */
- public Hyphenation hyphenate(char[] w, int offset, int len,
- int remainCharCount, int pushCharCount)
- {
- int i;
- char[] word = new char[len+3];
-
- // normalize word
- char[] c = new char[2];
- for(i=1; i<=len; i++) {
- c[0] = w[offset+i-1];
- int nc = classmap.find(c,0);
- if ( nc < 0 ) { // found a non-letter character, abort
- return null;
+ p = d < 0 ? lo[p] : hi[p];
+ }
+ }
+
+ /**
+ * Hyphenate word and return a Hyphenation object.
+ * @param word the word to be hyphenated
+ * @param remainCharCount Minimum number of characters allowed
+ * before the hyphenation point.
+ * @param pushCharCount Minimum number of characters allowed after
+ * the hyphenation point.
+ * @return a {@link Hyphenation Hyphenation} object representing
+ * the hyphenated word or null if word is not hyphenated.
+ */
+ public Hyphenation hyphenate(String word, int remainCharCount,
+ int pushCharCount) {
+ char[] w = word.toCharArray();
+ return hyphenate(w, 0, w.length, remainCharCount, pushCharCount);
+ }
+
+ /**
+ * Hyphenate word and return an array of hyphenation points.
+ * @param w char array that contains the word
+ * @param offset Offset to first character in word
+ * @param len Length of word
+ * @param remainCharCount Minimum number of characters allowed
+ * before the hyphenation point.
+ * @param pushCharCount Minimum number of characters allowed after
+ * the hyphenation point.
+ * @return a {@link Hyphenation Hyphenation} object representing
+ * the hyphenated word or null if word is not hyphenated.
+ */
+ public Hyphenation hyphenate(char[] w, int offset, int len,
+ int remainCharCount, int pushCharCount) {
+ int i;
+ char[] word = new char[len + 3];
+
+ // normalize word
+ char[] c = new char[2];
+ for (i = 1; i <= len; i++) {
+ c[0] = w[offset + i - 1];
+ int nc = classmap.find(c, 0);
+ if (nc < 0) { // found a non-letter character, abort
+ return null;
}
word[i] = (char)nc;
- }
- int[] result = new int[len+1];
- int k=0;
+ }
+ int[] result = new int[len + 1];
+ int k = 0;
- // check exception list first
- String sw = new String(word,1,len);
- if ( stoplist.containsKey(sw) ) {
+ // check exception list first
+ String sw = new String(word, 1, len);
+ if (stoplist.containsKey(sw)) {
// assume only simple hyphens (Hyphen.pre="-", Hyphen.post = Hyphen.no = null)
Vector hw = (Vector)stoplist.get(sw);
int j = 0;
- for(i=0; i= remainCharCount && j < (len - pushCharCount) )
- result[k++] = j;
- }
+ for (i = 0; i < hw.size(); i++) {
+ Object o = hw.elementAt(i);
+ if (o instanceof String) {
+ j += ((String)o).length();
+ if (j >= remainCharCount && j < (len - pushCharCount))
+ result[k++] = j;
+ }
}
- } else {
+ } else {
// use algorithm to get hyphenation points
- word[0] = '.'; // word start marker
- word[len+1] = '.'; // word end marker
- word[len+2] = 0; // null terminated
- byte[] il = new byte[len+3]; // initialized to zero
- for(i=0; i= remainCharCount
- && i < (len-pushCharCount) ) {
- result[k++] = i;
- }
+ for (i = 0; i < len; i++) {
+ if (((il[i + 1] & 1) == 1) && i >= remainCharCount
+ && i < (len - pushCharCount)) {
+ result[k++] = i;
+ }
}
- }
-
+ }
+
- if ( k > 0 ) {
+ if (k > 0) {
// trim result array
int[] res = new int[k];
System.arraycopy(result, 0, res, 0, k);
- return new Hyphenation(new String(w,offset,len), res);
- } else {
+ return new Hyphenation(new String(w, offset, len), res);
+ } else {
return null;
- }
- }
-
- /**
- * Add a character class to the tree. It is used by
- * {@link PatternParser PatternParser} as callback to
- * add character classes. Character classes define the
- * valid word characters for hyphenation. If a word contains
- * a character not defined in any of the classes, it is not hyphenated.
- * It also defines a way to normalize the characters in order
- * to compare them with the stored patterns. Usually pattern
- * files use only lower case characters, in this case a class
- * for letter 'a', for example, should be defined as "aA", the first
- * character being the normalization char.
- */
- public void addClass(String chargroup)
- {
- if ( chargroup.length() > 0 ) {
+ }
+ }
+
+ /**
+ * Add a character class to the tree. It is used by
+ * {@link PatternParser PatternParser} as callback to
+ * add character classes. Character classes define the
+ * valid word characters for hyphenation. If a word contains
+ * a character not defined in any of the classes, it is not hyphenated.
+ * It also defines a way to normalize the characters in order
+ * to compare them with the stored patterns. Usually pattern
+ * files use only lower case characters, in this case a class
+ * for letter 'a', for example, should be defined as "aA", the first
+ * character being the normalization char.
+ */
+ public void addClass(String chargroup) {
+ if (chargroup.length() > 0) {
char equivChar = chargroup.charAt(0);
char[] key = new char[2];
key[1] = 0;
- for(int i=0; i 0 && path.charAt(0) != '/')
- path = '/' + path;
- try {
- return new InputSource(new URL("file", null, path).toString());
- }
- catch (java.net.MalformedURLException e) {
- throw new HyphenationException("unexpected MalformedURLException");
- }
- }
-
- protected String readToken(StringBuffer chars)
- {
- String word;
- boolean space = false;
- int i;
- for(i=0; i 0 && path.charAt(0) != '/')
+ path = '/' + path;
+ try {
+ return new InputSource(new URL("file", null, path).toString());
+ } catch (java.net.MalformedURLException e) {
+ throw new HyphenationException("unexpected MalformedURLException");
+ }
+ }
+
+ protected String readToken(StringBuffer chars) {
+ String word;
+ boolean space = false;
+ int i;
+ for (i = 0; i < chars.length(); i++)
+ if (Character.isWhitespace(chars.charAt(i)))
+ space = true;
else
- break;
- if ( space ) {
- //chars.delete(0,i);
- for ( int countr = i ; countr < chars.length() ; countr++ )
- chars.setCharAt(countr - i, chars.charAt(countr));
- chars.setLength(chars.length() - i);
- if ( token.length() > 0 ) {
- word = token.toString();
- token.setLength(0);
- return word;
+ break;
+ if (space) {
+ // chars.delete(0,i);
+ for (int countr = i; countr < chars.length(); countr++)
+ chars.setCharAt(countr - i, chars.charAt(countr));
+ chars.setLength(chars.length() - i);
+ if (token.length() > 0) {
+ word = token.toString();
+ token.setLength(0);
+ return word;
}
- }
- space = false;
- for(i=0; i 0 )
- res.addElement(buf.toString());
+ if (item instanceof String) {
+ String str = (String)item;
+ StringBuffer buf = new StringBuffer();
+ for (int j = 0; j < str.length(); j++) {
+ char c = str.charAt(j);
+ if (c != hyphenChar)
+ buf.append(c);
+ else {
+ res.addElement(buf.toString());
+ buf.setLength(0);
+ char[] h = new char[1];
+ h[0] = hyphenChar;
+ // we use here hyphenChar which is not necessarily
+ // the one to be printed
+ res.addElement(new Hyphen(new String(h), null, null));
+ }
+ }
+ if (buf.length() > 0)
+ res.addElement(buf.toString());
} else
- res.addElement(item);
- }
- return res;
- }
-
- protected String getExceptionWord(Vector ex)
- {
- StringBuffer res = new StringBuffer();
- for(int i=0; i 0 ) {
- exception.addElement(token.toString());
+ } else if (local.equals("hyphen")) {
+ if (token.length() > 0) {
+ exception.addElement(token.toString());
}
exception.addElement(new Hyphen(attrs.getValue("pre"),
attrs.getValue("no"),
attrs.getValue("post")));
currElement = ELEM_HYPHEN;
- }
- token.setLength(0);
- }
+ }
+ token.setLength(0);
+ }
- public void endElement(String uri, String local, String raw)
- {
+ public void endElement(String uri, String local, String raw) {
- if ( token.length() > 0 ) {
+ if (token.length() > 0) {
String word = token.toString();
- switch ( currElement ) {
- case ELEM_CLASSES:
- consumer.addClass(word);
- break;
- case ELEM_EXCEPTIONS:
- exception.addElement(word);
- exception = normalizeException(exception);
- consumer.addException(getExceptionWord(exception),
- (Vector)exception.clone());
- break;
- case ELEM_PATTERNS:
- consumer.addPattern(getPattern(word), getInterletterValues(word));
- break;
- case ELEM_HYPHEN:
- // nothing to do
- break;
+ switch (currElement) {
+ case ELEM_CLASSES:
+ consumer.addClass(word);
+ break;
+ case ELEM_EXCEPTIONS:
+ exception.addElement(word);
+ exception = normalizeException(exception);
+ consumer.addException(getExceptionWord(exception),
+ (Vector)exception.clone());
+ break;
+ case ELEM_PATTERNS:
+ consumer.addPattern(getPattern(word),
+ getInterletterValues(word));
+ break;
+ case ELEM_HYPHEN:
+ // nothing to do
+ break;
}
- if ( currElement != ELEM_HYPHEN )
- token.setLength(0);
- }
- if ( currElement == ELEM_HYPHEN )
+ if (currElement != ELEM_HYPHEN)
+ token.setLength(0);
+ }
+ if (currElement == ELEM_HYPHEN)
currElement = ELEM_EXCEPTIONS;
- else
+ else
currElement = 0;
- }
+ }
- /** Characters. */
- public void characters(char ch[], int start, int length)
- {
- StringBuffer chars = new StringBuffer(length);
- chars.append(ch, start, length);
- String word = readToken(chars);
- while ( word != null ) {
+ /**
+ * Characters.
+ */
+ public void characters(char ch[], int start, int length) {
+ StringBuffer chars = new StringBuffer(length);
+ chars.append(ch, start, length);
+ String word = readToken(chars);
+ while (word != null) {
// System.out.println("\"" + word + "\"");
- switch ( currElement ) {
- case ELEM_CLASSES:
- consumer.addClass(word);
- break;
- case ELEM_EXCEPTIONS:
- exception.addElement(word);
- exception = normalizeException(exception);
- consumer.addException(getExceptionWord(exception),
- (Vector)exception.clone());
- exception.removeAllElements();
- break;
- case ELEM_PATTERNS:
- consumer.addPattern(getPattern(word), getInterletterValues(word));
- break;
+ switch (currElement) {
+ case ELEM_CLASSES:
+ consumer.addClass(word);
+ break;
+ case ELEM_EXCEPTIONS:
+ exception.addElement(word);
+ exception = normalizeException(exception);
+ consumer.addException(getExceptionWord(exception),
+ (Vector)exception.clone());
+ exception.removeAllElements();
+ break;
+ case ELEM_PATTERNS:
+ consumer.addPattern(getPattern(word),
+ getInterletterValues(word));
+ break;
}
word = readToken(chars);
- }
-
- }
-
- //
- // ErrorHandler methods
- //
-
- /** Warning. */
- public void warning(SAXParseException ex) {
- errMsg = "[Warning] "+ getLocationString(ex)+": "+ ex.getMessage();
- }
-
- /** Error. */
- public void error(SAXParseException ex) {
- errMsg = "[Error] "+ getLocationString(ex)+": "+ ex.getMessage();
- }
-
- /** Fatal error. */
- public void fatalError(SAXParseException ex) throws SAXException {
- errMsg = "[Fatal Error] "+getLocationString(ex)+": "+ ex.getMessage();
- throw ex;
- }
-
- /** Returns a string of the location. */
- private String getLocationString(SAXParseException ex) {
- StringBuffer str = new StringBuffer();
-
- String systemId = ex.getSystemId();
- if (systemId != null) {
+ }
+
+ }
+
+ //
+ // ErrorHandler methods
+ //
+
+ /**
+ * Warning.
+ */
+ public void warning(SAXParseException ex) {
+ errMsg = "[Warning] " + getLocationString(ex) + ": "
+ + ex.getMessage();
+ }
+
+ /**
+ * Error.
+ */
+ public void error(SAXParseException ex) {
+ errMsg = "[Error] " + getLocationString(ex) + ": " + ex.getMessage();
+ }
+
+ /**
+ * Fatal error.
+ */
+ public void fatalError(SAXParseException ex) throws SAXException {
+ errMsg = "[Fatal Error] " + getLocationString(ex) + ": "
+ + ex.getMessage();
+ throw ex;
+ }
+
+ /**
+ * Returns a string of the location.
+ */
+ private String getLocationString(SAXParseException ex) {
+ StringBuffer str = new StringBuffer();
+
+ String systemId = ex.getSystemId();
+ if (systemId != null) {
int index = systemId.lastIndexOf('/');
- if (index != -1)
- systemId = systemId.substring(index + 1);
+ if (index != -1)
+ systemId = systemId.substring(index + 1);
str.append(systemId);
- }
- str.append(':');
- str.append(ex.getLineNumber());
- str.append(':');
- str.append(ex.getColumnNumber());
-
- return str.toString();
-
- } // getLocationString(SAXParseException):String
-
-
- // PatternConsumer implementation for testing purposes
- public void addClass(String c)
- {
- System.out.println("class: " + c);
- }
-
- public void addException(String w, Vector e)
- {
- System.out.println("exception: " + w + " : " + e.toString());
- }
-
- public void addPattern(String p, String v)
- {
- System.out.println("pattern: " + p + " : " + v);
- }
-
- public static void main(String[] args)
- throws Exception
- {
- if ( args.length > 0 ){
+ }
+ str.append(':');
+ str.append(ex.getLineNumber());
+ str.append(':');
+ str.append(ex.getColumnNumber());
+
+ return str.toString();
+
+ } // getLocationString(SAXParseException):String
+
+
+ // PatternConsumer implementation for testing purposes
+ public void addClass(String c) {
+ System.out.println("class: " + c);
+ }
+
+ public void addException(String w, Vector e) {
+ System.out.println("exception: " + w + " : " + e.toString());
+ }
+
+ public void addPattern(String p, String v) {
+ System.out.println("pattern: " + p + " : " + v);
+ }
+
+ public static void main(String[] args) throws Exception {
+ if (args.length > 0) {
PatternParser pp = new PatternParser();
pp.setConsumer(pp);
pp.parse(args[0]);
- }
- }
+ }
+ }
+
}
diff --git a/src/org/apache/fop/layout/hyphenation/TernaryTree.java b/src/org/apache/fop/layout/hyphenation/TernaryTree.java
index d084706f0..b6ad6120a 100644
--- a/src/org/apache/fop/layout/hyphenation/TernaryTree.java
+++ b/src/org/apache/fop/layout/hyphenation/TernaryTree.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -11,635 +12,623 @@ import java.util.Stack;
import java.io.Serializable;
/**
- * Ternary Search Tree
+ * Ternary Search Tree
*
- * A ternary search tree is a hibrid between a binary tree and
- * a digital search tree (trie). Keys are limited to strings.
- * A data value of type char is stored in each leaf node.
- * It can be used as an index (or pointer) to the data.
- * Branches that only contain one key are compressed to one node
- * by storing a pointer to the trailer substring of the key.
- * This class is intended to serve as base class or helper class
- * to implement Dictionary collections or the like. Ternary trees
- * have some nice properties as the following: the tree can be
- * traversed in sorted order, partial matches (wildcard) can be
- * implemented, retrieval of all keys within a given distance
- * from the target, etc. The storage requirements are higher than
- * a binary tree but a lot less than a trie. Performance is
- * comparable with a hash table, sometimes it outperforms a hash
- * function (most of the time can determine a miss faster than a hash).
+ * A ternary search tree is a hibrid between a binary tree and
+ * a digital search tree (trie). Keys are limited to strings.
+ * A data value of type char is stored in each leaf node.
+ * It can be used as an index (or pointer) to the data.
+ * Branches that only contain one key are compressed to one node
+ * by storing a pointer to the trailer substring of the key.
+ * This class is intended to serve as base class or helper class
+ * to implement Dictionary collections or the like. Ternary trees
+ * have some nice properties as the following: the tree can be
+ * traversed in sorted order, partial matches (wildcard) can be
+ * implemented, retrieval of all keys within a given distance
+ * from the target, etc. The storage requirements are higher than
+ * a binary tree but a lot less than a trie. Performance is
+ * comparable with a hash table, sometimes it outperforms a hash
+ * function (most of the time can determine a miss faster than a hash).
*
- * The main purpose of this java port is to serve as a base for
- * implementing TeX's hyphenation algorithm (see The TeXBook,
- * appendix H). Each language requires from 5000 to 15000 hyphenation
- * patterns which will be keys in this tree. The strings patterns
- * are usually small (from 2 to 5 characters), but each char in the
- * tree is stored in a node. Thus memory usage is the main concern.
- * We will sacrify 'elegance' to keep memory requirenments to the
- * minimum. Using java's char type as pointer (yes, I know pointer
- * it is a forbidden word in java) we can keep the size of the node
- * to be just 8 bytes (3 pointers and the data char). This gives
- * room for about 65000 nodes. In my tests the english patterns
- * took 7694 nodes and the german patterns 10055 nodes,
- * so I think we are safe.
+ * The main purpose of this java port is to serve as a base for
+ * implementing TeX's hyphenation algorithm (see The TeXBook,
+ * appendix H). Each language requires from 5000 to 15000 hyphenation
+ * patterns which will be keys in this tree. The strings patterns
+ * are usually small (from 2 to 5 characters), but each char in the
+ * tree is stored in a node. Thus memory usage is the main concern.
+ * We will sacrify 'elegance' to keep memory requirenments to the
+ * minimum. Using java's char type as pointer (yes, I know pointer
+ * it is a forbidden word in java) we can keep the size of the node
+ * to be just 8 bytes (3 pointers and the data char). This gives
+ * room for about 65000 nodes. In my tests the english patterns
+ * took 7694 nodes and the german patterns 10055 nodes,
+ * so I think we are safe.
*
- * All said, this is a map with strings as keys and char as value.
- * Pretty limited!. It can be extended to a general map by
- * using the string representation of an object and using the
- * char value as an index to an array that contains the object
- * values.
+ * All said, this is a map with strings as keys and char as value.
+ * Pretty limited!. It can be extended to a general map by
+ * using the string representation of an object and using the
+ * char value as an index to an array that contains the object
+ * values.
*
- * @author cav@uniscope.co.jp
+ * @author cav@uniscope.co.jp
*/
public class TernaryTree implements Cloneable, Serializable {
- /**
- * We use 4 arrays to represent a node. I guess I should have created
- * a proper node class, but somehow Knuth's pascal code made me forget
- * we now have a portable language with virtual memory management and
- * automatic garbage collection! And now is kind of late, furthermore,
- * if it ain't broken, don't fix it.
- */
-
- /**
- * Pointer to low branch and to rest of the key when it is
- * stored directly in this node, we don't have unions in java!
- */
- protected char[] lo;
-
- /**
- * Pointer to high branch.
- */
- protected char[] hi;
-
- /**
- * Pointer to equal branch and to data when this node is a string terminator.
- */
- protected char[] eq;
-
- /**
- * The character stored in this node: splitchar
- * Two special values are reserved:
- * - 0x0000 as string terminator
- * - 0xFFFF to indicate that the branch starting at
- * this node is compressed
- * This shouldn't be a problem if we give the usual semantics to
- * strings since 0xFFFF is garanteed not to be an Unicode character.
- */
- protected char[] sc;
-
- /**
- * This vector holds the trailing of the keys when the branch is compressed.
- */
- protected CharVector kv;
-
- protected char root;
- protected char freenode;
- protected int length; // number of items in tree
-
- protected final static int BLOCK_SIZE=2048; // allocation size for arrays
-
- TernaryTree()
- {
- init();
- }
-
- protected void init()
- {
- root = 0;
- freenode = 1;
- length = 0;
- lo = new char[BLOCK_SIZE];
- hi = new char[BLOCK_SIZE];
- eq = new char[BLOCK_SIZE];
- sc = new char[BLOCK_SIZE];
- kv = new CharVector();
- }
-
- /**
- * Branches are initially compressed, needing
- * one node per key plus the size of the string
- * key. They are decompressed as needed when
- * another key with same prefix
- * is inserted. This saves a lot of space,
- * specially for long keys.
- */
- public void insert(String key, char val)
- {
- // make sure we have enough room in the arrays
- int len = key.length() + 1; // maximum number of nodes that may be generated
- if ( freenode + len > eq.length )
+ /**
+ * We use 4 arrays to represent a node. I guess I should have created
+ * a proper node class, but somehow Knuth's pascal code made me forget
+ * we now have a portable language with virtual memory management and
+ * automatic garbage collection! And now is kind of late, furthermore,
+ * if it ain't broken, don't fix it.
+ */
+
+ /**
+ * Pointer to low branch and to rest of the key when it is
+ * stored directly in this node, we don't have unions in java!
+ */
+ protected char[] lo;
+
+ /**
+ * Pointer to high branch.
+ */
+ protected char[] hi;
+
+ /**
+ * Pointer to equal branch and to data when this node is a string terminator.
+ */
+ protected char[] eq;
+
+ /**
+ * The character stored in this node: splitchar
+ * Two special values are reserved:
+ * - 0x0000 as string terminator
+ * - 0xFFFF to indicate that the branch starting at
+ * this node is compressed
+ * This shouldn't be a problem if we give the usual semantics to
+ * strings since 0xFFFF is garanteed not to be an Unicode character.
+ */
+ protected char[] sc;
+
+ /**
+ * This vector holds the trailing of the keys when the branch is compressed.
+ */
+ protected CharVector kv;
+
+ protected char root;
+ protected char freenode;
+ protected int length; // number of items in tree
+
+ protected final static int BLOCK_SIZE = 2048; // allocation size for arrays
+
+ TernaryTree() {
+ init();
+ }
+
+ protected void init() {
+ root = 0;
+ freenode = 1;
+ length = 0;
+ lo = new char[BLOCK_SIZE];
+ hi = new char[BLOCK_SIZE];
+ eq = new char[BLOCK_SIZE];
+ sc = new char[BLOCK_SIZE];
+ kv = new CharVector();
+ }
+
+ /**
+ * Branches are initially compressed, needing
+ * one node per key plus the size of the string
+ * key. They are decompressed as needed when
+ * another key with same prefix
+ * is inserted. This saves a lot of space,
+ * specially for long keys.
+ */
+ public void insert(String key, char val) {
+ // make sure we have enough room in the arrays
+ int len = key.length()
+ + 1; // maximum number of nodes that may be generated
+ if (freenode + len > eq.length)
redimNodeArrays(eq.length + BLOCK_SIZE);
- char strkey[] = new char[len--];
- key.getChars(0, len, strkey, 0);
- strkey[len] = 0;
- root = insert(root, strkey, 0, val);
- }
-
- public void insert(char[] key, int start, char val)
- {
- int len = strlen(key) + 1;
- if ( freenode + len > eq.length )
+ char strkey[] = new char[len--];
+ key.getChars(0, len, strkey, 0);
+ strkey[len] = 0;
+ root = insert(root, strkey, 0, val);
+ }
+
+ public void insert(char[] key, int start, char val) {
+ int len = strlen(key) + 1;
+ if (freenode + len > eq.length)
redimNodeArrays(eq.length + BLOCK_SIZE);
- root = insert(root, key, start, val);
- }
-
- /**
- * The actual insertion function, recursive version.
- */
- private char insert(char p, char[] key, int start, char val)
- {
- int len = strlen(key, start);
- if ( p == 0 ) {
+ root = insert(root, key, start, val);
+ }
+
+ /**
+ * The actual insertion function, recursive version.
+ */
+ private char insert(char p, char[] key, int start, char val) {
+ int len = strlen(key, start);
+ if (p == 0) {
// this means there is no branch, this node will start a new branch.
// Instead of doing that, we store the key somewhere else and create
// only one node with a pointer to the key
p = freenode++;
- eq[p] = val; //holds data
+ eq[p] = val; // holds data
length++;
hi[p] = 0;
- if ( len > 0 ) {
- sc[p] = 0xFFFF; // indicates branch is compressed
- lo[p] = (char)kv.alloc(len+1); // use 'lo' to hold pointer to key
- strcpy(kv.getArray(), lo[p], key, start);
+ if (len > 0) {
+ sc[p] = 0xFFFF; // indicates branch is compressed
+ lo[p] = (char)kv.alloc(len
+ + 1); // use 'lo' to hold pointer to key
+ strcpy(kv.getArray(), lo[p], key, start);
} else {
- sc[p] = 0;
- lo[p] = 0;
+ sc[p] = 0;
+ lo[p] = 0;
}
return p;
- }
+ }
- if ( sc[p] == 0xFFFF ) {
+ if (sc[p] == 0xFFFF) {
// branch is compressed: need to decompress
// this will generate garbage in the external key array
// but we can do some garbage collection later
char pp = freenode++;
- lo[pp] = lo[p]; // previous pointer to key
- eq[pp] = eq[p]; // previous pointer to data
+ lo[pp] = lo[p]; // previous pointer to key
+ eq[pp] = eq[p]; // previous pointer to data
lo[p] = 0;
- if ( len > 0 ) {
- sc[p] = kv.get(lo[pp]);
- eq[p] = pp;
- lo[pp]++;
- if ( kv.get(lo[pp]) == 0 ) {
- // key completly decompressed leaving garbage in key array
- lo[pp] = 0;
- sc[pp] = 0;
- hi[pp] = 0;
- } else
- sc[pp] = 0xFFFF; // we only got first char of key, rest is still there
+ if (len > 0) {
+ sc[p] = kv.get(lo[pp]);
+ eq[p] = pp;
+ lo[pp]++;
+ if (kv.get(lo[pp]) == 0) {
+ // key completly decompressed leaving garbage in key array
+ lo[pp] = 0;
+ sc[pp] = 0;
+ hi[pp] = 0;
+ } else
+ sc[pp] =
+ 0xFFFF; // we only got first char of key, rest is still there
} else {
- // In this case we can save a node by swapping the new node
- // with the compressed node
- sc[pp] = 0xFFFF;
- hi[p] = pp;
- sc[p] = 0;
- eq[p] = val;
- length++;
- return p;
- }
- }
- char s = key[start];
- if ( s < sc[p] )
+ // In this case we can save a node by swapping the new node
+ // with the compressed node
+ sc[pp] = 0xFFFF;
+ hi[p] = pp;
+ sc[p] = 0;
+ eq[p] = val;
+ length++;
+ return p;
+ }
+ }
+ char s = key[start];
+ if (s < sc[p])
lo[p] = insert(lo[p], key, start, val);
- else if ( s == sc[p] ) {
- if ( s != 0 )
- eq[p] = insert(eq[p], key, start+1, val);
+ else if (s == sc[p]) {
+ if (s != 0)
+ eq[p] = insert(eq[p], key, start + 1, val);
else {
- // key already in tree, overwrite data
- eq[p] = val;
+ // key already in tree, overwrite data
+ eq[p] = val;
}
-
- } else
+
+ } else
hi[p] = insert(hi[p], key, start, val);
- return p;
- }
-
- /** Compares 2 null terminated char arrays */
- public static int strcmp(char[] a, int startA, char[] b, int startB)
- {
- for(; a[startA] == b[startB]; startA++, startB++)
- if ( a[startA] == 0 )
- return 0;
- return a[startA] - b[startB];
- }
-
- /**
- * Compares a string with null terminated char array
- */
- public static int strcmp(String str, char[] a, int start)
- {
- int i,d,len=str.length();
- for(i=0; i= 0 );
- }
-
- // redimension the arrays
- private void redimNodeArrays(int newsize)
- {
- int len = newsize < lo.length ? newsize : lo.length;
- char[] na = new char[newsize];
- System.arraycopy(lo, 0, na, 0, len);
- lo = na;
- na = new char[newsize];
- System.arraycopy(hi, 0, na, 0, len);
- hi = na;
- na = new char[newsize];
- System.arraycopy(eq, 0, na, 0, len);
- eq = na;
- na = new char[newsize];
- System.arraycopy(sc, 0, na, 0, len);
- sc = na;
- }
-
- public int size()
- {
- return length;
- }
-
- public Object clone()
- {
- TernaryTree t = new TernaryTree();
- t.lo = (char[])this.lo.clone();
- t.hi = (char[])this.hi.clone();
- t.eq = (char[])this.eq.clone();
- t.sc = (char[])this.sc.clone();
- t.kv = (CharVector)this.kv.clone();
- t.root = this.root;
- t.freenode = this.freenode;
- t.length = this.length;
-
- return t;
- }
-
- /**
- * Recursively insert the median first and then the median of the
- * lower and upper halves, and so on in order to get a balanced
- * tree. The array of keys is assumed to be sorted in ascending
- * order.
- */
- protected void insertBalanced(String[] k, char[] v, int offset, int n)
- {
- int m;
- if ( n < 1) return;
- m = n >> 1;
-
- insert(k[m+offset], v[m+offset]);
- insertBalanced(k, v, offset, m);
-
- insertBalanced(k, v, offset+m+1, n-m-1);
- }
-
-
- /**
- * Balance the tree for best search performance
- */
- public void balance()
- {
- // System.out.print("Before root splitchar = "); System.out.println(sc[root]);
-
- int i=0, n = length;
- String[] k = new String[n];
- char[] v = new char[n];
- Iterator iter = new Iterator();
- while ( iter.hasMoreElements() ) {
- v[i] = iter.getValue();
+ p = hi[p];
+ }
+ return -1;
+ }
+
+ public boolean knows(String key) {
+ return (find(key) >= 0);
+ }
+
+ // redimension the arrays
+ private void redimNodeArrays(int newsize) {
+ int len = newsize < lo.length ? newsize : lo.length;
+ char[] na = new char[newsize];
+ System.arraycopy(lo, 0, na, 0, len);
+ lo = na;
+ na = new char[newsize];
+ System.arraycopy(hi, 0, na, 0, len);
+ hi = na;
+ na = new char[newsize];
+ System.arraycopy(eq, 0, na, 0, len);
+ eq = na;
+ na = new char[newsize];
+ System.arraycopy(sc, 0, na, 0, len);
+ sc = na;
+ }
+
+ public int size() {
+ return length;
+ }
+
+ public Object clone() {
+ TernaryTree t = new TernaryTree();
+ t.lo = (char[])this.lo.clone();
+ t.hi = (char[])this.hi.clone();
+ t.eq = (char[])this.eq.clone();
+ t.sc = (char[])this.sc.clone();
+ t.kv = (CharVector)this.kv.clone();
+ t.root = this.root;
+ t.freenode = this.freenode;
+ t.length = this.length;
+
+ return t;
+ }
+
+ /**
+ * Recursively insert the median first and then the median of the
+ * lower and upper halves, and so on in order to get a balanced
+ * tree. The array of keys is assumed to be sorted in ascending
+ * order.
+ */
+ protected void insertBalanced(String[] k, char[] v, int offset, int n) {
+ int m;
+ if (n < 1)
+ return;
+ m = n >> 1;
+
+ insert(k[m + offset], v[m + offset]);
+ insertBalanced(k, v, offset, m);
+
+ insertBalanced(k, v, offset + m + 1, n - m - 1);
+ }
+
+
+ /**
+ * Balance the tree for best search performance
+ */
+ public void balance() {
+ // System.out.print("Before root splitchar = "); System.out.println(sc[root]);
+
+ int i = 0, n = length;
+ String[] k = new String[n];
+ char[] v = new char[n];
+ Iterator iter = new Iterator();
+ while (iter.hasMoreElements()) {
+ v[i] = iter.getValue();
k[i++] = (String)iter.nextElement();
- }
- init();
- insertBalanced(k, v, 0, n);
-
- // With uniform letter distribution sc[root] should be around 'm'
- // System.out.print("After root splitchar = "); System.out.println(sc[root]);
- }
-
- /**
- * Each node stores a character (splitchar) which is part of
- * some key(s). In a compressed branch (one that only contain
- * a single string key) the trailer of the key which is not
- * already in nodes is stored externally in the kv array.
- * As items are inserted, key substrings decrease.
- * Some substrings may completely disappear when the whole
- * branch is totally decompressed.
- * The tree is traversed to find the key substrings actually
- * used. In addition, duplicate substrings are removed using
- * a map (implemented with a TernaryTree!).
- *
- */
- public void trimToSize()
- {
- // first balance the tree for best performance
- balance();
-
- // redimension the node arrays
- redimNodeArrays(freenode);
-
- // ok, compact kv array
- CharVector kx = new CharVector();
- kx.alloc(1);
- TernaryTree map = new TernaryTree();
- compact(kx, map, root);
- kv = kx;
- kv.trimToSize();
- }
-
- private void compact(CharVector kx, TernaryTree map, char p)
- {
- int k;
- if (p == 0) return;
- if ( sc[p] == 0xFFFF ) {
+ }
+ init();
+ insertBalanced(k, v, 0, n);
+
+ // With uniform letter distribution sc[root] should be around 'm'
+ // System.out.print("After root splitchar = "); System.out.println(sc[root]);
+ }
+
+ /**
+ * Each node stores a character (splitchar) which is part of
+ * some key(s). In a compressed branch (one that only contain
+ * a single string key) the trailer of the key which is not
+ * already in nodes is stored externally in the kv array.
+ * As items are inserted, key substrings decrease.
+ * Some substrings may completely disappear when the whole
+ * branch is totally decompressed.
+ * The tree is traversed to find the key substrings actually
+ * used. In addition, duplicate substrings are removed using
+ * a map (implemented with a TernaryTree!).
+ *
+ */
+ public void trimToSize() {
+ // first balance the tree for best performance
+ balance();
+
+ // redimension the node arrays
+ redimNodeArrays(freenode);
+
+ // ok, compact kv array
+ CharVector kx = new CharVector();
+ kx.alloc(1);
+ TernaryTree map = new TernaryTree();
+ compact(kx, map, root);
+ kv = kx;
+ kv.trimToSize();
+ }
+
+ private void compact(CharVector kx, TernaryTree map, char p) {
+ int k;
+ if (p == 0)
+ return;
+ if (sc[p] == 0xFFFF) {
k = map.find(kv.getArray(), lo[p]);
- if ( k < 0 ) {
- k = kx.alloc(strlen(kv.getArray(),lo[p])+1);
- strcpy(kx.getArray(), k, kv.getArray(), lo[p]);
- map.insert(kx.getArray(), k, (char)k);
+ if (k < 0) {
+ k = kx.alloc(strlen(kv.getArray(), lo[p]) + 1);
+ strcpy(kx.getArray(), k, kv.getArray(), lo[p]);
+ map.insert(kx.getArray(), k, (char)k);
}
lo[p] = (char)k;
- } else {
+ } else {
compact(kx, map, lo[p]);
- if ( sc[p] != 0 )
- compact(kx, map, eq[p]);
+ if (sc[p] != 0)
+ compact(kx, map, eq[p]);
compact(kx, map, hi[p]);
- }
- }
-
-
- public Enumeration keys()
- {
- return new Iterator();
- }
-
- public class Iterator implements Enumeration {
-
- /** current node index */
- int cur;
-
- /** current key */
- String curkey;
-
- private class Item implements Cloneable {
- char parent;
- char child;
-
- public Item()
- {
- parent = 0;
- child = 0;
- }
-
- public Item(char p, char c)
- {
- parent = p;
- child = c;
- }
-
- public Object clone()
- {
- return new Item(parent, child);
- }
- }
-
- /** Node stack */
- Stack ns;
-
- /** key stack implemented with a StringBuffer */
- StringBuffer ks;
-
- public Iterator()
- {
- cur = -1;
- ns = new Stack();
- ks = new StringBuffer();
- rewind();
- }
+ }
+ }
- public void rewind()
- {
- ns.removeAllElements();
- ks.setLength(0);
- cur = root;
- run();
- }
- public Object nextElement()
- {
- String res = new String(curkey);
- cur = up();
- run();
- return res;
+ public Enumeration keys() {
+ return new Iterator();
+ }
+
+ public class Iterator implements Enumeration {
+
+ /**
+ * current node index
+ */
+ int cur;
+
+ /**
+ * current key
+ */
+ String curkey;
+
+ private class Item implements Cloneable {
+ char parent;
+ char child;
+
+ public Item() {
+ parent = 0;
+ child = 0;
}
-
- public char getValue()
- {
- if ( cur >= 0 )
- return eq[cur];
- return 0;
+
+ public Item(char p, char c) {
+ parent = p;
+ child = c;
}
-
- public boolean hasMoreElements()
- {
- return (cur != -1);
+
+ public Object clone() {
+ return new Item(parent, child);
}
- /** traverse upwards */
- private int up()
- {
- Item i = new Item();
- int res=0;
-
- if ( ns.empty() )
- return -1;
-
- if ( cur != 0 && sc[cur] == 0 )
- return lo[cur];
-
- boolean climb=true;
-
- while(climb) {
- i = (Item)ns.pop();
- i.child++;
- switch( i.child ) {
- case 1:
- if ( sc[i.parent] != 0 ) {
- res = eq[i.parent];
- ns.push(i.clone());
- ks.append(sc[i.parent]);
- } else {
- i.child++;
- ns.push(i.clone());
- res = hi[i.parent];
- }
- climb = false;
- break;
+ }
- case 2:
- res = hi[i.parent];
- ns.push(i.clone());
- if ( ks.length() > 0 )
- ks.setLength(ks.length()-1); // pop
- climb=false;
- break;
+ /**
+ * Node stack
+ */
+ Stack ns;
- default:
- if ( ns.empty() )
- return -1;
- climb = true;
- break;
- }
- }
- return res;
+ /**
+ * key stack implemented with a StringBuffer
+ */
+ StringBuffer ks;
+
+ public Iterator() {
+ cur = -1;
+ ns = new Stack();
+ ks = new StringBuffer();
+ rewind();
+ }
+
+ public void rewind() {
+ ns.removeAllElements();
+ ks.setLength(0);
+ cur = root;
+ run();
+ }
+
+ public Object nextElement() {
+ String res = new String(curkey);
+ cur = up();
+ run();
+ return res;
+ }
+
+ public char getValue() {
+ if (cur >= 0)
+ return eq[cur];
+ return 0;
+ }
+
+ public boolean hasMoreElements() {
+ return (cur != -1);
+ }
+
+ /**
+ * traverse upwards
+ */
+ private int up() {
+ Item i = new Item();
+ int res = 0;
+
+ if (ns.empty())
+ return -1;
+
+ if (cur != 0 && sc[cur] == 0)
+ return lo[cur];
+
+ boolean climb = true;
+
+ while (climb) {
+ i = (Item)ns.pop();
+ i.child++;
+ switch (i.child) {
+ case 1:
+ if (sc[i.parent] != 0) {
+ res = eq[i.parent];
+ ns.push(i.clone());
+ ks.append(sc[i.parent]);
+ } else {
+ i.child++;
+ ns.push(i.clone());
+ res = hi[i.parent];
+ }
+ climb = false;
+ break;
+
+ case 2:
+ res = hi[i.parent];
+ ns.push(i.clone());
+ if (ks.length() > 0)
+ ks.setLength(ks.length() - 1); // pop
+ climb = false;
+ break;
+
+ default:
+ if (ns.empty())
+ return -1;
+ climb = true;
+ break;
+ }
}
+ return res;
+ }
- /** traverse the tree to find next key */
- private int run()
- {
- if ( cur == -1 )
- return -1;
-
- boolean leaf = false;
- for(;;) {
- // first go down on low branch until leaf or compressed branch
- while ( cur != 0 ) {
- if( sc[cur] == 0xFFFF ) {
+ /**
+ * traverse the tree to find next key
+ */
+ private int run() {
+ if (cur == -1)
+ return -1;
+
+ boolean leaf = false;
+ for (; ; ) {
+ // first go down on low branch until leaf or compressed branch
+ while (cur != 0) {
+ if (sc[cur] == 0xFFFF) {
leaf = true;
break;
- }
- ns.push( new Item((char)cur, '\u0000') );
- if ( sc[cur] == 0 ) {
+ }
+ ns.push(new Item((char)cur, ' '));
+ if (sc[cur] == 0) {
leaf = true;
break;
- }
- cur = lo[cur];
- }
- if ( leaf ) break;
- // nothing found, go up one node and try again
- cur = up();
- if ( cur == -1 ) {
- return -1;
- }
- }
- // The current node should be a data node and
- // the key should be in the key stack (at least partially)
- StringBuffer buf = new StringBuffer(ks.toString());
- if ( sc[cur] == 0xFFFF ) {
- int p = lo[cur];
- while( kv.get(p) != 0 )
- buf.append(kv.get(p++));
- }
- curkey = buf.toString();
- return 0;
+ }
+ cur = lo[cur];
+ }
+ if (leaf)
+ break;
+ // nothing found, go up one node and try again
+ cur = up();
+ if (cur == -1) {
+ return -1;
+ }
}
-
- }
-
- public void printStats()
- {
- System.out.println("Number of keys = " + Integer.toString(length));
- System.out.println("Node count = " + Integer.toString(freenode));
- // System.out.println("Array length = " + Integer.toString(eq.length));
- System.out.println("Key Array length = " + Integer.toString(kv.length()));
-
- /*
- for(int i=0; i. For more information on the Apache
- Software Foundation, please see .
-
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.messaging;
/**
- * A trivial implementation of a MessageListener
- * For further explanation
+ * A trivial implementation of a MessageListener
+ * For further explanation
* @see MessageListener
*/
-public class DefaultMessageListener implements MessageListener{
+public class DefaultMessageListener implements MessageListener {
- /**
- * The method processMessage has to be overwritten to handle the MessageEvents.
- * The message type (information or error) is accessible via event.getMessageType().
- */
+ /**
+ * The method processMessage has to be overwritten to handle the MessageEvents.
+ * The message type (information or error) is accessible via event.getMessageType().
+ */
- public void processMessage (MessageEvent event) {
- switch (event.getMessageType()) {
- case MessageEvent.ERROR:
- System.err.print("ERROR: "+event.getMessage());
- break;
- case MessageEvent.LOG:
- System.out.print("LOG: "+event.getMessage());
- break;
- default:
- System.out.print("Unknown message type: "+event.getMessage());
+ public void processMessage(MessageEvent event) {
+ switch (event.getMessageType()) {
+ case MessageEvent.ERROR:
+ System.err.print("ERROR: " + event.getMessage());
+ break;
+ case MessageEvent.LOG:
+ System.out.print("LOG: " + event.getMessage());
+ break;
+ default:
+ System.out.print("Unknown message type: " + event.getMessage());
+ }
}
- }
-}
\ No newline at end of file
+
+}
diff --git a/src/org/apache/fop/messaging/MessageEvent.java b/src/org/apache/fop/messaging/MessageEvent.java
index 0c7945905..ac4c6f683 100644
--- a/src/org/apache/fop/messaging/MessageEvent.java
+++ b/src/org/apache/fop/messaging/MessageEvent.java
@@ -1,51 +1,8 @@
/*
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.messaging;
@@ -54,49 +11,49 @@ import java.util.EventObject;
/**
* a container for the text and the type of a message
- * MessageEvents are created by MessageHandler and can be received by any
- * MessageListener, which is added to MessageHandler;
- * @see org.apache.fop.MessageListener MessageListener
+ * MessageEvents are created by MessageHandler and can be received by any
+ * MessageListener, which is added to MessageHandler;
+ * @see org.apache.fop.MessageListener MessageListener
*
*/
public class MessageEvent extends EventObject {
- public static final int LOG = 0;
- public static final int ERROR = 1;
- String message;
- int messageType = MessageEvent.LOG;
-
- public MessageEvent (Object source) {
- super (source);
- message = (String) source; //MessageHandler.getMessage()
- }
-
-/**
- * retrieves the message
- * @return String containing the message
- *
- */
- public String getMessage () {
- return message;
- }
-
-/**
- * sets the message type
- * @param messageType the type of the message as int in the form of MessageEvent.LOG or MessageEvent.ERROR
- *
- */
- void setMessageType (int messageType) {
- this.messageType = messageType;
- }
-
-/**
- * returns the type of message as int
- *
- * @return messageType the type of the message as int in the form of MessageEvent.LOG or MessageEvent.ERROR
- */
- public int getMessageType () {
- return messageType;
- }
+ public static final int LOG = 0;
+ public static final int ERROR = 1;
+ String message;
+ int messageType = MessageEvent.LOG;
+
+ public MessageEvent(Object source) {
+ super(source);
+ message = (String)source; // MessageHandler.getMessage()
+ }
+
+ /**
+ * retrieves the message
+ * @return String containing the message
+ *
+ */
+ public String getMessage() {
+ return message;
+ }
+
+ /**
+ * sets the message type
+ * @param messageType the type of the message as int in the form of MessageEvent.LOG or MessageEvent.ERROR
+ *
+ */
+ void setMessageType(int messageType) {
+ this.messageType = messageType;
+ }
+
+ /**
+ * returns the type of message as int
+ *
+ * @return messageType the type of the message as int in the form of MessageEvent.LOG or MessageEvent.ERROR
+ */
+ public int getMessageType() {
+ return messageType;
+ }
}
diff --git a/src/org/apache/fop/messaging/MessageHandler.java b/src/org/apache/fop/messaging/MessageHandler.java
index e18bd44ca..e6ca11828 100644
--- a/src/org/apache/fop/messaging/MessageHandler.java
+++ b/src/org/apache/fop/messaging/MessageHandler.java
@@ -11,39 +11,40 @@ import java.io.*;
import java.util.*;
-/** The class MessageHandler contains the static methods log and error which
- * should be used for any end user information instead of System.out.print() or
- * System.err.print(). The class defines several output methods:
- * writing to the screen (default), logging to a file, creating message events and repressing all
- * output. If you don't want to change the default behaviour, you should be
- * happy with MessageHandler.log(message) and MessageHandler.error(message)
- * The class MessageHandler also supports the setting of an id. If set every message
- * has as a prefix an identifying string. That way Fop probably can also be used in
- * environments, where more than one Fop instance are running in same JVM.
- * If Fop is embedded in a gui application or for any reasons the existing
- * messaging system doesn't meet the programmer's requirements, one can add
- * a MessageEvent listener to MessageHandler and handle the incoming messages
- * in an appropriate way. See the class DefaultMessageListener, which is a trivial
- * implementation of the MessageListener.
- * Here is an example how to configure MessageHandler for the DefaultMessageListener (anybody
- * can provide his own listener by extending MessageListener
- *
- * MessageHandler.setOutputMethod(MessageHandler.EVENT);
- * MessageHandler.addListener(new DefaultMessageListener());
- *
- * This examples shows, how to redirect the messages to a log file called fop.log.
- * All messages are appended to this file.
- *
- * MessageHandler.setOutputMethod(MessageHandler.FILE);
- * MessageHandler.setLogfileName("\\fop.log",true);
- *
+/**
+ * The class MessageHandler contains the static methods log and error which
+ * should be used for any end user information instead of System.out.print() or
+ * System.err.print(). The class defines several output methods:
+ * writing to the screen (default), logging to a file, creating message events and repressing all
+ * output. If you don't want to change the default behaviour, you should be
+ * happy with MessageHandler.log(message) and MessageHandler.error(message)
+ * The class MessageHandler also supports the setting of an id. If set every message
+ * has as a prefix an identifying string. That way Fop probably can also be used in
+ * environments, where more than one Fop instance are running in same JVM.
+ * If Fop is embedded in a gui application or for any reasons the existing
+ * messaging system doesn't meet the programmer's requirements, one can add
+ * a MessageEvent listener to MessageHandler and handle the incoming messages
+ * in an appropriate way. See the class DefaultMessageListener, which is a trivial
+ * implementation of the MessageListener.
+ * Here is an example how to configure MessageHandler for the DefaultMessageListener (anybody
+ * can provide his own listener by extending MessageListener
+ *
+ * MessageHandler.setOutputMethod(MessageHandler.EVENT);
+ * MessageHandler.addListener(new DefaultMessageListener());
+ *
+ * This examples shows, how to redirect the messages to a log file called fop.log.
+ * All messages are appended to this file.
+ *
+ * MessageHandler.setOutputMethod(MessageHandler.FILE);
+ * MessageHandler.setLogfileName("\\fop.log",true);
+ *
*/
public class MessageHandler {
public static final int SCREEN = 0;
public static final int FILE = 1;
public static final int EVENT = 2;
- public static final int NONE = 3; //this should always be the last method
+ public static final int NONE = 3; // this should always be the last method
private static String logfileName = "fop.log";
private static PrintWriter writer;
@@ -57,20 +58,20 @@ public class MessageHandler {
private static boolean quiet = false;
/**
- * helper class to access the message
- * @return a string containing the message
+ * helper class to access the message
+ * @return a string containing the message
*/
- private static String getMessage () {
+ private static String getMessage() {
return message;
}
/**
- * helper class which sets the message
- * and adds a prefix which can contain
- * the id of the thread which uses this messagehandler
- */
- private static void setMessage (String m) {
+ * helper class which sets the message
+ * and adds a prefix which can contain
+ * the id of the thread which uses this messagehandler
+ */
+ private static void setMessage(String m) {
if (IDisSet) {
message = getID() + ":" + m;
} else {
@@ -79,62 +80,15 @@ public class MessageHandler {
}
/**
- * informs the user of the message
- * @param message the message for the user
- */
- public static void log (String message) {
+ * informs the user of the message
+ * @param message the message for the user
+ */
+ public static void log(String message) {
if (!quiet) {
- setMessage(message);
+ setMessage(message);
switch (outputMethod) {
- case SCREEN:
- System.out.print(getMessage ());
- break;
- case FILE:
- if (fileOpened) {
- writer.print(getMessage ());
- writer.flush();
- } else {
- openFile();
- writer.print(getMessage ());
- writer.flush();
- }
- break;
- case EVENT:
- setMessage(message);
- Enumeration enum = listeners.elements();
- while (enum.hasMoreElements()) {
- ((MessageListener) enum.nextElement()).
- processMessage(
- new MessageEvent(getMessage()));
- }
- break;
- case NONE:
- //do nothing
- break;
- default:
- System.out.print(message);
- }
- }
- }
-
- /**
- * convenience method which adds a return to the message
- * @param message the message for the user
- */
- public static void logln (String message) {
- log (message + "\n");
- }
-
- /**
- * error warning for the user
- * @param errorMessage contains the warning string
- */
-
- public static void error (String errorMessage) {
- setMessage(errorMessage);
- switch (outputMethod) {
case SCREEN:
- System.err.print(getMessage());
+ System.out.print(getMessage());
break;
case FILE:
if (fileOpened) {
@@ -150,51 +104,95 @@ public class MessageHandler {
setMessage(message);
Enumeration enum = listeners.elements();
while (enum.hasMoreElements()) {
- MessageEvent messEv = new MessageEvent(getMessage());
- messEv.setMessageType(MessageEvent.ERROR);
- ((MessageListener) enum.nextElement()).
- processMessage(messEv);
+ ((MessageListener)enum.nextElement()).processMessage(new MessageEvent(getMessage()));
}
break;
case NONE:
- //do nothing
+ // do nothing
break;
default:
- System.err.print(errorMessage);
+ System.out.print(message);
+ }
+ }
+ }
+
+ /**
+ * convenience method which adds a return to the message
+ * @param message the message for the user
+ */
+ public static void logln(String message) {
+ log(message + "\n");
+ }
+
+ /**
+ * error warning for the user
+ * @param errorMessage contains the warning string
+ */
+
+ public static void error(String errorMessage) {
+ setMessage(errorMessage);
+ switch (outputMethod) {
+ case SCREEN:
+ System.err.print(getMessage());
+ break;
+ case FILE:
+ if (fileOpened) {
+ writer.print(getMessage());
+ writer.flush();
+ } else {
+ openFile();
+ writer.print(getMessage());
+ writer.flush();
+ }
+ break;
+ case EVENT:
+ setMessage(message);
+ Enumeration enum = listeners.elements();
+ while (enum.hasMoreElements()) {
+ MessageEvent messEv = new MessageEvent(getMessage());
+ messEv.setMessageType(MessageEvent.ERROR);
+ ((MessageListener)enum.nextElement()).processMessage(messEv);
+ }
+ break;
+ case NONE:
+ // do nothing
+ break;
+ default:
+ System.err.print(errorMessage);
}
}
/**
- * convenience method which adds a return to the error message
- * @param errorMessage the message for the user
- */
- public static void errorln (String errorMessage) {
- error (errorMessage + "\n");
+ * convenience method which adds a return to the error message
+ * @param errorMessage the message for the user
+ */
+ public static void errorln(String errorMessage) {
+ error(errorMessage + "\n");
}
/**
- * adds a MessageListener which listens for MessageEvents
- * @param MessageListener the listener to add
- */
+ * adds a MessageListener which listens for MessageEvents
+ * @param MessageListener the listener to add
+ */
public static void addListener(MessageListener listener) {
listeners.addElement(listener);
}
/**
- * removes a MessageListener
- * @param MessageListener the listener to remove
- */
+ * removes a MessageListener
+ * @param MessageListener the listener to remove
+ */
public static void removeListener(MessageListener listener) {
listeners.removeElement(listener);
}
/**
- * sets the output method
- * @param method the output method to use, allowed values are
- * MessageHandler.SCREEN, MessageHandler.FILE, MessageHandler.EVENT
- * MessageHandler.NONE
- */
- public static void setOutputMethod (int method) {
+ * sets the output method
+ * @param method the output method to use, allowed values are
+ * MessageHandler.SCREEN, MessageHandler.FILE, MessageHandler.EVENT
+ * MessageHandler.NONE
+ */
+ public static void setOutputMethod(int method) {
if (method > NONE) {
MessageHandler.error("Error: Unknown output method");
} else {
@@ -203,38 +201,39 @@ public class MessageHandler {
}
/**
- * informs what output method is set
- * @return the output method
- */
- public static int getOutputMethod () {
+ * informs what output method is set
+ * @return the output method
+ */
+ public static int getOutputMethod() {
return outputMethod;
}
/**
- * sets the logfile name
- * @param filename name of the logfile
- * @param append if true, the logfile is appended
- */
- public static void setLogfileName (String filename, boolean append) {
+ * sets the logfile name
+ * @param filename name of the logfile
+ * @param append if true, the logfile is appended
+ */
+ public static void setLogfileName(String filename, boolean append) {
logfileName = filename;
appendToFile = append;
}
/**
- * returns the logfile name
- * @return String containing the logfile name
- */
- public static String getLogfileName () {
+ * returns the logfile name
+ * @return String containing the logfile name
+ */
+ public static String getLogfileName() {
return logfileName;
}
/**
- * helper file which opens the file for output method FILE
- */
- private static void openFile () {
+ * helper file which opens the file for output method FILE
+ */
+ private static void openFile() {
try {
- writer = new PrintWriter (
- new FileWriter (logfileName, appendToFile), true);
+ writer =
+ new PrintWriter(new FileWriter(logfileName, appendToFile),
+ true);
writer.println("\n==============================================");
fileOpened = true;
} catch (IOException ioe) {
@@ -243,35 +242,36 @@ public class MessageHandler {
}
/**
- * if set to true an id string is prefixed to every message
- * uses the thread info as an id for the message producer. Should be used if
- * more than one instance of Fop is running in the same JVM
- * this id becomes a prefix to every message
- */
- private static String getID () {
+ * if set to true an id string is prefixed to every message
+ * uses the thread info as an id for the message producer. Should be used if
+ * more than one instance of Fop is running in the same JVM
+ * this id becomes a prefix to every message
+ */
+ private static String getID() {
return Thread.currentThread().toString();
}
/**
- * if set to true an id string is prefixed to every message
- * uses the thread info as an id for the message producer. Should be used if
- * more than one instance of Fop is running in the same JVM
- * this id becomes a prefix to every message
- *
- * @param id boolean (default is false)
- */
+ * if set to true an id string is prefixed to every message
+ * uses the thread info as an id for the message producer. Should be used if
+ * more than one instance of Fop is running in the same JVM
+ * this id becomes a prefix to every message
+ *
+ * @param id boolean (default is false)
+ */
- public static void setID (boolean id) {
+ public static void setID(boolean id) {
IDisSet = id;
}
- /**
- * if set to true all normal messages are suppressed.
- * error messages are displayed allthesame
- *
- * @param quietMode boolean (default is false)
- */
- public static void setQuiet(boolean quietMode) {
- quiet = quietMode;
- }
+ /**
+ * if set to true all normal messages are suppressed.
+ * error messages are displayed allthesame
+ *
+ * @param quietMode boolean (default is false)
+ */
+ public static void setQuiet(boolean quietMode) {
+ quiet = quietMode;
+ }
+
}
diff --git a/src/org/apache/fop/messaging/MessageListener.java b/src/org/apache/fop/messaging/MessageListener.java
index 20a5520fc..77340aeda 100644
--- a/src/org/apache/fop/messaging/MessageListener.java
+++ b/src/org/apache/fop/messaging/MessageListener.java
@@ -1,68 +1,25 @@
/*
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.messaging;
-/**
- * For situations, where the messages Fop directs to the user have to be handled in some
- * special way, the interface MessageListener and the class MessageEvent are provided.
- * Embedding Fop into a graphical user interface could be such a scenario.
- * Any MessageListener listens for MessageEvents, which contain the user message and
- * also the message type information (progress information or error warning).
+/**
+ * For situations, where the messages Fop directs to the user have to be handled in some
+ * special way, the interface MessageListener and the class MessageEvent are provided.
+ * Embedding Fop into a graphical user interface could be such a scenario.
+ * Any MessageListener listens for MessageEvents, which contain the user message and
+ * also the message type information (progress information or error warning).
* The class DefaultMessageListener shows an trivial implementation of MessageListener.
*/
public interface MessageListener {
- void processMessage (MessageEvent event);
+ void processMessage(MessageEvent event);
}
diff --git a/src/org/apache/fop/mif/MIFDocument.java b/src/org/apache/fop/mif/MIFDocument.java
index b44cdc3b5..ea4a16277 100644
--- a/src/org/apache/fop/mif/MIFDocument.java
+++ b/src/org/apache/fop/mif/MIFDocument.java
@@ -1,10 +1,11 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
-//Author : Seshadri G
+// Author : Seshadri G
package org.apache.fop.mif;
@@ -35,12 +36,14 @@ import java.awt.Rectangle;
*/
public class MIFDocument {
- /** the version of MIF supported */
+ /**
+ * the version of MIF supported
+ */
protected static final String mifVersion = "5.5";
protected BookComponent bookComponent;
- private Flow curFlow; // this is a ref to the current flow which could be a textflow or
+ private Flow curFlow; // this is a ref to the current flow which could be a textflow or
// a table
private ID curIDCounter = new ID();
@@ -56,13 +59,14 @@ public class MIFDocument {
class FontFormat {
- public FontFormat() { }
+ public FontFormat() {}
}
class ParagraphFormat extends FontFormat {
public ParagraphFormat() {}
+
int startIndent;
int endIndent;
@@ -77,8 +81,8 @@ public class MIFDocument {
public void output(OutputStream stream) throws IOException {
- String mif = "\n\n>";
+ String mif = "\n\n>";
byte buf[] = mif.getBytes();
stream.write(buf);
@@ -91,6 +95,7 @@ public class MIFDocument {
class PolyLine {
public PolyLine() {}
+
}
class ImportObject {
@@ -114,11 +119,11 @@ public class MIFDocument {
String path = this.url;
- //Strip 'file:'
+ // Strip 'file:'
path = path.substring(5);
String result = "";
int i;
- do { // replace all matching '/'
+ do { // replace all matching '/'
i = path.indexOf("/");
if (i != -1) {
@@ -128,14 +133,12 @@ public class MIFDocument {
path = result;
}
- } while (i != -1)
- ;
+ } while (i != -1);
String mif = "\n";
mif += "\n\t" + path + "'" + " >";
- mif += "\n\t";
+ mif += "\n\t";
mif += "\n> #End ImportObj";
stream.write(mif.getBytes());
@@ -169,13 +172,14 @@ public class MIFDocument {
public void output(OutputStream stream) throws IOException {
String mif = "\n";
- mif += "\n\t\n\t\n\t\n\t\n\t\n\t \n >";
+ mif +=
+ "\n\t\n\t\n\t\n\t\n\t\n\t \n >";
- mif += "\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t";
+ mif +=
+ "\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t";
- mif += "\n\t";
+ mif += "\n\t";
stream.write(mif.getBytes());
@@ -183,7 +187,7 @@ public class MIFDocument {
Enumeration e = content.elements();
while (e.hasMoreElements()) {
- ((ImportObject) e.nextElement()).output(stream);
+ ((ImportObject)e.nextElement()).output(stream);
}
mif = "\n> #End Frame";
stream.write(mif.getBytes());
@@ -191,6 +195,7 @@ public class MIFDocument {
}
+
public int getID() {
return this.ID;
@@ -201,7 +206,7 @@ public class MIFDocument {
class TextRect {
private int rx, ry, w, h;
private int numCols;
- private int curCol = 0; //Current column being processed
+ private int curCol = 0; // Current column being processed
private int colGap = 0;
private int textRectID;
public TextRect(int numCols) {
@@ -225,11 +230,11 @@ public class MIFDocument {
if (curCol == 0) {
- //Use the left and top margins
+ // Use the left and top margins
rx = left;
ry = top;
- w = width; // current column width , not the entire span
+ w = width; // current column width , not the entire span
h = height;
curCol++;
@@ -248,16 +253,16 @@ public class MIFDocument {
public void output(OutputStream stream) throws IOException {
- String mif = "\n" +
- "\n\t" ;
+ String mif = "\n"
+ + "\n\t";
if (numCols > 1) {
mif += "\n";
mif += "\n";
}
- mif += "\n> #End TextRect" ;
+ mif += "\n> #End TextRect";
byte buf[] = mif.getBytes();
stream.write(buf);
}
@@ -269,8 +274,7 @@ public class MIFDocument {
private String pageTag;
private String pageBackground;
private Vector textRects;
- public Page(String pageType, String pageTag,
- String pageBackground) {
+ public Page(String pageType, String pageTag, String pageBackground) {
this.pageType = pageType;
this.pageTag = pageTag;
@@ -295,7 +299,7 @@ public class MIFDocument {
public TextRect curTextRect() {
- return (TextRect) textRects.lastElement();
+ return (TextRect)textRects.lastElement();
}
@@ -304,9 +308,9 @@ public class MIFDocument {
public void output(OutputStream stream) throws IOException {
- String mif = "\n" +
- "\n\t";
+ String mif = "\n"
+ + "\n\t";
byte buf[] = mif.getBytes();
@@ -316,7 +320,7 @@ public class MIFDocument {
while (e.hasMoreElements()) {
- ((TextRect) e.nextElement()).output(stream);
+ ((TextRect)e.nextElement()).output(stream);
}
mif = "\n> #End Page\n";
@@ -330,6 +334,7 @@ public class MIFDocument {
abstract class Flow {
public Flow() {}
+
public abstract Para curPara();
public abstract void startPara();
}
@@ -338,17 +343,17 @@ public class MIFDocument {
class TextFlow extends Flow {
Vector paras;
- private int ID; // This ID is used within ParaLine, however it is
+ private int ID; // This ID is used within ParaLine, however it is
// logical to keep it unique to a textflow
public TextFlow() {
- //The current textrect into which the textflow goes
- //is the last created.
+ // The current textrect into which the textflow goes
+ // is the last created.
- this.ID = ((bookComponent.curPage()).curTextRect()).
- getTextRectID();
+ this.ID =
+ ((bookComponent.curPage()).curTextRect()).getTextRectID();
this.paras = new Vector();
}
@@ -362,7 +367,7 @@ public class MIFDocument {
public Para curPara() {
- return (Para) paras.lastElement();
+ return (Para)paras.lastElement();
}
public void startPara() {
@@ -376,7 +381,7 @@ public class MIFDocument {
Enumeration e = paras.elements();
while (e.hasMoreElements()) {
- ((Para) e.nextElement()).output(stream);
+ ((Para)e.nextElement()).output(stream);
}
mif = "\n> #End TextFlow";
stream.write(mif.getBytes());
@@ -388,8 +393,9 @@ public class MIFDocument {
class Para {
Vector paraLines;
- int ID; // Same as TextRectID
- ParagraphFormat pgf = null; // This corresponds to to the block properties
+ int ID; // Same as TextRectID
+ ParagraphFormat pgf =
+ null; // This corresponds to to the block properties
public Para() {
this.ID = 0;
@@ -408,7 +414,7 @@ public class MIFDocument {
if (paraLines.isEmpty()) {
return null;
} else {
- return (ParaLine) paraLines.lastElement();
+ return (ParaLine)paraLines.lastElement();
}
}
@@ -432,10 +438,10 @@ public class MIFDocument {
public void output(OutputStream stream) throws IOException {
String mif = "\n";
mif += "\n";
mif += "\n";
@@ -445,7 +451,7 @@ public class MIFDocument {
Enumeration e = paraLines.elements();
while (e.hasMoreElements()) {
- ((ParaLine) e.nextElement()).output(stream);
+ ((ParaLine)e.nextElement()).output(stream);
}
mif = "\n> #End ParaLine";
stream.write(mif.getBytes());
@@ -465,9 +471,10 @@ public class MIFDocument {
this.content = new Vector();
}
- public ParaLine () {
- this.textRectID = 0; // There is no ID used, in tables
+ public ParaLine() {
+
+ this.textRectID = 0; // There is no ID used, in tables
this.content = new Vector();
}
@@ -476,6 +483,7 @@ public class MIFDocument {
this.content.addElement(obj);
}
+
public void output(OutputStream stream) throws IOException {
String mif = "\n";
+ mif = "\n\t";
stream.write(mif.getBytes());
} else if (elem instanceof Tbl) {
- mif = "\n\t";
+ mif = "\n\t";
stream.write(mif.getBytes());
}
}
@@ -514,16 +522,17 @@ public class MIFDocument {
stream.write(mif.getBytes());
}
+
}
class PgfCatalog {
- Vector pgfs; // Paragraph formats
+ Vector pgfs; // Paragraph formats
public PgfCatalog() {}
public void output(OutputStream stream) throws IOException {
- String mif = "\n" +
- "\n>" + "\n>";
+ String mif = "\n"
+ + "\n>" + "\n>";
stream.write(mif.getBytes());
}
@@ -532,11 +541,13 @@ public class MIFDocument {
class Color {
public Color() {}
+
}
class ColorCatalog {
public ColorCatalog() {}
+
}
class Ruling {
@@ -583,7 +594,7 @@ public class MIFDocument {
stream.write(mif.getBytes());
Enumeration e = ruling.elements();
while (e.hasMoreElements()) {
- ((Ruling) e.nextElement()).output(stream);
+ ((Ruling)e.nextElement()).output(stream);
}
mif = "\n> #End RulingCatalog";
stream.write(mif.getBytes());
@@ -594,6 +605,7 @@ public class MIFDocument {
class TblFormat {
public TblFormat() {}
+
}
class TblCatalog {
@@ -610,6 +622,7 @@ public class MIFDocument {
this.width = width;
}
+
public void output(OutputStream stream) throws IOException {
String mif = "\n\t";
@@ -625,7 +638,7 @@ public class MIFDocument {
class Cell {
private int rowSpan, colSpan;
- private Vector paras; // Paras
+ private Vector paras; // Paras
public Cell(int rowSpan, int colSpan) {
this.rowSpan = rowSpan;
@@ -633,17 +646,19 @@ public class MIFDocument {
paras = new Vector();
}
+
public void startPara() {
this.paras.addElement(new Para());
}
+
public void output(OutputStream stream) throws IOException {
String mif = "\n\t\t #End Cell";
@@ -663,9 +678,10 @@ public class MIFDocument {
cells = new Vector();
}
+
public Cell curCell() {
- return (Cell) this.cells.lastElement();
+ return (Cell)this.cells.lastElement();
}
public void output(OutputStream stream) throws IOException {
@@ -674,7 +690,7 @@ public class MIFDocument {
stream.write(mif.getBytes());
Enumeration e = cells.elements();
while (e.hasMoreElements()) {
- ((Cell) e.nextElement()).output(stream);
+ ((Cell)e.nextElement()).output(stream);
}
mif = "\n\t> #End Row";
stream.write(mif.getBytes());
@@ -687,7 +703,7 @@ public class MIFDocument {
private int ID;
private Vector tblColumns = new Vector();
private Vector tblBody, tblHead, tblFoot;
- private Vector current; // is a reference to one of tblHead,tblBody or tblFoot
+ private Vector current; // is a reference to one of tblHead,tblBody or tblFoot
public void addColumn(int colWidth) {
tblColumns.addElement(new TblColumn(colWidth));
@@ -712,9 +728,9 @@ public class MIFDocument {
public void startCell(int rowSpan, int colSpan) {
- //Add a cell into the current row
+ // Add a cell into the current row
- ((Row) this.current.lastElement()).addCell(rowSpan, colSpan);
+ ((Row)this.current.lastElement()).addCell(rowSpan, colSpan);
}
@@ -737,16 +753,17 @@ public class MIFDocument {
// Return the last para of the current cell
Row curRow;
- curRow = (Row) this.current.lastElement();
- return (Para) curRow.curCell().paras.lastElement();
+ curRow = (Row)this.current.lastElement();
+ return (Para)curRow.curCell().paras.lastElement();
}
+
public void startPara() {
// start a new para in the current cell
Row curRow;
- curRow = (Row) this.current.lastElement();
+ curRow = (Row)this.current.lastElement();
curRow.curCell().startPara();
}
@@ -769,24 +786,24 @@ public class MIFDocument {
mif += "\n\t";
stream.write(mif.getBytes());
- if (! tblHead.isEmpty()) {
+ if (!tblHead.isEmpty()) {
Enumeration e = tblHead.elements();
while (e.hasMoreElements()) {
- ((Row) e.nextElement()).output(stream);
+ ((Row)e.nextElement()).output(stream);
}
}
- if (! tblFoot.isEmpty()) {
+ if (!tblFoot.isEmpty()) {
Enumeration e = tblFoot.elements();
while (e.hasMoreElements()) {
- ((Row) e.nextElement()).output(stream);
+ ((Row)e.nextElement()).output(stream);
}
}
- if (! tblBody.isEmpty()) {
+ if (!tblBody.isEmpty()) {
mif = "\n\t" ;
+ String mif = "" + "\n";
stream.write(mif.getBytes());
pgfCatalog.output(stream);
rulingCatalog.output(stream);
document.output(stream);
- if (! aFrames.isEmpty()) {
+ if (!aFrames.isEmpty()) {
mif = "\n. For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-public class ASCII85Filter extends PDFFilter
-{
+public class ASCII85Filter extends PDFFilter {
private static final char ASCII85_ZERO = 'z';
private static final char ASCII85_START = '!';
- private static final String ASCII85_EOD = "~>";
-
+ private static final String ASCII85_EOD = "~>";
+
private static final long base85_4 = 85;
private static final long base85_3 = base85_4 * base85_4;
private static final long base85_2 = base85_3 * base85_4;
private static final long base85_1 = base85_2 * base85_4;
-
-
- public String getName()
- {
- return "/ASCII85Decode";
+
+
+ public String getName() {
+ return "/ASCII85Decode";
}
-
- public String getDecodeParms()
- {
- return null;
+
+ public String getDecodeParms() {
+ return null;
}
- public byte[] encode(byte[] data)
- {
-
- ByteArrayOutputStream buffer = new ByteArrayOutputStream();
-
- int i;
- int total = 0;
- int diff = 0;
-
- // first encode the majority of the data
- // each 4 byte group becomes a 5 byte group
- for (i = 0; i+3 < data.length; i+=4) {
-
- long val = ((data[i] << 24) & 0xff000000L) // note: must have the L at the
- + ((data[i+1] << 16) & 0xff0000L) // end, otherwise you get into
- + ((data[i+2] << 8) & 0xff00L) // weird signed value problems
- + (data[i+3] & 0xffL); // cause we're using a full 32 bits
- byte[] conv = convertWord(val);
-
- buffer.write(conv,0,conv.length);
-
- }
-
- // now take care of the trailing few bytes.
- // with n leftover bytes, we append 0 bytes to make a full group of 4
+ public byte[] encode(byte[] data) {
+
+ ByteArrayOutputStream buffer = new ByteArrayOutputStream();
+
+ int i;
+ int total = 0;
+ int diff = 0;
+
+ // first encode the majority of the data
+ // each 4 byte group becomes a 5 byte group
+ for (i = 0; i + 3 < data.length; i += 4) {
+
+ long val = ((data[i] << 24)
+ & 0xff000000L) // note: must have the L at the
+ + ((data[i + 1] << 16) & 0xff0000L) // end, otherwise you get into
+ + ((data[i + 2] << 8) & 0xff00L) // weird signed value problems
+ + (data[i + 3] & 0xffL); // cause we're using a full 32 bits
+ byte[] conv = convertWord(val);
+
+ buffer.write(conv, 0, conv.length);
+
+ }
+
+ // now take care of the trailing few bytes.
+ // with n leftover bytes, we append 0 bytes to make a full group of 4
// then convert like normal (except not applying the special zero rule)
- // and write out the first n+1 bytes from the result
- if (i < data.length) {
- int n = data.length - i;
- byte[] lastdata = new byte[4];
- for (int j=0; j<4; j++) {
- if (j 117) {
- System.out.println("illegal char value "+new Integer(ret[i]));
- }
- }
-
- return ret;
-
-
- }
+ private byte[] convertWord(long word) {
+ word = word & 0xffffffff;
+ if (word < 0) {
+ word = -word;
+ }
+
+ if (word == 0) {
+ byte[] result = {
+ (byte)ASCII85_ZERO
+ };
+ return result;
+ } else {
+ byte c1 = (byte)((word / base85_1) & 0xFF);
+ byte c2 = (byte)(((word - (c1 * base85_1)) / base85_2) & 0xFF);
+ byte c3 =
+ (byte)(((word - (c1 * base85_1) - (c2 * base85_2)) / base85_3)
+ & 0xFF);
+ byte c4 =
+ (byte)(((word - (c1 * base85_1) - (c2 * base85_2) - (c3 * base85_3)) / base85_4)
+ & 0xFF);
+ byte c5 =
+ (byte)(((word - (c1 * base85_1) - (c2 * base85_2) - (c3 * base85_3) - (c4 * base85_4)))
+ & 0xFF);
+
+ byte[] ret = {
+ (byte)(c1 + ASCII85_START), (byte)(c2 + ASCII85_START),
+ (byte)(c3 + ASCII85_START), (byte)(c4 + ASCII85_START),
+ (byte)(c5 + ASCII85_START)
+ };
+ for (int i = 0; i < ret.length; i++) {
+ if (ret[i] < 33 || ret[i] > 117) {
+ System.out.println("illegal char value "
+ + new Integer(ret[i]));
+ }
+ }
+
+ return ret;
+
+
+ }
}
}
diff --git a/src/org/apache/fop/pdf/ASCIIHexFilter.java b/src/org/apache/fop/pdf/ASCIIHexFilter.java
index e1a103127..775a7fcb4 100644
--- a/src/org/apache/fop/pdf/ASCIIHexFilter.java
+++ b/src/org/apache/fop/pdf/ASCIIHexFilter.java
@@ -1,86 +1,39 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.pdf;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-public class ASCIIHexFilter extends PDFFilter
-{
+public class ASCIIHexFilter extends PDFFilter {
private static final String ASCIIHEX_EOD = ">";
-
- public String getName()
- {
- return "/ASCIIHexDecode";
+
+ public String getName() {
+ return "/ASCIIHexDecode";
}
-
- public String getDecodeParms()
- {
- return null;
+
+ public String getDecodeParms() {
+ return null;
}
- public byte[] encode(byte[] data)
- {
-
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < data.length; i++) {
- int val = (int) (data[i] & 0xFF);
- if (val < 16) buffer.append("0");
- buffer.append(Integer.toHexString(val));
- }
- buffer.append(ASCIIHEX_EOD);
-
- return buffer.toString().getBytes();
-
+ public byte[] encode(byte[] data) {
+
+ StringBuffer buffer = new StringBuffer();
+ for (int i = 0; i < data.length; i++) {
+ int val = (int)(data[i] & 0xFF);
+ if (val < 16)
+ buffer.append("0");
+ buffer.append(Integer.toHexString(val));
+ }
+ buffer.append(ASCIIHEX_EOD);
+
+ return buffer.toString().getBytes();
+
}
-
+
}
diff --git a/src/org/apache/fop/pdf/FlateFilter.java b/src/org/apache/fop/pdf/FlateFilter.java
index d3994aecf..b10aa78f4 100644
--- a/src/org/apache/fop/pdf/FlateFilter.java
+++ b/src/org/apache/fop/pdf/FlateFilter.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
import java.io.ByteArrayOutputStream;
@@ -59,143 +16,121 @@ import java.util.zip.DeflaterOutputStream;
* prediction, colors, bitsPerComponent, and columns are not supported
* when this filter is used to handle the data compression. They are
* only valid for externally encoded data such as that from a graphics
- * file.
+ * file.
*/
public class FlateFilter extends PDFFilter {
public static final int PREDICTION_NONE = 1;
public static final int PREDICTION_TIFF2 = 2;
public static final int PREDICTION_PNG_NONE = 10;
- public static final int PREDICTION_PNG_SUB = 11;
- public static final int PREDICTION_PNG_UP = 12;
- public static final int PREDICTION_PNG_AVG = 13;
- public static final int PREDICTION_PNG_PAETH= 14;
- public static final int PREDICTION_PNG_OPT = 15;
-
-
+ public static final int PREDICTION_PNG_SUB = 11;
+ public static final int PREDICTION_PNG_UP = 12;
+ public static final int PREDICTION_PNG_AVG = 13;
+ public static final int PREDICTION_PNG_PAETH = 14;
+ public static final int PREDICTION_PNG_OPT = 15;
+
+
private int _predictor = PREDICTION_NONE;
private int _colors;
private int _bitsPerComponent;
private int _columns;
-
- public String getName()
- {
- return "/FlateDecode";
+
+ public String getName() {
+ return "/FlateDecode";
}
-
- public String getDecodeParms()
- {
- if (_predictor > PREDICTION_NONE) {
- StringBuffer sb = new StringBuffer();
- sb.append("<< /Predictor ");
- sb.append(_predictor);
- if (_colors > 0) {
- sb.append(" /Colors "+_colors);
- }
- if (_bitsPerComponent > 0) {
- sb.append(" /BitsPerComponent "+_bitsPerComponent);
- }
- if (_columns > 0) {
- sb.append(" /Columns "+_columns);
- }
- sb.append(" >> ");
- return sb.toString();
- }
- return null;
+
+ public String getDecodeParms() {
+ if (_predictor > PREDICTION_NONE) {
+ StringBuffer sb = new StringBuffer();
+ sb.append("<< /Predictor ");
+ sb.append(_predictor);
+ if (_colors > 0) {
+ sb.append(" /Colors " + _colors);
+ }
+ if (_bitsPerComponent > 0) {
+ sb.append(" /BitsPerComponent " + _bitsPerComponent);
+ }
+ if (_columns > 0) {
+ sb.append(" /Columns " + _columns);
+ }
+ sb.append(" >> ");
+ return sb.toString();
+ }
+ return null;
}
-
+
/**
* Encode the given data and return it. Note: a side effect of
* this method is that it resets the prediction to the default
* because these attributes are not supported. So the DecodeParms
- * should be retrieved after calling this method.
+ * should be retrieved after calling this method.
*/
- public byte[] encode(byte[] data)
- {
- ByteArrayOutputStream outArrayStream = new ByteArrayOutputStream();
- _predictor = PREDICTION_NONE;
- try {
- DeflaterOutputStream compressedStream =
- new DeflaterOutputStream(outArrayStream);
- compressedStream.write(data, 0, data.length);
- compressedStream.flush();
- compressedStream.close();
- }
- catch (IOException e) {
- org.apache.fop.messaging.MessageHandler.error("Fatal error: "+
- e.getMessage());
- e.printStackTrace();
- }
-
- return outArrayStream.toByteArray();
+ public byte[] encode(byte[] data) {
+ ByteArrayOutputStream outArrayStream = new ByteArrayOutputStream();
+ _predictor = PREDICTION_NONE;
+ try {
+ DeflaterOutputStream compressedStream =
+ new DeflaterOutputStream(outArrayStream);
+ compressedStream.write(data, 0, data.length);
+ compressedStream.flush();
+ compressedStream.close();
+ } catch (IOException e) {
+ org.apache.fop.messaging.MessageHandler.error("Fatal error: "
+ + e.getMessage());
+ e.printStackTrace();
+ }
+
+ return outArrayStream.toByteArray();
}
-
- public void setPredictor(int predictor)
- throws PDFFilterException
- {
- _predictor = predictor;
-
+
+ public void setPredictor(int predictor) throws PDFFilterException {
+ _predictor = predictor;
+
}
- public int getPredictor()
- {
- return _predictor;
+ public int getPredictor() {
+ return _predictor;
}
-
-
- public void setColors(int colors)
- throws PDFFilterException
- {
- if (_predictor != PREDICTION_NONE) {
- _colors = colors;
- }
- else {
- throw new PDFFilterException
- ("Prediction must not be PREDICTION_NONE in order to set Colors");
- }
+
+
+ public void setColors(int colors) throws PDFFilterException {
+ if (_predictor != PREDICTION_NONE) {
+ _colors = colors;
+ } else {
+ throw new PDFFilterException("Prediction must not be PREDICTION_NONE in order to set Colors");
+ }
}
- public int getColors()
- {
- return _colors;
+ public int getColors() {
+ return _colors;
}
-
-
- public void setBitsPerComponent(int bits)
- throws PDFFilterException
- {
- if (_predictor != PREDICTION_NONE) {
- _bitsPerComponent = bits;
- }
- else {
- throw new PDFFilterException
- ("Prediction must not be PREDICTION_NONE in order to set bitsPerComponent");
- }
+
+
+ public void setBitsPerComponent(int bits) throws PDFFilterException {
+ if (_predictor != PREDICTION_NONE) {
+ _bitsPerComponent = bits;
+ } else {
+ throw new PDFFilterException("Prediction must not be PREDICTION_NONE in order to set bitsPerComponent");
+ }
}
- public int getBitsPerComponent()
- {
- return _bitsPerComponent;
+ public int getBitsPerComponent() {
+ return _bitsPerComponent;
}
-
-
- public void setColumns(int columns)
- throws PDFFilterException
- {
- if (_predictor != PREDICTION_NONE) {
- _columns = columns;
- }
- else {
- throw new PDFFilterException
- ("Prediction must not be PREDICTION_NONE in order to set Columns");
- }
+
+
+ public void setColumns(int columns) throws PDFFilterException {
+ if (_predictor != PREDICTION_NONE) {
+ _columns = columns;
+ } else {
+ throw new PDFFilterException("Prediction must not be PREDICTION_NONE in order to set Columns");
+ }
}
- public int getColumns()
- {
- return _columns;
+ public int getColumns() {
+ return _columns;
}
-
+
}
diff --git a/src/org/apache/fop/pdf/PDFAction.java b/src/org/apache/fop/pdf/PDFAction.java
index cd6e83bde..2749a221f 100644
--- a/src/org/apache/fop/pdf/PDFAction.java
+++ b/src/org/apache/fop/pdf/PDFAction.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.pdf;
@@ -56,27 +12,25 @@ package org.apache.fop.pdf;
*/
public abstract class PDFAction extends PDFObject {
-
+
/**
* create an Action object.
* this constructor is used for passing on the object number to the PDFObject
*
- * @param number the object's number
+ * @param number the object's number
*/
public PDFAction(int number) {
- /* generic creation of object */
- super(number);
+ /* generic creation of object */
+ super(number);
}
/**
* empty constructor for PDFAction.
* this constructor is used when there is no additional object being created
- *
+ *
*/
- public PDFAction()
- {
- }
+ public PDFAction() {}
/**
* represent the action to call
@@ -87,7 +41,7 @@ public abstract class PDFAction extends PDFObject {
* @return the action to place next to /A within a Link
*/
abstract public String getAction();
-
+
/**
* represent the object in PDF
@@ -98,4 +52,4 @@ public abstract class PDFAction extends PDFObject {
*/
abstract public byte[] toPDF();
- }
+}
diff --git a/src/org/apache/fop/pdf/PDFAnnotList.java b/src/org/apache/fop/pdf/PDFAnnotList.java
index 058fd0cc6..1a23d85d5 100644
--- a/src/org/apache/fop/pdf/PDFAnnotList.java
+++ b/src/org/apache/fop/pdf/PDFAnnotList.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.pdf;
@@ -62,10 +18,14 @@ import java.util.Vector;
*/
public class PDFAnnotList extends PDFObject {
- /** the /Annot objects */
+ /**
+ * the /Annot objects
+ */
protected Vector links = new Vector();
- /** the number of /Annot objects */
+ /**
+ * the number of /Annot objects
+ */
protected int count = 0;
/**
@@ -75,8 +35,8 @@ public class PDFAnnotList extends PDFObject {
*/
public PDFAnnotList(int number) {
- /* generic creation of object */
- super(number);
+ /* generic creation of object */
+ super(number);
}
/**
@@ -85,8 +45,8 @@ public class PDFAnnotList extends PDFObject {
* @param link the PDFLink to add.
*/
public void addLink(PDFLink link) {
- this.links.addElement(link);
- this.count++;
+ this.links.addElement(link);
+ this.count++;
}
/**
@@ -95,7 +55,7 @@ public class PDFAnnotList extends PDFObject {
* @return the number of links
*/
public int getCount() {
- return this.count;
+ return this.count;
}
/**
@@ -104,22 +64,22 @@ public class PDFAnnotList extends PDFObject {
* @return the PDF string
*/
public byte[] toPDF() {
- StringBuffer p = new StringBuffer(this.number + " "
- + this.generation
- + " obj\n[\n");
- for (int i = 0; i < this.count; i++) {
- p = p.append(((PDFObject)
- links.elementAt(i)).referencePDF() + "\n");
- }
- p = p.append("]\nendobj\n");
- return p.toString().getBytes();
+ StringBuffer p = new StringBuffer(this.number + " " + this.generation
+ + " obj\n[\n");
+ for (int i = 0; i < this.count; i++) {
+ p = p.append(((PDFObject)links.elementAt(i)).referencePDF()
+ + "\n");
+ }
+ p = p.append("]\nendobj\n");
+ return p.toString().getBytes();
}
- /* example
- 20 0 obj
- [
- 19 0 R
- ]
- endobj
- */
+ /*
+ * example
+ * 20 0 obj
+ * [
+ * 19 0 R
+ * ]
+ * endobj
+ */
}
diff --git a/src/org/apache/fop/pdf/PDFArray.java b/src/org/apache/fop/pdf/PDFArray.java
index da9a19381..243c19f09 100644
--- a/src/org/apache/fop/pdf/PDFArray.java
+++ b/src/org/apache/fop/pdf/PDFArray.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
/**
@@ -55,36 +12,37 @@ package org.apache.fop.pdf;
*/
public class PDFArray extends PDFObject {
- protected int[] values;
-
- /**
- * create the array object
- *
- * @param number the object's number
- * @param values the actual array wrapped by this object
- */
- public PDFArray(int number, int[] values) {
-
- /* generic creation of PDF object */
- super(number);
-
- /* set fields using paramaters */
- this.values = values;
- }
+ protected int[] values;
+
+ /**
+ * create the array object
+ *
+ * @param number the object's number
+ * @param values the actual array wrapped by this object
+ */
+ public PDFArray(int number, int[] values) {
+
+ /* generic creation of PDF object */
+ super(number);
+
+ /* set fields using paramaters */
+ this.values = values;
+ }
+
+ /**
+ * produce the PDF representation for the object
+ *
+ * @return the PDF
+ */
+ public byte[] toPDF() {
+ StringBuffer p = new StringBuffer();
+ p.append(this.number + " " + this.generation + " obj\n[");
+ for (int i = 0; i < values.length; i++) {
+ p.append(" ");
+ p.append(values[i]);
+ }
+ p.append("]\nendobj\n");
+ return p.toString().getBytes();
+ }
- /**
- * produce the PDF representation for the object
- *
- * @return the PDF
- */
- public byte[] toPDF() {
- StringBuffer p = new StringBuffer();
- p.append(this.number + " " + this.generation + " obj\n[");
- for (int i = 0; i < values.length; i++) {
- p.append(" ");
- p.append(values[i]);
- }
- p.append("]\nendobj\n");
- return p.toString().getBytes();
- }
}
diff --git a/src/org/apache/fop/pdf/PDFCIDFont.java b/src/org/apache/fop/pdf/PDFCIDFont.java
index 65588c6a6..5323996bb 100644
--- a/src/org/apache/fop/pdf/PDFCIDFont.java
+++ b/src/org/apache/fop/pdf/PDFCIDFont.java
@@ -1,216 +1,200 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
// based on work by Takayuki Takeuchi
+
/**
* class representing a "character identifier" font (p 210 and onwards).
*/
public class PDFCIDFont extends PDFObject {
- public static final byte CID_TYPE0 = 0;
- public static final byte CID_TYPE2 = 1;
- protected static final String[] TYPE_NAMES = {"CIDFontType0", "CIDFontType2"};
-
- protected String basefont;
-
- protected String cidtype;
- protected Integer dw;
- protected PDFWArray w;
- protected int[] dw2;
- protected PDFWArray w2;
- protected PDFCIDSystemInfo systemInfo;
- protected PDFCIDFontDescriptor descriptor;
- protected PDFCMap cmap;
- /**
- * /CIDToGIDMap (only for CIDFontType2, see p 212)
- * can be either "Identity" (default) or a PDFStream
- */
- protected PDFStream cidMap;
-
- // compatibility with Takayuki Takeuchi
- /**
- * create the /Font object
- */
- public PDFCIDFont(int number, String basefont, byte cidtype,
- int dw, int[] w,
- String registry, String ordering, int supplement,
- PDFCIDFontDescriptor descriptor) {
-
- super(number);
-
- this.basefont = basefont;
- this.cidtype = TYPE_NAMES[(int)cidtype];
- this.dw = new Integer(dw);
- this.w = new PDFWArray();
- this.w.addEntry(0, w);
- this.dw2 = null;
- this.w2 = null;
- this.systemInfo = new PDFCIDSystemInfo(registry, ordering, supplement);
- this.descriptor = descriptor;
- this.cidMap = null;
- this.cmap = null;
- }
-
- /**
- * create the /Font object
- */
- public PDFCIDFont(int number, String basefont, byte cidtype,
- int dw, PDFWArray w, PDFCIDSystemInfo systemInfo,
- PDFCIDFontDescriptor descriptor) {
-
- super(number);
-
- this.basefont = basefont;
- this.cidtype = TYPE_NAMES[(int)cidtype];
- this.dw = new Integer(dw);
- this.w = w;
- this.dw2 = null;
- this.w2 = null;
- this.systemInfo = systemInfo;
- this.descriptor = descriptor;
- this.cidMap = null;
- this.cmap = null;
- }
-
- /** set the /DW attribute */
- public void setDW(int dw) {
- this.dw = new Integer(dw);
- }
-
- /** set the /W array */
- public void setW(PDFWArray w) {
- this.w = w;
- }
-
- /** set the (two elements) /DW2 array */
- public void setDW2(int[] dw2) {
- this.dw2 = dw2;
- }
-
- /** set the two elements of the /DW2 array */
- public void setDW2(int posY, int displacementY) {
- this.dw2 = new int[] {posY, displacementY};
- }
-
- /**
- * Set the CMap used as /ToUnicode cmap
- */
+ public static final byte CID_TYPE0 = 0;
+ public static final byte CID_TYPE2 = 1;
+ protected static final String[] TYPE_NAMES = {
+ "CIDFontType0", "CIDFontType2"
+ };
+
+ protected String basefont;
+
+ protected String cidtype;
+ protected Integer dw;
+ protected PDFWArray w;
+ protected int[] dw2;
+ protected PDFWArray w2;
+ protected PDFCIDSystemInfo systemInfo;
+ protected PDFCIDFontDescriptor descriptor;
+ protected PDFCMap cmap;
+
+ /**
+ * /CIDToGIDMap (only for CIDFontType2, see p 212)
+ * can be either "Identity" (default) or a PDFStream
+ */
+ protected PDFStream cidMap;
+
+ // compatibility with Takayuki Takeuchi
+
+ /**
+ * create the /Font object
+ */
+ public PDFCIDFont(int number, String basefont, byte cidtype, int dw,
+ int[] w, String registry, String ordering,
+ int supplement, PDFCIDFontDescriptor descriptor) {
+
+ super(number);
+
+ this.basefont = basefont;
+ this.cidtype = TYPE_NAMES[(int)cidtype];
+ this.dw = new Integer(dw);
+ this.w = new PDFWArray();
+ this.w.addEntry(0, w);
+ this.dw2 = null;
+ this.w2 = null;
+ this.systemInfo = new PDFCIDSystemInfo(registry, ordering,
+ supplement);
+ this.descriptor = descriptor;
+ this.cidMap = null;
+ this.cmap = null;
+ }
+
+ /**
+ * create the /Font object
+ */
+ public PDFCIDFont(int number, String basefont, byte cidtype, int dw,
+ PDFWArray w, PDFCIDSystemInfo systemInfo,
+ PDFCIDFontDescriptor descriptor) {
+
+ super(number);
+
+ this.basefont = basefont;
+ this.cidtype = TYPE_NAMES[(int)cidtype];
+ this.dw = new Integer(dw);
+ this.w = w;
+ this.dw2 = null;
+ this.w2 = null;
+ this.systemInfo = systemInfo;
+ this.descriptor = descriptor;
+ this.cidMap = null;
+ this.cmap = null;
+ }
+
+ /**
+ * set the /DW attribute
+ */
+ public void setDW(int dw) {
+ this.dw = new Integer(dw);
+ }
+
+ /**
+ * set the /W array
+ */
+ public void setW(PDFWArray w) {
+ this.w = w;
+ }
+
+ /**
+ * set the (two elements) /DW2 array
+ */
+ public void setDW2(int[] dw2) {
+ this.dw2 = dw2;
+ }
+
+ /**
+ * set the two elements of the /DW2 array
+ */
+ public void setDW2(int posY, int displacementY) {
+ this.dw2 = new int[] {
+ posY, displacementY
+ };
+ }
+
+ /**
+ * Set the CMap used as /ToUnicode cmap
+ */
public void setCMAP(PDFCMap cmap) {
this.cmap = cmap;
}
-
- /** set the /W2 array */
- public void setW2(PDFWArray w2) {
- this.w2 = w2;
- }
-
- /** set the /CIDToGIDMap (to be used only for CIDFontType2) */
- public void setCIDMap(PDFStream map) {
- this.cidMap = map;
- }
-
- /** set the /CIDToGIDMap (to be used only for CIDFontType2) to "Identity" */
- public void setCIDMapIdentity() {
- this.cidMap = null; // not an error here, simply use the default
- }
-
- /**
- * produce the PDF representation for the object
- *
- * @return the PDF
- */
- public byte[] toPDF() {
- return toPDFString().getBytes();
- }
-
- public String toPDFString() {
- StringBuffer p = new StringBuffer();
- p.append(this.number); p.append(" ");
- p.append(this.generation);
- p.append(" obj\n<< /Type /Font");
- p.append("\n/BaseFont /"); p.append(this.basefont);
- if (cidMap != null) {
- p.append(" \n/CIDToGIDMap ");
- p.append(cidMap.referencePDF());
- }
- p.append(" \n/Subtype /"); p.append(this.cidtype);
- p.append("\n"); p.append(systemInfo.toPDFString());
- p.append("\n/FontDescriptor ");
- p.append(this.descriptor.referencePDF());
-
- if (cmap != null) {
- p.append("\n/ToUnicode ");
- p.append(cmap.referencePDF());
- }
- if (dw != null) {
- p.append("\n/DW "); p.append(this.dw);
- }
- if (w != null) {
- p.append("\n/W ");
- p.append(w.toPDFString());
- }
- if (dw2 != null) {
- p.append("\n/DW2 ["); // always two values, see p 211
- p.append(this.dw2[0]);
- p.append(this.dw2[1]);
- p.append("] \n>>\nendobj\n");
- }
- if (w2 != null) {
- p.append("\n/W2 ");
- p.append(w2.toPDFString());
- p.append(" \n>>\nendobj\n");
- }
- p.append(" \n>>\nendobj\n");
- return p.toString();
- }
+
+ /**
+ * set the /W2 array
+ */
+ public void setW2(PDFWArray w2) {
+ this.w2 = w2;
+ }
+
+ /**
+ * set the /CIDToGIDMap (to be used only for CIDFontType2)
+ */
+ public void setCIDMap(PDFStream map) {
+ this.cidMap = map;
+ }
+
+ /**
+ * set the /CIDToGIDMap (to be used only for CIDFontType2) to "Identity"
+ */
+ public void setCIDMapIdentity() {
+ this.cidMap = null; // not an error here, simply use the default
+ }
+
+ /**
+ * produce the PDF representation for the object
+ *
+ * @return the PDF
+ */
+ public byte[] toPDF() {
+ return toPDFString().getBytes();
+ }
+
+ public String toPDFString() {
+ StringBuffer p = new StringBuffer();
+ p.append(this.number);
+ p.append(" ");
+ p.append(this.generation);
+ p.append(" obj\n<< /Type /Font");
+ p.append("\n/BaseFont /");
+ p.append(this.basefont);
+ if (cidMap != null) {
+ p.append(" \n/CIDToGIDMap ");
+ p.append(cidMap.referencePDF());
+ }
+ p.append(" \n/Subtype /");
+ p.append(this.cidtype);
+ p.append("\n");
+ p.append(systemInfo.toPDFString());
+ p.append("\n/FontDescriptor ");
+ p.append(this.descriptor.referencePDF());
+
+ if (cmap != null) {
+ p.append("\n/ToUnicode ");
+ p.append(cmap.referencePDF());
+ }
+ if (dw != null) {
+ p.append("\n/DW ");
+ p.append(this.dw);
+ }
+ if (w != null) {
+ p.append("\n/W ");
+ p.append(w.toPDFString());
+ }
+ if (dw2 != null) {
+ p.append("\n/DW2 ["); // always two values, see p 211
+ p.append(this.dw2[0]);
+ p.append(this.dw2[1]);
+ p.append("] \n>>\nendobj\n");
+ }
+ if (w2 != null) {
+ p.append("\n/W2 ");
+ p.append(w2.toPDFString());
+ p.append(" \n>>\nendobj\n");
+ }
+ p.append(" \n>>\nendobj\n");
+ return p.toString();
+ }
+
}
diff --git a/src/org/apache/fop/pdf/PDFCIDFontDescriptor.java b/src/org/apache/fop/pdf/PDFCIDFontDescriptor.java
index eabc818e6..a1a6dca6a 100644
--- a/src/org/apache/fop/pdf/PDFCIDFontDescriptor.java
+++ b/src/org/apache/fop/pdf/PDFCIDFontDescriptor.java
@@ -1,56 +1,14 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
// based on work by Takayuki Takeuchi
+
/**
* class representing a font descriptor for CID fonts.
*
@@ -73,31 +31,30 @@ public class PDFCIDFontDescriptor extends PDFFontDescriptor {
* @param italicAngle the angle of the vertical dominant strokes
* @param lang the language
*/
- public PDFCIDFontDescriptor(int number,
- String basefont,
- int[] fontBBox,
- int capHeight,
- int flags,
- int italicAngle, int stemV,
- String lang) {
+ public PDFCIDFontDescriptor(int number, String basefont, int[] fontBBox,
+ int capHeight, int flags, int italicAngle,
+ int stemV, String lang) {
- super(number, basefont, fontBBox[3], fontBBox[1], capHeight, flags,
- new PDFRectangle(fontBBox), italicAngle, stemV);
+ super(number, basefont, fontBBox[3], fontBBox[1], capHeight, flags,
+ new PDFRectangle(fontBBox), italicAngle, stemV);
- this.lang = lang;
+ this.lang = lang;
}
public void setCIDSet(PDFStream cidSet) {
- this.cidSet = cidSet;
+ this.cidSet = cidSet;
}
protected void fillInPDF(StringBuffer p) {
p.append("\n/MissingWidth 500\n");
- if (lang != null) {
- p.append("\n/Lang /"); p.append(lang);
- }
- if (cidSet != null) {
- p.append("\n/CIDSet /"); this.cidSet.referencePDF();
- }
+ if (lang != null) {
+ p.append("\n/Lang /");
+ p.append(lang);
+ }
+ if (cidSet != null) {
+ p.append("\n/CIDSet /");
+ this.cidSet.referencePDF();
+ }
}
+
}
diff --git a/src/org/apache/fop/pdf/PDFCIDSystemInfo.java b/src/org/apache/fop/pdf/PDFCIDSystemInfo.java
index c8b87bde4..7104fd9d7 100644
--- a/src/org/apache/fop/pdf/PDFCIDSystemInfo.java
+++ b/src/org/apache/fop/pdf/PDFCIDSystemInfo.java
@@ -1,92 +1,55 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
// based on work by Takayuki Takeuchi
+
/**
* class representing system information for "character identifier" fonts.
*
* this small object is used in the CID fonts and in the CMaps.
*/
public class PDFCIDSystemInfo extends PDFObject {
- private static final StringBuffer p = new StringBuffer();
- protected String registry;
- protected String ordering;
- protected int supplement;
-
- public PDFCIDSystemInfo(String registry, String ordering, int supplement) {
- this.registry = registry;
- this.ordering = ordering;
- this.supplement = supplement;
- }
-
- /**
- * produce the PDF representation for the object.
- *
- * unlike the other objects, the CIDSystemInfo is written directly inside
- * the referencing object
- *
- * @return the PDF
- */
- public byte[] toPDF() {
- return toPDFString().getBytes();
- }
+ private static final StringBuffer p = new StringBuffer();
+ protected String registry;
+ protected String ordering;
+ protected int supplement;
+
+ public PDFCIDSystemInfo(String registry, String ordering,
+ int supplement) {
+ this.registry = registry;
+ this.ordering = ordering;
+ this.supplement = supplement;
+ }
+
+ /**
+ * produce the PDF representation for the object.
+ *
+ * unlike the other objects, the CIDSystemInfo is written directly inside
+ * the referencing object
+ *
+ * @return the PDF
+ */
+ public byte[] toPDF() {
+ return toPDFString().getBytes();
+ }
+
+ public String toPDFString() {
+ p.setLength(0);
+ p.append("/CIDSystemInfo << /Registry (");
+ p.append(registry);
+ p.append(")/Ordering (");
+ p.append(ordering);
+ p.append(")/Supplement ");
+ p.append(supplement);
+ p.append(" >>");
+ return p.toString();
+ }
- public String toPDFString() {
- p.setLength(0);
- p.append("/CIDSystemInfo << /Registry ("); p.append(registry);
- p.append(")/Ordering ("); p.append(ordering);
- p.append(")/Supplement "); p.append(supplement);
- p.append(" >>");
- return p.toString();
- }
}
diff --git a/src/org/apache/fop/pdf/PDFCMap.java b/src/org/apache/fop/pdf/PDFCMap.java
index de0292fb0..4e339f162 100644
--- a/src/org/apache/fop/pdf/PDFCMap.java
+++ b/src/org/apache/fop/pdf/PDFCMap.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
/**
@@ -58,176 +15,206 @@ package org.apache.fop.pdf;
* on pages 215, 216 and 217 .
*/
public class PDFCMap extends PDFStream {
- /** Chinese (simplified) */
- public static final String GB_EUC_H= "GB-EUC-H";
- public static final String GB_EUC_V= "GB_EUC_V";
- public static final String GBpc_EUC_H= "GBpc-EUC-H";
- public static final String GBpc_EUC_V= "GBpc-EUC-V";
- public static final String GBK_EUC_H= "GBK-EUC-H";
- public static final String GBK_EUC_V= "GBK-EUC-V";
- public static final String UniGB_UCS2_H= "UniGB-UCS2-H";
- public static final String UniGB_UCS2_V= "UniGB-UCS2-V";
- /** Chinese (traditional) */
- public static final String B5pc_H= "B5pc-H";
- public static final String B5pc_V= "B5pc-V";
- public static final String ETen_B5_H= "ETen-B5-H";
- public static final String ETen_B5_V= "ETen-B5-V";
- public static final String ETenms_B5_H= "ETenms-B5-H";
- public static final String ETenms_B5_V= "ETenms-B5-V";
- public static final String CNS_EUC_H= "CNS-EUC-H";
- public static final String CNS_EUC_V= "CNS-EUC-V";
- public static final String UniCNS_UCS2_H= "UniCNS-UCS2-H";
- public static final String UniCNS_UCS2_V= "UniCNS-UCS2-V";
- /** Japanese */
- public static final String _83pv_RKSJ_H= "83pv-RKSJ-H"; // no V version
- public static final String _90ms_RKSJ_H= "90ms-RKSJ-H";
- public static final String _90ms_RKSJ_V= "90ms-RKSJ-V";
- public static final String _90msp_RKSJ_H= "90msp-RKSJ-H";
- public static final String _90msp_RKSJ_V= "90msp-RKSJ-V";
- public static final String _90pv_RKSJ_H= "90pv-RKSJ-H"; // no V version
- public static final String Add_RKSJ_H= "Add-RKSJ-H";
- public static final String Add_RKSJ_V= "Add-RKSJ-V";
- public static final String EUC_H= "EUC-H";
- public static final String EUC_V= "EUC-V";
- public static final String Ext_RKSJ_H= "Ext-RKSJ-H";
- public static final String Ext_RKSJ_V= "Ext-RKSJ-V";
- public static final String H= "H";
- public static final String V= "V";
- public static final String UniJIS_UCS2_H= "UniJIS-UCS2-H";
- public static final String UniJIS_UCS2_V= "UniJIS-UCS2-V";
- public static final String UniJIS_UCS2_HW_H= "UniJIS-UCS2-HW-H";
- public static final String UniJIS_UCS2_HW_V= "UniJIS-UCS2-HW-V";
- /** Korean */
- public static final String KSC_EUC_H= "KSC-EUC-H";
- public static final String KSC_EUC_V= "KSC-EUC-V";
- public static final String KSCms_UHC_H= "KSCms-UHC-H";
- public static final String KSCms_UHC_V= "KSCms-UHC-V";
- public static final String KSCms_UHC_HW_H= "KSCms-UHC-HW-H";
- public static final String KSCms_UHC_HW_V= "KSCms-UHC-HW-V";
- public static final String KSCpc_EUC_H= "KSCpc-EUC-H"; // no V version
- public static final String UniKSC_UCS2_H= "UniKSC-UCS2-H";
- public static final String UniKSC_UCS2_V= "UniKSC-UCS2-V";
- /** Generic */
- public static final String Identity_H= "Identity-H";
- public static final String Identity_V= "Identity-V";
-
- /** /CMapName attribute, one of the predefined constants */
- protected String name;
-
- /** /CIDSystemInfo attribute */
- protected PDFCIDSystemInfo sysInfo;
-
- /** horizontal writing direction */
- public static final byte WMODE_HORIZONTAL = 0;
- /** vertical writing direction */
- public static final byte WMODE_VERTICAL = 1;
- /** font's writing direction */
- protected byte wMode = WMODE_HORIZONTAL;
-
- /** base CMap (String or PDFStream) */
- protected Object base;
-
- /**
- * create the /CMap object
- *
- * @param name one the registered names (see Table 7.20 on p 215)
- * @param sysInfo the attributes of the character collection of the CIDFont
- */
- public PDFCMap(int number, String name, PDFCIDSystemInfo sysInfo) {
- super(number);
- this.name = name;
- this.sysInfo = sysInfo;
- this.base = null;
- }
-
- /**
- * set the writing direction
- *
- * @param mode is either WMODE_HORIZONTAL
- * or WMODE_VERTICAL
- */
- public void setWMode(byte mode) {
- this.wMode = mode;
- }
+
+ /**
+ * Chinese (simplified)
+ */
+ public static final String GB_EUC_H = "GB-EUC-H";
+ public static final String GB_EUC_V = "GB_EUC_V";
+ public static final String GBpc_EUC_H = "GBpc-EUC-H";
+ public static final String GBpc_EUC_V = "GBpc-EUC-V";
+ public static final String GBK_EUC_H = "GBK-EUC-H";
+ public static final String GBK_EUC_V = "GBK-EUC-V";
+ public static final String UniGB_UCS2_H = "UniGB-UCS2-H";
+ public static final String UniGB_UCS2_V = "UniGB-UCS2-V";
+
+ /**
+ * Chinese (traditional)
+ */
+ public static final String B5pc_H = "B5pc-H";
+ public static final String B5pc_V = "B5pc-V";
+ public static final String ETen_B5_H = "ETen-B5-H";
+ public static final String ETen_B5_V = "ETen-B5-V";
+ public static final String ETenms_B5_H = "ETenms-B5-H";
+ public static final String ETenms_B5_V = "ETenms-B5-V";
+ public static final String CNS_EUC_H = "CNS-EUC-H";
+ public static final String CNS_EUC_V = "CNS-EUC-V";
+ public static final String UniCNS_UCS2_H = "UniCNS-UCS2-H";
+ public static final String UniCNS_UCS2_V = "UniCNS-UCS2-V";
+
+ /**
+ * Japanese
+ */
+ public static final String _83pv_RKSJ_H = "83pv-RKSJ-H"; // no V version
+ public static final String _90ms_RKSJ_H = "90ms-RKSJ-H";
+ public static final String _90ms_RKSJ_V = "90ms-RKSJ-V";
+ public static final String _90msp_RKSJ_H = "90msp-RKSJ-H";
+ public static final String _90msp_RKSJ_V = "90msp-RKSJ-V";
+ public static final String _90pv_RKSJ_H = "90pv-RKSJ-H"; // no V version
+ public static final String Add_RKSJ_H = "Add-RKSJ-H";
+ public static final String Add_RKSJ_V = "Add-RKSJ-V";
+ public static final String EUC_H = "EUC-H";
+ public static final String EUC_V = "EUC-V";
+ public static final String Ext_RKSJ_H = "Ext-RKSJ-H";
+ public static final String Ext_RKSJ_V = "Ext-RKSJ-V";
+ public static final String H = "H";
+ public static final String V = "V";
+ public static final String UniJIS_UCS2_H = "UniJIS-UCS2-H";
+ public static final String UniJIS_UCS2_V = "UniJIS-UCS2-V";
+ public static final String UniJIS_UCS2_HW_H = "UniJIS-UCS2-HW-H";
+ public static final String UniJIS_UCS2_HW_V = "UniJIS-UCS2-HW-V";
+
+ /**
+ * Korean
+ */
+ public static final String KSC_EUC_H = "KSC-EUC-H";
+ public static final String KSC_EUC_V = "KSC-EUC-V";
+ public static final String KSCms_UHC_H = "KSCms-UHC-H";
+ public static final String KSCms_UHC_V = "KSCms-UHC-V";
+ public static final String KSCms_UHC_HW_H = "KSCms-UHC-HW-H";
+ public static final String KSCms_UHC_HW_V = "KSCms-UHC-HW-V";
+ public static final String KSCpc_EUC_H = "KSCpc-EUC-H"; // no V version
+ public static final String UniKSC_UCS2_H = "UniKSC-UCS2-H";
+ public static final String UniKSC_UCS2_V = "UniKSC-UCS2-V";
+
+ /**
+ * Generic
+ */
+ public static final String Identity_H = "Identity-H";
+ public static final String Identity_V = "Identity-V";
+
+ /**
+ * /CMapName attribute, one of the predefined constants
+ */
+ protected String name;
+
+ /**
+ * /CIDSystemInfo attribute
+ */
+ protected PDFCIDSystemInfo sysInfo;
+
+ /**
+ * horizontal writing direction
+ */
+ public static final byte WMODE_HORIZONTAL = 0;
+
+ /**
+ * vertical writing direction
+ */
+ public static final byte WMODE_VERTICAL = 1;
+
+ /**
+ * font's writing direction
+ */
+ protected byte wMode = WMODE_HORIZONTAL;
+
+ /**
+ * base CMap (String or PDFStream)
+ */
+ protected Object base;
+
+ /**
+ * create the /CMap object
+ *
+ * @param name one the registered names (see Table 7.20 on p 215)
+ * @param sysInfo the attributes of the character collection of the CIDFont
+ */
+ public PDFCMap(int number, String name, PDFCIDSystemInfo sysInfo) {
+ super(number);
+ this.name = name;
+ this.sysInfo = sysInfo;
+ this.base = null;
+ }
+
+ /**
+ * set the writing direction
+ *
+ * @param mode is either WMODE_HORIZONTAL
+ * or WMODE_VERTICAL
+ */
+ public void setWMode(byte mode) {
+ this.wMode = mode;
+ }
public void addContents() {
- StringBuffer p=new StringBuffer();
+ StringBuffer p = new StringBuffer();
fillInPDF(p);
add(p.toString());
}
-
- /**
- * set the base CMap
- *
- * @param base the name of the base CMap (see Table 7.20)
- */
- public void setUseCMap(String base) {
- this.base = base;
- }
-
- /**
- * set the base CMap
- *
- * @param base the stream to be used as base CMap
- */
- public void setUseCMap(PDFStream base) {
- this.base = base;
- }
-
- public void fillInPDF(StringBuffer p) {
- //p.append("/Type /CMap\n");
- //p.append(sysInfo.toPDFString());
- //p.append("/CMapName /" + name);
- //p.append("\n");
- p.append("%!PS-Adobe-3.0 Resource-CMap\n");
- p.append("%%DocumentNeededResources: ProcSet (CIDInit)\n");
- p.append("%%IncludeResource: ProcSet (CIDInit)\n");
- p.append("%%BeginResource: CMap (" + name + ")\n");
- p.append("%%EndComments\n");
-
- p.append("/CIDInit /ProcSet findresource begin\n");
- p.append("12 dict begin\n");
- p.append("begincmap\n");
-
- p.append("/CIDSystemInfo 3 dict dup begin\n");
- p.append(" /Registry (Adobe) def\n");
- p.append(" /Ordering (Identity) def\n");
- p.append(" /Supplement 0 def\n");
- p.append("end def\n");
-
- p.append("/CMapVersion 1 def\n");
- p.append("/CMapType 1 def\n");
- p.append("/CMapName /" + name + " def\n");
-
- p.append("1 begincodespacerange\n");
- p.append("<0000> \n");
- p.append("endcodespacerange\n");
- p.append("1 begincidrange\n");
- p.append("<0000> 0\n");
- p.append("endcidrange\n");
-
- //p.append("1 beginbfrange\n");
- //p.append("<0020> <0100> <0000>\n");
- //p.append("endbfrange\n");
-
- p.append("endcmap\n");
- p.append("CMapName currentdict /CMap defineresource pop\n");
- p.append("end\n");
- p.append("end\n");
- p.append("%%EndResource\n");
- p.append("%%EOF\n");
- /*
- p.append(" /Type /CMap\n/CMapName /" + name);
- p.append("\n");
- p.append("\n/WMode "); p.append(wMode);
- if (base != null) {
- p.append("\n/UseCMap ");
- if (base instanceof String) {
- p.append("/"+base);
- } else { // base instanceof PDFStream
- p.append(((PDFStream)base).referencePDF());
- }
- }
- */
- }
+
+ /**
+ * set the base CMap
+ *
+ * @param base the name of the base CMap (see Table 7.20)
+ */
+ public void setUseCMap(String base) {
+ this.base = base;
+ }
+
+ /**
+ * set the base CMap
+ *
+ * @param base the stream to be used as base CMap
+ */
+ public void setUseCMap(PDFStream base) {
+ this.base = base;
+ }
+
+ public void fillInPDF(StringBuffer p) {
+ // p.append("/Type /CMap\n");
+ // p.append(sysInfo.toPDFString());
+ // p.append("/CMapName /" + name);
+ // p.append("\n");
+ p.append("%!PS-Adobe-3.0 Resource-CMap\n");
+ p.append("%%DocumentNeededResources: ProcSet (CIDInit)\n");
+ p.append("%%IncludeResource: ProcSet (CIDInit)\n");
+ p.append("%%BeginResource: CMap (" + name + ")\n");
+ p.append("%%EndComments\n");
+
+ p.append("/CIDInit /ProcSet findresource begin\n");
+ p.append("12 dict begin\n");
+ p.append("begincmap\n");
+
+ p.append("/CIDSystemInfo 3 dict dup begin\n");
+ p.append(" /Registry (Adobe) def\n");
+ p.append(" /Ordering (Identity) def\n");
+ p.append(" /Supplement 0 def\n");
+ p.append("end def\n");
+
+ p.append("/CMapVersion 1 def\n");
+ p.append("/CMapType 1 def\n");
+ p.append("/CMapName /" + name + " def\n");
+
+ p.append("1 begincodespacerange\n");
+ p.append("<0000> \n");
+ p.append("endcodespacerange\n");
+ p.append("1 begincidrange\n");
+ p.append("<0000> 0\n");
+ p.append("endcidrange\n");
+
+ // p.append("1 beginbfrange\n");
+ // p.append("<0020> <0100> <0000>\n");
+ // p.append("endbfrange\n");
+
+ p.append("endcmap\n");
+ p.append("CMapName currentdict /CMap defineresource pop\n");
+ p.append("end\n");
+ p.append("end\n");
+ p.append("%%EndResource\n");
+ p.append("%%EOF\n");
+ /*
+ * p.append(" /Type /CMap\n/CMapName /" + name);
+ * p.append("\n");
+ * p.append("\n/WMode "); p.append(wMode);
+ * if (base != null) {
+ * p.append("\n/UseCMap ");
+ * if (base instanceof String) {
+ * p.append("/"+base);
+ * } else { // base instanceof PDFStream
+ * p.append(((PDFStream)base).referencePDF());
+ * }
+ * }
+ */
+ }
+
}
diff --git a/src/org/apache/fop/pdf/PDFCharProcs.java b/src/org/apache/fop/pdf/PDFCharProcs.java
index 2ba96f277..33c493841 100644
--- a/src/org/apache/fop/pdf/PDFCharProcs.java
+++ b/src/org/apache/fop/pdf/PDFCharProcs.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
import java.util.Hashtable;
@@ -63,26 +20,31 @@ import java.util.Hashtable;
*/
public class PDFCharProcs extends PDFObject {
- /** the (character name, drawing stream) pairs for a Type3 font */
- protected Hashtable keys;
-
- public PDFCharProcs() {
- keys = new Hashtable();
- }
-
- /**
- * add a character definition in the dictionary
- *
- * @param name the character name
- * @param stream the stream that draws the character
- */
- public void addCharacter(String name, PDFStream stream) {
- keys.put(name, stream);
- }
+ /**
+ * the (character name, drawing stream) pairs for a Type3 font
+ */
+ protected Hashtable keys;
+
+ public PDFCharProcs() {
+ keys = new Hashtable();
+ }
+
+ /**
+ * add a character definition in the dictionary
+ *
+ * @param name the character name
+ * @param stream the stream that draws the character
+ */
+ public void addCharacter(String name, PDFStream stream) {
+ keys.put(name, stream);
+ }
+
+ /**
+ * not done yet
+ */
+ public byte[] toPDF() {
+ // TODO: implement this org.apache.fop.pdf.PDFObject abstract method
+ return new byte[0];
+ }
- /** not done yet */
- public byte[] toPDF() {
- //TODO: implement this org.apache.fop.pdf.PDFObject abstract method
- return new byte[0];
- }
}
diff --git a/src/org/apache/fop/pdf/PDFColor.java b/src/org/apache/fop/pdf/PDFColor.java
index f98dcc267..45279a852 100644
--- a/src/org/apache/fop/pdf/PDFColor.java
+++ b/src/org/apache/fop/pdf/PDFColor.java
@@ -1,8 +1,10 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
// Java
@@ -10,343 +12,310 @@ import java.util.Vector;
import java.io.IOException;
import java.io.PrintWriter;
-//FOP
+// FOP
import org.apache.fop.datatypes.ColorType;
import org.apache.fop.datatypes.ColorSpace;
public class PDFColor extends PDFPathPaint {
- protected static double blackFactor = 2.0;//could be 3.0 as well.
- protected double red = -1.0;
- protected double green= -1.0;
- protected double blue = -1.0;
-
- protected double cyan = -1.0;
- protected double magenta= -1.0;
- protected double yellow = -1.0;
- protected double black = -1.0;
-
- public PDFColor(org.apache.fop.datatypes.ColorType theColor)
- {
- this.colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
- //super(theNumber)
- this.red = (double)theColor.red();
- this.green = (double)theColor.green();
- this.blue = (double)theColor.blue();
-
- }
-
- public PDFColor(double theRed, double theGreen, double theBlue) {
- //super(theNumber);
- this.colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
-
- this.red = theRed;
- this.green = theGreen;
- this.blue = theBlue;
- }
-
- // components from 0 to 255
- public PDFColor(int theRed, int theGreen, int theBlue) {
- this(((double) theRed) / 255d, ((double) theGreen) / 255d, ((double) theBlue) / 255d );
-
- }
-
- public PDFColor(double theCyan, double theMagenta, double theYellow, double theBlack) {
- //super(theNumber);//?
-
- this.colorSpace = new ColorSpace(ColorSpace.DEVICE_CMYK);
-
- this.cyan = theCyan;
- this.magenta = theMagenta;
- this.yellow = theYellow;
- this.black = theBlack;
- }
-
-
- public Vector getVector()
- {//return a vector representation of the color
- //in the appropriate colorspace.
- Vector theColorVector= new Vector();
- if (this.colorSpace.getColorSpace() == ColorSpace.DEVICE_RGB)
- {//RGB
- theColorVector.addElement(new Double(this.red));
- theColorVector.addElement(new Double(this.green));
- theColorVector.addElement(new Double(this.blue));
- }
- else if (this.colorSpace.getColorSpace() == ColorSpace.DEVICE_CMYK)
- {//CMYK
- theColorVector.addElement(new Double(this.cyan));
- theColorVector.addElement(new Double(this.magenta));
- theColorVector.addElement(new Double(this.yellow));
- theColorVector.addElement(new Double(this.black));
- }
- else
- {//GRAY
- theColorVector.addElement(new Double(this.black));
- }
- return(theColorVector);
- }
-
- public double red()
- {
- return(this.red);
- }
- public double green()
- {
- return(this.green);
- }
- public double blue()
- {
- return(this.blue);
- }
- public int red255()
- {
- return (int) (this.red * 255d);
- }
- public int green255()
- {
- return (int) (this.green * 255d);
- }
- public int blue255()
- {
- return (int) (this.blue * 255d);
- }
- public double cyan()
- {
- return(this.cyan);
- }
- public double magenta()
- {
- return(this.magenta);
- }
- public double yellow()
- {
- return(this.yellow);
- }
- public double black()
- {
- return(this.black);
- }
-
- public void setColorSpace(int theColorSpace)
- {
- int theOldColorSpace = this.colorSpace.getColorSpace();
- if(theOldColorSpace!=theColorSpace)
- {
- if (theOldColorSpace==ColorSpace.DEVICE_RGB)
- {
- if(theColorSpace==ColorSpace.DEVICE_CMYK)
- {
- this.convertRGBtoCMYK();
- }
- else //convert to Gray?
- {
- this.convertRGBtoGRAY();
- }
-
- } else if(theOldColorSpace==ColorSpace.DEVICE_CMYK)
- {
- if(theColorSpace == ColorSpace.DEVICE_RGB)
- {
- this.convertCMYKtoRGB();
- }
- else //convert to Gray?
- {
- this.convertCMYKtoGRAY();
- }
- } else //used to be Gray
- {
- if(theColorSpace == ColorSpace.DEVICE_RGB)
- {
- this.convertGRAYtoRGB();
- }
- else //convert to CMYK?
- {
- this.convertGRAYtoCMYK();
- }
- }
- this.colorSpace.setColorSpace(theColorSpace);
- }
- }
-
- public String getColorSpaceOut(boolean fillNotStroke)
- {
- StringBuffer p = new StringBuffer("");
-
- double tempDouble;
-
- if(this.colorSpace.getColorSpace()==ColorSpace.DEVICE_RGB)
- {//colorspace is RGB
- // according to pdfspec 12.1 p.399
- // if the colors are the same then just use the g or G operator
- boolean same = false;
- if(this.red == this.green && this.red == this.blue) {
- same = true;
- }
- //output RGB
- if(fillNotStroke)
- { //fill
- if(same) {
- p.append(PDFNumber.doubleOut(this.red) + " g\n");
- } else {
- p.append(PDFNumber.doubleOut(this.red)+" "
- +PDFNumber.doubleOut(this.green)+" "
- +PDFNumber.doubleOut(this.blue)+" "
- +" rg \n");
- }
- }
- else
- {//stroke/border
- if(same) {
- p.append(PDFNumber.doubleOut(this.red) + " G\n");
- } else {
- p.append(PDFNumber.doubleOut(this.red)+" "
- +PDFNumber.doubleOut(this.green)+" "
- +PDFNumber.doubleOut(this.blue)+" "
- +" RG \n");
- }
- }
- }//end of output RGB
- else if (this.colorSpace.getColorSpace() == ColorSpace.DEVICE_CMYK)
- {//colorspace is CMYK
-
- if(fillNotStroke)
- { //fill
- p.append(PDFNumber.doubleOut(this.cyan) + " "
- + PDFNumber.doubleOut(this.magenta) + " "
- + PDFNumber.doubleOut(this.yellow) + " "
- + PDFNumber.doubleOut(this.black) + " k \n");
- }
- else
- { //fill
- p.append(PDFNumber.doubleOut(this.cyan) + " "
- + PDFNumber.doubleOut(this.magenta) + " "
- + PDFNumber.doubleOut(this.yellow) + " "
- + PDFNumber.doubleOut(this.black) + " K \n");
- }
-
- }//end of if CMYK
- else { //means we're in DeviceGray or Unknown.
- //assume we're in DeviceGray, because otherwise we're screwed.
-
- if(fillNotStroke)
- {
- p.append(PDFNumber.doubleOut(this.black) + " g \n");
- }
- else
- {
- p.append(PDFNumber.doubleOut(this.black) + " G \n");
- }
-
- }
- return(p.toString());
- }
-
-
-
-
- protected void convertCMYKtoRGB()
- {
- //convert CMYK to RGB
- this.red = 1.0 - this.cyan;
- this.green = 1.0 - this.green;
- this.blue= 1.0 - this.yellow;
-
- this.red = (this.black / this.blackFactor) + this.red;
- this.green = (this.black / this.blackFactor) + this.green;
- this.blue = (this.black / this.blackFactor) + this.blue;
-
- }
-
- protected void convertRGBtoCMYK()
- {
- //convert RGB to CMYK
- this.cyan = 1.0 - this.red;
- this.magenta= 1.0 - this.green;
- this.yellow = 1.0 - this.blue;
-
- this.black = 0.0;
- /* If you want to calculate black, uncomment this
- //pick the lowest color
- tempDouble = this.red;
-
- if (this.green < tempDouble)
- tempDouble = this.green;
-
- if (this.blue < tempDouble)
- tempDouble = this.blue;
-
- this.black = tempDouble / this.blackFactor;
- */
- }
-
- protected void convertGRAYtoRGB()
- {
- this.red = 1.0 - this.black;
- this.green= 1.0 - this.black;
- this.blue = 1.0 - this.black;
- }
-
- protected void convertGRAYtoCMYK()
- {
- this.cyan = this.black;
- this.magenta= this.black;
- this.yellow = this.black;
- //this.black=0.0;//?
- }
-
- protected void convertCMYKtoGRAY()
- {
- double tempDouble=0.0;
-
- //pick the lowest color
- tempDouble = this.cyan;
-
- if (this.magenta < tempDouble)
- tempDouble = this.magenta;
-
- if (this.yellow < tempDouble)
- tempDouble = this.yellow;
-
- this.black = (tempDouble / this.blackFactor);
-
- }
-
- protected void convertRGBtoGRAY()
- {
- double tempDouble=0.0;
-
- //pick the lowest color
- tempDouble = this.red;
-
- if (this.green < tempDouble)
- tempDouble = this.green;
-
- if (this.blue < tempDouble)
- tempDouble = this.blue;
-
- this.black = 1.0 - (tempDouble / this.blackFactor);
-
- }
-
- byte[] toPDF()
- {
- return (new byte[0]);
-
- } //end of toPDF
-
- public boolean equals(Object obj)
- {
- if (!(obj instanceof PDFColor)) {
- return false;
- }
- PDFColor color = (PDFColor)obj;
-
- if (color.red == this.red &&
- color.green == this.green &&
- color.blue == this.blue) {
- return true;
- }
- return false;
+ protected static double blackFactor = 2.0; // could be 3.0 as well.
+ protected double red = -1.0;
+ protected double green = -1.0;
+ protected double blue = -1.0;
+
+ protected double cyan = -1.0;
+ protected double magenta = -1.0;
+ protected double yellow = -1.0;
+ protected double black = -1.0;
+
+ public PDFColor(org.apache.fop.datatypes.ColorType theColor) {
+ this.colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
+ // super(theNumber)
+ this.red = (double)theColor.red();
+ this.green = (double)theColor.green();
+ this.blue = (double)theColor.blue();
+
+ }
+
+ public PDFColor(double theRed, double theGreen, double theBlue) {
+ // super(theNumber);
+ this.colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
+
+ this.red = theRed;
+ this.green = theGreen;
+ this.blue = theBlue;
+ }
+
+ // components from 0 to 255
+ public PDFColor(int theRed, int theGreen, int theBlue) {
+ this(((double)theRed) / 255d, ((double)theGreen) / 255d,
+ ((double)theBlue) / 255d);
+
+ }
+
+ public PDFColor(double theCyan, double theMagenta, double theYellow,
+ double theBlack) {
+ // super(theNumber);//?
+
+ this.colorSpace = new ColorSpace(ColorSpace.DEVICE_CMYK);
+
+ this.cyan = theCyan;
+ this.magenta = theMagenta;
+ this.yellow = theYellow;
+ this.black = theBlack;
+ }
+
+
+ public Vector getVector() { // return a vector representation of the color
+ // in the appropriate colorspace.
+ Vector theColorVector = new Vector();
+ if (this.colorSpace.getColorSpace() == ColorSpace.DEVICE_RGB) { // RGB
+ theColorVector.addElement(new Double(this.red));
+ theColorVector.addElement(new Double(this.green));
+ theColorVector.addElement(new Double(this.blue));
+ } else if (this.colorSpace.getColorSpace()
+ == ColorSpace.DEVICE_CMYK) { // CMYK
+ theColorVector.addElement(new Double(this.cyan));
+ theColorVector.addElement(new Double(this.magenta));
+ theColorVector.addElement(new Double(this.yellow));
+ theColorVector.addElement(new Double(this.black));
+ } else { // GRAY
+ theColorVector.addElement(new Double(this.black));
+ }
+ return (theColorVector);
+ }
+
+ public double red() {
+ return (this.red);
+ }
+
+ public double green() {
+ return (this.green);
+ }
+
+ public double blue() {
+ return (this.blue);
+ }
+
+ public int red255() {
+ return (int)(this.red * 255d);
+ }
+
+ public int green255() {
+ return (int)(this.green * 255d);
+ }
+
+ public int blue255() {
+ return (int)(this.blue * 255d);
+ }
+
+ public double cyan() {
+ return (this.cyan);
+ }
+
+ public double magenta() {
+ return (this.magenta);
+ }
+
+ public double yellow() {
+ return (this.yellow);
+ }
+
+ public double black() {
+ return (this.black);
+ }
+
+ public void setColorSpace(int theColorSpace) {
+ int theOldColorSpace = this.colorSpace.getColorSpace();
+ if (theOldColorSpace != theColorSpace) {
+ if (theOldColorSpace == ColorSpace.DEVICE_RGB) {
+ if (theColorSpace == ColorSpace.DEVICE_CMYK) {
+ this.convertRGBtoCMYK();
+ } else // convert to Gray?
+ {
+ this.convertRGBtoGRAY();
+ }
+
+ } else if (theOldColorSpace == ColorSpace.DEVICE_CMYK) {
+ if (theColorSpace == ColorSpace.DEVICE_RGB) {
+ this.convertCMYKtoRGB();
+ } else // convert to Gray?
+ {
+ this.convertCMYKtoGRAY();
+ }
+ } else // used to be Gray
+ {
+ if (theColorSpace == ColorSpace.DEVICE_RGB) {
+ this.convertGRAYtoRGB();
+ } else // convert to CMYK?
+ {
+ this.convertGRAYtoCMYK();
+ }
+ }
+ this.colorSpace.setColorSpace(theColorSpace);
+ }
+ }
+
+ public String getColorSpaceOut(boolean fillNotStroke) {
+ StringBuffer p = new StringBuffer("");
+
+ double tempDouble;
+
+ if (this.colorSpace.getColorSpace()
+ == ColorSpace.DEVICE_RGB) { // colorspace is RGB
+ // according to pdfspec 12.1 p.399
+ // if the colors are the same then just use the g or G operator
+ boolean same = false;
+ if (this.red == this.green && this.red == this.blue) {
+ same = true;
+ }
+ // output RGB
+ if (fillNotStroke) { // fill
+ if (same) {
+ p.append(PDFNumber.doubleOut(this.red) + " g\n");
+ } else {
+ p.append(PDFNumber.doubleOut(this.red) + " "
+ + PDFNumber.doubleOut(this.green) + " "
+ + PDFNumber.doubleOut(this.blue) + " "
+ + " rg \n");
+ }
+ } else { // stroke/border
+ if (same) {
+ p.append(PDFNumber.doubleOut(this.red) + " G\n");
+ } else {
+ p.append(PDFNumber.doubleOut(this.red) + " "
+ + PDFNumber.doubleOut(this.green) + " "
+ + PDFNumber.doubleOut(this.blue) + " "
+ + " RG \n");
+ }
+ }
+ } // end of output RGB
+ else if (this.colorSpace.getColorSpace()
+ == ColorSpace.DEVICE_CMYK) { // colorspace is CMYK
+
+ if (fillNotStroke) { // fill
+ p.append(PDFNumber.doubleOut(this.cyan) + " "
+ + PDFNumber.doubleOut(this.magenta) + " "
+ + PDFNumber.doubleOut(this.yellow) + " "
+ + PDFNumber.doubleOut(this.black) + " k \n");
+ } else { // fill
+ p.append(PDFNumber.doubleOut(this.cyan) + " "
+ + PDFNumber.doubleOut(this.magenta) + " "
+ + PDFNumber.doubleOut(this.yellow) + " "
+ + PDFNumber.doubleOut(this.black) + " K \n");
+ }
+
+ } // end of if CMYK
+ else { // means we're in DeviceGray or Unknown.
+ // assume we're in DeviceGray, because otherwise we're screwed.
+
+ if (fillNotStroke) {
+ p.append(PDFNumber.doubleOut(this.black) + " g \n");
+ } else {
+ p.append(PDFNumber.doubleOut(this.black) + " G \n");
+ }
+
+ }
+ return (p.toString());
+ }
+
+
+
+
+ protected void convertCMYKtoRGB() {
+ // convert CMYK to RGB
+ this.red = 1.0 - this.cyan;
+ this.green = 1.0 - this.green;
+ this.blue = 1.0 - this.yellow;
+
+ this.red = (this.black / this.blackFactor) + this.red;
+ this.green = (this.black / this.blackFactor) + this.green;
+ this.blue = (this.black / this.blackFactor) + this.blue;
+
+ }
+
+ protected void convertRGBtoCMYK() {
+ // convert RGB to CMYK
+ this.cyan = 1.0 - this.red;
+ this.magenta = 1.0 - this.green;
+ this.yellow = 1.0 - this.blue;
+
+ this.black = 0.0;
+ /*
+ * If you want to calculate black, uncomment this
+ * //pick the lowest color
+ * tempDouble = this.red;
+ *
+ * if (this.green < tempDouble)
+ * tempDouble = this.green;
+ *
+ * if (this.blue < tempDouble)
+ * tempDouble = this.blue;
+ *
+ * this.black = tempDouble / this.blackFactor;
+ */
+ }
+
+ protected void convertGRAYtoRGB() {
+ this.red = 1.0 - this.black;
+ this.green = 1.0 - this.black;
+ this.blue = 1.0 - this.black;
+ }
+
+ protected void convertGRAYtoCMYK() {
+ this.cyan = this.black;
+ this.magenta = this.black;
+ this.yellow = this.black;
+ // this.black=0.0;//?
}
-
+
+ protected void convertCMYKtoGRAY() {
+ double tempDouble = 0.0;
+
+ // pick the lowest color
+ tempDouble = this.cyan;
+
+ if (this.magenta < tempDouble)
+ tempDouble = this.magenta;
+
+ if (this.yellow < tempDouble)
+ tempDouble = this.yellow;
+
+ this.black = (tempDouble / this.blackFactor);
+
+ }
+
+ protected void convertRGBtoGRAY() {
+ double tempDouble = 0.0;
+
+ // pick the lowest color
+ tempDouble = this.red;
+
+ if (this.green < tempDouble)
+ tempDouble = this.green;
+
+ if (this.blue < tempDouble)
+ tempDouble = this.blue;
+
+ this.black = 1.0 - (tempDouble / this.blackFactor);
+
+ }
+
+ byte[] toPDF() {
+ return (new byte[0]);
+
+ } // end of toPDF
+
+ public boolean equals(Object obj) {
+ if (!(obj instanceof PDFColor)) {
+ return false;
+ }
+ PDFColor color = (PDFColor)obj;
+
+ if (color.red == this.red && color.green == this.green
+ && color.blue == this.blue) {
+ return true;
+ }
+ return false;
+ }
+
}
diff --git a/src/org/apache/fop/pdf/PDFDocument.java b/src/org/apache/fop/pdf/PDFDocument.java
index 542107a6a..e26c59982 100644
--- a/src/org/apache/fop/pdf/PDFDocument.java
+++ b/src/org/apache/fop/pdf/PDFDocument.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
/* image support modified from work of BoBoGi */
@@ -61,7 +17,7 @@ import org.apache.fop.image.FopImage;
import org.apache.fop.layout.LinkSet;
import org.apache.fop.datatypes.ColorSpace;
-import org.apache.fop.render.pdf.CIDFont;
+import org.apache.fop.render.pdf.CIDFont;
import org.apache.fop.datatypes.IDReferences;
import org.apache.fop.layout.Page;
@@ -90,54 +46,86 @@ import java.awt.Rectangle;
*/
public class PDFDocument {
- /** the version of PDF supported */
+ /**
+ * the version of PDF supported
+ */
protected static final String pdfVersion = "1.3";
- /** the current character position */
+ /**
+ * the current character position
+ */
protected int position = 0;
- /** the character position of each object */
+ /**
+ * the character position of each object
+ */
protected Vector location = new Vector();
- /** the counter for object numbering */
+ /**
+ * the counter for object numbering
+ */
protected int objectcount = 0;
- /** the objects themselves */
+ /**
+ * the objects themselves
+ */
protected Vector objects = new Vector();
- /** character position of xref table */
+ /**
+ * character position of xref table
+ */
protected int xref;
- /** the /Root object */
+ /**
+ * the /Root object
+ */
protected PDFRoot root;
- /** the /Info object */
+ /**
+ * the /Info object
+ */
protected PDFInfo info;
- /** the /Resources object */
+ /**
+ * the /Resources object
+ */
protected PDFResources resources;
- /** the documents idReferences */
+ /**
+ * the documents idReferences
+ */
protected IDReferences idReferences;
- /** the colorspace (0=RGB, 1=CMYK) **/
- //protected int colorspace = 0;
+ /**
+ * the colorspace (0=RGB, 1=CMYK)
+ */
+ // protected int colorspace = 0;
protected ColorSpace colorspace = new ColorSpace(ColorSpace.DEVICE_RGB);
- /** the counter for Pattern name numbering (e.g. 'Pattern1')*/
+ /**
+ * the counter for Pattern name numbering (e.g. 'Pattern1')
+ */
protected int patternCount = 0;
- /** the counter for Shading name numbering */
+ /**
+ * the counter for Shading name numbering
+ */
protected int shadingCount = 0;
- /** the counter for XObject numbering */
+ /**
+ * the counter for XObject numbering
+ */
protected int xObjectCount = 0;
- /** the XObjects */
+ /**
+ * the XObjects
+ */
protected Vector xObjects = new Vector();
- /** the XObjects Map.
- Should be modified (works only for image subtype) */
+ /**
+ * the XObjects Map.
+ * Should be modified (works only for image subtype)
+ */
protected Hashtable xObjectsMap = new Hashtable();
/**
@@ -167,13 +155,17 @@ public class PDFDocument {
*/
protected PDFRoot makeRoot() {
- /* create a PDFRoot with the next object number and add to
- list of objects */
+ /*
+ * create a PDFRoot with the next object number and add to
+ * list of objects
+ */
PDFRoot pdfRoot = new PDFRoot(++this.objectcount);
this.objects.addElement(pdfRoot);
- /* create a new /Pages object to be root of Pages hierarchy
- and add to list of objects */
+ /*
+ * create a new /Pages object to be root of Pages hierarchy
+ * and add to list of objects
+ */
PDFPages rootPages = new PDFPages(++this.objectcount);
this.objects.addElement(rootPages);
@@ -190,12 +182,14 @@ public class PDFDocument {
*/
protected PDFInfo makeInfo() {
- /* create a PDFInfo with the next object number and add to
- list of objects */
+ /*
+ * create a PDFInfo with the next object number and add to
+ * list of objects
+ */
PDFInfo pdfInfo = new PDFInfo(++this.objectcount);
- // set the default producer
- pdfInfo.setProducer(org.apache.fop.apps.Version.getVersion());
- this.objects.addElement(pdfInfo);
+ // set the default producer
+ pdfInfo.setProducer(org.apache.fop.apps.Version.getVersion());
+ this.objects.addElement(pdfInfo);
return pdfInfo;
}
@@ -206,8 +200,10 @@ public class PDFDocument {
*/
private PDFResources makeResources() {
- /* create a PDFResources with the next object number and add
- to list of objects */
+ /*
+ * create a PDFResources with the next object number and add
+ * to list of objects
+ */
PDFResources pdfResources = new PDFResources(++this.objectcount);
this.objects.addElement(pdfResources);
return pdfResources;
@@ -215,7 +211,7 @@ public class PDFDocument {
/**
* Make a Type 0 sampled function
- *
+ *
* @param theDomain Vector objects of Double objects.
* This is the domain of the function.
* See page 264 of the PDF 1.3 Spec.
@@ -226,39 +222,39 @@ public class PDFDocument {
* This is the number of samples in each input dimension.
* I can't imagine there being more or less than two input dimensions,
* so maybe this should be an array of length 2.
- *
+ *
* See page 265 of the PDF 1.3 Spec.
* @param theBitsPerSample An int specifying the number of bits user to represent each sample value.
* Limited to 1,2,4,8,12,16,24 or 32.
* See page 265 of the 1.3 PDF Spec.
* @param theOrder The order of interpolation between samples. Default is 1 (one). Limited
* to 1 (one) or 3, which means linear or cubic-spline interpolation.
- *
+ *
* This attribute is optional.
- *
+ *
* See page 265 in the PDF 1.3 spec.
* @param theEncode Vector objects of Double objects.
* This is the linear mapping of input values intop the domain
* of the function's sample table. Default is hard to represent in
* ascii, but basically [0 (Size0 1) 0 (Size1 1)...].
* This attribute is optional.
- *
+ *
* See page 265 in the PDF 1.3 spec.
* @param theDecode Vector objects of Double objects.
* This is a linear mapping of sample values into the range.
* The default is just the range.
- *
+ *
* This attribute is optional.
* Read about it on page 265 of the PDF 1.3 spec.
* @param theFunctionDataStream The sample values that specify the function are provided in a stream.
- *
+ *
* This is optional, but is almost always used.
- *
+ *
* Page 265 of the PDF 1.3 spec has more.
* @param theFilter This is a vector of String objects which are the various filters that
* have are to be applied to the stream to make sense of it. Order matters,
* so watch out.
- *
+ *
* This is not documented in the Function section of the PDF 1.3 spec,
* it was deduced from samples that this is sometimes used, even if we may never
* use it in FOP. It is added for completeness sake.
@@ -266,27 +262,28 @@ public class PDFDocument {
* @param theFunctionType This is the type of function (0,2,3, or 4).
* It should be 0 as this is the constructor for sampled functions.
*/
- public PDFFunction makeFunction(int theFunctionType,
- Vector theDomain, Vector theRange,
- Vector theSize,int theBitsPerSample,
- int theOrder,Vector theEncode,Vector theDecode,
- StringBuffer theFunctionDataStream, Vector theFilter)
- {//Type 0 function
- PDFFunction function = new PDFFunction(
- ++this.objectcount, theFunctionType,
- theDomain, theRange, theSize,
- theBitsPerSample, theOrder,
- theEncode, theDecode,
- theFunctionDataStream, theFilter);
+ public PDFFunction makeFunction(int theFunctionType, Vector theDomain,
+ Vector theRange, Vector theSize,
+ int theBitsPerSample, int theOrder,
+ Vector theEncode, Vector theDecode,
+ StringBuffer theFunctionDataStream,
+ Vector theFilter) { // Type 0 function
+ PDFFunction function = new PDFFunction(++this.objectcount,
+ theFunctionType, theDomain,
+ theRange, theSize,
+ theBitsPerSample, theOrder,
+ theEncode, theDecode,
+ theFunctionDataStream,
+ theFilter);
this.objects.addElement(function);
- return(function);
+ return (function);
}
/**
* make a type Exponential interpolation function
* (for shading usually)
- *
+ *
* @param theDomain Vector objects of Double objects.
* This is the domain of the function.
* See page 264 of the PDF 1.3 Spec.
@@ -294,40 +291,36 @@ public class PDFDocument {
* See page 264 of the PDF 1.3 Spec.
* @param theCZero This is a vector of Double objects which defines the function result
* when x=0.
- *
+ *
* This attribute is optional.
* It's described on page 268 of the PDF 1.3 spec.
* @param theCOne This is a vector of Double objects which defines the function result
* when x=1.
- *
+ *
* This attribute is optional.
* It's described on page 268 of the PDF 1.3 spec.
* @param theInterpolationExponentN This is the inerpolation exponent.
- *
+ *
* This attribute is required.
* PDF Spec page 268
* @param theFunctionType The type of the function, which should be 2.
*/
- public PDFFunction makeFunction(int theFunctionType,
- Vector theDomain, Vector theRange,
- Vector theCZero, Vector theCOne,
- double theInterpolationExponentN)
-
- {//type 2
- PDFFunction function = new PDFFunction(
- ++this.objectcount,
- theFunctionType,
- theDomain, theRange,
- theCZero, theCOne,
- theInterpolationExponentN);
+ public PDFFunction makeFunction(int theFunctionType, Vector theDomain,
+ Vector theRange, Vector theCZero,
+ Vector theCOne,
+ double theInterpolationExponentN) { // type 2
+ PDFFunction function = new PDFFunction(++this.objectcount,
+ theFunctionType, theDomain,
+ theRange, theCZero, theCOne,
+ theInterpolationExponentN);
this.objects.addElement(function);
- return(function);
+ return (function);
}
/**
* Make a Type 3 Stitching function
- *
+ *
* @param theDomain Vector objects of Double objects.
* This is the domain of the function.
* See page 264 of the PDF 1.3 Spec.
@@ -335,16 +328,16 @@ public class PDFDocument {
* This is the Range of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theFunctions A Vector of the PDFFunction objects that the stitching function stitches.
- *
+ *
* This attributed is required.
* It is described on page 269 of the PDF spec.
* @param theBounds This is a vector of Doubles representing the numbers that,
* in conjunction with Domain define the intervals to which each function from
* the 'functions' object applies. It must be in order of increasing magnitude,
* and each must be within Domain.
- *
+ *
* It basically sets how much of the gradient each function handles.
- *
+ *
* This attributed is required.
* It's described on page 269 of the PDF 1.3 spec.
* @param theEncode Vector objects of Double objects.
@@ -352,31 +345,28 @@ public class PDFDocument {
* of the function's sample table. Default is hard to represent in
* ascii, but basically [0 (Size0 1) 0 (Size1 1)...].
* This attribute is required.
- *
+ *
* See page 270 in the PDF 1.3 spec.
* @param theFunctionType This is the function type. It should be 3,
* for a stitching function.
*/
- public PDFFunction makeFunction(int theFunctionType,
- Vector theDomain, Vector theRange,
- Vector theFunctions, Vector theBounds,
- Vector theEncode)
- {//Type 3
-
- PDFFunction function = new PDFFunction(
- ++this.objectcount,
- theFunctionType,
- theDomain, theRange,
- theFunctions, theBounds,
- theEncode);
+ public PDFFunction makeFunction(int theFunctionType, Vector theDomain,
+ Vector theRange, Vector theFunctions,
+ Vector theBounds,
+ Vector theEncode) { // Type 3
+
+ PDFFunction function = new PDFFunction(++this.objectcount,
+ theFunctionType, theDomain,
+ theRange, theFunctions,
+ theBounds, theEncode);
this.objects.addElement(function);
- return(function);
+ return (function);
}
/**
* make a postscript calculator function
- *
+ *
* @param theNumber
* @param theFunctionType
* @param theDomain
@@ -384,23 +374,21 @@ public class PDFDocument {
* @param theFunctionDataStream
*/
public PDFFunction makeFunction(int theNumber, int theFunctionType,
- Vector theDomain, Vector theRange,
- StringBuffer theFunctionDataStream)
- { //Type 4
- PDFFunction function = new PDFFunction(
- ++this.objectcount,
- theFunctionType,
- theDomain, theRange,
- theFunctionDataStream);
+ Vector theDomain, Vector theRange,
+ StringBuffer theFunctionDataStream) { // Type 4
+ PDFFunction function = new PDFFunction(++this.objectcount,
+ theFunctionType, theDomain,
+ theRange,
+ theFunctionDataStream);
this.objects.addElement(function);
- return(function);
+ return (function);
}
/**
* make a function based shading object
- *
+ *
* @param theShadingType The type of shading object, which should be 1 for function
* based shading.
* @param theColorSpace The colorspace is 'DeviceRGB' or something similar.
@@ -419,67 +407,73 @@ public class PDFDocument {
* It's optional, the default is the identity matrix
* @param theFunction The PDF Function that maps an (x,y) location to a color
*/
- public PDFShading makeShading(int theShadingType, ColorSpace theColorSpace,
- Vector theBackground, Vector theBBox, boolean theAntiAlias,
- Vector theDomain, Vector theMatrix, PDFFunction theFunction)
- { //make Shading of Type 1
- String theShadingName = new String("Sh"+(++this.shadingCount));
-
- PDFShading shading = new PDFShading(++this.objectcount, theShadingName,
- theShadingType, theColorSpace, theBackground, theBBox,
- theAntiAlias, theDomain, theMatrix, theFunction);
+ public PDFShading makeShading(int theShadingType,
+ ColorSpace theColorSpace,
+ Vector theBackground, Vector theBBox,
+ boolean theAntiAlias, Vector theDomain,
+ Vector theMatrix,
+ PDFFunction theFunction) { // make Shading of Type 1
+ String theShadingName = new String("Sh" + (++this.shadingCount));
+
+ PDFShading shading = new PDFShading(++this.objectcount,
+ theShadingName, theShadingType,
+ theColorSpace, theBackground,
+ theBBox, theAntiAlias, theDomain,
+ theMatrix, theFunction);
this.objects.addElement(shading);
- //add this shading to resources
+ // add this shading to resources
this.resources.addShading(shading);
- return(shading);
+ return (shading);
}
/**
* Make an axial or radial shading object.
- *
- * @param theShadingType 2 or 3 for axial or radial shading
- * @param theColorSpace "DeviceRGB" or similar.
- * @param theBackground theBackground An array of color components appropriate to the
- * colorspace key specifying a single color value.
- * This key is used by the f operator buy ignored by the sh operator.
- * @param theBBox Vector of double's representing a rectangle
- * in the coordinate space that is current at the
- * time of shading is imaged. Temporary clipping
- * boundary.
- * @param theAntiAlias Default is false
- * @param theCoords Vector of four (type 2) or 6 (type 3) Double
- * @param theDomain Vector of Doubles specifying the domain
- * @param theFunction the Stitching (PDFfunction type 3) function, even if it's stitching a single function
- * @param theExtend Vector of Booleans of whether to extend teh start and end colors past the start and end points
- * The default is [false, false]
+ *
+ * @param theShadingType 2 or 3 for axial or radial shading
+ * @param theColorSpace "DeviceRGB" or similar.
+ * @param theBackground theBackground An array of color components appropriate to the
+ * colorspace key specifying a single color value.
+ * This key is used by the f operator buy ignored by the sh operator.
+ * @param theBBox Vector of double's representing a rectangle
+ * in the coordinate space that is current at the
+ * time of shading is imaged. Temporary clipping
+ * boundary.
+ * @param theAntiAlias Default is false
+ * @param theCoords Vector of four (type 2) or 6 (type 3) Double
+ * @param theDomain Vector of Doubles specifying the domain
+ * @param theFunction the Stitching (PDFfunction type 3) function, even if it's stitching a single function
+ * @param theExtend Vector of Booleans of whether to extend teh start and end colors past the start and end points
+ * The default is [false, false]
*/
public PDFShading makeShading(int theShadingType,
- ColorSpace theColorSpace, Vector theBackground,
- Vector theBBox, boolean theAntiAlias,
- Vector theCoords, Vector theDomain,
- PDFFunction theFunction, Vector theExtend)
- { //make Shading of Type 2 or 3
- String theShadingName = new String("Sh"+(++this.shadingCount));
-
- PDFShading shading = new PDFShading(++this.objectcount, theShadingName,
- theShadingType, theColorSpace,
- theBackground, theBBox, theAntiAlias,
- theCoords, theDomain,theFunction,theExtend);
+ ColorSpace theColorSpace,
+ Vector theBackground, Vector theBBox,
+ boolean theAntiAlias, Vector theCoords,
+ Vector theDomain, PDFFunction theFunction,
+ Vector theExtend) { // make Shading of Type 2 or 3
+ String theShadingName = new String("Sh" + (++this.shadingCount));
+
+ PDFShading shading = new PDFShading(++this.objectcount,
+ theShadingName, theShadingType,
+ theColorSpace, theBackground,
+ theBBox, theAntiAlias, theCoords,
+ theDomain, theFunction,
+ theExtend);
this.resources.addShading(shading);
this.objects.addElement(shading);
- return(shading);
+ return (shading);
}
/**
- * Make a free-form gouraud shaded triangle mesh, coons patch mesh, or tensor patch mesh
+ * Make a free-form gouraud shaded triangle mesh, coons patch mesh, or tensor patch mesh
* shading object
- *
+ *
* @param theShadingType 4, 6, or 7 depending on whether it's
- * Free-form gouraud-shaded triangle meshes, coons patch meshes,
+ * Free-form gouraud-shaded triangle meshes, coons patch meshes,
* or tensor product patch meshes, respectively.
* @param theColorSpace "DeviceRGB" or similar.
* @param theBackground theBackground An array of color components appropriate to the
@@ -496,28 +490,34 @@ public class PDFDocument {
* @param theDecode Vector of Doubles see PDF 1.3 spec pages 303 to 312.
* @param theFunction the PDFFunction
*/
- public PDFShading makeShading(int theShadingType, ColorSpace theColorSpace,
- Vector theBackground, Vector theBBox, boolean theAntiAlias,
- int theBitsPerCoordinate, int theBitsPerComponent,
- int theBitsPerFlag, Vector theDecode, PDFFunction theFunction)
- { //make Shading of type 4,6 or 7
- String theShadingName = new String("Sh"+(++this.shadingCount));
-
- PDFShading shading = new PDFShading(++this.objectcount, theShadingName,
- theShadingType, theColorSpace,
- theBackground, theBBox, theAntiAlias,
- theBitsPerCoordinate,theBitsPerComponent,
- theBitsPerFlag, theDecode, theFunction);
+ public PDFShading makeShading(int theShadingType,
+ ColorSpace theColorSpace,
+ Vector theBackground, Vector theBBox,
+ boolean theAntiAlias,
+ int theBitsPerCoordinate,
+ int theBitsPerComponent,
+ int theBitsPerFlag, Vector theDecode,
+ PDFFunction theFunction) { // make Shading of type 4,6 or 7
+ String theShadingName = new String("Sh" + (++this.shadingCount));
+
+ PDFShading shading = new PDFShading(++this.objectcount,
+ theShadingName, theShadingType,
+ theColorSpace, theBackground,
+ theBBox, theAntiAlias,
+ theBitsPerCoordinate,
+ theBitsPerComponent,
+ theBitsPerFlag, theDecode,
+ theFunction);
this.resources.addShading(shading);
this.objects.addElement(shading);
- return(shading);
+ return (shading);
}
/**
* make a Lattice-Form Gouraud mesh shading object
- *
+ *
* @param theShadingType 5 for lattice-Form Gouraud shaded-triangle mesh
* without spaces. "Shading1" or "Sh1" are good examples.
* @param theColorSpace "DeviceRGB" or similar.
@@ -535,30 +535,35 @@ public class PDFDocument {
* @param theVerticesPerRow number of vertices in each "row" of the lattice.
* @param theFunction The PDFFunction that's mapped on to this shape
*/
- public PDFShading makeShading(int theShadingType, ColorSpace theColorSpace,
- Vector theBackground, Vector theBBox, boolean theAntiAlias,
- int theBitsPerCoordinate, int theBitsPerComponent,
- Vector theDecode, int theVerticesPerRow, PDFFunction theFunction)
- { //make shading of Type 5
- String theShadingName = new String("Sh"+(++this.shadingCount));
-
- PDFShading shading= new PDFShading(++this.objectcount,
- theShadingName, theShadingType, theColorSpace,
- theBackground, theBBox, theAntiAlias,
- theBitsPerCoordinate, theBitsPerComponent,
- theDecode, theVerticesPerRow, theFunction);
+ public PDFShading makeShading(int theShadingType,
+ ColorSpace theColorSpace,
+ Vector theBackground, Vector theBBox,
+ boolean theAntiAlias,
+ int theBitsPerCoordinate,
+ int theBitsPerComponent, Vector theDecode,
+ int theVerticesPerRow,
+ PDFFunction theFunction) { // make shading of Type 5
+ String theShadingName = new String("Sh" + (++this.shadingCount));
+
+ PDFShading shading = new PDFShading(++this.objectcount,
+ theShadingName, theShadingType,
+ theColorSpace, theBackground,
+ theBBox, theAntiAlias,
+ theBitsPerCoordinate,
+ theBitsPerComponent, theDecode,
+ theVerticesPerRow, theFunction);
this.resources.addShading(shading);
this.objects.addElement(shading);
- return(shading);
+ return (shading);
}
/**
* Make a tiling pattern
- *
- * @param thePatternType the type of pattern, which is 1 for tiling.
+ *
+ * @param thePatternType the type of pattern, which is 1 for tiling.
* @param theResources the resources associated with this pattern
* @param thePaintType 1 or 2, colored or uncolored.
* @param theTilingType 1, 2, or 3, constant spacing, no distortion, or faster tiling
@@ -569,71 +574,63 @@ public class PDFDocument {
* @param theXUID Optional vector of Integers that uniquely identify the pattern
* @param thePatternDataStream The stream of pattern data to be tiled.
*/
- public PDFPattern makePattern(
- int thePatternType, //1
- PDFResources theResources,
- int thePaintType, int theTilingType,
- Vector theBBox, double theXStep, double theYStep,
- Vector theMatrix, Vector theXUID, StringBuffer thePatternDataStream)
- {
- String thePatternName = new String("Pa"+(++this.patternCount));
- //int theNumber, String thePatternName,
- //PDFResources theResources
+ public PDFPattern makePattern(int thePatternType, // 1
+ PDFResources theResources, int thePaintType, int theTilingType,
+ Vector theBBox, double theXStep, double theYStep, Vector theMatrix,
+ Vector theXUID, StringBuffer thePatternDataStream) {
+ String thePatternName = new String("Pa" + (++this.patternCount));
+ // int theNumber, String thePatternName,
+ // PDFResources theResources
PDFPattern pattern = new PDFPattern(++this.objectcount,
- thePatternName,
- theResources, 1,
- thePaintType, theTilingType,
- theBBox, theXStep, theYStep,
- theMatrix, theXUID, thePatternDataStream);
+ thePatternName, theResources, 1,
+ thePaintType, theTilingType,
+ theBBox, theXStep, theYStep,
+ theMatrix, theXUID,
+ thePatternDataStream);
this.resources.addPattern(pattern);
this.objects.addElement(pattern);
- return(pattern);
+ return (pattern);
}
/**
* Make a smooth shading pattern
- *
+ *
* @param thePatternType the type of the pattern, which is 2, smooth shading
* @param theShading the PDF Shading object that comprises this pattern
* @param theXUID optional:the extended unique Identifier if used.
* @param theExtGState optional: the extended graphics state, if used.
* @param theMatrix Optional:Vector of Doubles that specify the matrix.
*/
- public PDFPattern makePattern(int thePatternType,
- PDFShading theShading, Vector theXUID,
- StringBuffer theExtGState,Vector theMatrix)
- {
- String thePatternName = new String("Pa"+(++this.patternCount));
+ public PDFPattern makePattern(int thePatternType, PDFShading theShading,
+ Vector theXUID, StringBuffer theExtGState,
+ Vector theMatrix) {
+ String thePatternName = new String("Pa" + (++this.patternCount));
PDFPattern pattern = new PDFPattern(++this.objectcount,
- thePatternName, 2, theShading, theXUID,
- theExtGState, theMatrix);
+ thePatternName, 2, theShading,
+ theXUID, theExtGState, theMatrix);
this.resources.addPattern(pattern);
this.objects.addElement(pattern);
- return(pattern);
+ return (pattern);
}
- public int getColorSpace()
- {
- return(this.colorspace.getColorSpace());
+ public int getColorSpace() {
+ return (this.colorspace.getColorSpace());
}
- public void setColorSpace(int theColorspace)
- {
+ public void setColorSpace(int theColorspace) {
this.colorspace.setColorSpace(theColorspace);
return;
}
public PDFPattern createGradient(boolean radial,
- ColorSpace theColorspace,
- Vector theColors,
- Vector theBounds,
- Vector theCoords)
- {
+ ColorSpace theColorspace,
+ Vector theColors, Vector theBounds,
+ Vector theCoords) {
PDFShading myShad;
PDFFunction myfunky;
PDFFunction myfunc;
@@ -641,58 +638,52 @@ public class PDFDocument {
Vector theCone;
PDFPattern myPattern;
ColorSpace theColorSpace;
- double interpolation = (double) 1.000;
+ double interpolation = (double)1.000;
Vector theFunctions = new Vector();
int currentPosition;
- int lastPosition = theColors.size()-1;
-
-
- //if 5 elements, the penultimate element is 3.
- //do not go beyond that, because you always need
- //to have a next color when creating the function.
-
- for ( currentPosition=0;
- currentPosition < lastPosition;
- currentPosition++ ) {//for every consecutive color pair
- PDFColor currentColor =
- (PDFColor)theColors.elementAt(currentPosition);
- PDFColor nextColor =
- (PDFColor)theColors.elementAt(currentPosition+1);
- //colorspace must be consistant
- if ( this.colorspace.getColorSpace() != currentColor.getColorSpace() )
+ int lastPosition = theColors.size() - 1;
+
+
+ // if 5 elements, the penultimate element is 3.
+ // do not go beyond that, because you always need
+ // to have a next color when creating the function.
+
+ for (currentPosition = 0; currentPosition < lastPosition;
+ currentPosition++) { // for every consecutive color pair
+ PDFColor currentColor =
+ (PDFColor)theColors.elementAt(currentPosition);
+ PDFColor nextColor = (PDFColor)theColors.elementAt(currentPosition
+ + 1);
+ // colorspace must be consistant
+ if (this.colorspace.getColorSpace()
+ != currentColor.getColorSpace())
currentColor.setColorSpace(this.colorspace.getColorSpace());
- if ( this.colorspace.getColorSpace() != nextColor.getColorSpace() )
+ if (this.colorspace.getColorSpace() != nextColor.getColorSpace())
nextColor.setColorSpace(this.colorspace.getColorSpace());
theCzero = currentColor.getVector();
theCone = nextColor.getVector();
- myfunc = this.makeFunction(
- 2, null, null,
- theCzero, theCone,
- interpolation);
+ myfunc = this.makeFunction(2, null, null, theCzero, theCone,
+ interpolation);
theFunctions.addElement(myfunc);
- }//end of for every consecutive color pair
+ } // end of for every consecutive color pair
- myfunky = this.makeFunction(3,
- null, null,
- theFunctions, theBounds,
- null);
+ myfunky = this.makeFunction(3, null, null, theFunctions, theBounds,
+ null);
- if ( radial ) {
- if ( theCoords.size() ==6 ) {
- myShad = this.makeShading(
- 3, this.colorspace,
- null, null, false,
- theCoords, null, myfunky, null);
- }
- else { //if the center x, center y, and radius specifiy
- //the gradient, then assume the same center x, center y,
- //and radius of zero for the other necessary component
+ if (radial) {
+ if (theCoords.size() == 6) {
+ myShad = this.makeShading(3, this.colorspace, null, null,
+ false, theCoords, null, myfunky,
+ null);
+ } else { // if the center x, center y, and radius specifiy
+ // the gradient, then assume the same center x, center y,
+ // and radius of zero for the other necessary component
Vector newCoords = new Vector();
newCoords.addElement(theCoords.elementAt(0));
newCoords.addElement(theCoords.elementAt(1));
@@ -701,42 +692,40 @@ public class PDFDocument {
newCoords.addElement(theCoords.elementAt(1));
newCoords.addElement(new Double(0.0));
- myShad = this.makeShading(
- 3, this.colorspace,
- null, null, false,
- newCoords, null, myfunky, null);
+ myShad = this.makeShading(3, this.colorspace, null, null,
+ false, newCoords, null, myfunky,
+ null);
}
- }
- else {
- myShad = this.makeShading(
- 2, this.colorspace,
- null, null, false,
- theCoords, null, myfunky, null);
+ } else {
+ myShad = this.makeShading(2, this.colorspace, null, null, false,
+ theCoords, null, myfunky, null);
}
- myPattern = this.makePattern(
- 2, myShad, null, null, null);
+ myPattern = this.makePattern(2, myShad, null, null, null);
- return(myPattern);
+ return (myPattern);
}
- /**
- * make a /Encoding object
- *
- * @param encodingName character encoding scheme name
- * @return the created /Encoding object
- */
- public PDFEncoding makeEncoding(String encodingName) {
-
- /* create a PDFEncoding with the next object number and add to the
- list of objects */
- PDFEncoding encoding = new PDFEncoding(++this.objectcount, encodingName);
- this.objects.addElement(encoding);
- return encoding;
- }
+ /**
+ * make a /Encoding object
+ *
+ * @param encodingName character encoding scheme name
+ * @return the created /Encoding object
+ */
+ public PDFEncoding makeEncoding(String encodingName) {
+
+ /*
+ * create a PDFEncoding with the next object number and add to the
+ * list of objects
+ */
+ PDFEncoding encoding = new PDFEncoding(++this.objectcount,
+ encodingName);
+ this.objects.addElement(encoding);
+ return encoding;
+ }
/**
@@ -750,50 +739,56 @@ public class PDFDocument {
* @return the created /Font object
*/
public PDFFont makeFont(String fontname, String basefont,
- String encoding, FontMetric metrics, FontDescriptor descriptor) {
+ String encoding, FontMetric metrics,
+ FontDescriptor descriptor) {
- /* create a PDFFont with the next object number and add to the
- list of objects */
+ /*
+ * create a PDFFont with the next object number and add to the
+ * list of objects
+ */
if (descriptor == null) {
PDFFont font = new PDFFont(++this.objectcount, fontname,
- PDFFont.TYPE1,
- basefont, encoding);
+ PDFFont.TYPE1, basefont, encoding);
this.objects.addElement(font);
return font;
} else {
- byte subtype=PDFFont.TYPE1;
+ byte subtype = PDFFont.TYPE1;
if (metrics instanceof org.apache.fop.render.pdf.Font)
- subtype=((org.apache.fop.render.pdf.Font)metrics).getSubType();
-
+ subtype =
+ ((org.apache.fop.render.pdf.Font)metrics).getSubType();
+
PDFFontDescriptor pdfdesc = makeFontDescriptor(descriptor,
- subtype);
-
+ subtype);
+
PDFFontNonBase14 font = null;
if (subtype == PDFFont.TYPE0) {
- /*
- * Temporary commented out - customized CMaps
- * isn't needed until /ToUnicode support is added
- PDFCMap cmap = new PDFCMap(++this.objectcount,
- "fop-ucs-H",
- new PDFCIDSystemInfo("Adobe",
- "Identity",
- 0));
- cmap.addContents();
- this.objects.addElement(cmap);
- */
- font = (PDFFontNonBase14)PDFFont.createFont(
- ++this.objectcount, fontname,
- subtype, basefont, "Identity-H");
+ /*
+ * Temporary commented out - customized CMaps
+ * isn't needed until /ToUnicode support is added
+ * PDFCMap cmap = new PDFCMap(++this.objectcount,
+ * "fop-ucs-H",
+ * new PDFCIDSystemInfo("Adobe",
+ * "Identity",
+ * 0));
+ * cmap.addContents();
+ * this.objects.addElement(cmap);
+ */
+ font =
+ (PDFFontNonBase14)PDFFont.createFont(++this.objectcount,
+ fontname, subtype,
+ basefont,
+ "Identity-H");
} else {
-
- font = (PDFFontNonBase14)PDFFont.createFont(
- ++this.objectcount, fontname,
- subtype, basefont, encoding);
+
+ font =
+ (PDFFontNonBase14)PDFFont.createFont(++this.objectcount,
+ fontname, subtype,
+ basefont, encoding);
}
this.objects.addElement(font);
-
+
font.setDescriptor(pdfdesc);
-
+
if (subtype == PDFFont.TYPE0) {
CIDFont cidMetrics = (CIDFont)metrics;
PDFCIDSystemInfo sysInfo =
@@ -804,93 +799,88 @@ public class PDFDocument {
new PDFCIDFont(++this.objectcount, basefont,
cidMetrics.getCidType(),
cidMetrics.getDefaultWidth(),
- cidMetrics.getWidths(),
- sysInfo, (PDFCIDFontDescriptor)pdfdesc);
+ cidMetrics.getWidths(), sysInfo,
+ (PDFCIDFontDescriptor)pdfdesc);
this.objects.addElement(cidFont);
-
- //((PDFFontType0)font).setCMAP(cmap);
-
+
+ // ((PDFFontType0)font).setCMAP(cmap);
+
((PDFFontType0)font).setDescendantFonts(cidFont);
} else {
font.setWidthMetrics(metrics.getFirstChar(),
metrics.getLastChar(),
makeArray(metrics.getWidths(1)));
}
-
+
return font;
}
}
- /**
- * make a /FontDescriptor object
- */
+ /**
+ * make a /FontDescriptor object
+ */
public PDFFontDescriptor makeFontDescriptor(FontDescriptor desc,
byte subtype) {
PDFFontDescriptor font = null;
-
+
if (subtype == PDFFont.TYPE0) {
- // CID Font
- font =
- new PDFCIDFontDescriptor(++this.objectcount,
- desc.fontName(),
- desc.getFontBBox(),
- //desc.getAscender(),
- //desc.getDescender(),
+ // CID Font
+ font = new PDFCIDFontDescriptor(++this.objectcount,
+ desc.fontName(),
+ desc.getFontBBox(),
+ // desc.getAscender(),
+ // desc.getDescender(),
+ desc.getCapHeight(), desc.getFlags(),
+ // new PDFRectangle(desc.getFontBBox()),
+ desc.getItalicAngle(), desc.getStemV(), null); // desc.getLang(),
+ // null);//desc.getPanose());
+ } else {
+ // Create normal FontDescriptor
+ font = new PDFFontDescriptor(++this.objectcount, desc.fontName(),
+ desc.getAscender(),
+ desc.getDescender(),
desc.getCapHeight(),
desc.getFlags(),
- //new PDFRectangle(desc.getFontBBox()),
- desc.getItalicAngle(),
+ new PDFRectangle(desc.getFontBBox()),
desc.getStemV(),
- null); //desc.getLang(),
- //null);//desc.getPanose());
- } else {
- // Create normal FontDescriptor
- font =
- new PDFFontDescriptor(++this.objectcount,
- desc.fontName(),
- desc.getAscender(),
- desc.getDescender(),
- desc.getCapHeight(),
- desc.getFlags(),
- new PDFRectangle(desc.getFontBBox()),
- desc.getStemV(),
- desc.getItalicAngle());
+ desc.getItalicAngle());
}
- this.objects.addElement(font);
-
- // Check if the font is embeddable
+ this.objects.addElement(font);
+
+ // Check if the font is embeddable
if (desc.isEmbeddable()) {
- PDFStream stream=desc.getFontFile(this.objectcount+1);
- if (stream!=null) {
+ PDFStream stream = desc.getFontFile(this.objectcount + 1);
+ if (stream != null) {
this.objectcount++;
font.setFontFile(desc.getSubType(), stream);
this.objects.addElement(stream);
}
}
- return font;
+ return font;
}
- /**
- * make an Array object (ex. Widths array for a font)
- */
- public PDFArray makeArray(int[] values) {
+ /**
+ * make an Array object (ex. Widths array for a font)
+ */
+ public PDFArray makeArray(int[] values) {
PDFArray array = new PDFArray(++this.objectcount, values);
- this.objects.addElement(array);
- return array;
- }
+ this.objects.addElement(array);
+ return array;
+ }
public int addImage(FopImage img) {
// check if already created
String url = img.getURL();
- PDFXObject xObject = (PDFXObject) this.xObjectsMap.get(url);
- if ( xObject != null ) return xObject.getXNumber();
- // else, create a new one
- xObject = new PDFXObject(++this.objectcount,
- ++this.xObjectCount, img);
+ PDFXObject xObject = (PDFXObject)this.xObjectsMap.get(url);
+ if (xObject != null)
+ return xObject.getXNumber();
+ // else, create a new one
+ xObject = new PDFXObject(++this.objectcount, ++this.xObjectCount,
+ img);
this.objects.addElement(xObject);
this.xObjects.addElement(xObject);
this.xObjectsMap.put(url, xObject);
@@ -907,25 +897,24 @@ public class PDFDocument {
*
* @return the created /Page object
*/
- public PDFPage makePage(PDFResources resources,
- PDFStream contents,
- int pagewidth,
- int pageheight,
- Page currentPage) {
-
- /* create a PDFPage with the next object number, the given
- resources, contents and dimensions */
- PDFPage page = new PDFPage(++this.objectcount, resources,
- contents,
- pagewidth, pageheight);
-
- if(currentPage != null) {
- Enumeration enum=currentPage.getIDList().elements();
- while ( enum.hasMoreElements() ) {
- String id=enum.nextElement().toString();
- idReferences.setInternalGoToPageReference(id,page.referencePDF());
+ public PDFPage makePage(PDFResources resources, PDFStream contents,
+ int pagewidth, int pageheight, Page currentPage) {
+
+ /*
+ * create a PDFPage with the next object number, the given
+ * resources, contents and dimensions
+ */
+ PDFPage page = new PDFPage(++this.objectcount, resources, contents,
+ pagewidth, pageheight);
+
+ if (currentPage != null) {
+ Enumeration enum = currentPage.getIDList().elements();
+ while (enum.hasMoreElements()) {
+ String id = enum.nextElement().toString();
+ idReferences.setInternalGoToPageReference(id,
+ page.referencePDF());
+ }
}
- }
/* add it to the list of objects */
this.objects.addElement(page);
@@ -938,35 +927,35 @@ public class PDFDocument {
/**
* make a link object
- *
+ *
* @param rect the clickable rectangle
* @param destination the destination file
* @param linkType the link type
* @return the PDFLink object created
*/
- public PDFLink makeLink(Rectangle rect, String destination, int linkType) {
+ public PDFLink makeLink(Rectangle rect, String destination,
+ int linkType) {
PDFLink linkObject;
PDFAction action;
PDFLink link = new PDFLink(++this.objectcount, rect);
- this.objects.addElement(link);
+ this.objects.addElement(link);
- if ( linkType == LinkSet.EXTERNAL ) {
- //check destination
- if ( destination.endsWith(".pdf") ) { //FileSpec
- PDFFileSpec fileSpec = new PDFFileSpec(++this.objectcount,destination);
+ if (linkType == LinkSet.EXTERNAL) {
+ // check destination
+ if (destination.endsWith(".pdf")) { // FileSpec
+ PDFFileSpec fileSpec = new PDFFileSpec(++this.objectcount,
+ destination);
this.objects.addElement(fileSpec);
- action = new PDFGoToRemote(++this.objectcount,fileSpec);
+ action = new PDFGoToRemote(++this.objectcount, fileSpec);
this.objects.addElement(action);
- link.setAction(action);
- }
- else { //URI
- PDFUri uri = new PDFUri(destination);
- link.setAction(uri);
+ link.setAction(action);
+ } else { // URI
+ PDFUri uri = new PDFUri(destination);
+ link.setAction(uri);
}
- }
- else { // linkType is internal
+ } else { // linkType is internal
String goToReference = getGoToReference(destination);
PDFInternalLink internalLink = new PDFInternalLink(goToReference);
link.setAction(internalLink);
@@ -974,28 +963,29 @@ public class PDFDocument {
return link;
}
- private String getGoToReference(String destination)
- {
- String goToReference;
- if ( idReferences.doesIDExist(destination) ) {
- if ( idReferences.doesGoToReferenceExist(destination) ) {
- goToReference = idReferences.getInternalLinkGoToReference(destination);
- }
- else { //assign Internal Link GoTo object
- goToReference = idReferences.createInternalLinkGoTo(destination,++this.objectcount);
- this.objects.addElement(idReferences.getPDFGoTo(destination));
- }
- }
- else { //id was not found, so create it
- idReferences.createNewId(destination);
- idReferences.addToIdValidationList(destination);
- goToReference = idReferences.createInternalLinkGoTo(destination,++this.objectcount);
- this.objects.addElement(idReferences.getPDFGoTo(destination));
- }
- return goToReference;
+ private String getGoToReference(String destination) {
+ String goToReference;
+ if (idReferences.doesIDExist(destination)) {
+ if (idReferences.doesGoToReferenceExist(destination)) {
+ goToReference =
+ idReferences.getInternalLinkGoToReference(destination);
+ } else { // assign Internal Link GoTo object
+ goToReference =
+ idReferences.createInternalLinkGoTo(destination,
+ ++this.objectcount);
+ this.objects.addElement(idReferences.getPDFGoTo(destination));
+ }
+ } else { // id was not found, so create it
+ idReferences.createNewId(destination);
+ idReferences.addToIdValidationList(destination);
+ goToReference = idReferences.createInternalLinkGoTo(destination,
+ ++this.objectcount);
+ this.objects.addElement(idReferences.getPDFGoTo(destination));
+ }
+ return goToReference;
}
-
-
+
+
/**
* make a stream object
*
@@ -1003,16 +993,18 @@ public class PDFDocument {
*/
public PDFStream makeStream() {
- /* create a PDFStream with the next object number and add it
-
- to the list of objects */
- PDFStream obj = new PDFStream(++this.objectcount);
- obj.addDefaultFilters();
-
+ /*
+ * create a PDFStream with the next object number and add it
+ *
+ * to the list of objects
+ */
+ PDFStream obj = new PDFStream(++this.objectcount);
+ obj.addDefaultFilters();
+
this.objects.addElement(obj);
return obj;
}
-
+
/**
* make an annotation list object
@@ -1021,8 +1013,10 @@ public class PDFDocument {
*/
public PDFAnnotList makeAnnotList() {
- /* create a PDFAnnotList with the next object number and add it
- to the list of objects */
+ /*
+ * create a PDFAnnotList with the next object number and add it
+ * to the list of objects
+ */
PDFAnnotList obj = new PDFAnnotList(++this.objectcount);
this.objects.addElement(obj);
return obj;
@@ -1031,35 +1025,33 @@ public class PDFDocument {
/**
* Make the root Outlines object
*/
- public PDFOutline makeOutlineRoot()
- {
- PDFOutline obj = new PDFOutline(++this.objectcount, null, null);
- this.objects.addElement(obj);
- root.setRootOutline(obj);
-
- return obj;
+ public PDFOutline makeOutlineRoot() {
+ PDFOutline obj = new PDFOutline(++this.objectcount, null, null);
+ this.objects.addElement(obj);
+ root.setRootOutline(obj);
+
+ return obj;
}
-
- /** Make an outline object and add it to the given outline
+
+ /**
+ * Make an outline object and add it to the given outline
* @param parent parent PDFOutline object
* @param label the title for the new outline object
* @param action the PDFAction to reference
*/
- public PDFOutline makeOutline(PDFOutline parent,
- String label,
- String destination)
- {
- String goToRef = getGoToReference(destination);
-
- PDFOutline obj = new PDFOutline(++this.objectcount, label, goToRef);
- // System.out.println("created new outline object");
-
- if (parent != null) {
- parent.addOutline(obj);
- }
- this.objects.addElement(obj);
- return obj;
-
+ public PDFOutline makeOutline(PDFOutline parent, String label,
+ String destination) {
+ String goToRef = getGoToReference(destination);
+
+ PDFOutline obj = new PDFOutline(++this.objectcount, label, goToRef);
+ // System.out.println("created new outline object");
+
+ if (parent != null) {
+ parent.addOutline(obj);
+ }
+ this.objects.addElement(obj);
+ return obj;
+
}
/**
@@ -1078,28 +1070,36 @@ public class PDFDocument {
*/
public void output(OutputStream stream) throws IOException {
- /* output the header and increment the character position by
- the header's length */
+ /*
+ * output the header and increment the character position by
+ * the header's length
+ */
this.position += outputHeader(stream);
this.resources.setXObjects(xObjects);
- Enumeration en = this.objects.elements();
- while (en.hasMoreElements()) {
+ Enumeration en = this.objects.elements();
+ while (en.hasMoreElements()) {
/* retrieve the object with the current number */
PDFObject object = (PDFObject)en.nextElement();
- /* add the position of this object to the list of object
- locations */
+ /*
+ * add the position of this object to the list of object
+ * locations
+ */
this.location.addElement(new Integer(this.position));
-
- /* output the object and increment the character position
- by the object's length */
+
+ /*
+ * output the object and increment the character position
+ * by the object's length
+ */
this.position += object.output(stream);
- }
-
- /* output the xref table and increment the character position
- by the table's length */
+ }
+
+ /*
+ * output the xref table and increment the character position
+ * by the table's length
+ */
this.position += outputXref(stream);
/* output the trailer and flush the Stream */
@@ -1114,17 +1114,20 @@ public class PDFDocument {
* @return the number of bytes written
*/
protected int outputHeader(OutputStream stream) throws IOException {
- int length = 0;
- byte[] pdf = ("%PDF-" + this.pdfVersion + "\n").getBytes();
- stream.write(pdf);
- length += pdf.length;
-
- // output a binary comment as recommended by the PDF spec (3.4.1)
- byte[] bin = {(byte)'%', (byte)0xAA, (byte)0xAB, (byte)0xAC, (byte)0xAD, (byte)'\n'};
- stream.write(bin);
- length += bin.length;
-
- return length;
+ int length = 0;
+ byte[] pdf = ("%PDF-" + this.pdfVersion + "\n").getBytes();
+ stream.write(pdf);
+ length += pdf.length;
+
+ // output a binary comment as recommended by the PDF spec (3.4.1)
+ byte[] bin = {
+ (byte)'%', (byte)0xAA, (byte)0xAB, (byte)0xAC, (byte)0xAD,
+ (byte)'\n'
+ };
+ stream.write(bin);
+ length += bin.length;
+
+ return length;
}
/**
@@ -1135,11 +1138,11 @@ public class PDFDocument {
protected void outputTrailer(OutputStream stream) throws IOException {
/* construct the trailer */
- String pdf = "trailer\n<<\n/Size " + (this.objectcount+1)
- + "\n/Root " + this.root.number + " " + this.root.generation
- + " R\n/Info " + this.info.number + " "
- + this.info.generation + " R\n>>\nstartxref\n" + this.xref
- + "\n%%EOF\n";
+ String pdf = "trailer\n<<\n/Size " + (this.objectcount + 1)
+ + "\n/Root " + this.root.number + " "
+ + this.root.generation + " R\n/Info " + this.info.number
+ + " " + this.info.generation + " R\n>>\nstartxref\n"
+ + this.xref + "\n%%EOF\n";
/* write the trailer */
stream.write(pdf.getBytes());
@@ -1157,13 +1160,14 @@ public class PDFDocument {
this.xref = this.position;
/* construct initial part of xref */
- StringBuffer pdf = new StringBuffer("xref\n0 " + (this.objectcount+1)
- + "\n0000000000 65535 f \n");
+ StringBuffer pdf = new StringBuffer("xref\n0 "
+ + (this.objectcount + 1)
+ + "\n0000000000 65535 f \n");
+
+ Enumeration en = this.location.elements();
+ while (en.hasMoreElements()) {
+ String x = en.nextElement().toString();
- Enumeration en = this.location.elements();
- while (en.hasMoreElements()) {
- String x = en.nextElement().toString();
-
/* contruct xref entry for object */
String padding = "0000000000";
String loc = padding.substring(x.length()) + x;
@@ -1173,12 +1177,13 @@ public class PDFDocument {
}
/* write the xref table and return the character length */
- byte[] pdfBytes = pdf.toString().getBytes();
- stream.write(pdfBytes);
+ byte[] pdfBytes = pdf.toString().getBytes();
+ stream.write(pdfBytes);
return pdfBytes.length;
- }
+ }
- public void setIDReferences(IDReferences idReferences){
- this.idReferences= idReferences;
+ public void setIDReferences(IDReferences idReferences) {
+ this.idReferences = idReferences;
}
+
}
diff --git a/src/org/apache/fop/pdf/PDFEncoding.java b/src/org/apache/fop/pdf/PDFEncoding.java
index ad937f417..68151bdfd 100644
--- a/src/org/apache/fop/pdf/PDFEncoding.java
+++ b/src/org/apache/fop/pdf/PDFEncoding.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
// Java
@@ -67,22 +24,32 @@ import java.util.Vector;
*/
public class PDFEncoding extends PDFObject {
- /** the name for the standard encoding scheme */
- public static final String MacRomanEncoding = "MacRomanEncoding";
- /** the name for the standard encoding scheme */
- public static final String MacExpertEncoding = "MacExpertEncoding";
- /** the name for the standard encoding scheme */
- public static final String WinAnsiEncoding = "WinAnsiEncoding";
+ /**
+ * the name for the standard encoding scheme
+ */
+ public static final String MacRomanEncoding = "MacRomanEncoding";
+
+ /**
+ * the name for the standard encoding scheme
+ */
+ public static final String MacExpertEncoding = "MacExpertEncoding";
+
+ /**
+ * the name for the standard encoding scheme
+ */
+ public static final String WinAnsiEncoding = "WinAnsiEncoding";
/**
- * the name for the base encoding.
- * One of the three base encoding scheme names or
- * the default font's base encoding if null.
- */
+ * the name for the base encoding.
+ * One of the three base encoding scheme names or
+ * the default font's base encoding if null.
+ */
protected String basename;
- /** the differences from the base encoding */
- protected Hashtable differences;
+ /**
+ * the differences from the base encoding
+ */
+ protected Hashtable differences;
/**
* create the /Encoding object
@@ -92,61 +59,65 @@ public class PDFEncoding extends PDFObject {
*/
public PDFEncoding(int number, String basename) {
- /* generic creation of PDF object */
- super(number);
+ /* generic creation of PDF object */
+ super(number);
- /* set fields using paramaters */
- this.basename = basename;
- this.differences = new Hashtable();
- }
+ /* set fields using paramaters */
+ this.basename = basename;
+ this.differences = new Hashtable();
+ }
- /**
- * add differences to the encoding
- *
- * @param code the first index of the sequence to be changed
- * @param sequence the sequence of glyph names (as String)
- */
- public void addDifferences(int code, Vector sequence) {
- differences.put(new Integer(code), sequence);
- }
+ /**
+ * add differences to the encoding
+ *
+ * @param code the first index of the sequence to be changed
+ * @param sequence the sequence of glyph names (as String)
+ */
+ public void addDifferences(int code, Vector sequence) {
+ differences.put(new Integer(code), sequence);
+ }
- /**
- * produce the PDF representation for the object
- *
- * @return the PDF
- */
- public byte[] toPDF() {
- StringBuffer p = new StringBuffer();
- p.append(this.number + " " + this.generation
- + " obj\n<< /Type /Encoding");
- if ((basename != null) && (!basename.equals(""))) {
- p.append("\n/BaseEncoding /" + this.basename);
- }
- if (!differences.isEmpty()) {
- p.append("\n/Differences [ ");
- Object code;
- Enumeration codes = differences.keys();
- while (codes.hasMoreElements()) {
- code = codes.nextElement();
- p.append(" "); p.append(code);
- Vector sequence = (Vector)differences.get(code);
- for (int i = 0; i < sequence.size(); i++) {
- p.append(" /"); p.append((String)sequence.elementAt(i));
- }
- }
- p.append(" ]");
- }
- p.append(" >>\nendobj\n");
- return p.toString().getBytes();
- }
- /* example (p. 214)
- 25 0 obj
- <<
- /Type /Encoding
- /Differences [39 /quotesingle 96 /grave 128
- /Adieresis /Aring /Ccedilla /Eacute /Ntilde
- /Odieresis /Udieresis /aacute /agrave]
- >>
- endobj
- */
+ /**
+ * produce the PDF representation for the object
+ *
+ * @return the PDF
+ */
+ public byte[] toPDF() {
+ StringBuffer p = new StringBuffer();
+ p.append(this.number + " " + this.generation
+ + " obj\n<< /Type /Encoding");
+ if ((basename != null) && (!basename.equals(""))) {
+ p.append("\n/BaseEncoding /" + this.basename);
+ }
+ if (!differences.isEmpty()) {
+ p.append("\n/Differences [ ");
+ Object code;
+ Enumeration codes = differences.keys();
+ while (codes.hasMoreElements()) {
+ code = codes.nextElement();
+ p.append(" ");
+ p.append(code);
+ Vector sequence = (Vector)differences.get(code);
+ for (int i = 0; i < sequence.size(); i++) {
+ p.append(" /");
+ p.append((String)sequence.elementAt(i));
+ }
+ }
+ p.append(" ]");
+ }
+ p.append(" >>\nendobj\n");
+ return p.toString().getBytes();
+ }
+
+ /*
+ * example (p. 214)
+ * 25 0 obj
+ * <<
+ * /Type /Encoding
+ * /Differences [39 /quotesingle 96 /grave 128
+ * /Adieresis /Aring /Ccedilla /Eacute /Ntilde
+ * /Odieresis /Udieresis /aacute /agrave]
+ * >>
+ * endobj
+ */
}
diff --git a/src/org/apache/fop/pdf/PDFFileSpec.java b/src/org/apache/fop/pdf/PDFFileSpec.java
index fdfd0ea1c..d7c5338d0 100644
--- a/src/org/apache/fop/pdf/PDFFileSpec.java
+++ b/src/org/apache/fop/pdf/PDFFileSpec.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.pdf;
@@ -57,7 +13,9 @@ package org.apache.fop.pdf;
*/
public class PDFFileSpec extends PDFObject {
- /** the filename */
+ /**
+ * the filename
+ */
protected String filename;
/**
@@ -68,10 +26,10 @@ public class PDFFileSpec extends PDFObject {
*/
public PDFFileSpec(int number, String filename) {
- /* generic creation of object */
- super(number);
-
- this.filename = filename;
+ /* generic creation of object */
+ super(number);
+
+ this.filename = filename;
}
/**
@@ -80,19 +38,19 @@ public class PDFFileSpec extends PDFObject {
* @return the PDF string
*/
public byte[] toPDF() {
- String p = new String(this.number + " " + this.generation +
- " obj\n<<\n/Type /FileSpec\n" +
- "/F (" + this.filename + ")\n" +
- ">>\nendobj\n");
- return p.getBytes();
+ String p = new String(this.number + " " + this.generation
+ + " obj\n<<\n/Type /FileSpec\n" + "/F ("
+ + this.filename + ")\n" + ">>\nendobj\n");
+ return p.getBytes();
}
- /* example
- 29 0 obj
- <<
- /Type /FileSpec
- /F (table1.pdf)
- >>
- endobj
- */
+ /*
+ * example
+ * 29 0 obj
+ * <<
+ * /Type /FileSpec
+ * /F (table1.pdf)
+ * >>
+ * endobj
+ */
}
diff --git a/src/org/apache/fop/pdf/PDFFilter.java b/src/org/apache/fop/pdf/PDFFilter.java
index 5783b829b..1cb6ce18c 100644
--- a/src/org/apache/fop/pdf/PDFFilter.java
+++ b/src/org/apache/fop/pdf/PDFFilter.java
@@ -1,83 +1,38 @@
-/*-- $Id$ --
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
-*/
-
-
-//Author: Eric SCHAEFFER, Kelly A. Campbell
-//Description: represent a PDF filter object
+// Author: Eric SCHAEFFER, Kelly A. Campbell
+// Description: represent a PDF filter object
package org.apache.fop.pdf;
public abstract class PDFFilter {
- /* These are no longer needed, but are here as a reminder about what
- filters pdf supports.
-
- public static final int ASCII_HEX_DECODE = 1;
- public static final int ASCII_85_DECODE = 2;
- public static final int LZW_DECODE = 3;
- public static final int RUN_LENGTH_DECODE = 4;
- public static final int CCITT_FAX_DECODE = 5;
- public static final int DCT_DECODE = 6;
- public static final int FLATE_DECODE = 7;
-
- */
+ /*
+ * These are no longer needed, but are here as a reminder about what
+ * filters pdf supports.
+ * public static final int ASCII_HEX_DECODE = 1;
+ * public static final int ASCII_85_DECODE = 2;
+ * public static final int LZW_DECODE = 3;
+ * public static final int RUN_LENGTH_DECODE = 4;
+ * public static final int CCITT_FAX_DECODE = 5;
+ * public static final int DCT_DECODE = 6;
+ * public static final int FLATE_DECODE = 7;
+ */
- /** Marker to know if this filter has already been applied to the data */
+ /**
+ * Marker to know if this filter has already been applied to the data
+ */
private boolean _applied = false;
-
- public boolean isApplied()
- {
- return _applied;
+
+ public boolean isApplied() {
+ return _applied;
}
-
+
/**
* Set the applied attribute to the given value. This attribute is
* used to determine if this filter is just a placeholder for the
@@ -85,23 +40,28 @@ public abstract class PDFFilter {
* actually encode the data. For example if the raw data is copied
* out of an image file in it's compressed format, then this
* should be set to true and the filter options should be set to
- * those which the raw data was encoded with.
+ * those which the raw data was encoded with.
*/
- public void setApplied(boolean b)
- {
- _applied = b;
+ public void setApplied(boolean b) {
+ _applied = b;
}
-
-
- /** return a PDF string representation of the filter, e.g. /FlateDecode */
+
+
+ /**
+ * return a PDF string representation of the filter, e.g. /FlateDecode
+ */
public abstract String getName();
-
- /** return a parameter dictionary for this filter, or null */
+
+ /**
+ * return a parameter dictionary for this filter, or null
+ */
public abstract String getDecodeParms();
-
- /** encode the given data with the filter */
+
+ /**
+ * encode the given data with the filter
+ */
public abstract byte[] encode(byte[] data);
-
-
-
+
+
+
}
diff --git a/src/org/apache/fop/pdf/PDFFilterException.java b/src/org/apache/fop/pdf/PDFFilterException.java
index cb39e554c..06cd038f8 100644
--- a/src/org/apache/fop/pdf/PDFFilterException.java
+++ b/src/org/apache/fop/pdf/PDFFilterException.java
@@ -1,11 +1,12 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
-//Author: Eric SCHAEFFER
-//Description: Filter Exception
+// Author: Eric SCHAEFFER
+// Description: Filter Exception
package org.apache.fop.pdf;
@@ -18,4 +19,5 @@ public class PDFFilterException extends Exception {
public PDFFilterException(String message) {
super(message);
}
+
}
diff --git a/src/org/apache/fop/pdf/PDFFont.java b/src/org/apache/fop/pdf/PDFFont.java
index ed43a8017..3d1c2ec05 100644
--- a/src/org/apache/fop/pdf/PDFFont.java
+++ b/src/org/apache/fop/pdf/PDFFont.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
/**
@@ -61,22 +18,43 @@ package org.apache.fop.pdf;
*/
public class PDFFont extends PDFObject {
- /** font subtype to be used as parameter to createFont() */
+ /**
+ * font subtype to be used as parameter to createFont()
+ */
public static final byte TYPE0 = 0;
- /** font subtype to be used as parameter to createFont() */
+
+ /**
+ * font subtype to be used as parameter to createFont()
+ */
public static final byte TYPE1 = 1;
- /** font subtype to be used as parameter to createFont() */
+
+ /**
+ * font subtype to be used as parameter to createFont()
+ */
public static final byte MMTYPE1 = 2;
- /** font subtype to be used as parameter to createFont() */
+
+ /**
+ * font subtype to be used as parameter to createFont()
+ */
public static final byte TYPE3 = 3;
- /** font subtype to be used as parameter to createFont() */
+
+ /**
+ * font subtype to be used as parameter to createFont()
+ */
public static final byte TRUETYPE = 4;
- /** font subtype names as output in the PDF */
- protected static final String[] TYPE_NAMES = new String[] // take care of the order
- {"Type0", "Type1", "MMType1", "Type3", "TrueType"};
+ /**
+ * font subtype names as output in the PDF
+ */
+ protected static final String[] TYPE_NAMES =
+ new String[] // take care of the order
+ {
+ "Type0", "Type1", "MMType1", "Type3", "TrueType"
+ };
- /** the internal name for the font (eg "F1") */
+ /**
+ * the internal name for the font (eg "F1")
+ */
protected String fontname;
/**
@@ -85,7 +63,9 @@ public class PDFFont extends PDFObject {
*/
protected byte subtype;
- /** the base font name (eg "Helvetica") */
+ /**
+ * the base font name (eg "Helvetica")
+ */
protected String basefont;
/**
@@ -97,8 +77,10 @@ public class PDFFont extends PDFObject {
*/
protected Object encoding;
- /** the Unicode mapping mechanism */
- //protected PDFToUnicode mapping;
+ /**
+ * the Unicode mapping mechanism
+ */
+ // protected PDFToUnicode mapping;
/**
* create the /Font object
@@ -110,8 +92,9 @@ public class PDFFont extends PDFObject {
* @param encoding the character encoding schema used by the font
* @param mapping the Unicode mapping mechanism
*/
- public PDFFont(int number, String fontname, byte subtype, String basefont,
- Object encoding/*, PDFToUnicode mapping*/) {
+ public PDFFont(int number, String fontname, byte subtype,
+ String basefont,
+ Object encoding /* , PDFToUnicode mapping */) {
/* generic creation of PDF object */
super(number);
@@ -121,7 +104,7 @@ public class PDFFont extends PDFObject {
this.subtype = subtype;
this.basefont = basefont;
this.encoding = encoding;
- //this.mapping = mapping;
+ // this.mapping = mapping;
}
/**
@@ -134,20 +117,23 @@ public class PDFFont extends PDFObject {
* @param encoding the character encoding schema used by the font
*/
public static PDFFont createFont(int number, String fontname,
- byte subtype, String basefont, Object encoding) {
+ byte subtype, String basefont,
+ Object encoding) {
switch (subtype) {
- case TYPE0 :
- return new PDFFontType0(number, fontname, subtype,
- basefont, encoding);
- case TYPE1 :
- case MMTYPE1 :
- return new PDFFontType1(number, fontname, subtype, basefont, encoding);
- /*
- case TYPE3 :
- return new PDFFontType3(number, fontname, subtype, basefont, encoding);
- */
- case TRUETYPE :
- return new PDFFontTrueType(number, fontname, subtype, basefont, encoding);
+ case TYPE0:
+ return new PDFFontType0(number, fontname, subtype, basefont,
+ encoding);
+ case TYPE1:
+ case MMTYPE1:
+ return new PDFFontType1(number, fontname, subtype, basefont,
+ encoding);
+ /*
+ * case TYPE3 :
+ * return new PDFFontType3(number, fontname, subtype, basefont, encoding);
+ */
+ case TRUETYPE:
+ return new PDFFontTrueType(number, fontname, subtype, basefont,
+ encoding);
}
return null; // should not happend
}
@@ -167,31 +153,34 @@ public class PDFFont extends PDFObject {
* @param descriptor the descriptor for other font's metrics
*/
public static PDFFont createFont(int number, String fontname,
- byte subtype, String basefont, Object encoding,
- int firstChar, int lastChar, PDFArray widths,
- PDFFontDescriptor descriptor) {
+ byte subtype, String basefont,
+ Object encoding, int firstChar,
+ int lastChar, PDFArray widths,
+ PDFFontDescriptor descriptor) {
PDFFontNonBase14 font;
switch (subtype) {
- case TYPE0 :
- font = new PDFFontType0(number, fontname, subtype,
- basefont, encoding);
- font.setDescriptor(descriptor);
- return font;
- case TYPE1 :
- case MMTYPE1 :
- font = new PDFFontType1(number, fontname, subtype, basefont, encoding);
- font.setWidthMetrics(firstChar, lastChar, widths);
- font.setDescriptor(descriptor);
- return font;
- case TYPE3 :
- return null; // should not happend
-
- case TRUETYPE :
- font = new PDFFontTrueType(number, fontname, subtype, basefont, encoding);
- font.setWidthMetrics(firstChar, lastChar, widths);
- font.setDescriptor(descriptor);
- return font;
+ case TYPE0:
+ font = new PDFFontType0(number, fontname, subtype, basefont,
+ encoding);
+ font.setDescriptor(descriptor);
+ return font;
+ case TYPE1:
+ case MMTYPE1:
+ font = new PDFFontType1(number, fontname, subtype, basefont,
+ encoding);
+ font.setWidthMetrics(firstChar, lastChar, widths);
+ font.setDescriptor(descriptor);
+ return font;
+ case TYPE3:
+ return null; // should not happend
+
+ case TRUETYPE:
+ font = new PDFFontTrueType(number, fontname, subtype, basefont,
+ encoding);
+ font.setWidthMetrics(firstChar, lastChar, widths);
+ font.setDescriptor(descriptor);
+ return font;
}
return null; // should not happend
@@ -214,8 +203,9 @@ public class PDFFont extends PDFObject {
public byte[] toPDF() {
StringBuffer p = new StringBuffer();
p.append(this.number + " " + this.generation
- + " obj\n<< /Type /Font\n/Subtype /" + TYPE_NAMES[this.subtype]
- + "\n/Name /" + this.fontname + "\n/BaseFont /" + this.basefont);
+ + " obj\n<< /Type /Font\n/Subtype /"
+ + TYPE_NAMES[this.subtype] + "\n/Name /" + this.fontname
+ + "\n/BaseFont /" + this.basefont);
if (encoding != null) {
p.append("\n/Encoding ");
if (encoding instanceof PDFEncoding) {
@@ -238,6 +228,6 @@ public class PDFFont extends PDFObject {
*
* @param begin the buffer to be completed with the type specific fields
*/
- protected void fillInPDF(StringBuffer begin) {
- }
+ protected void fillInPDF(StringBuffer begin) {}
+
}
diff --git a/src/org/apache/fop/pdf/PDFFontDescriptor.java b/src/org/apache/fop/pdf/PDFFontDescriptor.java
index b13030d24..203879b35 100644
--- a/src/org/apache/fop/pdf/PDFFontDescriptor.java
+++ b/src/org/apache/fop/pdf/PDFFontDescriptor.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
/**
@@ -57,153 +14,164 @@ package org.apache.fop.pdf;
*/
public class PDFFontDescriptor extends PDFObject {
- // Required fields
- protected int ascent;
+ // Required fields
+ protected int ascent;
protected int capHeight;
- protected int descent;
+ protected int descent;
protected int flags;
protected PDFRectangle fontBBox;
- protected String basefont; //PDF-spec: FontName
+ protected String basefont; // PDF-spec: FontName
protected int italicAngle;
protected int stemV;
- // Optional fields
- protected int stemH = 0;
- protected int xHeight = 0;
- protected int leading = 0;
- protected int avgWidth = 0;
- protected int maxWidth = 0;
- protected int missingWidth = 0;
- protected PDFStream fontfile;
- //protected String charSet = null;
-
- protected byte subtype;
-
- /**
- * create the /FontDescriptor object
- *
- * @param number the object's number
- * @param ascent the maximum height above the baseline
- * @param descent the maximum depth below the baseline
- * @param capHeight height of the capital letters
- * @param flags various characteristics of the font
- * @param fontBBox the bounding box for the described font
- * @param basefont the base font name
- * @param italicAngle the angle of the vertical dominant strokes
- * @param stemV the width of the dominant vertical stems of glyphs
- */
- public PDFFontDescriptor(int number,
- String basefont,
- int ascent, int descent,
- int capHeight, int flags,
- PDFRectangle fontBBox,
- int italicAngle, int stemV) {
-
- /* generic creation of PDF object */
- super(number);
-
- /* set fields using paramaters */
- this.basefont = basefont;
- this.ascent = ascent;
- this.descent = descent;
- this.capHeight = capHeight;
- this.flags = flags;
- this.fontBBox = fontBBox;
- this.italicAngle = italicAngle;
- this.stemV = stemV;
- }
+ // Optional fields
+ protected int stemH = 0;
+ protected int xHeight = 0;
+ protected int leading = 0;
+ protected int avgWidth = 0;
+ protected int maxWidth = 0;
+ protected int missingWidth = 0;
+ protected PDFStream fontfile;
+ // protected String charSet = null;
+
+ protected byte subtype;
+
+ /**
+ * create the /FontDescriptor object
+ *
+ * @param number the object's number
+ * @param ascent the maximum height above the baseline
+ * @param descent the maximum depth below the baseline
+ * @param capHeight height of the capital letters
+ * @param flags various characteristics of the font
+ * @param fontBBox the bounding box for the described font
+ * @param basefont the base font name
+ * @param italicAngle the angle of the vertical dominant strokes
+ * @param stemV the width of the dominant vertical stems of glyphs
+ */
+ public PDFFontDescriptor(int number, String basefont, int ascent,
+ int descent, int capHeight, int flags,
+ PDFRectangle fontBBox, int italicAngle,
+ int stemV) {
+
+ /* generic creation of PDF object */
+ super(number);
+
+ /* set fields using paramaters */
+ this.basefont = basefont;
+ this.ascent = ascent;
+ this.descent = descent;
+ this.capHeight = capHeight;
+ this.flags = flags;
+ this.fontBBox = fontBBox;
+ this.italicAngle = italicAngle;
+ this.stemV = stemV;
+ }
- /**
- * set the optional metrics
- */
- public void setMetrics(int avgWidth, int maxWidth, int missingWidth, int leading, int stemH, int xHeight) {
- this.avgWidth = avgWidth;
- this.maxWidth = maxWidth;
- this.missingWidth = missingWidth;
- this.leading = leading;
- this.stemH = stemH;
- this.xHeight = xHeight;
- }
+ /**
+ * set the optional metrics
+ */
+ public void setMetrics(int avgWidth, int maxWidth, int missingWidth,
+ int leading, int stemH, int xHeight) {
+ this.avgWidth = avgWidth;
+ this.maxWidth = maxWidth;
+ this.missingWidth = missingWidth;
+ this.leading = leading;
+ this.stemH = stemH;
+ this.xHeight = xHeight;
+ }
- /**
- * set the optional font file stream
- *
- * @param subtype the font type defined in the font stream
- * @param fontfile the stream containing an embedded font
- */
- public void setFontFile(byte subtype, PDFStream fontfile) {
- this.subtype = subtype;
- this.fontfile = fontfile;
- }
+ /**
+ * set the optional font file stream
+ *
+ * @param subtype the font type defined in the font stream
+ * @param fontfile the stream containing an embedded font
+ */
+ public void setFontFile(byte subtype, PDFStream fontfile) {
+ this.subtype = subtype;
+ this.fontfile = fontfile;
+ }
- //public void setCharSet(){}//for subset fonts
+ // public void setCharSet(){}//for subset fonts
- /**
- * produce the PDF representation for the object
- *
- * @return the PDF
- */
+ /**
+ * produce the PDF representation for the object
+ *
+ * @return the PDF
+ */
public byte[] toPDF() {
- StringBuffer p = new StringBuffer(
- this.number + " " + this.generation
- + " obj\n<< /Type /FontDescriptor"
- + "\n/FontName /" + this.basefont);
-
- p.append("\n/FontBBox "); p.append(fontBBox.toPDFString());
- p.append("\n/Flags "); p.append(flags);
- p.append("\n/CapHeight "); p.append(capHeight);
- p.append("\n/Ascent "); p.append(ascent);
- p.append("\n/Descent "); p.append(descent);
- p.append("\n/ItalicAngle "); p.append(italicAngle);
- p.append("\n/StemV "); p.append(stemV);
- // optional fields
- if (stemH != 0) {
- p.append("\n/StemH "); p.append(stemH);
- }
- if (xHeight != 0) {
- p.append("\n/XHeight "); p.append(xHeight);
- }
- if (avgWidth != 0) {
- p.append("\n/AvgWidth "); p.append(avgWidth);
- }
- if (maxWidth != 0) {
- p.append("\n/MaxWidth "); p.append(maxWidth);
- }
- if (missingWidth != 0) {
- p.append("\n/MissingWidth "); p.append(missingWidth);
- }
- if (leading != 0) {
- p.append("\n/Leading "); p.append(leading);
- }
- if (fontfile != null) {
- switch (subtype) {
- case PDFFont.TYPE1:
- p.append("\n/FontFile ");
- break;
- case PDFFont.TRUETYPE:
- p.append("\n/FontFile2 ");
- break;
- case PDFFont.TYPE0:
- p.append("\n/FontFile2 ");
- break;
- default:
- p.append("\n/FontFile2 ");
- }
- p.append(fontfile.referencePDF());
- }
- // charSet for subset fonts // not yet implemented
- // CID optional field
- fillInPDF(p);
- p.append("\n >>\nendobj\n");
- return p.toString().getBytes();
+ StringBuffer p = new StringBuffer(this.number + " " + this.generation
+ + " obj\n<< /Type /FontDescriptor"
+ + "\n/FontName /" + this.basefont);
+
+ p.append("\n/FontBBox ");
+ p.append(fontBBox.toPDFString());
+ p.append("\n/Flags ");
+ p.append(flags);
+ p.append("\n/CapHeight ");
+ p.append(capHeight);
+ p.append("\n/Ascent ");
+ p.append(ascent);
+ p.append("\n/Descent ");
+ p.append(descent);
+ p.append("\n/ItalicAngle ");
+ p.append(italicAngle);
+ p.append("\n/StemV ");
+ p.append(stemV);
+ // optional fields
+ if (stemH != 0) {
+ p.append("\n/StemH ");
+ p.append(stemH);
+ }
+ if (xHeight != 0) {
+ p.append("\n/XHeight ");
+ p.append(xHeight);
+ }
+ if (avgWidth != 0) {
+ p.append("\n/AvgWidth ");
+ p.append(avgWidth);
+ }
+ if (maxWidth != 0) {
+ p.append("\n/MaxWidth ");
+ p.append(maxWidth);
+ }
+ if (missingWidth != 0) {
+ p.append("\n/MissingWidth ");
+ p.append(missingWidth);
+ }
+ if (leading != 0) {
+ p.append("\n/Leading ");
+ p.append(leading);
+ }
+ if (fontfile != null) {
+ switch (subtype) {
+ case PDFFont.TYPE1:
+ p.append("\n/FontFile ");
+ break;
+ case PDFFont.TRUETYPE:
+ p.append("\n/FontFile2 ");
+ break;
+ case PDFFont.TYPE0:
+ p.append("\n/FontFile2 ");
+ break;
+ default:
+ p.append("\n/FontFile2 ");
+ }
+ p.append(fontfile.referencePDF());
+ }
+ // charSet for subset fonts // not yet implemented
+ // CID optional field
+ fillInPDF(p);
+ p.append("\n >>\nendobj\n");
+ return p.toString().getBytes();
}
- /**
- * fill in the specifics for the font's descriptor.
- *
- * the given buffer already contains the fields common to all descriptors.
- *
- * @param begin the buffer to be completed with the specific fields
- */
- protected void fillInPDF(StringBuffer begin) {
- }
+ /**
+ * fill in the specifics for the font's descriptor.
+ *
+ * the given buffer already contains the fields common to all descriptors.
+ *
+ * @param begin the buffer to be completed with the specific fields
+ */
+ protected void fillInPDF(StringBuffer begin) {}
+
}
diff --git a/src/org/apache/fop/pdf/PDFFontNonBase14.java b/src/org/apache/fop/pdf/PDFFontNonBase14.java
index 583af810d..ac4abb261 100644
--- a/src/org/apache/fop/pdf/PDFFontNonBase14.java
+++ b/src/org/apache/fop/pdf/PDFFontNonBase14.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
// Java
@@ -58,67 +15,84 @@ package org.apache.fop.pdf;
*/
public abstract class PDFFontNonBase14 extends PDFFont {
- /** first character code in the font */
- protected int firstChar;
- /** last character code in the font */
- protected int lastChar;
- /** widths of characters from firstChar to lastChar */
- protected PDFArray widths;
- /** descriptor of font metrics */
- protected PDFFontDescriptor descriptor;
-
- /**
- * create the /Font object
- *
- * @param number the object's number
- * @param fontname the internal name for the font
- * @param subtype the font's subtype
- * @param basefont the base font name
- * @param encoding the character encoding schema used by the font
- * @param mapping the Unicode mapping mechanism
- */
- public PDFFontNonBase14(int number, String fontname, byte subtype,
- String basefont, Object encoding/*, PDFToUnicode mapping*/) {
-
- /* generic creation of PDF object */
- super(number, fontname, subtype, basefont, encoding);
-
- this.descriptor = null;
- }
-
- /**
- * set the width metrics for the font
- *
- * @param firstChar the first character code in the font
- * @param lastChar the last character code in the font
- * @param widths an array of size (lastChar - firstChar +1)
- */
- public void setWidthMetrics(int firstChar, int lastChar, PDFArray widths) {
- /* set fields using paramaters */
- this.firstChar = firstChar;
- this.lastChar = lastChar;
- this.widths = widths;
- }
-
- /**
- * set the font descriptor (unused for the Type3 fonts)
- *
- * @param descriptor the descriptor for other font's metrics
- */
- public void setDescriptor(PDFFontDescriptor descriptor) {
- this.descriptor = descriptor;
- }
+ /**
+ * first character code in the font
+ */
+ protected int firstChar;
+
+ /**
+ * last character code in the font
+ */
+ protected int lastChar;
+
+ /**
+ * widths of characters from firstChar to lastChar
+ */
+ protected PDFArray widths;
+
+ /**
+ * descriptor of font metrics
+ */
+ protected PDFFontDescriptor descriptor;
+
+ /**
+ * create the /Font object
+ *
+ * @param number the object's number
+ * @param fontname the internal name for the font
+ * @param subtype the font's subtype
+ * @param basefont the base font name
+ * @param encoding the character encoding schema used by the font
+ * @param mapping the Unicode mapping mechanism
+ */
+ public PDFFontNonBase14(int number, String fontname, byte subtype,
+ String basefont,
+ Object encoding /* , PDFToUnicode mapping */) {
+
+ /* generic creation of PDF object */
+ super(number, fontname, subtype, basefont, encoding);
+
+ this.descriptor = null;
+ }
+
+ /**
+ * set the width metrics for the font
+ *
+ * @param firstChar the first character code in the font
+ * @param lastChar the last character code in the font
+ * @param widths an array of size (lastChar - firstChar +1)
+ */
+ public void setWidthMetrics(int firstChar, int lastChar,
+ PDFArray widths) {
+ /* set fields using paramaters */
+ this.firstChar = firstChar;
+ this.lastChar = lastChar;
+ this.widths = widths;
+ }
+
+ /**
+ * set the font descriptor (unused for the Type3 fonts)
+ *
+ * @param descriptor the descriptor for other font's metrics
+ */
+ public void setDescriptor(PDFFontDescriptor descriptor) {
+ this.descriptor = descriptor;
+ }
+
+ /**
+ * fill in the specifics for the font's subtype
+ */
+ protected void fillInPDF(StringBuffer p) {
+ p.append("\n/FirstChar ");
+ p.append(firstChar);
+ p.append("\n/LastChar ");
+ p.append(lastChar);
+ p.append("\n/Widths ");
+ p.append(this.widths.referencePDF());
+ if (descriptor != null) {
+ p.append("\n/FontDescriptor ");
+ p.append(this.descriptor.referencePDF());
+ }
+ }
- /**
- * fill in the specifics for the font's subtype
- */
- protected void fillInPDF(StringBuffer p) {
- p.append("\n/FirstChar "); p.append(firstChar);
- p.append("\n/LastChar "); p.append(lastChar);
- p.append("\n/Widths "); p.append(this.widths.referencePDF());
- if (descriptor != null) {
- p.append("\n/FontDescriptor ");
- p.append(this.descriptor.referencePDF());
- }
- }
}
diff --git a/src/org/apache/fop/pdf/PDFFontTrueType.java b/src/org/apache/fop/pdf/PDFFontTrueType.java
index be1f37131..444670d38 100644
--- a/src/org/apache/fop/pdf/PDFFontTrueType.java
+++ b/src/org/apache/fop/pdf/PDFFontTrueType.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
/**
@@ -58,21 +15,22 @@ package org.apache.fop.pdf;
*/
public class PDFFontTrueType extends PDFFontNonBase14 {
- /**
- * create the /Font object
- *
- * @param number the object's number
- * @param fontname the internal name for the font
- * @param subtype the font's subtype (PDFFont.TRUETYPE)
- * @param basefont the base font name
- * @param encoding the character encoding schema used by the font
- * @param mapping the Unicode mapping mechanism
- */
- public PDFFontTrueType(int number, String fontname, byte subtype,
- String basefont, Object encoding/*, PDFToUnicode mapping*/) {
-
- /* generic creation of PDF object */
- super(number, fontname, subtype, basefont, encoding/*, mapping*/);
- }
+ /**
+ * create the /Font object
+ *
+ * @param number the object's number
+ * @param fontname the internal name for the font
+ * @param subtype the font's subtype (PDFFont.TRUETYPE)
+ * @param basefont the base font name
+ * @param encoding the character encoding schema used by the font
+ * @param mapping the Unicode mapping mechanism
+ */
+ public PDFFontTrueType(int number, String fontname, byte subtype,
+ String basefont,
+ Object encoding /* , PDFToUnicode mapping */) {
+
+ /* generic creation of PDF object */
+ super(number, fontname, subtype, basefont, encoding /* , mapping */);
+ }
}
diff --git a/src/org/apache/fop/pdf/PDFFontType0.java b/src/org/apache/fop/pdf/PDFFontType0.java
index 7ca15647c..1044ade09 100644
--- a/src/org/apache/fop/pdf/PDFFontType0.java
+++ b/src/org/apache/fop/pdf/PDFFontType0.java
@@ -1,54 +1,12 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
+
/**
* class representing a Type0 font.
*
@@ -56,76 +14,82 @@ package org.apache.fop.pdf;
*/
public class PDFFontType0 extends PDFFontNonBase14 {
- /** this should be an array of CIDFont but only the first one is used */
- protected PDFCIDFont descendantFonts;
+ /**
+ * this should be an array of CIDFont but only the first one is used
+ */
+ protected PDFCIDFont descendantFonts;
protected PDFCMap cmap;
-
- /**
- * create the /Font object
- *
- * @param number the object's number
- * @param fontname the internal name for the font
- * @param subtype the font's subtype (PDFFont.TYPE0)
- * @param basefont the base font name
- * @param encoding the character encoding schema used by the font
- * @param mapping the Unicode mapping mechanism
- */
- public PDFFontType0(int number, String fontname, byte subtype,
- String basefont, Object encoding/*, PDFToUnicode mapping*/) {
-
- /* generic creation of PDF object */
- super(number, fontname, subtype, basefont, encoding/*, mapping*/);
-
- /* set fields using paramaters */
- this.descendantFonts = null;
- cmap=null;
- }
-
- /**
- * create the /Font object
- *
- * @param number the object's number
- * @param fontname the internal name for the font
- * @param subtype the font's subtype (PDFFont.TYPE0)
- * @param basefont the base font name
- * @param encoding the character encoding schema used by the font
- * @param mapping the Unicode mapping mechanism
- * @param descendantFonts the CIDFont upon which this font is based
- */
- public PDFFontType0(int number, String fontname, byte subtype,
- String basefont, Object encoding/*, PDFToUnicode mapping*/,
- PDFCIDFont descendantFonts) {
- /* generic creation of PDF object */
- super(number, fontname, subtype, basefont, encoding/*, mapping*/);
+ /**
+ * create the /Font object
+ *
+ * @param number the object's number
+ * @param fontname the internal name for the font
+ * @param subtype the font's subtype (PDFFont.TYPE0)
+ * @param basefont the base font name
+ * @param encoding the character encoding schema used by the font
+ * @param mapping the Unicode mapping mechanism
+ */
+ public PDFFontType0(int number, String fontname, byte subtype,
+ String basefont,
+ Object encoding /* , PDFToUnicode mapping */) {
+
+ /* generic creation of PDF object */
+ super(number, fontname, subtype, basefont, encoding /* , mapping */);
+
+ /* set fields using paramaters */
+ this.descendantFonts = null;
+ cmap = null;
+ }
- /* set fields using paramaters */
- this.descendantFonts = descendantFonts;
- }
+ /**
+ * create the /Font object
+ *
+ * @param number the object's number
+ * @param fontname the internal name for the font
+ * @param subtype the font's subtype (PDFFont.TYPE0)
+ * @param basefont the base font name
+ * @param encoding the character encoding schema used by the font
+ * @param mapping the Unicode mapping mechanism
+ * @param descendantFonts the CIDFont upon which this font is based
+ */
+ public PDFFontType0(int number, String fontname, byte subtype,
+ String basefont,
+ Object encoding /* , PDFToUnicode mapping */,
+ PDFCIDFont descendantFonts) {
+
+ /* generic creation of PDF object */
+ super(number, fontname, subtype, basefont, encoding /* , mapping */);
+
+ /* set fields using paramaters */
+ this.descendantFonts = descendantFonts;
+ }
- /**
- * set the descendant font
- *
- * @param descendantFonts the CIDFont upon which this font is based
- */
- public void setDescendantFonts(PDFCIDFont descendantFonts) {
- this.descendantFonts = descendantFonts;
- }
+ /**
+ * set the descendant font
+ *
+ * @param descendantFonts the CIDFont upon which this font is based
+ */
+ public void setDescendantFonts(PDFCIDFont descendantFonts) {
+ this.descendantFonts = descendantFonts;
+ }
public void setCMAP(PDFCMap cmap) {
- this.cmap=cmap;
+ this.cmap = cmap;
}
- /**
- * fill in the specifics for the font's subtype
- */
+
+ /**
+ * fill in the specifics for the font's subtype
+ */
protected void fillInPDF(StringBuffer p) {
if (descendantFonts != null) {
- p.append("\n/DescendantFonts [ " +
- this.descendantFonts.referencePDF() + " ] ");
+ p.append("\n/DescendantFonts [ "
+ + this.descendantFonts.referencePDF() + " ] ");
}
if (cmap != null) {
- p.append("\n/ToUnicode "+cmap.referencePDF());
+ p.append("\n/ToUnicode " + cmap.referencePDF());
}
}
+
}
diff --git a/src/org/apache/fop/pdf/PDFFontType1.java b/src/org/apache/fop/pdf/PDFFontType1.java
index 3516b670b..2a98c131d 100644
--- a/src/org/apache/fop/pdf/PDFFontType1.java
+++ b/src/org/apache/fop/pdf/PDFFontType1.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
/**
@@ -61,21 +18,22 @@ package org.apache.fop.pdf;
*/
public class PDFFontType1 extends PDFFontNonBase14 {
- /**
- * create the /Font object
- *
- * @param number the object's number
- * @param fontname the internal name for the font
- * @param subtype the font's subtype (PDFFont.TYPE1 or PDFFont.MMTYPE1)
- * @param basefont the base font name
- * @param encoding the character encoding schema used by the font
- * @param mapping the Unicode mapping mechanism
- */
- public PDFFontType1(int number, String fontname, byte subtype,
- String basefont, Object encoding/*, PDFToUnicode mapping*/) {
-
- /* generic creation of PDF object */
- super(number, fontname, subtype, basefont, encoding);
- }
+ /**
+ * create the /Font object
+ *
+ * @param number the object's number
+ * @param fontname the internal name for the font
+ * @param subtype the font's subtype (PDFFont.TYPE1 or PDFFont.MMTYPE1)
+ * @param basefont the base font name
+ * @param encoding the character encoding schema used by the font
+ * @param mapping the Unicode mapping mechanism
+ */
+ public PDFFontType1(int number, String fontname, byte subtype,
+ String basefont,
+ Object encoding /* , PDFToUnicode mapping */) {
+
+ /* generic creation of PDF object */
+ super(number, fontname, subtype, basefont, encoding);
+ }
}
diff --git a/src/org/apache/fop/pdf/PDFFontType3.java b/src/org/apache/fop/pdf/PDFFontType3.java
index 0461228d2..dc1173d46 100644
--- a/src/org/apache/fop/pdf/PDFFontType3.java
+++ b/src/org/apache/fop/pdf/PDFFontType3.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
/**
@@ -61,108 +18,123 @@ package org.apache.fop.pdf;
*/
public class PDFFontType3 extends PDFFontNonBase14 {
- /** font's required /FontBBox bounding box */
- protected PDFRectangle fontBBox;
-
- /** font's required /FontMatrix array */
- protected PDFArray fontMatrix;
-
- /** font's required /CharProcs dictionary */
- protected PDFCharProcs charProcs;
-
- /** font's optional /Resources object */
- protected PDFResources resources;
-
- /**
- * create the /Font object
- *
- * @param number the object's number
- * @param fontname the internal name for the font
- * @param subtype the font's subtype (PDFFont.TYPE3)
- * @param basefont the base font name
- * @param encoding the character encoding schema used by the font
- * @param mapping the Unicode mapping mechanism
- */
- public PDFFontType3(int number, String fontname, byte subtype,
- String basefont, Object encoding/*, PDFToUnicode mapping*/) {
-
- /* generic creation of PDF object */
- super(number, fontname, subtype, basefont, encoding/*, mapping*/);
-
- this.fontBBox = null;
- this.fontMatrix = null;
- this.charProcs = null;
- }
-
- /**
- * create the /Font object
- *
- * @param number the object's number
- * @param fontname the internal name for the font
- * @param subtype the font's subtype (PDFFont.TYPE3)
- * @param basefont the base font name
- * @param encoding the character encoding schema used by the font
- * @param mapping the Unicode mapping mechanism
- * @param fontBBox the font's bounding box
- * @param fontMatrix the font's transformation matrix
- * @param charProcs the glyphs' definitions
- */
- public PDFFontType3(int number, String fontname, byte subtype,
- String basefont, Object encoding/*, PDFToUnicode mapping*/,
- PDFRectangle fontBBox, PDFArray fontMatrix, PDFCharProcs charProcs) {
-
- /* generic creation of PDF object */
- super(number, fontname, subtype, basefont, encoding/*, mapping*/);
-
- this.fontBBox = fontBBox;
- this.fontMatrix = fontMatrix;
- this.charProcs = charProcs;
- }
-
- /**
- * set the font's bounding box
- *
- * @param bbox bounding box for the font
- */
- public void setFontBBox(PDFRectangle bbox) {
- this.fontBBox = bbox;
- }
-
- /**
- * set the font's transformation matrix
- *
- * @param matrix the transformation matrix for the font
- */
- public void setFontMatrix(PDFArray matrix) {
- this.fontMatrix = matrix;
- }
-
- /**
- * set the glyphs' definitions.
- * The /CharProcs object needs to be registered in the document's resources.
- *
- * @param chars the glyphs' dictionary
- */
- public void setCharProcs(PDFCharProcs chars) {
- this.charProcs = chars;
- }
-
- /**
- * fill in the specifics for the font's subtype.
- *
- * the given buffer already contains the fields common to all font types.
- *
- * @param p the buffer to be completed with the type specific fields
- */
- protected void fillInPDF(StringBuffer p) {
- if (fontBBox != null) {
- p.append("\n/FontBBox "); p.append(fontBBox.toPDF());
- }
- if (fontMatrix != null) {
- p.append("\n/FontMatrix "); p.append(fontMatrix.toPDF());
- }
- if (charProcs != null) {
- p.append("\n/CharProcs "); p.append(charProcs.referencePDF());
- }
- }
+ /**
+ * font's required /FontBBox bounding box
+ */
+ protected PDFRectangle fontBBox;
+
+ /**
+ * font's required /FontMatrix array
+ */
+ protected PDFArray fontMatrix;
+
+ /**
+ * font's required /CharProcs dictionary
+ */
+ protected PDFCharProcs charProcs;
+
+ /**
+ * font's optional /Resources object
+ */
+ protected PDFResources resources;
+
+ /**
+ * create the /Font object
+ *
+ * @param number the object's number
+ * @param fontname the internal name for the font
+ * @param subtype the font's subtype (PDFFont.TYPE3)
+ * @param basefont the base font name
+ * @param encoding the character encoding schema used by the font
+ * @param mapping the Unicode mapping mechanism
+ */
+ public PDFFontType3(int number, String fontname, byte subtype,
+ String basefont,
+ Object encoding /* , PDFToUnicode mapping */) {
+
+ /* generic creation of PDF object */
+ super(number, fontname, subtype, basefont, encoding /* , mapping */);
+
+ this.fontBBox = null;
+ this.fontMatrix = null;
+ this.charProcs = null;
+ }
+
+ /**
+ * create the /Font object
+ *
+ * @param number the object's number
+ * @param fontname the internal name for the font
+ * @param subtype the font's subtype (PDFFont.TYPE3)
+ * @param basefont the base font name
+ * @param encoding the character encoding schema used by the font
+ * @param mapping the Unicode mapping mechanism
+ * @param fontBBox the font's bounding box
+ * @param fontMatrix the font's transformation matrix
+ * @param charProcs the glyphs' definitions
+ */
+ public PDFFontType3(int number, String fontname, byte subtype,
+ String basefont,
+ Object encoding /* , PDFToUnicode mapping */,
+ PDFRectangle fontBBox, PDFArray fontMatrix,
+ PDFCharProcs charProcs) {
+
+ /* generic creation of PDF object */
+ super(number, fontname, subtype, basefont, encoding /* , mapping */);
+
+ this.fontBBox = fontBBox;
+ this.fontMatrix = fontMatrix;
+ this.charProcs = charProcs;
+ }
+
+ /**
+ * set the font's bounding box
+ *
+ * @param bbox bounding box for the font
+ */
+ public void setFontBBox(PDFRectangle bbox) {
+ this.fontBBox = bbox;
+ }
+
+ /**
+ * set the font's transformation matrix
+ *
+ * @param matrix the transformation matrix for the font
+ */
+ public void setFontMatrix(PDFArray matrix) {
+ this.fontMatrix = matrix;
+ }
+
+ /**
+ * set the glyphs' definitions.
+ * The /CharProcs object needs to be registered in the document's resources.
+ *
+ * @param chars the glyphs' dictionary
+ */
+ public void setCharProcs(PDFCharProcs chars) {
+ this.charProcs = chars;
+ }
+
+ /**
+ * fill in the specifics for the font's subtype.
+ *
+ * the given buffer already contains the fields common to all font types.
+ *
+ * @param p the buffer to be completed with the type specific fields
+ */
+ protected void fillInPDF(StringBuffer p) {
+ if (fontBBox != null) {
+ p.append("\n/FontBBox ");
+ p.append(fontBBox.toPDF());
+ }
+ if (fontMatrix != null) {
+ p.append("\n/FontMatrix ");
+ p.append(fontMatrix.toPDF());
+ }
+ if (charProcs != null) {
+ p.append("\n/CharProcs ");
+ p.append(charProcs.referencePDF());
+ }
+ }
+
}
diff --git a/src/org/apache/fop/pdf/PDFFunction.java b/src/org/apache/fop/pdf/PDFFunction.java
index 18213e5fd..185addc9e 100644
--- a/src/org/apache/fop/pdf/PDFFunction.java
+++ b/src/org/apache/fop/pdf/PDFFunction.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -6,707 +7,664 @@
package org.apache.fop.pdf;
-//Java...
+// Java...
import java.util.Vector;
/**
* class representing a PDF Function.
- *
+ *
* PDF Functions represent parameterized mathematical formulas and sampled representations with
* arbitrary resolution. Functions are used in two areas: device-dependent
* rasterization information for halftoning and transfer
* functions, and color specification for smooth shading (a PDF 1.3 feature).
- *
+ *
* All PDF Functions have a FunctionType (0,2,3, or 4), a Domain, and a Range.
*/
public class PDFFunction extends PDFObject {
- //Guts common to all function types
- /** Required: The Type of function (0,2,3,4) default is 0.*/
- protected int functionType =0; //Default
-
- /**
- * Required: 2 * m Array of Double numbers which are possible inputs to the function
- */
- protected Vector domain = null;
-
- /**
- * Required: 2 * n Array of Double numbers which are possible outputs to the function
- */
- protected Vector range = null;
-
- /* ********************TYPE 0***************************** */
- //FunctionType 0 specific function guts
- /**
- * Required: Array containing the Integer size of the Domain and Range, respectively.
- * Note: This is really more like two seperate integers, sizeDomain, and sizeRange,
- * but since they're expressed as an array in PDF, my implementation reflects that.
- */
- protected Vector size = null;
-
- /** Required for Type 0: Number of Bits used to represent each sample value. Limited to 1,2,4,8,12,16,24, or 32 */
- protected int bitsPerSample = 1;
- /** Optional for Type 0: order of interpolation between samples. Limited to linear (1) or cubic (3). Default is 1 */
- protected int order = 1;
- /**
- * Optional for Type 0: A 2 * m array of Doubles which provides a linear mapping of input values to the domain.
- *
- * Required for Type 3: A 2 * k array of Doubles that, taken in pairs, map each subset of the domain defined by Domain and the Bounds array to the domain of the corresponding function.
- * Should be two values per function, usually (0,1), as in [0 1 0 1] for 2 functions.
- */
- protected Vector encode = null;
- /**
- * Optinoal for Type 0: A 2 * n array of Doubles which provides a linear mapping of sample values to the range. Defaults to Range.
- */
- protected Vector decode = null;
- /** Optional For Type 0: A stream of sample values */
- /** Required For Type 4: Postscript Calculator function composed of arithmetic, boolean, and stack operators + boolean constants */
- protected StringBuffer functionDataStream = null;
- /**
- * Required (?) For Type 0: A vector of Strings for the various filters to be used to decode the stream.
- * These are how the string is compressed. Flate, LZW, etc.
- */
- protected Vector filter = null;
- /* *************************TYPE 2************************** */
- /**
- * Required For Type 2: An Array of n Doubles defining the function result when x=0. Default is [0].
- */
- protected Vector cZero = null;
- /**
- * Required For Type 2: An Array of n Doubles defining the function result when x=1. Default is [1].
- */
- protected Vector cOne = null;
- /**
- * Required for Type 2: The interpolation exponent.
- * Each value x will return n results.
- * Must be greater than 0.
- */
- protected double interpolationExponentN = 1;
-
- /* *************************TYPE 3************************** */
- /** Required for Type 3: An vector of PDFFunctions which form an array of k single input functions making up the stitching function. */
- protected Vector functions = null;
- /**
- * Optional for Type 3: An array of (k-1) Doubles that, in combination with Domain, define the intervals to which each function from the Functions array apply. Bounds elements must be in order of increasing magnitude, and each value must be within the value of Domain.
- * k is the number of functions.
- * If you pass null, it will output (1/k) in an array of k-1 elements.
- * This makes each function responsible for an equal amount of the stitching function.
- * It makes the gradient even.
- */
- protected Vector bounds = null;
- // See encode above, as it's also part of Type 3 Functions.
-
- /* *************************TYPE 4************************** */
- //See 'data' above.
-
- /**
- * create an complete Function object of Type 0, A Sampled function.
- *
- * Use null for an optional object parameter if you choose not to use it.
- * For optional int parameters, pass the default.
- *
- * @param theDomain Vector objects of Double objects.
- * This is the domain of the function.
- * See page 264 of the PDF 1.3 Spec.
- * @param theRange Vector objects of Double objects.
- * This is the Range of the function.
- * See page 264 of the PDF 1.3 Spec.
- * @param theSize A Vector object of Integer objects.
- * This is the number of samples in each input dimension.
- * I can't imagine there being more or less than two input dimensions,
- * so maybe this should be an array of length 2.
- *
- * See page 265 of the PDF 1.3 Spec.
- * @param theBitsPerSample An int specifying the number of bits user to represent each sample value.
- * Limited to 1,2,4,8,12,16,24 or 32.
- * See page 265 of the 1.3 PDF Spec.
- * @param theOrder The order of interpolation between samples. Default is 1 (one). Limited
- * to 1 (one) or 3, which means linear or cubic-spline interpolation.
- *
- * This attribute is optional.
- *
- * See page 265 in the PDF 1.3 spec.
- * @param theEncode Vector objects of Double objects.
- * This is the linear mapping of input values intop the domain
- * of the function's sample table. Default is hard to represent in
- * ascii, but basically [0 (Size0 1) 0 (Size1 1)...].
- * This attribute is optional.
- *
- * See page 265 in the PDF 1.3 spec.
- * @param theDecode Vector objects of Double objects.
- * This is a linear mapping of sample values into the range.
- * The default is just the range.
- *
- * This attribute is optional.
- * Read about it on page 265 of the PDF 1.3 spec.
- * @param theFunctionDataStream The sample values that specify the function are provided in a stream.
- *
- * This is optional, but is almost always used.
- *
- * Page 265 of the PDF 1.3 spec has more.
- * @param theFilter This is a vector of String objects which are the various filters that
- * have are to be applied to the stream to make sense of it. Order matters,
- * so watch out.
- *
- * This is not documented in the Function section of the PDF 1.3 spec,
- * it was deduced from samples that this is sometimes used, even if we may never
- * use it in FOP. It is added for completeness sake.
- * @param theNumber The object number of this PDF object.
- * @param theFunctionType This is the type of function (0,2,3, or 4).
- * It should be 0 as this is the constructor for sampled functions.
- */
- public PDFFunction(int theNumber, int theFunctionType,
- Vector theDomain, Vector theRange,
- Vector theSize,int theBitsPerSample,
- int theOrder,Vector theEncode,Vector theDecode,
- StringBuffer theFunctionDataStream, Vector theFilter)
- {
- super(theNumber);
-
- this.functionType = 0; //dang well better be 0;
- this.size = theSize;
- this.bitsPerSample = theBitsPerSample;
- this.order = theOrder; //int
- this.encode = theEncode;//vector of int
- this.decode = theDecode; //vector of int
- this.functionDataStream = theFunctionDataStream;
- this.filter = theFilter;//vector of Strings
-
- //the domain and range are actually two dimensional arrays.
- //so if there's not an even number of items, bad stuff
- //happens.
- this.domain = theDomain;
- this.range = theRange;
- }
-
- /**
- * create an complete Function object of Type 2, an Exponential Interpolation function.
- *
- * Use null for an optional object parameter if you choose not to use it.
- * For optional int parameters, pass the default.
- *
- * @param theNumber the object's number
- * @param theDomain Vector objects of Double objects.
- * This is the domain of the function.
- * See page 264 of the PDF 1.3 Spec.
- * @param theRange Vector of Doubles that is the Range of the function.
- * See page 264 of the PDF 1.3 Spec.
- * @param theCZero This is a vector of Double objects which defines the function result
- * when x=0.
- *
- * This attribute is optional.
- * It's described on page 268 of the PDF 1.3 spec.
- * @param theCOne This is a vector of Double objects which defines the function result
- * when x=1.
- *
- * This attribute is optional.
- * It's described on page 268 of the PDF 1.3 spec.
- * @param theInterpolationExponentN This is the inerpolation exponent.
- *
- * This attribute is required.
- * PDF Spec page 268
- * @param theFunctionType The type of the function, which should be 2.
- */
- public PDFFunction(int theNumber, int theFunctionType,
- Vector theDomain, Vector theRange,
- Vector theCZero, Vector theCOne,
- double theInterpolationExponentN)
- {
- super(theNumber);
-
- this.functionType = 2; //dang well better be 2;
-
- this.cZero = theCZero;
- this.cOne = theCOne;
- this.interpolationExponentN = theInterpolationExponentN;
-
-
- this.domain = theDomain;
- this.range = theRange;
-
- }
-
- /**
- * create an complete Function object of Type 3, a Stitching function.
- *
- * Use null for an optional object parameter if you choose not to use it.
- * For optional int parameters, pass the default.
- *
- * @param theNumber the object's number
- * @param theDomain Vector objects of Double objects.
- * This is the domain of the function.
- * See page 264 of the PDF 1.3 Spec.
- * @param theRange Vector objects of Double objects.
- * This is the Range of the function.
- * See page 264 of the PDF 1.3 Spec.
- * @param theFunctions A Vector of the PDFFunction objects that the stitching function stitches.
- *
- * This attributed is required.
- * It is described on page 269 of the PDF spec.
- * @param theBounds This is a vector of Doubles representing the numbers that,
- * in conjunction with Domain define the intervals to which each function from
- * the 'functions' object applies. It must be in order of increasing magnitude,
- * and each must be within Domain.
- *
- * It basically sets how much of the gradient each function handles.
- *
- * This attributed is required.
- * It's described on page 269 of the PDF 1.3 spec.
- * @param theEncode Vector objects of Double objects.
- * This is the linear mapping of input values intop the domain
- * of the function's sample table. Default is hard to represent in
- * ascii, but basically [0 (Size0 1) 0 (Size1 1)...].
- * This attribute is required.
- *
- * See page 270 in the PDF 1.3 spec.
- * @param theFunctionType This is the function type. It should be 3,
- * for a stitching function.
- */
- public PDFFunction(int theNumber, int theFunctionType,
- Vector theDomain, Vector theRange,
- Vector theFunctions, Vector theBounds,
- Vector theEncode)
- {
- super(theNumber);
-
- this.functionType = 3; //dang well better be 3;
-
- this.functions = theFunctions;
- this.bounds = theBounds;
- this.encode = theEncode;
- this.domain = theDomain;
- this.range = theRange;
-
- }
-
- /**
- * create an complete Function object of Type 4, a postscript calculator function.
- *
- * Use null for an optional object parameter if you choose not to use it.
- * For optional int parameters, pass the default.
- *
- * @param theDomain Vector object of Double objects.
- * This is the domain of the function.
- * See page 264 of the PDF 1.3 Spec.
- * @param theRange Vector object of Double objects.
- * This is the Range of the function.
- * See page 264 of the PDF 1.3 Spec.
- * @param theFunctionDataStream This is a stream of arithmetic, boolean, and stack operators and boolean constants.
- * I end up enclosing it in the '{' and '}' braces for you, so don't do it
- * yourself.
- *
- * This attribute is required.
- * It's described on page 269 of the PDF 1.3 spec.
- * @param theNumber The object number of this PDF object.
- * @param theFunctionType The type of function which should be 4, as this is
- * a Postscript calculator function
- */
- public PDFFunction(int theNumber, int theFunctionType,
- Vector theDomain, Vector theRange,
- StringBuffer theFunctionDataStream)
- {
- super(theNumber);
-
- this.functionType = 4; //dang well better be 4;
- this.functionDataStream = theFunctionDataStream;
-
- this.domain = theDomain;
-
- this.range = theRange;
-
- }
-
-
- /**
- * represent as PDF. Whatever the FunctionType is, the correct
- * representation spits out. The sets of required and optional
- * attributes are different for each type, but if a required
- * attribute's object was constructed as null, then no error
- * is raised. Instead, the malformed PDF that was requested
- * by the construction is dutifully output.
- * This policy should be reviewed.
- *
- * @return the PDF string.
- */
- public byte[] toPDF() {
- int vectorSize=0;
- int numberOfFunctions=0;
- int tempInt=0;
- StringBuffer p = new StringBuffer();
- p.append(this.number + " " +this.generation
- + " obj\n<< \n/FunctionType "+this.functionType+" \n");
-
- //FunctionType 0
- if(this.functionType == 0)
- {
- if(this.domain != null)
- {
- //DOMAIN
- p.append("/Domain [ ");
- vectorSize = this.domain.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.domain.elementAt(tempInt))
- +" ");
- }
-
- p.append("] \n");
- }
- else
- {
- p.append("/Domain [ 0 1 ] \n");
- }
-
- //SIZE
- if(this.size != null)
- {
- p.append("/Size [ ");
- vectorSize = this.size.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.size.elementAt(tempInt)) +" ");
- }
- p.append("] \n");
- }
- //ENCODE
- if(this.encode != null)
- {
- p.append("/Encode [ ");
- vectorSize = this.encode.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.encode.elementAt(tempInt)) +" ");
- }
- p.append("] \n");
- }
- else
- {
- p.append("/Encode [ ");
- vectorSize = this.functions.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append("0 1 ");
- }
- p.append("] \n");
-
- }
-
- //BITSPERSAMPLE
- p.append("/BitsPerSample "+this.bitsPerSample);
-
- //ORDER (optional)
- if(this.order ==1 || this.order == 3)
- {
- p.append(" \n/Order "+this.order+" \n");
- }
-
- //RANGE
- if(this.range != null)
- {
- p.append("/Range [ ");
- vectorSize = this.range.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.range.elementAt(tempInt)) +" ");
- }
-
- p.append("] \n");
- }
-
- //DECODE
- if(this.decode != null)
- {
- p.append("/Decode [ ");
- vectorSize = this.decode.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.decode.elementAt(tempInt)) +" ");
- }
-
- p.append("] \n");
- }
-
- //LENGTH
- if(this.functionDataStream != null)
- {
- p.append("/Length "+(this.functionDataStream.length()+1)
- + " \n");
- }
-
- //FILTER?
- if (this.filter != null)
- {//if there's a filter
- vectorSize= this.filter.size();
- p.append("/Filter ");
- if (vectorSize == 1)
- {
- p.append("/"+((String)this.filter.elementAt(0))+" \n");
- }
- else
- {
- p.append("[ ");
- for(tempInt=0; tempInt > \n");
-
- //stream representing the function
- if(this.functionDataStream != null)
- {
- p.append("stream\n"+this.functionDataStream +"\nendstream\n");
- }
-
- p.append("endobj\n");
-
- }//end of if FunctionType 0
- else if(this.functionType == 2)
- {
- //DOMAIN
- if(this.domain != null)
- {
- p.append("/Domain [ ");
- vectorSize = this.domain.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.domain.elementAt(tempInt)) +" ");
- }
-
- p.append("] \n");
- }
- else
- {
- p.append("/Domain [ 0 1 ] \n");
- }
-
-
- //RANGE
- if(this.range != null)
- {
- p.append("/Range [ ");
- vectorSize = this.range.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.range.elementAt(tempInt)) +" ");
- }
-
- p.append("] \n");
- }
-
- //FunctionType, C0, C1, N are required in PDF
-
- //C0
- if(this.cZero != null)
- {
- p.append("/C0 [ ");
- vectorSize = this.cZero.size();
- for(tempInt = 0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.cZero.elementAt(tempInt))+" ");
- }
- p.append("] \n");
- }
-
- //C1
- if(this.cOne != null)
- {
- p.append("/C1 [ ");
- vectorSize = this.cOne.size();
- for(tempInt = 0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.cOne.elementAt(tempInt))+" ");
- }
- p.append("] \n");
- }
-
- //N: The interpolation Exponent
- p.append("/N "
- +PDFNumber.doubleOut(
- new Double(this.interpolationExponentN))
- +" \n");
-
- p.append(">> \nendobj\n");
-
- }
- else if(this.functionType == 3)
- {//fix this up when my eyes uncross
- //DOMAIN
- if(this.domain != null)
- {
- p.append("/Domain [ ");
- vectorSize = this.domain.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.domain.elementAt(tempInt)) +" ");
- }
- p.append("] \n");
- }
- else
- {
- p.append("/Domain [ 0 1 ] \n");
- }
-
- //RANGE
- if(this.range != null)
- {
- p.append("/Range [ ");
- vectorSize = this.range.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.range.elementAt(tempInt)) +" ");
- }
-
- p.append("] \n");
- }
-
- //FUNCTIONS
- if(this.functions != null)
- {
- p.append("/Functions [ ");
- numberOfFunctions = this.functions.size();
- for(tempInt =0;tempInt < numberOfFunctions; tempInt++)
- {
- p.append( ((PDFFunction)this.functions.elementAt(tempInt)).referencePDF()+" ");
-
- }
- p.append("] \n");
- }
-
-
- //ENCODE
- if(this.encode != null)
- {
- p.append("/Encode [ ");
- vectorSize = this.encode.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.encode.elementAt(tempInt)) +" ");
- }
-
- p.append("] \n");
- }
- else
- {
- p.append("/Encode [ ");
- vectorSize = this.functions.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append("0 1 ");
- }
- p.append("] \n");
-
- }
-
-
- //BOUNDS, required, but can be empty
- p.append("/Bounds [ ");
- if(this.bounds != null)
- {
-
- vectorSize= this.bounds.size();
- for(tempInt = 0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.bounds.elementAt(tempInt))+" ");
- }
-
- }
- else
- {
- if(this.functions != null)
- {
- //if there are n functions,
- // there must be n-1 bounds.
- // so let each function handle an equal portion
- // of the whole. e.g. if there are 4, then [ 0.25 0.25 0.25 ]
-
- String functionsFraction =
- PDFNumber.doubleOut(new Double(
- 1.0 / ((double)numberOfFunctions)));
-
- for(tempInt =0;tempInt+1 < numberOfFunctions; tempInt++)
- {
-
- p.append( functionsFraction + " ");
- }
- functionsFraction = null; //clean reference.
-
- }
-
- }
- p.append("] \n");
-
-
- p.append(">> \nendobj\n");
- }
- else if(this.functionType == 4)
- {//fix this up when my eyes uncross
- //DOMAIN
- if(this.domain != null)
- {
- p.append("/Domain [ ");
- vectorSize = this.domain.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.domain.elementAt(tempInt)) +" ");
- }
-
- p.append("] \n");
- }
- else
- {
- p.append("/Domain [ 0 1 ] \n");
- }
-
- //RANGE
- if(this.range != null)
- {
- p.append("/Range [ ");
- vectorSize = this.range.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.range.elementAt(tempInt)) +" ");
- }
-
- p.append("] \n");
- }
-
- //LENGTH
- if(this.functionDataStream != null)
- {
- p.append("/Length "+(this.functionDataStream.length()+1)
- + " \n");
- }
-
- p.append(">> \n");
-
- //stream representing the function
- if(this.functionDataStream != null)
- {
- p.append("stream\n{ "+this.functionDataStream +" } \nendstream\n");
- }
-
- p.append("endobj\n");
-
- }
-
- return (p.toString().getBytes());
-
- }
+ // Guts common to all function types
+
+ /**
+ * Required: The Type of function (0,2,3,4) default is 0.
+ */
+ protected int functionType = 0; // Default
+
+ /**
+ * Required: 2 * m Array of Double numbers which are possible inputs to the function
+ */
+ protected Vector domain = null;
+
+ /**
+ * Required: 2 * n Array of Double numbers which are possible outputs to the function
+ */
+ protected Vector range = null;
+
+ /* ********************TYPE 0***************************** */
+ // FunctionType 0 specific function guts
+
+ /**
+ * Required: Array containing the Integer size of the Domain and Range, respectively.
+ * Note: This is really more like two seperate integers, sizeDomain, and sizeRange,
+ * but since they're expressed as an array in PDF, my implementation reflects that.
+ */
+ protected Vector size = null;
+
+ /**
+ * Required for Type 0: Number of Bits used to represent each sample value. Limited to 1,2,4,8,12,16,24, or 32
+ */
+ protected int bitsPerSample = 1;
+
+ /**
+ * Optional for Type 0: order of interpolation between samples. Limited to linear (1) or cubic (3). Default is 1
+ */
+ protected int order = 1;
+
+ /**
+ * Optional for Type 0: A 2 * m array of Doubles which provides a linear mapping of input values to the domain.
+ *
+ * Required for Type 3: A 2 * k array of Doubles that, taken in pairs, map each subset of the domain defined by Domain and the Bounds array to the domain of the corresponding function.
+ * Should be two values per function, usually (0,1), as in [0 1 0 1] for 2 functions.
+ */
+ protected Vector encode = null;
+
+ /**
+ * Optinoal for Type 0: A 2 * n array of Doubles which provides a linear mapping of sample values to the range. Defaults to Range.
+ */
+ protected Vector decode = null;
+
+ /**
+ * Optional For Type 0: A stream of sample values
+ */
+
+ /**
+ * Required For Type 4: Postscript Calculator function composed of arithmetic, boolean, and stack operators + boolean constants
+ */
+ protected StringBuffer functionDataStream = null;
+
+ /**
+ * Required (?) For Type 0: A vector of Strings for the various filters to be used to decode the stream.
+ * These are how the string is compressed. Flate, LZW, etc.
+ */
+ protected Vector filter = null;
+ /* *************************TYPE 2************************** */
+
+ /**
+ * Required For Type 2: An Array of n Doubles defining the function result when x=0. Default is [0].
+ */
+ protected Vector cZero = null;
+
+ /**
+ * Required For Type 2: An Array of n Doubles defining the function result when x=1. Default is [1].
+ */
+ protected Vector cOne = null;
+
+ /**
+ * Required for Type 2: The interpolation exponent.
+ * Each value x will return n results.
+ * Must be greater than 0.
+ */
+ protected double interpolationExponentN = 1;
+
+ /* *************************TYPE 3************************** */
+
+ /**
+ * Required for Type 3: An vector of PDFFunctions which form an array of k single input functions making up the stitching function.
+ */
+ protected Vector functions = null;
+
+ /**
+ * Optional for Type 3: An array of (k-1) Doubles that, in combination with Domain, define the intervals to which each function from the Functions array apply. Bounds elements must be in order of increasing magnitude, and each value must be within the value of Domain.
+ * k is the number of functions.
+ * If you pass null, it will output (1/k) in an array of k-1 elements.
+ * This makes each function responsible for an equal amount of the stitching function.
+ * It makes the gradient even.
+ */
+ protected Vector bounds = null;
+ // See encode above, as it's also part of Type 3 Functions.
+
+ /* *************************TYPE 4************************** */
+ // See 'data' above.
+
+ /**
+ * create an complete Function object of Type 0, A Sampled function.
+ *
+ * Use null for an optional object parameter if you choose not to use it.
+ * For optional int parameters, pass the default.
+ *
+ * @param theDomain Vector objects of Double objects.
+ * This is the domain of the function.
+ * See page 264 of the PDF 1.3 Spec.
+ * @param theRange Vector objects of Double objects.
+ * This is the Range of the function.
+ * See page 264 of the PDF 1.3 Spec.
+ * @param theSize A Vector object of Integer objects.
+ * This is the number of samples in each input dimension.
+ * I can't imagine there being more or less than two input dimensions,
+ * so maybe this should be an array of length 2.
+ *
+ * See page 265 of the PDF 1.3 Spec.
+ * @param theBitsPerSample An int specifying the number of bits user to represent each sample value.
+ * Limited to 1,2,4,8,12,16,24 or 32.
+ * See page 265 of the 1.3 PDF Spec.
+ * @param theOrder The order of interpolation between samples. Default is 1 (one). Limited
+ * to 1 (one) or 3, which means linear or cubic-spline interpolation.
+ *
+ * This attribute is optional.
+ *
+ * See page 265 in the PDF 1.3 spec.
+ * @param theEncode Vector objects of Double objects.
+ * This is the linear mapping of input values intop the domain
+ * of the function's sample table. Default is hard to represent in
+ * ascii, but basically [0 (Size0 1) 0 (Size1 1)...].
+ * This attribute is optional.
+ *
+ * See page 265 in the PDF 1.3 spec.
+ * @param theDecode Vector objects of Double objects.
+ * This is a linear mapping of sample values into the range.
+ * The default is just the range.
+ *
+ * This attribute is optional.
+ * Read about it on page 265 of the PDF 1.3 spec.
+ * @param theFunctionDataStream The sample values that specify the function are provided in a stream.
+ *
+ * This is optional, but is almost always used.
+ *
+ * Page 265 of the PDF 1.3 spec has more.
+ * @param theFilter This is a vector of String objects which are the various filters that
+ * have are to be applied to the stream to make sense of it. Order matters,
+ * so watch out.
+ *
+ * This is not documented in the Function section of the PDF 1.3 spec,
+ * it was deduced from samples that this is sometimes used, even if we may never
+ * use it in FOP. It is added for completeness sake.
+ * @param theNumber The object number of this PDF object.
+ * @param theFunctionType This is the type of function (0,2,3, or 4).
+ * It should be 0 as this is the constructor for sampled functions.
+ */
+ public PDFFunction(int theNumber, int theFunctionType, Vector theDomain,
+ Vector theRange, Vector theSize, int theBitsPerSample,
+ int theOrder, Vector theEncode, Vector theDecode,
+ StringBuffer theFunctionDataStream, Vector theFilter) {
+ super(theNumber);
+
+ this.functionType = 0; // dang well better be 0;
+ this.size = theSize;
+ this.bitsPerSample = theBitsPerSample;
+ this.order = theOrder; // int
+ this.encode = theEncode; // vector of int
+ this.decode = theDecode; // vector of int
+ this.functionDataStream = theFunctionDataStream;
+ this.filter = theFilter; // vector of Strings
+
+ // the domain and range are actually two dimensional arrays.
+ // so if there's not an even number of items, bad stuff
+ // happens.
+ this.domain = theDomain;
+ this.range = theRange;
+ }
+
+ /**
+ * create an complete Function object of Type 2, an Exponential Interpolation function.
+ *
+ * Use null for an optional object parameter if you choose not to use it.
+ * For optional int parameters, pass the default.
+ *
+ * @param theNumber the object's number
+ * @param theDomain Vector objects of Double objects.
+ * This is the domain of the function.
+ * See page 264 of the PDF 1.3 Spec.
+ * @param theRange Vector of Doubles that is the Range of the function.
+ * See page 264 of the PDF 1.3 Spec.
+ * @param theCZero This is a vector of Double objects which defines the function result
+ * when x=0.
+ *
+ * This attribute is optional.
+ * It's described on page 268 of the PDF 1.3 spec.
+ * @param theCOne This is a vector of Double objects which defines the function result
+ * when x=1.
+ *
+ * This attribute is optional.
+ * It's described on page 268 of the PDF 1.3 spec.
+ * @param theInterpolationExponentN This is the inerpolation exponent.
+ *
+ * This attribute is required.
+ * PDF Spec page 268
+ * @param theFunctionType The type of the function, which should be 2.
+ */
+ public PDFFunction(int theNumber, int theFunctionType, Vector theDomain,
+ Vector theRange, Vector theCZero, Vector theCOne,
+ double theInterpolationExponentN) {
+ super(theNumber);
+
+ this.functionType = 2; // dang well better be 2;
+
+ this.cZero = theCZero;
+ this.cOne = theCOne;
+ this.interpolationExponentN = theInterpolationExponentN;
+
+
+ this.domain = theDomain;
+ this.range = theRange;
+
+ }
+
+ /**
+ * create an complete Function object of Type 3, a Stitching function.
+ *
+ * Use null for an optional object parameter if you choose not to use it.
+ * For optional int parameters, pass the default.
+ *
+ * @param theNumber the object's number
+ * @param theDomain Vector objects of Double objects.
+ * This is the domain of the function.
+ * See page 264 of the PDF 1.3 Spec.
+ * @param theRange Vector objects of Double objects.
+ * This is the Range of the function.
+ * See page 264 of the PDF 1.3 Spec.
+ * @param theFunctions A Vector of the PDFFunction objects that the stitching function stitches.
+ *
+ * This attributed is required.
+ * It is described on page 269 of the PDF spec.
+ * @param theBounds This is a vector of Doubles representing the numbers that,
+ * in conjunction with Domain define the intervals to which each function from
+ * the 'functions' object applies. It must be in order of increasing magnitude,
+ * and each must be within Domain.
+ *
+ * It basically sets how much of the gradient each function handles.
+ *
+ * This attributed is required.
+ * It's described on page 269 of the PDF 1.3 spec.
+ * @param theEncode Vector objects of Double objects.
+ * This is the linear mapping of input values intop the domain
+ * of the function's sample table. Default is hard to represent in
+ * ascii, but basically [0 (Size0 1) 0 (Size1 1)...].
+ * This attribute is required.
+ *
+ * See page 270 in the PDF 1.3 spec.
+ * @param theFunctionType This is the function type. It should be 3,
+ * for a stitching function.
+ */
+ public PDFFunction(int theNumber, int theFunctionType, Vector theDomain,
+ Vector theRange, Vector theFunctions,
+ Vector theBounds, Vector theEncode) {
+ super(theNumber);
+
+ this.functionType = 3; // dang well better be 3;
+
+ this.functions = theFunctions;
+ this.bounds = theBounds;
+ this.encode = theEncode;
+ this.domain = theDomain;
+ this.range = theRange;
+
+ }
+
+ /**
+ * create an complete Function object of Type 4, a postscript calculator function.
+ *
+ * Use null for an optional object parameter if you choose not to use it.
+ * For optional int parameters, pass the default.
+ *
+ * @param theDomain Vector object of Double objects.
+ * This is the domain of the function.
+ * See page 264 of the PDF 1.3 Spec.
+ * @param theRange Vector object of Double objects.
+ * This is the Range of the function.
+ * See page 264 of the PDF 1.3 Spec.
+ * @param theFunctionDataStream This is a stream of arithmetic, boolean, and stack operators and boolean constants.
+ * I end up enclosing it in the '{' and '}' braces for you, so don't do it
+ * yourself.
+ *
+ * This attribute is required.
+ * It's described on page 269 of the PDF 1.3 spec.
+ * @param theNumber The object number of this PDF object.
+ * @param theFunctionType The type of function which should be 4, as this is
+ * a Postscript calculator function
+ */
+ public PDFFunction(int theNumber, int theFunctionType, Vector theDomain,
+ Vector theRange, StringBuffer theFunctionDataStream) {
+ super(theNumber);
+
+ this.functionType = 4; // dang well better be 4;
+ this.functionDataStream = theFunctionDataStream;
+
+ this.domain = theDomain;
+
+ this.range = theRange;
+
+ }
+
+
+ /**
+ * represent as PDF. Whatever the FunctionType is, the correct
+ * representation spits out. The sets of required and optional
+ * attributes are different for each type, but if a required
+ * attribute's object was constructed as null, then no error
+ * is raised. Instead, the malformed PDF that was requested
+ * by the construction is dutifully output.
+ * This policy should be reviewed.
+ *
+ * @return the PDF string.
+ */
+ public byte[] toPDF() {
+ int vectorSize = 0;
+ int numberOfFunctions = 0;
+ int tempInt = 0;
+ StringBuffer p = new StringBuffer();
+ p.append(this.number + " " + this.generation
+ + " obj\n<< \n/FunctionType " + this.functionType + " \n");
+
+ // FunctionType 0
+ if (this.functionType == 0) {
+ if (this.domain != null) {
+ // DOMAIN
+ p.append("/Domain [ ");
+ vectorSize = this.domain.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.domain.elementAt(tempInt))
+ + " ");
+ }
+
+ p.append("] \n");
+ } else {
+ p.append("/Domain [ 0 1 ] \n");
+ }
+
+ // SIZE
+ if (this.size != null) {
+ p.append("/Size [ ");
+ vectorSize = this.size.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.size.elementAt(tempInt))
+ + " ");
+ }
+ p.append("] \n");
+ }
+ // ENCODE
+ if (this.encode != null) {
+ p.append("/Encode [ ");
+ vectorSize = this.encode.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.encode.elementAt(tempInt))
+ + " ");
+ }
+ p.append("] \n");
+ } else {
+ p.append("/Encode [ ");
+ vectorSize = this.functions.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append("0 1 ");
+ }
+ p.append("] \n");
+
+ }
+
+ // BITSPERSAMPLE
+ p.append("/BitsPerSample " + this.bitsPerSample);
+
+ // ORDER (optional)
+ if (this.order == 1 || this.order == 3) {
+ p.append(" \n/Order " + this.order + " \n");
+ }
+
+ // RANGE
+ if (this.range != null) {
+ p.append("/Range [ ");
+ vectorSize = this.range.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.range.elementAt(tempInt))
+ + " ");
+ }
+
+ p.append("] \n");
+ }
+
+ // DECODE
+ if (this.decode != null) {
+ p.append("/Decode [ ");
+ vectorSize = this.decode.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.decode.elementAt(tempInt))
+ + " ");
+ }
+
+ p.append("] \n");
+ }
+
+ // LENGTH
+ if (this.functionDataStream != null) {
+ p.append("/Length " + (this.functionDataStream.length() + 1)
+ + " \n");
+ }
+
+ // FILTER?
+ if (this.filter != null) { // if there's a filter
+ vectorSize = this.filter.size();
+ p.append("/Filter ");
+ if (vectorSize == 1) {
+ p.append("/" + ((String)this.filter.elementAt(0))
+ + " \n");
+ } else {
+ p.append("[ ");
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append("/" + ((String)this.filter.elementAt(0))
+ + " ");
+ }
+ p.append("] \n");
+ }
+ }
+ p.append(">> \n");
+
+ // stream representing the function
+ if (this.functionDataStream != null) {
+ p.append("stream\n" + this.functionDataStream
+ + "\nendstream\n");
+ }
+
+ p.append("endobj\n");
+
+ } // end of if FunctionType 0
+ else if (this.functionType == 2) {
+ // DOMAIN
+ if (this.domain != null) {
+ p.append("/Domain [ ");
+ vectorSize = this.domain.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.domain.elementAt(tempInt))
+ + " ");
+ }
+
+ p.append("] \n");
+ } else {
+ p.append("/Domain [ 0 1 ] \n");
+ }
+
+
+ // RANGE
+ if (this.range != null) {
+ p.append("/Range [ ");
+ vectorSize = this.range.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.range.elementAt(tempInt))
+ + " ");
+ }
+
+ p.append("] \n");
+ }
+
+ // FunctionType, C0, C1, N are required in PDF
+
+ // C0
+ if (this.cZero != null) {
+ p.append("/C0 [ ");
+ vectorSize = this.cZero.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.cZero.elementAt(tempInt))
+ + " ");
+ }
+ p.append("] \n");
+ }
+
+ // C1
+ if (this.cOne != null) {
+ p.append("/C1 [ ");
+ vectorSize = this.cOne.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.cOne.elementAt(tempInt))
+ + " ");
+ }
+ p.append("] \n");
+ }
+
+ // N: The interpolation Exponent
+ p.append("/N "
+ + PDFNumber.doubleOut(new Double(this.interpolationExponentN))
+ + " \n");
+
+ p.append(">> \nendobj\n");
+
+ } else if (this.functionType
+ == 3) { // fix this up when my eyes uncross
+ // DOMAIN
+ if (this.domain != null) {
+ p.append("/Domain [ ");
+ vectorSize = this.domain.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.domain.elementAt(tempInt))
+ + " ");
+ }
+ p.append("] \n");
+ } else {
+ p.append("/Domain [ 0 1 ] \n");
+ }
+
+ // RANGE
+ if (this.range != null) {
+ p.append("/Range [ ");
+ vectorSize = this.range.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.range.elementAt(tempInt))
+ + " ");
+ }
+
+ p.append("] \n");
+ }
+
+ // FUNCTIONS
+ if (this.functions != null) {
+ p.append("/Functions [ ");
+ numberOfFunctions = this.functions.size();
+ for (tempInt = 0; tempInt < numberOfFunctions; tempInt++) {
+ p.append(((PDFFunction)this.functions.elementAt(tempInt)).referencePDF()
+ + " ");
+
+ }
+ p.append("] \n");
+ }
+
+
+ // ENCODE
+ if (this.encode != null) {
+ p.append("/Encode [ ");
+ vectorSize = this.encode.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.encode.elementAt(tempInt))
+ + " ");
+ }
+
+ p.append("] \n");
+ } else {
+ p.append("/Encode [ ");
+ vectorSize = this.functions.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append("0 1 ");
+ }
+ p.append("] \n");
+
+ }
+
+
+ // BOUNDS, required, but can be empty
+ p.append("/Bounds [ ");
+ if (this.bounds != null) {
+
+ vectorSize = this.bounds.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.bounds.elementAt(tempInt))
+ + " ");
+ }
+
+ } else {
+ if (this.functions != null) {
+ // if there are n functions,
+ // there must be n-1 bounds.
+ // so let each function handle an equal portion
+ // of the whole. e.g. if there are 4, then [ 0.25 0.25 0.25 ]
+
+ String functionsFraction = PDFNumber.doubleOut(new Double(1.0
+ / ((double)numberOfFunctions)));
+
+ for (tempInt = 0; tempInt + 1 < numberOfFunctions;
+ tempInt++) {
+
+ p.append(functionsFraction + " ");
+ }
+ functionsFraction = null; // clean reference.
+
+ }
+
+ }
+ p.append("] \n");
+
+
+ p.append(">> \nendobj\n");
+ } else if (this.functionType
+ == 4) { // fix this up when my eyes uncross
+ // DOMAIN
+ if (this.domain != null) {
+ p.append("/Domain [ ");
+ vectorSize = this.domain.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.domain.elementAt(tempInt))
+ + " ");
+ }
+
+ p.append("] \n");
+ } else {
+ p.append("/Domain [ 0 1 ] \n");
+ }
+
+ // RANGE
+ if (this.range != null) {
+ p.append("/Range [ ");
+ vectorSize = this.range.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.range.elementAt(tempInt))
+ + " ");
+ }
+
+ p.append("] \n");
+ }
+
+ // LENGTH
+ if (this.functionDataStream != null) {
+ p.append("/Length " + (this.functionDataStream.length() + 1)
+ + " \n");
+ }
+
+ p.append(">> \n");
+
+ // stream representing the function
+ if (this.functionDataStream != null) {
+ p.append("stream\n{ " + this.functionDataStream
+ + " } \nendstream\n");
+ }
+
+ p.append("endobj\n");
+
+ }
+
+ return (p.toString().getBytes());
+
+ }
+
}
diff --git a/src/org/apache/fop/pdf/PDFGoTo.java b/src/org/apache/fop/pdf/PDFGoTo.java
index e88658fd5..bd32c58d5 100644
--- a/src/org/apache/fop/pdf/PDFGoTo.java
+++ b/src/org/apache/fop/pdf/PDFGoTo.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.pdf;
@@ -57,11 +13,11 @@ package org.apache.fop.pdf;
*/
public class PDFGoTo extends PDFAction {
- /** the pageReference */
+ /**
+ * the pageReference
+ */
protected String pageReference;
- protected float
- xPosition=0,
- yPosition=0;
+ protected float xPosition = 0, yPosition = 0;
/**
* create a /GoTo object.
@@ -71,21 +27,20 @@ public class PDFGoTo extends PDFAction {
*/
public PDFGoTo(int number, String pageReference) {
- /* generic creation of object */
- super(number);
-
- this.pageReference = pageReference;
+ /* generic creation of object */
+ super(number);
+
+ this.pageReference = pageReference;
}
/**
* Sets page reference after object has been created
- *
+ *
* @param pageReference
- * the new page reference to use
+ * the new page reference to use
*/
- public void setPageReference(String pageReference)
- {
+ public void setPageReference(String pageReference) {
this.pageReference = pageReference;
}
@@ -93,31 +48,28 @@ public class PDFGoTo extends PDFAction {
/**
* Sets the Y position to jump to
- *
+ *
* @param yPosition y position
*/
- public void setYPosition(int yPosition)
- {
- this.yPosition = (yPosition/1000f);
+ public void setYPosition(int yPosition) {
+ this.yPosition = (yPosition / 1000f);
}
-
+
/**
* Sets the x Position to jump to
- *
+ *
* @param xPosition x position
*/
- public void setXPosition(int xPosition)
- {
- this.xPosition = (xPosition/1000f);
+ public void setXPosition(int xPosition) {
+ this.xPosition = (xPosition / 1000f);
}
- public String getAction()
- {
- return referencePDF();
+ public String getAction() {
+ return referencePDF();
}
-
+
/**
* represent the object in PDF
@@ -125,19 +77,21 @@ public class PDFGoTo extends PDFAction {
* @return the PDF string
*/
public byte[] toPDF() {
- String p = new String(this.number + " " + this.generation +
- " obj\n<<\n/S /GoTo\n" +
- "/D [" + this.pageReference + " /XYZ "+xPosition+" "+yPosition+" null]\n" +
- ">>\nendobj\n");
- return p.getBytes();
+ String p = new String(this.number + " " + this.generation
+ + " obj\n<<\n/S /GoTo\n" + "/D ["
+ + this.pageReference + " /XYZ " + xPosition
+ + " " + yPosition + " null]\n"
+ + ">>\nendobj\n");
+ return p.getBytes();
}
- /* example
- 29 0 obj
- <<
- /S /GoTo
- /D [23 0 R /FitH 600]
- >>
- endobj
- */
+ /*
+ * example
+ * 29 0 obj
+ * <<
+ * /S /GoTo
+ * /D [23 0 R /FitH 600]
+ * >>
+ * endobj
+ */
}
diff --git a/src/org/apache/fop/pdf/PDFGoToRemote.java b/src/org/apache/fop/pdf/PDFGoToRemote.java
index 9164186f2..aa8ef5afa 100644
--- a/src/org/apache/fop/pdf/PDFGoToRemote.java
+++ b/src/org/apache/fop/pdf/PDFGoToRemote.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.pdf;
@@ -56,7 +12,9 @@ package org.apache.fop.pdf;
*/
public class PDFGoToRemote extends PDFAction {
- /** the file specification */
+ /**
+ * the file specification
+ */
protected PDFFileSpec pdfFileSpec;
/**
@@ -67,10 +25,10 @@ public class PDFGoToRemote extends PDFAction {
*/
public PDFGoToRemote(int number, PDFFileSpec pdfFileSpec) {
- /* generic creation of object */
- super(number);
-
- this.pdfFileSpec = pdfFileSpec;
+ /* generic creation of object */
+ super(number);
+
+ this.pdfFileSpec = pdfFileSpec;
}
/**
@@ -78,8 +36,7 @@ public class PDFGoToRemote extends PDFAction {
*
* @return the action String
*/
- public String getAction()
- {
+ public String getAction() {
return this.referencePDF();
}
@@ -89,23 +46,23 @@ public class PDFGoToRemote extends PDFAction {
* @return the PDF string
*/
public byte[] toPDF() {
- String p = new String(this.number + " " + this.generation +
- " obj\n" +
- "<<\n/S /GoToR\n" +
- "/F " + pdfFileSpec.referencePDF() + "\n" +
- "/D [ 0 /XYZ null null null ]" +
- " \n>>\nendobj\n");
- return p.getBytes();
+ String p = new String(this.number + " " + this.generation + " obj\n"
+ + "<<\n/S /GoToR\n" + "/F "
+ + pdfFileSpec.referencePDF() + "\n"
+ + "/D [ 0 /XYZ null null null ]"
+ + " \n>>\nendobj\n");
+ return p.getBytes();
}
-
- /* example
- 28 0 obj
- <<
- /S /GoToR
- /F 29 0 R
- /D [ 0 /XYZ -6 797 null ]
- >>
- endobj
- */
+
+ /*
+ * example
+ * 28 0 obj
+ * <<
+ * /S /GoToR
+ * /F 29 0 R
+ * /D [ 0 /XYZ -6 797 null ]
+ * >>
+ * endobj
+ */
}
diff --git a/src/org/apache/fop/pdf/PDFInfo.java b/src/org/apache/fop/pdf/PDFInfo.java
index ad9aba808..a8215fcea 100644
--- a/src/org/apache/fop/pdf/PDFInfo.java
+++ b/src/org/apache/fop/pdf/PDFInfo.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
// Java
@@ -59,7 +16,9 @@ import java.io.PrintWriter;
*/
public class PDFInfo extends PDFObject {
- /** the application producing the PDF */
+ /**
+ * the application producing the PDF
+ */
protected String producer;
/**
@@ -68,7 +27,7 @@ public class PDFInfo extends PDFObject {
* @param number the object's number
*/
public PDFInfo(int number) {
- super(number);
+ super(number);
}
/**
@@ -77,7 +36,7 @@ public class PDFInfo extends PDFObject {
* @param producer the producer string
*/
public void setProducer(String producer) {
- this.producer = producer;
+ this.producer = producer;
}
/**
@@ -86,9 +45,10 @@ public class PDFInfo extends PDFObject {
* @return the PDF
*/
public byte[] toPDF() {
- String p = this.number + " " + this.generation
- + " obj\n<< /Type /Info\n/Producer (" + this.producer
- + ") >>\nendobj\n";
- return p.getBytes();
+ String p = this.number + " " + this.generation
+ + " obj\n<< /Type /Info\n/Producer (" + this.producer
+ + ") >>\nendobj\n";
+ return p.getBytes();
}
+
}
diff --git a/src/org/apache/fop/pdf/PDFInternalLink.java b/src/org/apache/fop/pdf/PDFInternalLink.java
index d715b91c3..f365b0544 100644
--- a/src/org/apache/fop/pdf/PDFInternalLink.java
+++ b/src/org/apache/fop/pdf/PDFInternalLink.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.pdf;
@@ -56,36 +12,35 @@ package org.apache.fop.pdf;
*/
public class PDFInternalLink extends PDFAction {
-
+
String goToReference;
/**
* create an internal link instance.
*
- * @param goToReference the GoTo Reference to which the link should point
+ * @param goToReference the GoTo Reference to which the link should point
*/
public PDFInternalLink(String goToReference) {
- this.goToReference=goToReference;
+ this.goToReference = goToReference;
}
/**
* returns the action ncecessary for an internal link
- *
+ *
* @return the action to place next to /A within a Link
*/
- public String getAction()
- {
+ public String getAction() {
return goToReference;
}
/**
- * there is nothing to return for the toPDF method, as it should not be called
+ * there is nothing to return for the toPDF method, as it should not be called
*
* @return an empty string
*/
- public byte[] toPDF() {
- return new byte[0];
- }
-
+ public byte[] toPDF() {
+ return new byte[0];
+ }
+
}
diff --git a/src/org/apache/fop/pdf/PDFLink.java b/src/org/apache/fop/pdf/PDFLink.java
index b8caaae86..6af94f1d8 100644
--- a/src/org/apache/fop/pdf/PDFLink.java
+++ b/src/org/apache/fop/pdf/PDFLink.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.pdf;
@@ -65,7 +21,7 @@ public class PDFLink extends PDFObject {
float bry;
String color;
PDFAction action;
-
+
/**
* create objects associated with a link annotation (GoToR)
*
@@ -73,50 +29,48 @@ public class PDFLink extends PDFObject {
* @param producer the application producing the PDF
*/
public PDFLink(int number, Rectangle r) {
- /* generic creation of PDF object */
- super(number);
-
- this.ulx = r.x;
- this.uly = r.y;
- this.brx = r.x + r.width;
- this.bry = r.y - r.height;
- this.color = "0 0 0"; // just for now
-
+ /* generic creation of PDF object */
+ super(number);
+
+ this.ulx = r.x;
+ this.uly = r.y;
+ this.brx = r.x + r.width;
+ this.bry = r.y - r.height;
+ this.color = "0 0 0"; // just for now
+
}
public void setAction(PDFAction action) {
- this.action = action;
+ this.action = action;
}
-
+
/**
* produce the PDF representation of the object
*
* @return the PDF
*/
public byte[] toPDF() {
- String p = this.number + " " + this.generation + " obj\n" +
- "<< /Type /Annot\n" +
- "/Subtype /Link\n" +
- "/Rect [ " + (ulx/1000f) + " " + (uly/1000f) + " " +
- (brx/1000f) + " " + (bry/1000f) + " ]\n"
- + "/C [ " + this.color + " ]\n" +
- "/Border [ 0 0 0 ]\n" +
- "/A " + this.action.getAction() + "\n" +
- "/H /I\n>>\nendobj\n";
- return p.getBytes();
+ String p = this.number + " " + this.generation + " obj\n"
+ + "<< /Type /Annot\n" + "/Subtype /Link\n" + "/Rect [ "
+ + (ulx / 1000f) + " " + (uly / 1000f) + " "
+ + (brx / 1000f) + " " + (bry / 1000f) + " ]\n" + "/C [ "
+ + this.color + " ]\n" + "/Border [ 0 0 0 ]\n" + "/A "
+ + this.action.getAction() + "\n" + "/H /I\n>>\nendobj\n";
+ return p.getBytes();
}
- /* example
- 19 0 obj
- <<
- /Type /Annot
- /Subtype /Link
- /Rect [ 176.032 678.48412 228.73579 692.356 ]
- /C [ 0.86491 0.03421 0.02591 ]
- /Border [ 0 0 1 ]
- /A 28 0 R
- /H /I
- >>
- endobj
- */
+ /*
+ * example
+ * 19 0 obj
+ * <<
+ * /Type /Annot
+ * /Subtype /Link
+ * /Rect [ 176.032 678.48412 228.73579 692.356 ]
+ * /C [ 0.86491 0.03421 0.02591 ]
+ * /Border [ 0 0 1 ]
+ * /A 28 0 R
+ * /H /I
+ * >>
+ * endobj
+ */
}
diff --git a/src/org/apache/fop/pdf/PDFNumber.java b/src/org/apache/fop/pdf/PDFNumber.java
index c13e00ad4..deed898ac 100644
--- a/src/org/apache/fop/pdf/PDFNumber.java
+++ b/src/org/apache/fop/pdf/PDFNumber.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -7,127 +8,99 @@
package org.apache.fop.pdf;
public class PDFNumber {
-
- private PDFNumber()
- {
- }
-
- public static String doubleOut(Double doubleDown)
- {
- StringBuffer p = new StringBuffer();
- if(doubleDown.doubleValue() < 0) {
- doubleDown = new Double(-doubleDown.doubleValue());
- p.append("-");
- }
- double trouble = doubleDown.doubleValue() % 1;
- if(trouble > 0.950)
- {
- p.append(doubleDown.intValue()+1);
- }
- else if (trouble < 0.050)
- {
- p.append(doubleDown.intValue());
- }
- else
- {
- String doubleString = new String(doubleDown+"");
- int decimal = doubleString.indexOf(".");
- if(decimal != -1) {
- p.append(doubleString.substring(0, decimal));
- if ((doubleString.length() - decimal) > 6)
- {
- p.append(doubleString.substring(decimal,decimal+6));
- }
- else
- {
- p.append(doubleString.substring(decimal));
- }
- } else {
- p.append(doubleString);
- }
- }
- return(p.toString());
- }
-
- public static String doubleOut(double doubleDown)
- {
-
- StringBuffer p = new StringBuffer();
- if(doubleDown < 0) {
- doubleDown = -doubleDown;
- p.append("-");
- }
- double trouble = doubleDown % 1;
-
- if(trouble > 0.950)
- {
- p.append((int)doubleDown+1);
- }
- else if (trouble < 0.050)
- {
- p.append((int)doubleDown);
- }
- else
- {
- String doubleString = new String(doubleDown+"");
- int decimal = doubleString.indexOf(".");
- if(decimal != -1) {
- p.append(doubleString.substring(0, decimal));
+ private PDFNumber() {}
- if ((doubleString.length() - decimal) > 6)
- {
- p.append(doubleString.substring(decimal,decimal+6));
- }
- else
- {
- p.append(doubleString.substring(decimal));
- }
- } else {
- p.append(doubleString);
- }
- }
- return(p.toString());
- }
+ public static String doubleOut(Double doubleDown) {
+ StringBuffer p = new StringBuffer();
+ if (doubleDown.doubleValue() < 0) {
+ doubleDown = new Double(-doubleDown.doubleValue());
+ p.append("-");
+ }
+ double trouble = doubleDown.doubleValue() % 1;
+ if (trouble > 0.950) {
+ p.append(doubleDown.intValue() + 1);
+ } else if (trouble < 0.050) {
+ p.append(doubleDown.intValue());
+ } else {
+ String doubleString = new String(doubleDown + "");
+ int decimal = doubleString.indexOf(".");
+ if (decimal != -1) {
+ p.append(doubleString.substring(0, decimal));
- public static String doubleOut(double doubleDown, int dec)
- {
-
- StringBuffer p = new StringBuffer();
- if(doubleDown < 0) {
- doubleDown = -doubleDown;
- p.append("-");
- }
- double trouble = doubleDown % 1;
-
- if(trouble > (1.0 - (5.0 / (Math.pow(10.0, dec)))))
- {
- p.append((int)doubleDown+1);
- }
- else if (trouble < (5.0 / (Math.pow(10.0, dec))))
- {
- p.append((int)doubleDown);
- }
- else
- {
- String doubleString = new String(doubleDown+"");
- int decimal = doubleString.indexOf(".");
- if(decimal != -1) {
- p.append(doubleString.substring(0, decimal));
+ if ((doubleString.length() - decimal) > 6) {
+ p.append(doubleString.substring(decimal, decimal + 6));
+ } else {
+ p.append(doubleString.substring(decimal));
+ }
+ } else {
+ p.append(doubleString);
+ }
+ }
+ return (p.toString());
+ }
+
+ public static String doubleOut(double doubleDown) {
+
+ StringBuffer p = new StringBuffer();
+ if (doubleDown < 0) {
+ doubleDown = -doubleDown;
+ p.append("-");
+ }
+ double trouble = doubleDown % 1;
+
+ if (trouble > 0.950) {
+ p.append((int)doubleDown + 1);
+ } else if (trouble < 0.050) {
+ p.append((int)doubleDown);
+ } else {
+ String doubleString = new String(doubleDown + "");
+ int decimal = doubleString.indexOf(".");
+ if (decimal != -1) {
+ p.append(doubleString.substring(0, decimal));
+
+ if ((doubleString.length() - decimal) > 6) {
+ p.append(doubleString.substring(decimal, decimal + 6));
+ } else {
+ p.append(doubleString.substring(decimal));
+ }
+ } else {
+ p.append(doubleString);
+ }
+ }
+ return (p.toString());
+ }
+
+ public static String doubleOut(double doubleDown, int dec) {
+
+ StringBuffer p = new StringBuffer();
+ if (doubleDown < 0) {
+ doubleDown = -doubleDown;
+ p.append("-");
+ }
+ double trouble = doubleDown % 1;
+
+ if (trouble > (1.0 - (5.0 / (Math.pow(10.0, dec))))) {
+ p.append((int)doubleDown + 1);
+ } else if (trouble < (5.0 / (Math.pow(10.0, dec)))) {
+ p.append((int)doubleDown);
+ } else {
+ String doubleString = new String(doubleDown + "");
+ int decimal = doubleString.indexOf(".");
+ if (decimal != -1) {
+ p.append(doubleString.substring(0, decimal));
+
+ if ((doubleString.length() - decimal) > dec) {
+ p.append(doubleString.substring(decimal, decimal + dec));
+ } else {
+ p.append(doubleString.substring(decimal));
+ }
+ } else {
+ p.append(doubleString);
+ }
+ }
+ return (p.toString());
+ }
- if ((doubleString.length() - decimal) > dec)
- {
- p.append(doubleString.substring(decimal,decimal+dec));
- }
- else
- {
- p.append(doubleString.substring(decimal));
- }
- } else {
- p.append(doubleString);
- }
- }
- return(p.toString());
- }
}
-
+
diff --git a/src/org/apache/fop/pdf/PDFObject.java b/src/org/apache/fop/pdf/PDFObject.java
index 573923a6f..a20f358f0 100644
--- a/src/org/apache/fop/pdf/PDFObject.java
+++ b/src/org/apache/fop/pdf/PDFObject.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
// Java
@@ -56,17 +13,21 @@ import java.io.OutputStream;
/**
* generic PDF object.
- *
+ *
* A PDF Document is essentially a collection of these objects. A PDF
* Object has a number and a generation (although the generation will always
* be 0 in new documents).
*/
public abstract class PDFObject {
- /** the object's number */
+ /**
+ * the object's number
+ */
protected int number;
- /** the object's generation (0 in new documents) */
+ /**
+ * the object's generation (0 in new documents)
+ */
protected int generation = 0;
/**
@@ -75,17 +36,20 @@ public abstract class PDFObject {
* @param number the object's number
*/
public PDFObject(int number) {
- this.number = number;
+ this.number = number;
}
- public PDFObject() {
- //do nothing
- }
- /**
- * @return the PDF Object number
- */
- public int getNumber() {
- return this.number;
- }
+
+ public PDFObject() {
+ // do nothing
+ }
+
+ /**
+ * @return the PDF Object number
+ */
+ public int getNumber() {
+ return this.number;
+ }
+
/**
* write the PDF represention of this object
*
@@ -93,9 +57,9 @@ public abstract class PDFObject {
* @return the number of bytes written
*/
protected int output(OutputStream stream) throws IOException {
- byte[] pdf = this.toPDF();
- stream.write(pdf);
- return pdf.length;
+ byte[] pdf = this.toPDF();
+ stream.write(pdf);
+ return pdf.length;
}
/**
@@ -104,8 +68,8 @@ public abstract class PDFObject {
* @return the reference string
*/
public String referencePDF() {
- String p = this.number + " " + this.generation + " R";
- return p;
+ String p = this.number + " " + this.generation + " R";
+ return p;
}
/**
diff --git a/src/org/apache/fop/pdf/PDFOutline.java b/src/org/apache/fop/pdf/PDFOutline.java
index 0f4e8a1e6..ee5f3bc59 100644
--- a/src/org/apache/fop/pdf/PDFOutline.java
+++ b/src/org/apache/fop/pdf/PDFOutline.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.pdf;
@@ -63,156 +19,160 @@ import java.util.Vector;
*
*/
-public class PDFOutline extends PDFObject
-{
-
- /** list of sub-entries (outline objects) */
+public class PDFOutline extends PDFObject {
+
+ /**
+ * list of sub-entries (outline objects)
+ */
private Vector _subentries;
-
- /** parent outline object. Root Outlines parent is null */
+
+ /**
+ * parent outline object. Root Outlines parent is null
+ */
private PDFOutline _parent;
-
+
private PDFOutline _prev;
private PDFOutline _next;
-
+
private PDFOutline _first;
private PDFOutline _last;
-
+
private int _count;
-
- /** title to display for the bookmark entry */
+
+ /**
+ * title to display for the bookmark entry
+ */
private String _title;
-
+
String _actionRef;
-
-
-
+
+
+
/**
* @param number the object id number
* @param title the title of the outline entry (can only be null for root Outlines obj)
* @param page the page which this outline refers to.
*/
- public PDFOutline(int number, String title, String action)
- {
- super(number);
- _subentries = new Vector();
- _count = 0;
- _parent = null;
- _prev = null;
- _next = null;
- _first = null;
- _last = null;
- _title = title;
- _actionRef = action;
-
-
+ public PDFOutline(int number, String title, String action) {
+ super(number);
+ _subentries = new Vector();
+ _count = 0;
+ _parent = null;
+ _prev = null;
+ _next = null;
+ _first = null;
+ _last = null;
+ _title = title;
+ _actionRef = action;
+
+
}
-
- public void setTitle(String title)
- {
- _title = title;
+
+ public void setTitle(String title) {
+ _title = title;
}
/**
* Add a sub element to this outline
*/
- public void addOutline(PDFOutline outline)
- {
- if (_subentries.size() > 0) {
- outline._prev = (PDFOutline)_subentries.elementAt(_subentries.size() - 1);
- outline._prev._next = outline;
- }
- else {
- _first = outline;
- }
-
- _subentries.addElement(outline);
- outline._parent = this;
-
- incrementCount(); // note: count is not just the immediate children
-
- _last = outline;
+ public void addOutline(PDFOutline outline) {
+ if (_subentries.size() > 0) {
+ outline._prev =
+ (PDFOutline)_subentries.elementAt(_subentries.size() - 1);
+ outline._prev._next = outline;
+ } else {
+ _first = outline;
+ }
+
+ _subentries.addElement(outline);
+ outline._parent = this;
+
+ incrementCount(); // note: count is not just the immediate children
+
+ _last = outline;
}
-
- private void incrementCount()
- {
- // count is a total of our immediate subentries and all descendent subentries
- _count++;
- if (_parent != null) {
- _parent.incrementCount();
- }
+
+ private void incrementCount() {
+ // count is a total of our immediate subentries and all descendent subentries
+ _count++;
+ if (_parent != null) {
+ _parent.incrementCount();
+ }
}
-
-
- /** represent the object in PDF */
- protected byte[] toPDF()
- {
- StringBuffer result = new StringBuffer(this.number+" "+this.generation+" obj\n<<\n");
- if (_parent == null) {
- // root Outlines object
- if (_first != null && _last != null) {
- result.append(" /First "+_first.referencePDF()+"\n");
- result.append(" /Last "+_last.referencePDF()+"\n");
- // no count... we start with the outline completely closed for now
- }
- }
- else {
- // subentry Outline object
- result.append(" /Title ("+escapeString(_title)+")\n");
- result.append(" /Parent "+_parent.referencePDF()+"\n");
- if (_first != null && _last != null) {
- result.append(" /First "+_first.referencePDF()+"\n");
- result.append(" /Last "+_last.referencePDF()+"\n");
- }
- if (_prev != null) {
- result.append(" /Prev "+_prev.referencePDF()+"\n");
- }
- if (_next != null) {
- result.append(" /Next "+_next.referencePDF()+"\n");
- }
- if (_count > 0) {
- result.append(" /Count -"+_count+"\n");
- }
-
- if (_actionRef != null) {
- result.append(" /A "+_actionRef+"\n");
- }
-
-
- }
- result.append(">> endobj\n");
- return result.toString().getBytes();
-
+
+
+ /**
+ * represent the object in PDF
+ */
+ protected byte[] toPDF() {
+ StringBuffer result = new StringBuffer(this.number + " "
+ + this.generation
+ + " obj\n<<\n");
+ if (_parent == null) {
+ // root Outlines object
+ if (_first != null && _last != null) {
+ result.append(" /First " + _first.referencePDF() + "\n");
+ result.append(" /Last " + _last.referencePDF() + "\n");
+ // no count... we start with the outline completely closed for now
+ }
+ } else {
+ // subentry Outline object
+ result.append(" /Title (" + escapeString(_title) + ")\n");
+ result.append(" /Parent " + _parent.referencePDF() + "\n");
+ if (_first != null && _last != null) {
+ result.append(" /First " + _first.referencePDF() + "\n");
+ result.append(" /Last " + _last.referencePDF() + "\n");
+ }
+ if (_prev != null) {
+ result.append(" /Prev " + _prev.referencePDF() + "\n");
+ }
+ if (_next != null) {
+ result.append(" /Next " + _next.referencePDF() + "\n");
+ }
+ if (_count > 0) {
+ result.append(" /Count -" + _count + "\n");
+ }
+
+ if (_actionRef != null) {
+ result.append(" /A " + _actionRef + "\n");
+ }
+
+
+ }
+ result.append(">> endobj\n");
+ return result.toString().getBytes();
+
}
-
- /** escape parens, and other special chars for PDF */
- private String escapeString(String s)
- {
- StringBuffer result = new StringBuffer();
- if (s != null) {
- int l = s.length();
-
- for (int i = 0; i < l; i++) {
- char ch = s.charAt(i);
- if (ch > 127) {
- result.append("\\");
- result.append(Integer.toOctalString((int) ch));
- } else {
- switch (ch) {
- case '(' :
- case ')' :
- case '\\' :
- result.append('\\');
- break;
- }
- result.append(ch);
- }
- }
- }
-
- return result.toString();
+
+ /**
+ * escape parens, and other special chars for PDF
+ */
+ private String escapeString(String s) {
+ StringBuffer result = new StringBuffer();
+ if (s != null) {
+ int l = s.length();
+
+ for (int i = 0; i < l; i++) {
+ char ch = s.charAt(i);
+ if (ch > 127) {
+ result.append("\\");
+ result.append(Integer.toOctalString((int)ch));
+ } else {
+ switch (ch) {
+ case '(':
+ case ')':
+ case '\\':
+ result.append('\\');
+ break;
+ }
+ result.append(ch);
+ }
+ }
+ }
+
+ return result.toString();
}
-
+
}
diff --git a/src/org/apache/fop/pdf/PDFPage.java b/src/org/apache/fop/pdf/PDFPage.java
index e6838c1fd..4f9ae9d24 100644
--- a/src/org/apache/fop/pdf/PDFPage.java
+++ b/src/org/apache/fop/pdf/PDFPage.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
/**
@@ -60,22 +17,34 @@ package org.apache.fop.pdf;
*/
public class PDFPage extends PDFObject {
- /** the page's parent, a /Pages object */
+ /**
+ * the page's parent, a /Pages object
+ */
protected PDFPages parent;
- /** the page's /Resource object */
+ /**
+ * the page's /Resource object
+ */
protected PDFResources resources;
- /** the contents stream */
+ /**
+ * the contents stream
+ */
protected PDFStream contents;
- /** the width of the page in points */
+ /**
+ * the width of the page in points
+ */
protected int pagewidth;
- /** the height of the page in points */
+ /**
+ * the height of the page in points
+ */
protected int pageheight;
- /** the list of annotation objects for this page */
+ /**
+ * the list of annotation objects for this page
+ */
protected PDFAnnotList annotList;
/**
@@ -87,20 +56,19 @@ public class PDFPage extends PDFObject {
* @param pagewidth the page's width in points
* @param pageheight the page's height in points
*/
- public PDFPage(int number, PDFResources resources,
- PDFStream contents, int pagewidth,
- int pageheight) {
+ public PDFPage(int number, PDFResources resources, PDFStream contents,
+ int pagewidth, int pageheight) {
- /* generic creation of object */
- super(number);
+ /* generic creation of object */
+ super(number);
- /* set fields using parameters */
- this.resources = resources;
- this.contents = contents;
- this.pagewidth = pagewidth;
- this.pageheight = pageheight;
+ /* set fields using parameters */
+ this.resources = resources;
+ this.contents = contents;
+ this.pagewidth = pagewidth;
+ this.pageheight = pageheight;
- this.annotList = null;
+ this.annotList = null;
}
/**
@@ -109,16 +77,16 @@ public class PDFPage extends PDFObject {
* @param parent the /Pages object that is this page's parent
*/
public void setParent(PDFPages parent) {
- this.parent = parent;
+ this.parent = parent;
}
-
+
/**
* set this page's annotation list
*
* @param annotList a PDFAnnotList list of annotations
*/
public void setAnnotList(PDFAnnotList annotList) {
- this.annotList = annotList;
+ this.annotList = annotList;
}
/**
@@ -127,34 +95,35 @@ public class PDFPage extends PDFObject {
* @return annotList a PDFAnnotList list of annotations
*/
public PDFAnnotList getAnnotList() {
- return this.annotList;
+ return this.annotList;
+ }
+
+ public void addShading(PDFShading shading) {
+ this.resources.addShading(shading);
}
- public void addShading(PDFShading shading) {
- this.resources.addShading(shading);
- }
/**
* represent this object as PDF
*
* @return the PDF string
*/
public byte[] toPDF() {
- StringBuffer sb = new StringBuffer();
-
- sb = sb.append(this.number + " " + this.generation + " obj\n" +
- "<< /Type /Page\n" +
- "/Parent " + this.parent.referencePDF() + "\n" +
- "/MediaBox [ 0 0 " + this.pagewidth + " " +
- this.pageheight + " ]\n" +
- "/Resources " + this.resources.referencePDF() + "\n" +
- "/Contents " + this.contents.referencePDF() + "\n");
- if (this.annotList != null) {
- sb = sb.append("/Annots " +
- this.annotList.referencePDF() + "\n");
- }
-
- sb = sb.append(">>\nendobj\n");
-
- return sb.toString().getBytes();
+ StringBuffer sb = new StringBuffer();
+
+ sb = sb.append(this.number + " " + this.generation + " obj\n"
+ + "<< /Type /Page\n" + "/Parent "
+ + this.parent.referencePDF() + "\n"
+ + "/MediaBox [ 0 0 " + this.pagewidth + " "
+ + this.pageheight + " ]\n" + "/Resources "
+ + this.resources.referencePDF() + "\n" + "/Contents "
+ + this.contents.referencePDF() + "\n");
+ if (this.annotList != null) {
+ sb = sb.append("/Annots " + this.annotList.referencePDF() + "\n");
+ }
+
+ sb = sb.append(">>\nendobj\n");
+
+ return sb.toString().getBytes();
}
+
}
diff --git a/src/org/apache/fop/pdf/PDFPages.java b/src/org/apache/fop/pdf/PDFPages.java
index 3c099dacb..cef40f1d3 100644
--- a/src/org/apache/fop/pdf/PDFPages.java
+++ b/src/org/apache/fop/pdf/PDFPages.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
// Java
@@ -64,14 +21,18 @@ import java.util.Vector;
*/
public class PDFPages extends PDFObject {
- /** the /Page objects */
+ /**
+ * the /Page objects
+ */
protected Vector kids = new Vector();
- /** the number of /Page objects */
+ /**
+ * the number of /Page objects
+ */
protected int count = 0;
- // private PDFPages parent;
-
+ // private PDFPages parent;
+
/**
* create a /Pages object.
*
@@ -79,8 +40,8 @@ public class PDFPages extends PDFObject {
*/
public PDFPages(int number) {
- /* generic creation of object */
- super(number);
+ /* generic creation of object */
+ super(number);
}
/**
@@ -89,8 +50,8 @@ public class PDFPages extends PDFObject {
* @param page the PDFPage to add.
*/
public void addPage(PDFPage page) {
- this.kids.addElement(page);
- page.setParent(this);
+ this.kids.addElement(page);
+ page.setParent(this);
this.incrementCount();
}
@@ -100,14 +61,14 @@ public class PDFPages extends PDFObject {
* @return the number of pages
*/
public int getCount() {
- return this.count;
+ return this.count;
}
/**
* increment the count of /Page objects
*/
public void incrementCount() {
- this.count++;
+ this.count++;
// MessageHandler.logln("Incrementing count to " + this.getCount());
}
@@ -117,14 +78,14 @@ public class PDFPages extends PDFObject {
* @return the PDF string
*/
public byte[] toPDF() {
- StringBuffer p = new StringBuffer(this.number + " "
- + this.generation
- + " obj\n<< /Type /Pages\n/Count "
- + this.getCount() + "\n/Kids [");
- for (int i = 0; i < kids.size(); i++) {
- p = p.append(((PDFObject)kids.elementAt(i)).referencePDF() + " ");
- }
- p = p.append("] >>\nendobj\n");
- return p.toString().getBytes();
+ StringBuffer p = new StringBuffer(this.number + " " + this.generation
+ + " obj\n<< /Type /Pages\n/Count "
+ + this.getCount() + "\n/Kids [");
+ for (int i = 0; i < kids.size(); i++) {
+ p = p.append(((PDFObject)kids.elementAt(i)).referencePDF() + " ");
+ }
+ p = p.append("] >>\nendobj\n");
+ return p.toString().getBytes();
}
+
}
diff --git a/src/org/apache/fop/pdf/PDFPathPaint.java b/src/org/apache/fop/pdf/PDFPathPaint.java
index fd9c3eed8..2c2292823 100644
--- a/src/org/apache/fop/pdf/PDFPathPaint.java
+++ b/src/org/apache/fop/pdf/PDFPathPaint.java
@@ -1,86 +1,39 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
import org.apache.fop.datatypes.ColorSpace;
-public abstract class PDFPathPaint extends PDFObject
-{
+public abstract class PDFPathPaint extends PDFObject {
+
+ // protected int colorspace = 0; //default is 0:RGB, not 1:CMYK
+ protected ColorSpace colorSpace;
+
+ public PDFPathPaint(int theNumber) {
+ super(theNumber);
+
+ }
+
+ public PDFPathPaint() {
+ // do nothing
+ }
+
+ public String getColorSpaceOut(boolean fillNotStroke) {
+ return ("");
+ }
+
+ public void setColorSpace(int theColorSpace) {
+ this.colorSpace.setColorSpace(theColorSpace);
+ }
+
+ public int getColorSpace() {
+ return (this.colorSpace.getColorSpace());
+ }
- //protected int colorspace = 0; //default is 0:RGB, not 1:CMYK
- protected ColorSpace colorSpace;
-
- public PDFPathPaint(int theNumber) {
- super(theNumber);
-
- }
-
- public PDFPathPaint(){
- //do nothing
- }
-
- public String getColorSpaceOut(boolean fillNotStroke)
- {
- return("");
- }
-
- public void setColorSpace(int theColorSpace)
- {
- this.colorSpace.setColorSpace(theColorSpace);
- }
-
- public int getColorSpace()
- {
- return(this.colorSpace.getColorSpace());
- }
-
}
diff --git a/src/org/apache/fop/pdf/PDFPattern.java b/src/org/apache/fop/pdf/PDFPattern.java
index 8e76e5fcc..3fa15d59b 100644
--- a/src/org/apache/fop/pdf/PDFPattern.java
+++ b/src/org/apache/fop/pdf/PDFPattern.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -6,10 +7,10 @@
package org.apache.fop.pdf;
-//Java...
+// Java...
import java.util.Vector;
-//FOP...
+// FOP...
import org.apache.fop.datatypes.ColorSpace;
/**
@@ -23,294 +24,274 @@ import org.apache.fop.datatypes.ColorSpace;
* All PDF Functions have a FunctionType (0,2,3, or 4), a Domain, and a Range.
*/
public class PDFPattern extends PDFPathPaint {
- /**
- * The resources associated with this pattern
- */
- //Guts common to all function types
-
- protected PDFResources resources = null;
-
- /**
- * Either one (1) for tiling, or two (2) for shading.
- */
- protected int patternType = 2; //Default
-
- /**
- * The name of the pattern such as "Pa1" or "Pattern1"
- */
- protected String patternName = null;
-
- /**
- * 1 for colored pattern, 2 for uncolored
- */
- protected int paintType = 2;
-
- /**
- * 1 for constant spacing, 2 for no distortion, and 3 for fast rendering
- */
- protected int tilingType = 1;
-
- /**
- * Vector of Doubles representing the Bounding box rectangle
- */
- protected Vector bBox = null;
-
- /**
- * Horizontal spacing
- */
- protected double xStep = -1;
-
- /**
- * Vertical spacing
- */
- protected double yStep = -1;
-
- /**
- * The Shading object comprising the Type 2 pattern
- */
- protected PDFShading shading=null;
-
- /**
- * Vector of Integers represetning the Extended unique Identifier
- */
- protected Vector xUID=null;
-
- /**
- * String representing the extended Graphics state.
- * Probably will never be used like this.
- */
- protected StringBuffer extGState = null; //eventually, need a PDFExtGSState object... but not now.
-
- /**
- * Vector of Doubles representing the Transformation matrix.
- */
- protected Vector matrix=null;
-
- /**
- * The stream of a pattern
- */
- protected StringBuffer patternDataStream = null;
-
-
- /**
- * Create a tiling pattern (type 1).
- *
- * @param theNumber The object number of this PDF Object
- * @param thePatternName The name of the pattern such as "Pa1" or "Pattern1"
- * @param theResources the resources associated with this pattern
- * @param thePatternType the type of pattern, which is 1 for tiling.
- * @param thePaintType 1 or 2, colored or uncolored.
- * @param theTilingType 1, 2, or 3, constant spacing, no distortion, or faster tiling
- * @param theBBox Vector of Doubles: The pattern cell bounding box
- * @param theXStep horizontal spacing
- * @param theYStep vertical spacing
- * @param theMatrix Optional Vector of Doubles transformation matrix
- * @param theXUID Optional vector of Integers that uniquely identify the pattern
- * @param thePatternDataStream The stream of pattern data to be tiled.
- */
- public PDFPattern(int theNumber, String thePatternName,
- PDFResources theResources, int thePatternType, //1
- int thePaintType, int theTilingType,
- Vector theBBox, double theXStep, double theYStep,
- Vector theMatrix, Vector theXUID, StringBuffer thePatternDataStream)
- {
- super(theNumber);
- this.patternName = thePatternName;
-
- this.resources = theResources;
- //This next parameter is implicit to all constructors, and is
- //not directly passed.
-
- this.patternType = 1; //thePatternType;
- this.paintType = thePaintType;
- this.tilingType = theTilingType;
- this.bBox = theBBox;
- this.xStep = theXStep;
- this.yStep = theYStep;
- this.matrix = theMatrix;
- this.xUID = theXUID;
- this.patternDataStream = thePatternDataStream;
- }
-
- /**
- * Create a type 2 pattern (smooth shading)
- *
- * @param theNumber the object number of this PDF object
- * @param thePatternName the name of the pattern
- * @param thePatternType the type of the pattern, which is 2, smooth shading
- * @param theShading the PDF Shading object that comprises this pattern
- * @param theXUID optional:the extended unique Identifier if used.
- * @param theExtGState optional: the extended graphics state, if used.
- * @param theMatrix Optional:Vector of Doubles that specify the matrix.
- */
- public PDFPattern(int theNumber, String thePatternName,
- int thePatternType, PDFShading theShading, Vector theXUID,
- StringBuffer theExtGState,Vector theMatrix)
- {
- super(theNumber);
-
- this.patternName = thePatternName;
-
- this.patternType = 2; //thePatternType;
- this.shading = theShading;
- this.xUID = theXUID;
- //this isn't really implemented, so it should always be null.
- //I just don't want to have to add a new parameter once it is implemented.
- this.extGState = theExtGState; // always null
- this.matrix = theMatrix;
- }
-
- /**
- * Get the name of the pattern
- *
- * @return String representing the name of the pattern.
- */
- public String getName()
- {
- return (this.patternName);
- }
-
- public String getColorSpaceOut(boolean fillNotStroke)
- {
- if(fillNotStroke)
- { //fill but no stroke
- return("/Pattern cs /"+this.getName()+" scn \n");
- }
- else
- { //stroke (or border)
- return("/Pattern CS /"+this.getName()+" SCN \n");
- }
- }
-
-
- /**
- * represent as PDF. Whatever the FunctionType is, the correct
- * representation spits out. The sets of required and optional
- * attributes are different for each type, but if a required
- * attribute's object was constructed as null, then no error
- * is raised. Instead, the malformed PDF that was requested
- * by the construction is dutifully output.
- * This policy should be reviewed.
- *
- * @return the PDF string.
- */
- public byte[] toPDF() {
-
-
- int vectorSize=0;
- int tempInt=0;
- StringBuffer p = new StringBuffer();
- p.append(this.number + " " +this.generation
- + " obj\n<< \n/Type /Pattern \n");
-
- if(this.resources != null)
- {
- p.append("/Resources "+this.resources.referencePDF()+" \n");
- }
-
- p.append("/PatternType "+this.patternType+" \n");
-
- if(this.patternType == 1)
- {
- p.append("/PaintType "+this.paintType+" \n");
- p.append("/TilingType "+this.tilingType+" \n");
-
- if(this.bBox != null)
- {
- vectorSize = this.bBox.size();
- p.append("/BBox [ ");
- for (tempInt =0; tempInt < vectorSize; tempInt++)
- {
- p.append(
- PDFNumber.doubleOut((Double)this.bBox.elementAt(tempInt)));
- p.append(" ");
- }
- p.append("] \n");
- }
- p.append("/XStep "+PDFNumber.doubleOut(new Double(this.xStep))+" \n");
- p.append("/YStep "+PDFNumber.doubleOut(new Double(this.yStep))+" \n");
-
- if(this.matrix != null)
- {
- vectorSize = this.matrix.size();
- p.append("/Matrix [ ");
- for (tempInt =0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.matrix.elementAt(tempInt)));
- p.append(" ");
- }
- p.append("] \n");
- }
-
- if(this.xUID != null)
- {
- vectorSize = this.xUID.size();
- p.append("/XUID [ ");
- for (tempInt =0; tempInt < vectorSize; tempInt++)
- {
- p.append(((Integer)this.xUID.elementAt(tempInt))+" ");
- }
- p.append("] \n");
- }
- //don't forget the length of the stream.
- if(this.patternDataStream != null)
- {
- p.append("/Length "+(this.patternDataStream.length()+1)
- + " \n");
- }
-
- }
- else //if (this.patternType ==2)
- {//Smooth Shading...
- if(this.shading != null)
- {
- p.append("/Shading "+this.shading.referencePDF()+" \n");
- }
-
- if(this.xUID != null)
- {
- vectorSize = this.xUID.size();
- p.append("/XUID [ ");
- for (tempInt =0; tempInt < vectorSize; tempInt++)
- {
- p.append(((Integer)this.xUID.elementAt(tempInt))+" ");
- }
- p.append("] \n");
- }
-
- if(this.extGState != null)
- {//will probably have to change this if it's used.
- p.append("/ExtGState "+this.extGState+" \n");
- }
-
- if(this.matrix != null)
- {
- vectorSize = this.matrix.size();
- p.append("/Matrix [ ");
- for (tempInt =0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.matrix.elementAt(tempInt)));
- p.append(" ");
- }
- p.append("] \n");
- }
- }//end of if patterntype =1...else 2.
-
- p.append(">> \n");
-
- //stream representing the function
- if(this.patternDataStream != null)
- {
- p.append("stream\n"+this.patternDataStream +"\nendstream\n");
- }
-
- p.append("endobj\n");
-
-
-
- return (p.toString().getBytes());
-
- }
+
+ /**
+ * The resources associated with this pattern
+ */
+ // Guts common to all function types
+
+ protected PDFResources resources = null;
+
+ /**
+ * Either one (1) for tiling, or two (2) for shading.
+ */
+ protected int patternType = 2; // Default
+
+ /**
+ * The name of the pattern such as "Pa1" or "Pattern1"
+ */
+ protected String patternName = null;
+
+ /**
+ * 1 for colored pattern, 2 for uncolored
+ */
+ protected int paintType = 2;
+
+ /**
+ * 1 for constant spacing, 2 for no distortion, and 3 for fast rendering
+ */
+ protected int tilingType = 1;
+
+ /**
+ * Vector of Doubles representing the Bounding box rectangle
+ */
+ protected Vector bBox = null;
+
+ /**
+ * Horizontal spacing
+ */
+ protected double xStep = -1;
+
+ /**
+ * Vertical spacing
+ */
+ protected double yStep = -1;
+
+ /**
+ * The Shading object comprising the Type 2 pattern
+ */
+ protected PDFShading shading = null;
+
+ /**
+ * Vector of Integers represetning the Extended unique Identifier
+ */
+ protected Vector xUID = null;
+
+ /**
+ * String representing the extended Graphics state.
+ * Probably will never be used like this.
+ */
+ protected StringBuffer extGState =
+ null; // eventually, need a PDFExtGSState object... but not now.
+
+ /**
+ * Vector of Doubles representing the Transformation matrix.
+ */
+ protected Vector matrix = null;
+
+ /**
+ * The stream of a pattern
+ */
+ protected StringBuffer patternDataStream = null;
+
+
+ /**
+ * Create a tiling pattern (type 1).
+ *
+ * @param theNumber The object number of this PDF Object
+ * @param thePatternName The name of the pattern such as "Pa1" or "Pattern1"
+ * @param theResources the resources associated with this pattern
+ * @param thePatternType the type of pattern, which is 1 for tiling.
+ * @param thePaintType 1 or 2, colored or uncolored.
+ * @param theTilingType 1, 2, or 3, constant spacing, no distortion, or faster tiling
+ * @param theBBox Vector of Doubles: The pattern cell bounding box
+ * @param theXStep horizontal spacing
+ * @param theYStep vertical spacing
+ * @param theMatrix Optional Vector of Doubles transformation matrix
+ * @param theXUID Optional vector of Integers that uniquely identify the pattern
+ * @param thePatternDataStream The stream of pattern data to be tiled.
+ */
+ public PDFPattern(int theNumber, String thePatternName,
+ PDFResources theResources, int thePatternType, // 1
+ int thePaintType, int theTilingType, Vector theBBox, double theXStep,
+ double theYStep, Vector theMatrix, Vector theXUID,
+ StringBuffer thePatternDataStream) {
+ super(theNumber);
+ this.patternName = thePatternName;
+
+ this.resources = theResources;
+ // This next parameter is implicit to all constructors, and is
+ // not directly passed.
+
+ this.patternType = 1; // thePatternType;
+ this.paintType = thePaintType;
+ this.tilingType = theTilingType;
+ this.bBox = theBBox;
+ this.xStep = theXStep;
+ this.yStep = theYStep;
+ this.matrix = theMatrix;
+ this.xUID = theXUID;
+ this.patternDataStream = thePatternDataStream;
+ }
+
+ /**
+ * Create a type 2 pattern (smooth shading)
+ *
+ * @param theNumber the object number of this PDF object
+ * @param thePatternName the name of the pattern
+ * @param thePatternType the type of the pattern, which is 2, smooth shading
+ * @param theShading the PDF Shading object that comprises this pattern
+ * @param theXUID optional:the extended unique Identifier if used.
+ * @param theExtGState optional: the extended graphics state, if used.
+ * @param theMatrix Optional:Vector of Doubles that specify the matrix.
+ */
+ public PDFPattern(int theNumber, String thePatternName,
+ int thePatternType, PDFShading theShading,
+ Vector theXUID, StringBuffer theExtGState,
+ Vector theMatrix) {
+ super(theNumber);
+
+ this.patternName = thePatternName;
+
+ this.patternType = 2; // thePatternType;
+ this.shading = theShading;
+ this.xUID = theXUID;
+ // this isn't really implemented, so it should always be null.
+ // I just don't want to have to add a new parameter once it is implemented.
+ this.extGState = theExtGState; // always null
+ this.matrix = theMatrix;
+ }
+
+ /**
+ * Get the name of the pattern
+ *
+ * @return String representing the name of the pattern.
+ */
+ public String getName() {
+ return (this.patternName);
+ }
+
+ public String getColorSpaceOut(boolean fillNotStroke) {
+ if (fillNotStroke) { // fill but no stroke
+ return ("/Pattern cs /" + this.getName() + " scn \n");
+ } else { // stroke (or border)
+ return ("/Pattern CS /" + this.getName() + " SCN \n");
+ }
+ }
+
+
+ /**
+ * represent as PDF. Whatever the FunctionType is, the correct
+ * representation spits out. The sets of required and optional
+ * attributes are different for each type, but if a required
+ * attribute's object was constructed as null, then no error
+ * is raised. Instead, the malformed PDF that was requested
+ * by the construction is dutifully output.
+ * This policy should be reviewed.
+ *
+ * @return the PDF string.
+ */
+ public byte[] toPDF() {
+
+
+ int vectorSize = 0;
+ int tempInt = 0;
+ StringBuffer p = new StringBuffer();
+ p.append(this.number + " " + this.generation
+ + " obj\n<< \n/Type /Pattern \n");
+
+ if (this.resources != null) {
+ p.append("/Resources " + this.resources.referencePDF() + " \n");
+ }
+
+ p.append("/PatternType " + this.patternType + " \n");
+
+ if (this.patternType == 1) {
+ p.append("/PaintType " + this.paintType + " \n");
+ p.append("/TilingType " + this.tilingType + " \n");
+
+ if (this.bBox != null) {
+ vectorSize = this.bBox.size();
+ p.append("/BBox [ ");
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.bBox.elementAt(tempInt)));
+ p.append(" ");
+ }
+ p.append("] \n");
+ }
+ p.append("/XStep " + PDFNumber.doubleOut(new Double(this.xStep))
+ + " \n");
+ p.append("/YStep " + PDFNumber.doubleOut(new Double(this.yStep))
+ + " \n");
+
+ if (this.matrix != null) {
+ vectorSize = this.matrix.size();
+ p.append("/Matrix [ ");
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.matrix.elementAt(tempInt)));
+ p.append(" ");
+ }
+ p.append("] \n");
+ }
+
+ if (this.xUID != null) {
+ vectorSize = this.xUID.size();
+ p.append("/XUID [ ");
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(((Integer)this.xUID.elementAt(tempInt)) + " ");
+ }
+ p.append("] \n");
+ }
+ // don't forget the length of the stream.
+ if (this.patternDataStream != null) {
+ p.append("/Length " + (this.patternDataStream.length() + 1)
+ + " \n");
+ }
+
+ } else // if (this.patternType ==2)
+ { // Smooth Shading...
+ if (this.shading != null) {
+ p.append("/Shading " + this.shading.referencePDF() + " \n");
+ }
+
+ if (this.xUID != null) {
+ vectorSize = this.xUID.size();
+ p.append("/XUID [ ");
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(((Integer)this.xUID.elementAt(tempInt)) + " ");
+ }
+ p.append("] \n");
+ }
+
+ if (this.extGState
+ != null) { // will probably have to change this if it's used.
+ p.append("/ExtGState " + this.extGState + " \n");
+ }
+
+ if (this.matrix != null) {
+ vectorSize = this.matrix.size();
+ p.append("/Matrix [ ");
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.matrix.elementAt(tempInt)));
+ p.append(" ");
+ }
+ p.append("] \n");
+ }
+ } // end of if patterntype =1...else 2.
+
+ p.append(">> \n");
+
+ // stream representing the function
+ if (this.patternDataStream != null) {
+ p.append("stream\n" + this.patternDataStream + "\nendstream\n");
+ }
+
+ p.append("endobj\n");
+
+
+
+ return (p.toString().getBytes());
+
+ }
+
}
diff --git a/src/org/apache/fop/pdf/PDFRectangle.java b/src/org/apache/fop/pdf/PDFRectangle.java
index 24809d241..2dc04fb74 100644
--- a/src/org/apache/fop/pdf/PDFRectangle.java
+++ b/src/org/apache/fop/pdf/PDFRectangle.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
/**
@@ -56,52 +13,66 @@ package org.apache.fop.pdf;
* Rectangles are specified on page 183 of the PDF 1.3 spec.
*/
public class PDFRectangle {
- /** lower left x coordinate */
- protected int llx;
- /** lower left y coordinate */
- protected int lly;
- /** upper right x coordinate */
- protected int urx;
- /** upper right y coordinate */
- protected int ury;
- /**
- * create a rectangle giving the four separate values
- *
- * @param llx lower left x coordinate
- * @param lly lower left y coordinate
- * @param urx upper right x coordinate
- * @param ury upper right y coordinate
- */
- public PDFRectangle(int llx, int lly, int urx, int ury) {
- this.llx = llx;
- this.lly = lly;
- this.urx = urx;
- this.ury = ury;
- }
+ /**
+ * lower left x coordinate
+ */
+ protected int llx;
+
+ /**
+ * lower left y coordinate
+ */
+ protected int lly;
+
+ /**
+ * upper right x coordinate
+ */
+ protected int urx;
+
+ /**
+ * upper right y coordinate
+ */
+ protected int ury;
+
+ /**
+ * create a rectangle giving the four separate values
+ *
+ * @param llx lower left x coordinate
+ * @param lly lower left y coordinate
+ * @param urx upper right x coordinate
+ * @param ury upper right y coordinate
+ */
+ public PDFRectangle(int llx, int lly, int urx, int ury) {
+ this.llx = llx;
+ this.lly = lly;
+ this.urx = urx;
+ this.ury = ury;
+ }
+
+ /**
+ * create a rectangle giving an array of four values
+ *
+ * @param array values in the order llx, lly, urx, ury
+ */
+ public PDFRectangle(int[] array) {
+ this.llx = array[0];
+ this.lly = array[1];
+ this.urx = array[2];
+ this.ury = array[3];
+ }
+
+ /**
+ * produce the PDF representation for the object
+ *
+ * @return the PDF
+ */
+ public byte[] toPDF() {
+ return toPDFString().getBytes();
+ }
- /**
- * create a rectangle giving an array of four values
- *
- * @param array values in the order llx, lly, urx, ury
- */
- public PDFRectangle(int[] array) {
- this.llx = array[0];
- this.lly = array[1];
- this.urx = array[2];
- this.ury = array[3];
- }
+ public String toPDFString() {
+ return new String(" [" + llx + " " + lly + " " + urx + " " + ury
+ + "] ");
+ }
- /**
- * produce the PDF representation for the object
- *
- * @return the PDF
- */
- public byte[] toPDF() {
- return toPDFString().getBytes();
- }
-
- public String toPDFString() {
- return new String(" [" + llx + " " + lly + " " + urx + " " + ury + "] ");
- }
}
diff --git a/src/org/apache/fop/pdf/PDFResources.java b/src/org/apache/fop/pdf/PDFResources.java
index b4612b704..d51b716e4 100644
--- a/src/org/apache/fop/pdf/PDFResources.java
+++ b/src/org/apache/fop/pdf/PDFResources.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
// Java
@@ -61,15 +18,18 @@ import java.util.Hashtable;
*
* /Resources object contain a list of references to the fonts for the
* document
- */
+ */
public class PDFResources extends PDFObject {
- /** /Font objects keyed by their internal name */
+ /**
+ * /Font objects keyed by their internal name
+ */
protected Hashtable fonts = new Hashtable();
- protected Vector xObjects=null;
- protected Vector patterns= new Vector();
- protected Vector shadings=new Vector();
+ protected Vector xObjects = null;
+ protected Vector patterns = new Vector();
+ protected Vector shadings = new Vector();
+
/**
* create a /Resources object.
*
@@ -77,9 +37,9 @@ public class PDFResources extends PDFObject {
*/
public PDFResources(int number) {
- /* generic creation of object */
- super(number);
-
+ /* generic creation of object */
+ super(number);
+
}
/**
@@ -88,18 +48,19 @@ public class PDFResources extends PDFObject {
* @param font the PDFFont to add
*/
public void addFont(PDFFont font) {
- this.fonts.put(font.getName(),font);
+ this.fonts.put(font.getName(), font);
}
-
- public void addShading(PDFShading theShading){
- this.shadings.addElement(theShading);
- }
-
- public void addPattern(PDFPattern thePattern){
- this.patterns.addElement(thePattern);
- }
+
+ public void addShading(PDFShading theShading) {
+ this.shadings.addElement(theShading);
+ }
+
+ public void addPattern(PDFPattern thePattern) {
+ this.patterns.addElement(thePattern);
+ }
+
public void setXObjects(Vector xObjects) {
- this.xObjects = xObjects;
+ this.xObjects = xObjects;
}
/**
@@ -107,86 +68,77 @@ public class PDFResources extends PDFObject {
*
* @return the PDF
*/
- public byte[] toPDF() {
- StringBuffer p = new StringBuffer(this.number + " "
- + this.generation
- + " obj\n<< \n");
- if(!this.fonts.isEmpty())
- {
- p.append("/Font << ");
-
- /* construct PDF dictionary of font object references */
- Enumeration fontEnumeration = this.fonts.keys();
- while (fontEnumeration.hasMoreElements()) {
- String fontName = (String) fontEnumeration.nextElement();
- p.append("/" + fontName + " "
- + ((PDFFont) this.fonts.get(fontName)).referencePDF()
- + " ");
- }
-
- p.append(">> \n");
- }
-
- PDFShading currentShading = null;
- if(!this.shadings.isEmpty())
- {
- p.append("/Shading << ");
-
- for(int currentShadingNumber=0;
- currentShadingNumber < this.shadings.size();
- currentShadingNumber++)
- {
- currentShading = ((PDFShading)this.shadings.elementAt(currentShadingNumber));
-
- p.append("/" + currentShading.getName() + " "
- + currentShading.referencePDF()
- + " "); // \n ??????
- }
-
- p.append(">> \n");
- }
- //"free" the memory. Sorta.
- currentShading = null;
-
- PDFPattern currentPattern=null;
- if(!this.patterns.isEmpty())
- {
- p.append("/Pattern << ");
-
- for(int currentPatternNumber=0;
- currentPatternNumber < this.patterns.size();
- currentPatternNumber++)
- {
- currentPattern = ((PDFPattern)this.patterns.elementAt(currentPatternNumber));
-
- p.append("/" + currentPattern.getName() + " "
- + currentPattern.referencePDF()
- + " ");
- }
-
- p.append(">> \n");
- }
- //"free" the memory. Sorta.
- currentPattern = null;
-
- p.append("/ProcSet [ /PDF /ImageC /Text ] ");
-
- if (!this.xObjects.isEmpty())
- {
- p = p.append("/XObject <<");
- for (int i = 1; i <= this.xObjects.size(); i++) {
- p = p.append("/Im" + i + " " +
- ((PDFXObject)
- this.xObjects.elementAt(i -
- 1)).referencePDF()
- +
- " \n");
- }
- p = p.append(" >>\n");
- }
-
- p = p.append(">> \nendobj\n");
-
- return p.toString().getBytes();
- }
+ public byte[] toPDF() {
+ StringBuffer p = new StringBuffer(this.number + " " + this.generation
+ + " obj\n<< \n");
+ if (!this.fonts.isEmpty()) {
+ p.append("/Font << ");
+
+ /* construct PDF dictionary of font object references */
+ Enumeration fontEnumeration = this.fonts.keys();
+ while (fontEnumeration.hasMoreElements()) {
+ String fontName = (String)fontEnumeration.nextElement();
+ p.append("/" + fontName + " "
+ + ((PDFFont)this.fonts.get(fontName)).referencePDF()
+ + " ");
+ }
+
+ p.append(">> \n");
+ }
+
+ PDFShading currentShading = null;
+ if (!this.shadings.isEmpty()) {
+ p.append("/Shading << ");
+
+ for (int currentShadingNumber = 0;
+ currentShadingNumber < this.shadings.size();
+ currentShadingNumber++) {
+ currentShading =
+ ((PDFShading)this.shadings.elementAt(currentShadingNumber));
+
+ p.append("/" + currentShading.getName() + " "
+ + currentShading.referencePDF() + " "); // \n ??????
+ }
+
+ p.append(">> \n");
+ }
+ // "free" the memory. Sorta.
+ currentShading = null;
+
+ PDFPattern currentPattern = null;
+ if (!this.patterns.isEmpty()) {
+ p.append("/Pattern << ");
+
+ for (int currentPatternNumber = 0;
+ currentPatternNumber < this.patterns.size();
+ currentPatternNumber++) {
+ currentPattern =
+ ((PDFPattern)this.patterns.elementAt(currentPatternNumber));
+
+ p.append("/" + currentPattern.getName() + " "
+ + currentPattern.referencePDF() + " ");
+ }
+
+ p.append(">> \n");
+ }
+ // "free" the memory. Sorta.
+ currentPattern = null;
+
+ p.append("/ProcSet [ /PDF /ImageC /Text ] ");
+
+ if (!this.xObjects.isEmpty()) {
+ p = p.append("/XObject <<");
+ for (int i = 1; i <= this.xObjects.size(); i++) {
+ p = p.append("/Im" + i + " "
+ + ((PDFXObject)this.xObjects.elementAt(i - 1)).referencePDF()
+ + " \n");
+ }
+ p = p.append(" >>\n");
+ }
+
+ p = p.append(">> \nendobj\n");
+
+ return p.toString().getBytes();
+ }
+
}
diff --git a/src/org/apache/fop/pdf/PDFRoot.java b/src/org/apache/fop/pdf/PDFRoot.java
index f31543eab..1850fbf94 100644
--- a/src/org/apache/fop/pdf/PDFRoot.java
+++ b/src/org/apache/fop/pdf/PDFRoot.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
// Java
@@ -59,10 +16,14 @@ import java.io.PrintWriter;
*/
public class PDFRoot extends PDFObject {
- /** the /Pages object that is root of the Pages hierarchy */
+ /**
+ * the /Pages object that is root of the Pages hierarchy
+ */
protected PDFPages rootPages;
- /** Root outline object */
+ /**
+ * Root outline object
+ */
private PDFOutline _outline;
/**
@@ -71,7 +32,7 @@ public class PDFRoot extends PDFObject {
* @param number the object's number
*/
public PDFRoot(int number) {
- super(number);
+ super(number);
}
/**
@@ -80,7 +41,7 @@ public class PDFRoot extends PDFObject {
* @param page the /Page object to add
*/
public void addPage(PDFPage page) {
- this.rootPages.addPage(page);
+ this.rootPages.addPage(page);
}
/**
@@ -89,12 +50,11 @@ public class PDFRoot extends PDFObject {
* @param pages the /Pages object to set as root
*/
public void setRootPages(PDFPages pages) {
- this.rootPages = pages;
+ this.rootPages = pages;
}
- public void setRootOutline(PDFOutline outline)
- {
- _outline = outline;
+ public void setRootOutline(PDFOutline outline) {
+ _outline = outline;
}
@@ -104,15 +64,17 @@ public class PDFRoot extends PDFObject {
* @return the PDF string
*/
public byte[] toPDF() {
- StringBuffer p = new StringBuffer(this.number + " " + this.generation
- + " obj\n<< /Type /Catalog\n/Pages "
- + this.rootPages.referencePDF() + "\n");
- if (_outline != null) {
- p.append(" /Outlines "+_outline.referencePDF()+"\n");
- p.append(" /PageMode /UseOutlines\n");
-
- }
- p.append(" >>\nendobj\n");
- return p.toString().getBytes();
+ StringBuffer p = new StringBuffer(this.number + " " + this.generation
+ + " obj\n<< /Type /Catalog\n/Pages "
+ + this.rootPages.referencePDF()
+ + "\n");
+ if (_outline != null) {
+ p.append(" /Outlines " + _outline.referencePDF() + "\n");
+ p.append(" /PageMode /UseOutlines\n");
+
+ }
+ p.append(" >>\nendobj\n");
+ return p.toString().getBytes();
}
+
}
diff --git a/src/org/apache/fop/pdf/PDFShading.java b/src/org/apache/fop/pdf/PDFShading.java
index 47ff4cd17..a1a1a9be0 100644
--- a/src/org/apache/fop/pdf/PDFShading.java
+++ b/src/org/apache/fop/pdf/PDFShading.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -6,543 +7,505 @@
package org.apache.fop.pdf;
-//Java...
+// Java...
import java.util.Vector;
-//FOP
+// FOP
import org.apache.fop.datatypes.ColorSpace;
/**
* class representing a PDF Smooth Shading object.
- *
+ *
* PDF Functions represent parameterized mathematical formulas and sampled representations with
* arbitrary resolution. Functions are used in two areas: device-dependent
* rasterization information for halftoning and transfer
* functions, and color specification for smooth shading (a PDF 1.3 feature).
- *
+ *
* All PDF Functions have a shadingType (0,2,3, or 4), a Domain, and a Range.
*/
public class PDFShading extends PDFObject {
- //Guts common to all function types
- /** The name of the Shading e.g. "Shading1" */
- protected String shadingName = null;
-
- /**
- * Required: The Type of shading (1,2,3,4,5,6,7)
- */
- protected int shadingType = 3; //Default
-
- /**
- * A ColorSpace representing the colorspace. "DeviceRGB" is an example.
- */
- //protected StringBuffer colorSpace = null;
- protected ColorSpace colorSpace=null;
- /**
- * The background color. Since shading is opaque,
- * this is very rarely used.
- */
- protected Vector background = null;
- /**
- * Optional: A Vector specifying the clipping rectangle
- */
- protected Vector bBox = null;
-
- /**
- * Optional: A flag whether or not to filter the shading function
- * to prevent aliasing artifacts. Default is false.
- */
- protected boolean antiAlias = false;
-
- /**
- * Optional for Type 1: Array of four numbers, xmin, xmax, ymin, ymax. Default is [0 1 0 1]
- * Optional for Type 2: An array of two numbers between which the blend varies between start and end points. Default is 0, 1.
- * Optional for Type 3: An array of two numbers between which the blend varies between start and end points. Default is 0, 1.
- */
-
- protected Vector domain = null;
-
- /** Optional for Type 1: A transformation matrix */
- protected Vector matrix = null;
-
- /**
- * Required for Type 1, 2, and 3:
- * The object of the color mapping function (usually type 2 or 3).
- * Optional for Type 4,5,6, and 7: When it's nearly the same thing.
- */
- protected PDFFunction function = null;
-
- /** Required for Type 2: An Array of four numbers specifying the starting and ending coordinate pairs
- * Required for Type 3: An Array of six numbers [x0,y0,r0,x1,y1,r1] specifying the centers and radii of
- * the starting and ending circles.
- */
- protected Vector coords = null;
-
- /**
- * Required for Type 2+3: An Array of two boolean values specifying whether to extend the
- * start and end colors past the start and end points,
- * respectively. Default is false, false.
- */
- protected Vector extend = null;
-
- /**
- * Required for Type 4,5,6, and 7: Specifies the number of bits used to represent each vertex coordinate.
- * Allowed to be 1,2,4,8,12,16,24, or 32.
- */
- protected int bitsPerCoordinate = 0;
-
- /**
- * Required for Type 4,5,6, and 7: Specifies the number of bits used to represent the edge flag for each vertex.
- * Allowed to be 2,4,or 8, while the Edge flag itself is allowed to be 0,1 or 2.
- */
- protected int bitsPerFlag = 0;
-
- /**
- * Required for Type 4,5,6, and 7: Array of Doubles which specifies how to decode coordinate and color component values.
- * Each type has a differing number of decode array members, so check the spec.
- * Page 303 in PDF Spec 1.3
- */
- protected Vector decode = null;
-
- /**
- * Required for Type 4,5,6, and 7: Specifies the number of bits used to represent each color coordinate.
- * Allowed to be 1,2,4,8,12, or 16
- */
- protected int bitsPerComponent = 0;
-
- /**
- * Required for Type 5:The number of vertices in each "row" of the lattice; it must be greater than or equal to 2.
- */
- protected int verticesPerRow = 0;
-
- /**
- * Constructor for type function based shading
- *
- * @param theNumber The object number of this PDF object
- * @param theShadingName The name of the shading pattern. Can be anything
- * without spaces. "Shading1" or "Sh1" are good examples.
- * @param theShadingType The type of shading object, which should be 1 for function
- * based shading.
- * @param theColorSpace The colorspace is 'DeviceRGB' or something similar.
- * @param theBackground An array of color components appropriate to the
- * colorspace key specifying a single color value.
- * This key is used by the f operator buy ignored by the sh operator.
- * @param theBBox Vector of double's representing a rectangle
- * in the coordinate space that is current at the
- * time of shading is imaged. Temporary clipping
- * boundary.
- * @param theAntiAlias Whether or not to anti-alias.
- * @param theDomain Optional vector of Doubles specifying the domain.
- * @param theMatrix Vector of Doubles specifying the matrix.
- * If it's a pattern, then the matrix maps it to pattern space.
- * If it's a shading, then it maps it to current user space.
- * It's optional, the default is the identity matrix
- * @param theFunction The PDF Function that maps an (x,y) location to a color
- */
- public PDFShading(int theNumber, String theShadingName, int theShadingType, ColorSpace theColorSpace,
- Vector theBackground, Vector theBBox, boolean theAntiAlias,
- Vector theDomain, Vector theMatrix, PDFFunction theFunction)
- {
- super(theNumber);
- this.shadingName = theShadingName;
- this.shadingType = theShadingType; //1
- this.colorSpace=theColorSpace;
- this.background= theBackground;
- this.bBox = theBBox;
- this.antiAlias = theAntiAlias;
-
- this.domain = theDomain;
- this.matrix = theMatrix;
- this.function = theFunction;
-
- }
-
- /**
- * Constructor for Type 2 and 3
- *
- * @param theNumber The object number of this PDF object.
- * @param theShadingName The name of the shading pattern. Can be anything
- * without spaces. "Shading1" or "Sh1" are good examples.
- * @param theShadingType 2 or 3 for axial or radial shading
- * @param theColorSpace "DeviceRGB" or similar.
- * @param theBackground theBackground An array of color components appropriate to the
- * colorspace key specifying a single color value.
- * This key is used by the f operator buy ignored by the sh operator.
- * @param theBBox Vector of double's representing a rectangle
- * in the coordinate space that is current at the
- * time of shading is imaged. Temporary clipping
- * boundary.
- * @param theAntiAlias Default is false
- * @param theCoords Vector of four (type 2) or 6 (type 3) Double
- * @param theDomain Vector of Doubles specifying the domain
- * @param theFunction the Stitching (PDFfunction type 3) function, even if it's stitching a single function
- * @param theExtend Vector of Booleans of whether to extend teh start and end colors past the start and end points
- * The default is [false, false]
- */
- public PDFShading(int theNumber, String theShadingName,
- int theShadingType, ColorSpace theColorSpace,
- Vector theBackground, Vector theBBox, boolean theAntiAlias,
- Vector theCoords, Vector theDomain, PDFFunction theFunction,
- Vector theExtend)
- {
- super(theNumber);
- this.shadingName = theShadingName;
- this.shadingType=theShadingType; //2 or 3
- this.colorSpace=theColorSpace;
- this.background= theBackground;
- this.bBox = theBBox;
- this.antiAlias = theAntiAlias;
-
- this.coords = theCoords;
- this.domain = theDomain;
- this.function = theFunction;
- this.extend=theExtend;
-
- }
-
- /**
- * Constructor for Type 4,6, or 7
- *
- * @param theNumber The object number of this PDF object.
- * @param theShadingType 4, 6, or 7 depending on whether it's
- * Free-form gouraud-shaded triangle meshes, coons patch meshes,
- * or tensor product patch meshes, respectively.
- * @param theShadingName The name of the shading pattern. Can be anything
- * without spaces. "Shading1" or "Sh1" are good examples.
- * @param theColorSpace "DeviceRGB" or similar.
- * @param theBackground theBackground An array of color components appropriate to the
- * colorspace key specifying a single color value.
- * This key is used by the f operator buy ignored by the sh operator.
- * @param theBBox Vector of double's representing a rectangle
- * in the coordinate space that is current at the
- * time of shading is imaged. Temporary clipping
- * boundary.
- * @param theAntiAlias Default is false
- * @param theBitsPerCoordinate 1,2,4,8,12,16,24 or 32.
- * @param theBitsPerComponent 1,2,4,8,12, and 16
- * @param theBitsPerFlag 2,4,8.
- * @param theDecode Vector of Doubles see PDF 1.3 spec pages 303 to 312.
- * @param theFunction the PDFFunction
- */
- public PDFShading(int theNumber, String theShadingName, int theShadingType, ColorSpace theColorSpace,
- Vector theBackground, Vector theBBox, boolean theAntiAlias,
- int theBitsPerCoordinate, int theBitsPerComponent,
- int theBitsPerFlag, Vector theDecode, PDFFunction theFunction)
- {
- super(theNumber);
-
- this.shadingType = theShadingType;//4,6 or 7
- this.colorSpace = theColorSpace;
- this.background= theBackground;
- this.bBox = theBBox;
- this.antiAlias = theAntiAlias;
-
- this.bitsPerCoordinate = theBitsPerCoordinate;
- this.bitsPerComponent = theBitsPerComponent;
- this.bitsPerFlag = theBitsPerFlag;
- this.decode = theDecode;
- this.function =theFunction;
- }
-
- /**
- * Constructor for type 5
- *
- * @param theShadingType 5 for lattice-Form Gouraud shaded-triangle mesh
- * @param theShadingName The name of the shading pattern. Can be anything
- * without spaces. "Shading1" or "Sh1" are good examples.
- * @param theColorSpace "DeviceRGB" or similar.
- * @param theBackground theBackground An array of color components appropriate to the
- * colorspace key specifying a single color value.
- * This key is used by the f operator buy ignored by the sh operator.
- * @param theBBox Vector of double's representing a rectangle
- * in the coordinate space that is current at the
- * time of shading is imaged. Temporary clipping
- * boundary.
- * @param theAntiAlias Default is false
- * @param theBitsPerCoordinate 1,2,4,8,12,16, 24, or 32
- * @param theBitsPerComponent 1,2,4,8,12,24,32
- * @param theDecode Vector of Doubles. See page 305 in PDF 1.3 spec.
- * @param theVerticesPerRow number of vertices in each "row" of the lattice.
- * @param theFunction The PDFFunction that's mapped on to this shape
- * @param theNumber the object number of this PDF object.
- */
- public PDFShading(int theNumber, String theShadingName, int theShadingType, ColorSpace theColorSpace,
- Vector theBackground, Vector theBBox, boolean theAntiAlias,
- int theBitsPerCoordinate, int theBitsPerComponent,
- Vector theDecode, int theVerticesPerRow, PDFFunction theFunction)
- {
- super(theNumber);
- this.shadingName = theShadingName;
- this.shadingType = theShadingType;//5
- this.colorSpace=theColorSpace;
- this.background= theBackground;
- this.bBox = theBBox;
- this.antiAlias = theAntiAlias;
-
- this.bitsPerCoordinate = theBitsPerCoordinate;
- this.bitsPerComponent = theBitsPerComponent;
- this.decode = theDecode;
- this.verticesPerRow = theVerticesPerRow;
- this.function = theFunction;
-
- }
-
- public String getName() {
- return (this.shadingName);
- }
-
- /**
- * represent as PDF. Whatever the shadingType is, the correct
- * representation spits out. The sets of required and optional
- * attributes are different for each type, but if a required
- * attribute's object was constructed as null, then no error
- * is raised. Instead, the malformed PDF that was requested
- * by the construction is dutifully output.
- * This policy should be reviewed.
- *
- * @return the PDF string.
- */
- public byte[] toPDF() {
- int vectorSize;
- int tempInt;
- StringBuffer p = new StringBuffer();
- p.append(this.number + " " + this.generation
- + " obj\n<< \n/ShadingType "+this.shadingType+" \n");
- if(this.colorSpace != null)
- {
- p.append("/ColorSpace /"
- +this.colorSpace.getColorSpacePDFString()+" \n");
- }
-
- if(this.background != null)
- {
- p.append("/Background [ ");
- vectorSize = this.background.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.background.elementAt(tempInt)) +" ");
- }
- p.append("] \n");
- }
-
- if(this.bBox != null)
- {//I've never seen an example, so I guess this is right.
- p.append("/BBox [ ");
- vectorSize = this.bBox.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.bBox.elementAt(tempInt)) +" ");
- }
- p.append("] \n");
- }
-
- if(this.antiAlias)
- {
- p.append("/AntiAlias "+this.antiAlias+" \n");
- }
-
- //Here's where we differentiate based on what type it is.
- if(this.shadingType == 1)
- {//function based shading
- if(this.domain != null)
- {
- p.append("/Domain [ ");
- vectorSize = this.domain.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.domain.elementAt(tempInt)) +" ");
- }
- p.append("] \n");
- }
- else
- {
- p.append("/Domain [ 0 1 ] \n");
- }
-
- if(this.matrix != null)
- {
- p.append("/Matrix [ ");
- vectorSize = this.matrix.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.matrix.elementAt(tempInt)) +" ");
- }
- p.append("] \n");
- }
-
- if(this.function != null)
- {
- p.append("/Function ");
- p.append(this.function.referencePDF()+" \n");
- }
- }
- else if((this.shadingType == 2)
- || (this.shadingType == 3))
- {//2 is axial shading (linear gradient)
- //3 is radial shading (circular gradient)
- if(this.coords != null)
- {
- p.append("/Coords [ ");
- vectorSize = this.coords.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.coords.elementAt(tempInt)) +" ");
- }
- p.append("] \n");
- }
-
- //DOMAIN
- if(this.domain != null)
- {
- p.append("/Domain [ ");
- vectorSize = this.domain.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(PDFNumber.doubleOut(
- (Double)this.domain.elementAt(tempInt)) +" ");
- }
- p.append("] \n");
- }
- else
- {
- p.append("/Domain [ 0 1 ] \n");
- }
-
- if(this.extend != null)
- {
- p.append("/Extend [ ");
- vectorSize = this.extend.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(((Boolean)this.extend.elementAt(tempInt)) +" ");
- }
-
- p.append("] \n");
- }
- else
- {
- p.append("/Extend [ true true ] \n");
- }
-
-
- if(this.function != null)
- {
- p.append("/Function ");
- p.append(this.function.referencePDF()+" \n");
- }
-
-
- }
-
- else if ((this.shadingType == 4) ||
- (this.shadingType == 6) ||
- (this.shadingType == 7))
- {//4:Free-form Gouraud-shaded triangle meshes
- // 6:coons patch meshes
- // 7://tensor product patch meshes (which no one ever uses)
- if(this.bitsPerCoordinate > 0)
- {
- p.append("/BitsPerCoordinate "+this.bitsPerCoordinate+" \n");
- }
- else
- {
- p.append("/BitsPerCoordinate 1 \n");
- }
-
- if(this.bitsPerComponent > 0)
- {
- p.append("/BitsPerComponent "+this.bitsPerComponent+" \n");
- }
- else
- {
- p.append("/BitsPerComponent 1 \n");
- }
-
- if(this.bitsPerFlag > 0)
- {
- p.append("/BitsPerFlag "+this.bitsPerFlag+" \n");
- }
- else
- {
- p.append("/BitsPerFlag 2 \n");
- }
-
- if(this.decode != null)
- {
- p.append("/Decode [ ");
- vectorSize = this.decode.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(((Boolean)this.decode.elementAt(tempInt)) +" ");
- }
-
- p.append("] \n");
- }
-
- if(this.function != null)
- {
- p.append("/Function ");
- p.append(this.function.referencePDF()+" \n");
- }
-
- }
-
- else if (this.shadingType == 5)
- { //Lattice Free form gouraud-shaded triangle mesh
-
- if(this.bitsPerCoordinate > 0)
- {
- p.append("/BitsPerCoordinate "+this.bitsPerCoordinate+" \n");
- }
- else
- {
- p.append("/BitsPerCoordinate 1 \n");
- }
-
- if(this.bitsPerComponent > 0)
- {
- p.append("/BitsPerComponent "+this.bitsPerComponent+" \n");
- }
- else
- {
- p.append("/BitsPerComponent 1 \n");
- }
-
- if(this.decode != null)
- {
- p.append("/Decode [ ");
- vectorSize = this.decode.size();
- for(tempInt=0; tempInt < vectorSize; tempInt++)
- {
- p.append(((Boolean)this.decode.elementAt(tempInt)) +" ");
- }
-
- p.append("] \n");
- }
-
- if(this.function != null)
- {
- p.append("/Function ");
- p.append(this.function.referencePDF()+" \n");
- }
-
- if(this.verticesPerRow > 0)
- {
- p.append("/VerticesPerRow "+this.verticesPerRow+" \n");
- }
- else
- {
- p.append("/VerticesPerRow 2 \n");
- }
-
- }
-
- p.append(">> \nendobj\n");
-
- return(p.toString().getBytes());
- }
+ // Guts common to all function types
+
+ /**
+ * The name of the Shading e.g. "Shading1"
+ */
+ protected String shadingName = null;
+
+ /**
+ * Required: The Type of shading (1,2,3,4,5,6,7)
+ */
+ protected int shadingType = 3; // Default
+
+ /**
+ * A ColorSpace representing the colorspace. "DeviceRGB" is an example.
+ */
+ // protected StringBuffer colorSpace = null;
+ protected ColorSpace colorSpace = null;
+
+ /**
+ * The background color. Since shading is opaque,
+ * this is very rarely used.
+ */
+ protected Vector background = null;
+
+ /**
+ * Optional: A Vector specifying the clipping rectangle
+ */
+ protected Vector bBox = null;
+
+ /**
+ * Optional: A flag whether or not to filter the shading function
+ * to prevent aliasing artifacts. Default is false.
+ */
+ protected boolean antiAlias = false;
+
+ /**
+ * Optional for Type 1: Array of four numbers, xmin, xmax, ymin, ymax. Default is [0 1 0 1]
+ * Optional for Type 2: An array of two numbers between which the blend varies between start and end points. Default is 0, 1.
+ * Optional for Type 3: An array of two numbers between which the blend varies between start and end points. Default is 0, 1.
+ */
+
+ protected Vector domain = null;
+
+ /**
+ * Optional for Type 1: A transformation matrix
+ */
+ protected Vector matrix = null;
+
+ /**
+ * Required for Type 1, 2, and 3:
+ * The object of the color mapping function (usually type 2 or 3).
+ * Optional for Type 4,5,6, and 7: When it's nearly the same thing.
+ */
+ protected PDFFunction function = null;
+
+ /**
+ * Required for Type 2: An Array of four numbers specifying the starting and ending coordinate pairs
+ * Required for Type 3: An Array of six numbers [x0,y0,r0,x1,y1,r1] specifying the centers and radii of
+ * the starting and ending circles.
+ */
+ protected Vector coords = null;
+
+ /**
+ * Required for Type 2+3: An Array of two boolean values specifying whether to extend the
+ * start and end colors past the start and end points,
+ * respectively. Default is false, false.
+ */
+ protected Vector extend = null;
+
+ /**
+ * Required for Type 4,5,6, and 7: Specifies the number of bits used to represent each vertex coordinate.
+ * Allowed to be 1,2,4,8,12,16,24, or 32.
+ */
+ protected int bitsPerCoordinate = 0;
+
+ /**
+ * Required for Type 4,5,6, and 7: Specifies the number of bits used to represent the edge flag for each vertex.
+ * Allowed to be 2,4,or 8, while the Edge flag itself is allowed to be 0,1 or 2.
+ */
+ protected int bitsPerFlag = 0;
+
+ /**
+ * Required for Type 4,5,6, and 7: Array of Doubles which specifies how to decode coordinate and color component values.
+ * Each type has a differing number of decode array members, so check the spec.
+ * Page 303 in PDF Spec 1.3
+ */
+ protected Vector decode = null;
+
+ /**
+ * Required for Type 4,5,6, and 7: Specifies the number of bits used to represent each color coordinate.
+ * Allowed to be 1,2,4,8,12, or 16
+ */
+ protected int bitsPerComponent = 0;
+
+ /**
+ * Required for Type 5:The number of vertices in each "row" of the lattice; it must be greater than or equal to 2.
+ */
+ protected int verticesPerRow = 0;
+
+ /**
+ * Constructor for type function based shading
+ *
+ * @param theNumber The object number of this PDF object
+ * @param theShadingName The name of the shading pattern. Can be anything
+ * without spaces. "Shading1" or "Sh1" are good examples.
+ * @param theShadingType The type of shading object, which should be 1 for function
+ * based shading.
+ * @param theColorSpace The colorspace is 'DeviceRGB' or something similar.
+ * @param theBackground An array of color components appropriate to the
+ * colorspace key specifying a single color value.
+ * This key is used by the f operator buy ignored by the sh operator.
+ * @param theBBox Vector of double's representing a rectangle
+ * in the coordinate space that is current at the
+ * time of shading is imaged. Temporary clipping
+ * boundary.
+ * @param theAntiAlias Whether or not to anti-alias.
+ * @param theDomain Optional vector of Doubles specifying the domain.
+ * @param theMatrix Vector of Doubles specifying the matrix.
+ * If it's a pattern, then the matrix maps it to pattern space.
+ * If it's a shading, then it maps it to current user space.
+ * It's optional, the default is the identity matrix
+ * @param theFunction The PDF Function that maps an (x,y) location to a color
+ */
+ public PDFShading(int theNumber, String theShadingName,
+ int theShadingType, ColorSpace theColorSpace,
+ Vector theBackground, Vector theBBox,
+ boolean theAntiAlias, Vector theDomain,
+ Vector theMatrix, PDFFunction theFunction) {
+ super(theNumber);
+ this.shadingName = theShadingName;
+ this.shadingType = theShadingType; // 1
+ this.colorSpace = theColorSpace;
+ this.background = theBackground;
+ this.bBox = theBBox;
+ this.antiAlias = theAntiAlias;
+
+ this.domain = theDomain;
+ this.matrix = theMatrix;
+ this.function = theFunction;
+
+ }
+
+ /**
+ * Constructor for Type 2 and 3
+ *
+ * @param theNumber The object number of this PDF object.
+ * @param theShadingName The name of the shading pattern. Can be anything
+ * without spaces. "Shading1" or "Sh1" are good examples.
+ * @param theShadingType 2 or 3 for axial or radial shading
+ * @param theColorSpace "DeviceRGB" or similar.
+ * @param theBackground theBackground An array of color components appropriate to the
+ * colorspace key specifying a single color value.
+ * This key is used by the f operator buy ignored by the sh operator.
+ * @param theBBox Vector of double's representing a rectangle
+ * in the coordinate space that is current at the
+ * time of shading is imaged. Temporary clipping
+ * boundary.
+ * @param theAntiAlias Default is false
+ * @param theCoords Vector of four (type 2) or 6 (type 3) Double
+ * @param theDomain Vector of Doubles specifying the domain
+ * @param theFunction the Stitching (PDFfunction type 3) function, even if it's stitching a single function
+ * @param theExtend Vector of Booleans of whether to extend teh start and end colors past the start and end points
+ * The default is [false, false]
+ */
+ public PDFShading(int theNumber, String theShadingName,
+ int theShadingType, ColorSpace theColorSpace,
+ Vector theBackground, Vector theBBox,
+ boolean theAntiAlias, Vector theCoords,
+ Vector theDomain, PDFFunction theFunction,
+ Vector theExtend) {
+ super(theNumber);
+ this.shadingName = theShadingName;
+ this.shadingType = theShadingType; // 2 or 3
+ this.colorSpace = theColorSpace;
+ this.background = theBackground;
+ this.bBox = theBBox;
+ this.antiAlias = theAntiAlias;
+
+ this.coords = theCoords;
+ this.domain = theDomain;
+ this.function = theFunction;
+ this.extend = theExtend;
+
+ }
+
+ /**
+ * Constructor for Type 4,6, or 7
+ *
+ * @param theNumber The object number of this PDF object.
+ * @param theShadingType 4, 6, or 7 depending on whether it's
+ * Free-form gouraud-shaded triangle meshes, coons patch meshes,
+ * or tensor product patch meshes, respectively.
+ * @param theShadingName The name of the shading pattern. Can be anything
+ * without spaces. "Shading1" or "Sh1" are good examples.
+ * @param theColorSpace "DeviceRGB" or similar.
+ * @param theBackground theBackground An array of color components appropriate to the
+ * colorspace key specifying a single color value.
+ * This key is used by the f operator buy ignored by the sh operator.
+ * @param theBBox Vector of double's representing a rectangle
+ * in the coordinate space that is current at the
+ * time of shading is imaged. Temporary clipping
+ * boundary.
+ * @param theAntiAlias Default is false
+ * @param theBitsPerCoordinate 1,2,4,8,12,16,24 or 32.
+ * @param theBitsPerComponent 1,2,4,8,12, and 16
+ * @param theBitsPerFlag 2,4,8.
+ * @param theDecode Vector of Doubles see PDF 1.3 spec pages 303 to 312.
+ * @param theFunction the PDFFunction
+ */
+ public PDFShading(int theNumber, String theShadingName,
+ int theShadingType, ColorSpace theColorSpace,
+ Vector theBackground, Vector theBBox,
+ boolean theAntiAlias, int theBitsPerCoordinate,
+ int theBitsPerComponent, int theBitsPerFlag,
+ Vector theDecode, PDFFunction theFunction) {
+ super(theNumber);
+
+ this.shadingType = theShadingType; // 4,6 or 7
+ this.colorSpace = theColorSpace;
+ this.background = theBackground;
+ this.bBox = theBBox;
+ this.antiAlias = theAntiAlias;
+
+ this.bitsPerCoordinate = theBitsPerCoordinate;
+ this.bitsPerComponent = theBitsPerComponent;
+ this.bitsPerFlag = theBitsPerFlag;
+ this.decode = theDecode;
+ this.function = theFunction;
+ }
+
+ /**
+ * Constructor for type 5
+ *
+ * @param theShadingType 5 for lattice-Form Gouraud shaded-triangle mesh
+ * @param theShadingName The name of the shading pattern. Can be anything
+ * without spaces. "Shading1" or "Sh1" are good examples.
+ * @param theColorSpace "DeviceRGB" or similar.
+ * @param theBackground theBackground An array of color components appropriate to the
+ * colorspace key specifying a single color value.
+ * This key is used by the f operator buy ignored by the sh operator.
+ * @param theBBox Vector of double's representing a rectangle
+ * in the coordinate space that is current at the
+ * time of shading is imaged. Temporary clipping
+ * boundary.
+ * @param theAntiAlias Default is false
+ * @param theBitsPerCoordinate 1,2,4,8,12,16, 24, or 32
+ * @param theBitsPerComponent 1,2,4,8,12,24,32
+ * @param theDecode Vector of Doubles. See page 305 in PDF 1.3 spec.
+ * @param theVerticesPerRow number of vertices in each "row" of the lattice.
+ * @param theFunction The PDFFunction that's mapped on to this shape
+ * @param theNumber the object number of this PDF object.
+ */
+ public PDFShading(int theNumber, String theShadingName,
+ int theShadingType, ColorSpace theColorSpace,
+ Vector theBackground, Vector theBBox,
+ boolean theAntiAlias, int theBitsPerCoordinate,
+ int theBitsPerComponent, Vector theDecode,
+ int theVerticesPerRow, PDFFunction theFunction) {
+ super(theNumber);
+ this.shadingName = theShadingName;
+ this.shadingType = theShadingType; // 5
+ this.colorSpace = theColorSpace;
+ this.background = theBackground;
+ this.bBox = theBBox;
+ this.antiAlias = theAntiAlias;
+
+ this.bitsPerCoordinate = theBitsPerCoordinate;
+ this.bitsPerComponent = theBitsPerComponent;
+ this.decode = theDecode;
+ this.verticesPerRow = theVerticesPerRow;
+ this.function = theFunction;
+
+ }
+
+ public String getName() {
+ return (this.shadingName);
+ }
+
+ /**
+ * represent as PDF. Whatever the shadingType is, the correct
+ * representation spits out. The sets of required and optional
+ * attributes are different for each type, but if a required
+ * attribute's object was constructed as null, then no error
+ * is raised. Instead, the malformed PDF that was requested
+ * by the construction is dutifully output.
+ * This policy should be reviewed.
+ *
+ * @return the PDF string.
+ */
+ public byte[] toPDF() {
+ int vectorSize;
+ int tempInt;
+ StringBuffer p = new StringBuffer();
+ p.append(this.number + " " + this.generation
+ + " obj\n<< \n/ShadingType " + this.shadingType + " \n");
+ if (this.colorSpace != null) {
+ p.append("/ColorSpace /"
+ + this.colorSpace.getColorSpacePDFString() + " \n");
+ }
+
+ if (this.background != null) {
+ p.append("/Background [ ");
+ vectorSize = this.background.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.background.elementAt(tempInt))
+ + " ");
+ }
+ p.append("] \n");
+ }
+
+ if (this.bBox
+ != null) { // I've never seen an example, so I guess this is right.
+ p.append("/BBox [ ");
+ vectorSize = this.bBox.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.bBox.elementAt(tempInt))
+ + " ");
+ }
+ p.append("] \n");
+ }
+
+ if (this.antiAlias) {
+ p.append("/AntiAlias " + this.antiAlias + " \n");
+ }
+
+ // Here's where we differentiate based on what type it is.
+ if (this.shadingType == 1) { // function based shading
+ if (this.domain != null) {
+ p.append("/Domain [ ");
+ vectorSize = this.domain.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.domain.elementAt(tempInt))
+ + " ");
+ }
+ p.append("] \n");
+ } else {
+ p.append("/Domain [ 0 1 ] \n");
+ }
+
+ if (this.matrix != null) {
+ p.append("/Matrix [ ");
+ vectorSize = this.matrix.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.matrix.elementAt(tempInt))
+ + " ");
+ }
+ p.append("] \n");
+ }
+
+ if (this.function != null) {
+ p.append("/Function ");
+ p.append(this.function.referencePDF() + " \n");
+ }
+ } else if ((this.shadingType == 2)
+ || (this.shadingType
+ == 3)) { // 2 is axial shading (linear gradient)
+ // 3 is radial shading (circular gradient)
+ if (this.coords != null) {
+ p.append("/Coords [ ");
+ vectorSize = this.coords.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.coords.elementAt(tempInt))
+ + " ");
+ }
+ p.append("] \n");
+ }
+
+ // DOMAIN
+ if (this.domain != null) {
+ p.append("/Domain [ ");
+ vectorSize = this.domain.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(PDFNumber.doubleOut((Double)this.domain.elementAt(tempInt))
+ + " ");
+ }
+ p.append("] \n");
+ } else {
+ p.append("/Domain [ 0 1 ] \n");
+ }
+
+ if (this.extend != null) {
+ p.append("/Extend [ ");
+ vectorSize = this.extend.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(((Boolean)this.extend.elementAt(tempInt)) + " ");
+ }
+
+ p.append("] \n");
+ } else {
+ p.append("/Extend [ true true ] \n");
+ }
+
+
+ if (this.function != null) {
+ p.append("/Function ");
+ p.append(this.function.referencePDF() + " \n");
+ }
+
+
+ } else if ((this.shadingType == 4) || (this.shadingType == 6)
+ || (this.shadingType
+ == 7)) { // 4:Free-form Gouraud-shaded triangle meshes
+ // 6:coons patch meshes
+ // 7://tensor product patch meshes (which no one ever uses)
+ if (this.bitsPerCoordinate > 0) {
+ p.append("/BitsPerCoordinate " + this.bitsPerCoordinate
+ + " \n");
+ } else {
+ p.append("/BitsPerCoordinate 1 \n");
+ }
+
+ if (this.bitsPerComponent > 0) {
+ p.append("/BitsPerComponent " + this.bitsPerComponent
+ + " \n");
+ } else {
+ p.append("/BitsPerComponent 1 \n");
+ }
+
+ if (this.bitsPerFlag > 0) {
+ p.append("/BitsPerFlag " + this.bitsPerFlag + " \n");
+ } else {
+ p.append("/BitsPerFlag 2 \n");
+ }
+
+ if (this.decode != null) {
+ p.append("/Decode [ ");
+ vectorSize = this.decode.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(((Boolean)this.decode.elementAt(tempInt)) + " ");
+ }
+
+ p.append("] \n");
+ }
+
+ if (this.function != null) {
+ p.append("/Function ");
+ p.append(this.function.referencePDF() + " \n");
+ }
+
+ } else if (this.shadingType
+ == 5) { // Lattice Free form gouraud-shaded triangle mesh
+
+ if (this.bitsPerCoordinate > 0) {
+ p.append("/BitsPerCoordinate " + this.bitsPerCoordinate
+ + " \n");
+ } else {
+ p.append("/BitsPerCoordinate 1 \n");
+ }
+
+ if (this.bitsPerComponent > 0) {
+ p.append("/BitsPerComponent " + this.bitsPerComponent
+ + " \n");
+ } else {
+ p.append("/BitsPerComponent 1 \n");
+ }
+
+ if (this.decode != null) {
+ p.append("/Decode [ ");
+ vectorSize = this.decode.size();
+ for (tempInt = 0; tempInt < vectorSize; tempInt++) {
+ p.append(((Boolean)this.decode.elementAt(tempInt)) + " ");
+ }
+
+ p.append("] \n");
+ }
+
+ if (this.function != null) {
+ p.append("/Function ");
+ p.append(this.function.referencePDF() + " \n");
+ }
+
+ if (this.verticesPerRow > 0) {
+ p.append("/VerticesPerRow " + this.verticesPerRow + " \n");
+ } else {
+ p.append("/VerticesPerRow 2 \n");
+ }
+
+ }
+
+ p.append(">> \nendobj\n");
+
+ return (p.toString().getBytes());
+ }
+
}
diff --git a/src/org/apache/fop/pdf/PDFStream.java b/src/org/apache/fop/pdf/PDFStream.java
index ccf22db75..01b87b9d6 100644
--- a/src/org/apache/fop/pdf/PDFStream.java
+++ b/src/org/apache/fop/pdf/PDFStream.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
import java.io.ByteArrayOutputStream;
@@ -60,7 +17,7 @@ import org.apache.fop.messaging.MessageHandler;
/**
* class representing a PDF stream.
- *
+ *
* A derivative of the PDF Object, a PDF Stream has not only a dictionary
* but a stream of PDF commands. The stream of commands is where the real
* work is done, the dictionary just provides information like the stream
@@ -68,21 +25,25 @@ import org.apache.fop.messaging.MessageHandler;
*/
public class PDFStream extends PDFObject {
- /** the stream of PDF commands */
+ /**
+ * the stream of PDF commands
+ */
protected ByteArrayOutputStream _data;
- /** the filters that should be applied */
+ /**
+ * the filters that should be applied
+ */
private Vector _filters;
-
+
/**
* create an empty stream object
*
* @param number the object's number
*/
public PDFStream(int number) {
- super(number);
- _data = new ByteArrayOutputStream();
- _filters = new Vector();
+ super(number);
+ _data = new ByteArrayOutputStream();
+ _filters = new Vector();
}
/**
@@ -91,77 +52,68 @@ public class PDFStream extends PDFObject {
* @param s the string of PDF to add
*/
public void add(String s) {
- try {
- _data.write(s.getBytes());
- }
- catch (IOException ex) {
- ex.printStackTrace();
- }
-
+ try {
+ _data.write(s.getBytes());
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ }
+
}
/**
* Add a filter for compression of the stream. Filters are
- * applied in the order they are added. This should always be a
+ * applied in the order they are added. This should always be a
* new instance of the particular filter of choice. The applied
* flag in the filter is marked true after it has been applied to the
* data.
*/
- public void addFilter(PDFFilter filter)
- {
- if (filter != null) {
- _filters.addElement(filter);
- }
+ public void addFilter(PDFFilter filter) {
+ if (filter != null) {
+ _filters.addElement(filter);
+ }
}
- public void addFilter(String filterType)
- {
- if (filterType == null) {
- return;
- }
- if (filterType.equals("flate")) {
- addFilter(new FlateFilter());
- }
- else if (filterType.equals("ascii-85")) {
- addFilter(new ASCII85Filter());
- }
- else if (filterType.equals("ascii-hex")) {
- addFilter(new ASCIIHexFilter());
- }
- else if (filterType.equals("")) {
- return;
- }
- else {
- MessageHandler.errorln("Unsupported filter type in stream-filter-list: "+filterType);
- }
+ public void addFilter(String filterType) {
+ if (filterType == null) {
+ return;
+ }
+ if (filterType.equals("flate")) {
+ addFilter(new FlateFilter());
+ } else if (filterType.equals("ascii-85")) {
+ addFilter(new ASCII85Filter());
+ } else if (filterType.equals("ascii-hex")) {
+ addFilter(new ASCIIHexFilter());
+ } else if (filterType.equals("")) {
+ return;
+ } else {
+ MessageHandler.errorln("Unsupported filter type in stream-filter-list: "
+ + filterType);
+ }
}
-
-
- protected void addDefaultFilters()
- {
- Vector filters = Configuration.getListValue("stream-filter-list",
- Configuration.PDF);
- if (filters == null) {
- // try getting it as a String
- String filter = Configuration.getStringValue("stream-filter-list",
- Configuration.PDF);
- if (filter == null) {
- // built-in default to flate
- addFilter(new FlateFilter());
- }
- else {
- addFilter(filter);
- }
- }
- else {
- for (int i=0; i < filters.size(); i++) {
- String v = (String)filters.elementAt(i);
- addFilter(v);
- }
- }
+
+
+ protected void addDefaultFilters() {
+ Vector filters = Configuration.getListValue("stream-filter-list",
+ Configuration.PDF);
+ if (filters == null) {
+ // try getting it as a String
+ String filter = Configuration.getStringValue("stream-filter-list",
+ Configuration.PDF);
+ if (filter == null) {
+ // built-in default to flate
+ addFilter(new FlateFilter());
+ } else {
+ addFilter(filter);
+ }
+ } else {
+ for (int i = 0; i < filters.size(); i++) {
+ String v = (String)filters.elementAt(i);
+ addFilter(v);
+ }
+ }
}
-
+
/**
* append an array of xRGB pixels, ASCII Hex Encoding it first
@@ -171,117 +123,110 @@ public class PDFStream extends PDFObject {
* @param height the height of the image in pixels
*/
public void addImageArray(int[] pixels, int width, int height) {
- try {
- for (int i = 0; i < height; i++) {
- for (int j = 0; j < width; j++) {
- int p = pixels[i * width + j];
- int r = (p >> 16) & 0xFF;
- int g = (p >> 8) & 0xFF;
- int b = (p ) & 0xFF;
- if (r < 16) {
- _data.write('0');
- }
- _data.write(Integer.toHexString(r).getBytes());
- if (g < 16) {
- _data.write('0');
- }
- _data.write(Integer.toHexString(g).getBytes());
- if (b < 16) {
- _data.write('0');
- }
- _data.write(Integer.toHexString(b).getBytes());
- _data.write(' ');
- }
- }
- _data.write(">\n".getBytes());
- }
- catch (IOException ex) {
- ex.printStackTrace();
- }
-
+ try {
+ for (int i = 0; i < height; i++) {
+ for (int j = 0; j < width; j++) {
+ int p = pixels[i * width + j];
+ int r = (p >> 16) & 0xFF;
+ int g = (p >> 8) & 0xFF;
+ int b = (p) & 0xFF;
+ if (r < 16) {
+ _data.write('0');
+ }
+ _data.write(Integer.toHexString(r).getBytes());
+ if (g < 16) {
+ _data.write('0');
+ }
+ _data.write(Integer.toHexString(g).getBytes());
+ if (b < 16) {
+ _data.write('0');
+ }
+ _data.write(Integer.toHexString(b).getBytes());
+ _data.write(' ');
+ }
+ }
+ _data.write(">\n".getBytes());
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ }
+
}
- public void setData(byte[] data)
- throws IOException
- {
- _data.reset();
- _data.write(data);
+ public void setData(byte[] data) throws IOException {
+ _data.reset();
+ _data.write(data);
}
-
- public byte[] getData()
- {
- return _data.toByteArray();
+
+ public byte[] getData() {
+ return _data.toByteArray();
}
-
- public int getDataLength()
- {
- return _data.size();
+
+ public int getDataLength() {
+ return _data.size();
}
-
-
+
+
/**
* represent as PDF.
*
* @return the PDF string.
- */
+ */
/*
+ * public byte[] toPDF() {
+ * byte[] d = _data.toByteArray();
+ * ByteArrayOutputStream s = new ByteArrayOutputStream();
+ * String p = this.number + " " + this.generation
+ * + " obj\n<< /Length " + (d.length+1)
+ * + " >>\nstream\n";
+ * s.write(p.getBytes());
+ * s.write(d);
+ * s.write("\nendstream\nendobj\n".getBytes());
+ * return s.toByteArray();
+ * }
+ */
public byte[] toPDF() {
- byte[] d = _data.toByteArray();
- ByteArrayOutputStream s = new ByteArrayOutputStream();
- String p = this.number + " " + this.generation
- + " obj\n<< /Length " + (d.length+1)
- + " >>\nstream\n";
- s.write(p.getBytes());
- s.write(d);
- s.write("\nendstream\nendobj\n".getBytes());
- return s.toByteArray();
- }
- */
- public byte[] toPDF() {
- throw new RuntimeException();
+ throw new RuntimeException();
}
-
- // overload the base object method so we don't have to copy
+
+ // overload the base object method so we don't have to copy
// byte arrays around so much
- protected int output(OutputStream stream) throws IOException
- {
- int length = 0;
- String filterEntry = applyFilters();
- byte[] p = (this.number + " " + this.generation
- + " obj\n<< /Length " + (_data.size()+1) + " "
- + filterEntry + " >>\n").getBytes();
-
- stream.write(p);
- length += p.length;
- length += outputStreamData(stream);
- p = "endobj\n".getBytes();
- stream.write(p);
- length += p.length;
- return length;
-
+ protected int output(OutputStream stream) throws IOException {
+ int length = 0;
+ String filterEntry = applyFilters();
+ byte[] p = (this.number + " " + this.generation + " obj\n<< /Length "
+ + (_data.size() + 1) + " " + filterEntry
+ + " >>\n").getBytes();
+
+ stream.write(p);
+ length += p.length;
+ length += outputStreamData(stream);
+ p = "endobj\n".getBytes();
+ stream.write(p);
+ length += p.length;
+ return length;
+
}
/**
* Output just the stream data enclosed by stream/endstream markers
*/
- protected int outputStreamData(OutputStream stream) throws IOException
- {
- int length = 0;
- byte[] p ="stream\n".getBytes();
- stream.write(p);
- length += p.length;
- _data.writeTo(stream);
- length += _data.size();
- p = "\nendstream\n".getBytes();
- stream.write(p);
- length += p.length;
- return length;
-
+ protected int outputStreamData(OutputStream stream) throws IOException {
+ int length = 0;
+ byte[] p = "stream\n".getBytes();
+ stream.write(p);
+ length += p.length;
+ _data.writeTo(stream);
+ length += _data.size();
+ p = "\nendstream\n".getBytes();
+ stream.write(p);
+ length += p.length;
+ return length;
+
}
-
-
+
+
/**
* Apply the filters to the data
* in the order given and return the /Filter and /DecodeParms
@@ -289,86 +234,81 @@ public class PDFStream extends PDFObject {
* been applied to the data (either externally, or internally)
* then the dictionary entries are built and returned.
*/
- protected String applyFilters() throws IOException
- {
- if (_filters.size() > 0) {
- Vector names = new Vector();
- Vector parms = new Vector();
-
- // run the filters
- Enumeration e = _filters.elements();
- while (e.hasMoreElements()) {
- PDFFilter filter = (PDFFilter)e.nextElement();
- // apply the filter encoding if neccessary
- if (!filter.isApplied()) {
- byte[] tmp = filter.encode(_data.toByteArray());
- _data.reset();
- _data.write(tmp);
- filter.setApplied(true);
- }
- // place the names in our local vector in reverse order
- names.insertElementAt(filter.getName(), 0);
- parms.insertElementAt(filter.getDecodeParms(), 0);
- }
-
- // now build up the filter entries for the dictionary
- return buildFilterEntries(names) + buildDecodeParms(parms);
- }
- return "";
-
+ protected String applyFilters() throws IOException {
+ if (_filters.size() > 0) {
+ Vector names = new Vector();
+ Vector parms = new Vector();
+
+ // run the filters
+ Enumeration e = _filters.elements();
+ while (e.hasMoreElements()) {
+ PDFFilter filter = (PDFFilter)e.nextElement();
+ // apply the filter encoding if neccessary
+ if (!filter.isApplied()) {
+ byte[] tmp = filter.encode(_data.toByteArray());
+ _data.reset();
+ _data.write(tmp);
+ filter.setApplied(true);
+ }
+ // place the names in our local vector in reverse order
+ names.insertElementAt(filter.getName(), 0);
+ parms.insertElementAt(filter.getDecodeParms(), 0);
+ }
+
+ // now build up the filter entries for the dictionary
+ return buildFilterEntries(names) + buildDecodeParms(parms);
+ }
+ return "";
+
}
-
- private String buildFilterEntries(Vector names)
- {
- StringBuffer sb = new StringBuffer();
- sb.append("/Filter ");
- if (names.size() > 1) {
- sb.append("[ ");
- }
- Enumeration e = names.elements();
- while (e.hasMoreElements()) {
- sb.append((String)e.nextElement());
- sb.append(" ");
- }
- if (names.size() > 1) {
- sb.append("]");
- }
- sb.append("\n");
- return sb.toString();
+
+ private String buildFilterEntries(Vector names) {
+ StringBuffer sb = new StringBuffer();
+ sb.append("/Filter ");
+ if (names.size() > 1) {
+ sb.append("[ ");
+ }
+ Enumeration e = names.elements();
+ while (e.hasMoreElements()) {
+ sb.append((String)e.nextElement());
+ sb.append(" ");
+ }
+ if (names.size() > 1) {
+ sb.append("]");
+ }
+ sb.append("\n");
+ return sb.toString();
}
- private String buildDecodeParms(Vector parms)
- {
- StringBuffer sb = new StringBuffer();
- boolean needParmsEntry = false;
- sb.append("/DecodeParms ");
-
- if (parms.size() > 1) {
- sb.append("[ ");
- }
- Enumeration e = parms.elements();
- while (e.hasMoreElements()) {
- String s = (String)e.nextElement();
- if (s != null) {
- sb.append(s);
- needParmsEntry = true;
- }
- else {
- sb.append("null");
- }
- sb.append(" ");
- }
- if (parms.size() > 1) {
- sb.append("]");
- }
- sb.append("\n");
- if (needParmsEntry) {
- return sb.toString();
- }
- else {
- return "";
- }
+ private String buildDecodeParms(Vector parms) {
+ StringBuffer sb = new StringBuffer();
+ boolean needParmsEntry = false;
+ sb.append("/DecodeParms ");
+
+ if (parms.size() > 1) {
+ sb.append("[ ");
+ }
+ Enumeration e = parms.elements();
+ while (e.hasMoreElements()) {
+ String s = (String)e.nextElement();
+ if (s != null) {
+ sb.append(s);
+ needParmsEntry = true;
+ } else {
+ sb.append("null");
+ }
+ sb.append(" ");
+ }
+ if (parms.size() > 1) {
+ sb.append("]");
+ }
+ sb.append("\n");
+ if (needParmsEntry) {
+ return sb.toString();
+ } else {
+ return "";
+ }
}
-
+
}
diff --git a/src/org/apache/fop/pdf/PDFT1Stream.java b/src/org/apache/fop/pdf/PDFT1Stream.java
index 644831370..8de99f260 100644
--- a/src/org/apache/fop/pdf/PDFT1Stream.java
+++ b/src/org/apache/fop/pdf/PDFT1Stream.java
@@ -1,154 +1,107 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
public class PDFT1Stream extends PDFStream {
- private int origLength;
- private int len1, len3;
- private byte[] originalData=null;
-
- public PDFT1Stream(int num, int len) {
- super(num);
- origLength=len;
- }
+ private int origLength;
+ private int len1, len3;
+ private byte[] originalData = null;
- private final static boolean byteCmp(byte[] src, int offset, byte[] cmp) {
- boolean ret=true;
- for (int i=0; ret==true && i < cmp.length; i++) {
- //System.out.println("Compare: ");
- //System.out.println(" "+src[offset+i]+" "+cmp[i]);
- if (src[offset+i]!=cmp[i])
- ret=false;
- }
- return ret;
- }
+ public PDFT1Stream(int num, int len) {
+ super(num);
+ origLength = len;
+ }
- /**
- * calculates the Length1 and Length3 PDFStream attributes for type1
- * font embedding
- */
- private void calcLengths(byte[] originalData) {
- // Calculate length 1 and 3
- //System.out.println ("Checking font, size = "+originalData.length);
-
- // Length1 is the size of the initial ascii portion
- // search for "currentfile eexec"
- // Get the first binary number and search backwards for "eexec"
- len1=30;
+ private final static boolean byteCmp(byte[] src, int offset, byte[] cmp) {
+ boolean ret = true;
+ for (int i = 0; ret == true && i < cmp.length; i++) {
+ // System.out.println("Compare: ");
+ // System.out.println(" "+src[offset+i]+" "+cmp[i]);
+ if (src[offset + i] != cmp[i])
+ ret = false;
+ }
+ return ret;
+ }
- byte[] eexec=(new String("currentfile eexec")).getBytes();
- //System.out.println("Length1="+len1);
- while (!byteCmp(originalData, len1-eexec.length, eexec))
- len1++;
- // Skip newline
- len1++;
+ /**
+ * calculates the Length1 and Length3 PDFStream attributes for type1
+ * font embedding
+ */
+ private void calcLengths(byte[] originalData) {
+ // Calculate length 1 and 3
+ // System.out.println ("Checking font, size = "+originalData.length);
+
+ // Length1 is the size of the initial ascii portion
+ // search for "currentfile eexec"
+ // Get the first binary number and search backwards for "eexec"
+ len1 = 30;
+
+ byte[] eexec = (new String("currentfile eexec")).getBytes();
+ // System.out.println("Length1="+len1);
+ while (!byteCmp(originalData, len1 - eexec.length, eexec))
+ len1++;
+ // Skip newline
+ len1++;
+
+ // Length3 is length of the last portion of the file
+ len3 = 0;
+ byte[] cltom = (new String("cleartomark")).getBytes();
+ len3 -= cltom.length;
+ while (!byteCmp(originalData, origLength + len3, cltom)) {
+ len3--;
+ // System.out.println("Len3="+len3);
+ }
+ len3 = -len3;
+ len3++;
+ // Eat 512 zeroes
+ int numZeroes = 0;
+ byte[] ws1 = "\n".getBytes();
+ byte[] ws2 = "\r".getBytes();
+ byte[] ws3 = "0".getBytes();
+ while ((originalData[origLength - len3] == ws1[0] || originalData[origLength - len3] == ws2[0] || originalData[origLength - len3] == ws3[0])
+ && numZeroes < 512) {
+ len3++;
+ if (originalData[origLength - len3] == ws3[0])
+ numZeroes++;
+ }
+ // System.out.println("Length3="+len3);
+ }
+
+ // overload the base object method so we don't have to copy
+ // byte arrays around so much
+ protected int output(java.io.OutputStream stream)
+ throws java.io.IOException {
+ int length = 0;
+ String filterEntry = applyFilters();
+ String preData = new String(this.number + " " + this.generation
+ + " obj\n<< /Length "
+ + (_data.size() + 1) + " " + filterEntry
+ + " " + "/Length1 " + len1 + " /Length2 "
+ + (origLength - len3 - len1)
+ + " /Length3 " + len3 + " >>\n");
- // Length3 is length of the last portion of the file
- len3=0;
- byte[] cltom=(new String("cleartomark")).getBytes();
- len3 -= cltom.length;
- while (!byteCmp(originalData, origLength+len3, cltom)) {
- len3--;
- //System.out.println("Len3="+len3);
- }
- len3 = -len3;
- len3++;
- // Eat 512 zeroes
- int numZeroes=0;
- byte[] ws1="\n".getBytes();
- byte[] ws2="\r".getBytes();
- byte[] ws3="0".getBytes();
- while ((originalData[origLength-len3]==ws1[0] ||
- originalData[origLength-len3]==ws2[0] ||
- originalData[origLength-len3]==ws3[0]) && numZeroes < 512) {
- len3++;
- if (originalData[origLength-len3]==ws3[0])
- numZeroes++;
- }
- //System.out.println("Length3="+len3);
- }
-
- // overload the base object method so we don't have to copy
- // byte arrays around so much
- protected int output(java.io.OutputStream stream) throws java.io.IOException
- {
- int length = 0;
- String filterEntry = applyFilters();
- String preData=
- new String(this.number + " " + this.generation
- + " obj\n<< /Length " +
- (_data.size()+1) + " "
- + filterEntry + " " +
- "/Length1 " + len1 +
- " /Length2 " + (origLength-len3 -len1) +
- " /Length3 " + len3 +
- " >>\n");
-
byte[] p = preData.getBytes();
stream.write(p);
length += p.length;
- length += outputStreamData(stream);
- p = "endobj\n".getBytes();
- stream.write(p);
- length += p.length;
+ length += outputStreamData(stream);
+ p = "endobj\n".getBytes();
+ stream.write(p);
+ length += p.length;
System.out.println("Embedded Type1 font");
- return length;
+ return length;
+ }
+
+ public void setData(byte[] data, int size) throws java.io.IOException {
+ calcLengths(data);
+ _data.reset();
+ // System.out.println("Writing " + size + " bytes of font data");
+ _data.write(data, 0, size);
}
- public void setData(byte[] data, int size)
- throws java.io.IOException {
- calcLengths(data);
- _data.reset();
- //System.out.println("Writing " + size + " bytes of font data");
- _data.write(data, 0, size);
- }
}
diff --git a/src/org/apache/fop/pdf/PDFTTFStream.java b/src/org/apache/fop/pdf/PDFTTFStream.java
index 1b17e02f8..f56e5f587 100644
--- a/src/org/apache/fop/pdf/PDFTTFStream.java
+++ b/src/org/apache/fop/pdf/PDFTTFStream.java
@@ -1,91 +1,47 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
public class PDFTTFStream extends PDFStream {
- private int origLength;
-
- public PDFTTFStream(int num, int len) {
- super(num);
- origLength=len;
- }
- // overload the base object method so we don't have to copy
- // byte arrays around so much
- protected int output(java.io.OutputStream stream) throws java.io.IOException
- {
- int length = 0;
- String filterEntry = applyFilters();
- String preData=
- new String(this.number + " " + this.generation
- + " obj\n<< /Length " +
- (_data.size()+1) + " "
- + filterEntry + " " +
- "/Length1 " + origLength +
- " >>\n");
-
+ private int origLength;
+
+ public PDFTTFStream(int num, int len) {
+ super(num);
+ origLength = len;
+ }
+
+ // overload the base object method so we don't have to copy
+ // byte arrays around so much
+ protected int output(java.io.OutputStream stream)
+ throws java.io.IOException {
+ int length = 0;
+ String filterEntry = applyFilters();
+ String preData = new String(this.number + " " + this.generation
+ + " obj\n<< /Length "
+ + (_data.size() + 1) + " " + filterEntry
+ + " " + "/Length1 " + origLength
+ + " >>\n");
+
byte[] p = preData.getBytes();
stream.write(p);
length += p.length;
- length += outputStreamData(stream);
- p = "endobj\n".getBytes();
- stream.write(p);
- length += p.length;
- return length;
+ length += outputStreamData(stream);
+ p = "endobj\n".getBytes();
+ stream.write(p);
+ length += p.length;
+ return length;
+ }
+
+ public void setData(byte[] data, int size) throws java.io.IOException {
+ _data.reset();
+ System.out.println("Writing " + size + " bytes of font data");
+ _data.write(data, 0, size);
}
- public void setData(byte[] data, int size)
- throws java.io.IOException {
- _data.reset();
- System.out.println("Writing " + size + " bytes of font data");
- _data.write(data, 0, size);
- }
}
diff --git a/src/org/apache/fop/pdf/PDFUri.java b/src/org/apache/fop/pdf/PDFUri.java
index 9709fa684..85c1838b8 100644
--- a/src/org/apache/fop/pdf/PDFUri.java
+++ b/src/org/apache/fop/pdf/PDFUri.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "FOP" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.pdf;
@@ -56,36 +12,35 @@ package org.apache.fop.pdf;
*/
public class PDFUri extends PDFAction {
-
+
String uri;
/**
* create a Uri instance.
*
- * @param uri the uri to which the link should point
+ * @param uri the uri to which the link should point
*/
public PDFUri(String uri) {
- this.uri=uri;
+ this.uri = uri;
}
/**
* returns the action ncecessary for a uri
- *
+ *
* @return the action to place next to /A within a Link
*/
- public String getAction()
- {
- return "<< /URI ("+uri+")\n/S /URI >>";
+ public String getAction() {
+ return "<< /URI (" + uri + ")\n/S /URI >>";
}
/**
- * there is nothing to return for the toPDF method, as it should not be called
+ * there is nothing to return for the toPDF method, as it should not be called
*
* @return an empty string
*/
- public byte[] toPDF() {
- return new byte[0];
- }
-
+ public byte[] toPDF() {
+ return new byte[0];
+ }
+
}
diff --git a/src/org/apache/fop/pdf/PDFWArray.java b/src/org/apache/fop/pdf/PDFWArray.java
index be1ed8b8e..a391f45f3 100644
--- a/src/org/apache/fop/pdf/PDFWArray.java
+++ b/src/org/apache/fop/pdf/PDFWArray.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.pdf;
import java.util.Vector;
@@ -57,88 +14,100 @@ import java.util.Vector;
*/
public class PDFWArray {
- /** the metrics */
- private Vector entries;
-
- public PDFWArray() {
- entries = new Vector();
- }
-
- /**
- * add an entry for single starting CID.
- * i.e. in the form "c [w ...]"
- *
- * @param start the starting CID value.
- * @param metrics the metrics array.
- */
- public void addEntry(int start, int[] metrics) {
- entries.addElement(new Entry(start, metrics));
- }
-
- /**
- * add an entry for a range of CIDs (/W element on p 213)
- *
- * @param first the first CID in the range
- * @param last the last CID in the range
- * @param width the width for all CIDs in the range
- */
- public void addEntry(int first, int last, int width) {
- entries.addElement(new int[] {first, last, width});
- }
-
- /**
- * add an entry for a range of CIDs (/W2 element on p 210)
- *
- * @param first the first CID in the range
- * @param last the last CID in the range
- * @param width the width for all CIDs in the range
- * @param posX the x component for the vertical position vector
- * @param posY the y component for the vertical position vector
- */
- public void addEntry(int first, int last, int width, int posX, int posY) {
- entries.addElement(new int[] {first, last, width, posX, posY});
- }
-
- public byte[] toPDF() {
- return toPDFString().getBytes();
- }
-
- public String toPDFString() {
- StringBuffer p = new StringBuffer();
- p.append("[ ");
- int len = entries.size();
- for (int i = 0; i>\n";
+
+ // don't know if it's the good place (other objects can have references to it)
+ fopimage.close();
+
+ // push the pdf dictionary on the writer
+ byte[] pdfBytes = p.getBytes();
+ stream.write(pdfBytes);
+ length += pdfBytes.length;
+ // push all the image data on the writer and takes care of length for trailer
+ length += imgStream.outputStreamData(stream);
+
+ pdfBytes = ("endobj\n").getBytes();
+ stream.write(pdfBytes);
+ length += pdfBytes.length;
+ } catch (FopImageException imgex) {
+ MessageHandler.errorln("Error in XObject : "
+ + imgex.getMessage());
+ }
+
+ return length;
}
- p = p + dictEntries;
- p = p + ">>\n";
-
- // don't know if it's the good place (other objects can have references to it)
- fopimage.close();
-
- // push the pdf dictionary on the writer
- byte[] pdfBytes = p.getBytes();
- stream.write(pdfBytes);
- length += pdfBytes.length;
- // push all the image data on the writer and takes care of length for trailer
- length += imgStream.outputStreamData(stream);
-
- pdfBytes = ("endobj\n").getBytes();
- stream.write(pdfBytes);
- length += pdfBytes.length;
- } catch (FopImageException imgex) {
- MessageHandler.errorln("Error in XObject : " + imgex.getMessage());
- }
-
- return length;
- }
-
+
byte[] toPDF() {
-/* Not used any more
- String p = this.number + " " + this.generation + " obj\n";
- p = p + "<. For more information on the Apache
- Software Foundation, please see .
-
+/*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/
+
+/*
+ * -- $Id$ --
+ * ============================================================================
+ * The Apache Software License, Version 1.1
+ * ============================================================================
+ *
+ * Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * 3. The end-user documentation included with the redistribution, if any, must
+ * include the following acknowledgment: "This product includes software
+ * developed by the Apache Software Foundation (http://www.apache.org/)."
+ * Alternately, this acknowledgment may appear in the software itself, if
+ * and wherever such third-party acknowledgments normally appear.
+ *
+ * 4. The names "Fop" and "Apache Software Foundation" must not be used to
+ * endorse or promote products derived from this software without prior
+ * written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache", nor may
+ * "Apache" appear in their name, without prior written permission of the
+ * Apache Software Foundation.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
+ * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This software consists of voluntary contributions made by many individuals
+ * on behalf of the Apache Software Foundation and was originally created by
+ * James Tauber . For more information on the Apache
+ * Software Foundation, please see .
+ *
*/
package org.apache.fop.render;
@@ -63,61 +65,96 @@ import java.io.IOException;
/**
* interface implement by all renderers.
- *
+ *
* a Renderer implementation takes areas/spaces and produces output in
* some format.
*/
public interface Renderer {
-
- /** set up the given FontInfo */
+
+ /**
+ * set up the given FontInfo
+ */
public void setupFontInfo(FontInfo fontInfo);
- /** set up renderer options */
- public void setOptions(java.util.Hashtable options);
-
- /** set the producer of the rendering */
+ /**
+ * set up renderer options
+ */
+ public void setOptions(java.util.Hashtable options);
+
+ /**
+ * set the producer of the rendering
+ */
public void setProducer(String producer);
- /** render the given area tree to the given stream */
- public void render(AreaTree areaTree, OutputStream stream) throws IOException, FOPException;
-
- /** render the given area container */
+ /**
+ * render the given area tree to the given stream
+ */
+ public void render(AreaTree areaTree,
+ OutputStream stream) throws IOException, FOPException;
+
+ /**
+ * render the given area container
+ */
public void renderAreaContainer(AreaContainer area);
- /** render the given area container */
+ /**
+ * render the given area container
+ */
public void renderBodyAreaContainer(BodyAreaContainer area);
- /** render the given span area */
- public void renderSpanArea(SpanArea area);
+ /**
+ * render the given span area
+ */
+ public void renderSpanArea(SpanArea area);
- /** render the given block area */
+ /**
+ * render the given block area
+ */
public void renderBlockArea(BlockArea area);
- /** render the given display space */
+ /**
+ * render the given display space
+ */
public void renderDisplaySpace(DisplaySpace space);
- /** render the given SVG area */
+ /**
+ * render the given SVG area
+ */
public void renderSVGArea(SVGArea area);
- /** render a foreign object area */
+ /**
+ * render a foreign object area
+ */
public void renderForeignObjectArea(ForeignObjectArea area);
- /** render the given image area */
+ /**
+ * render the given image area
+ */
public void renderImageArea(ImageArea area);
- /** render the given inline area */
+ /**
+ * render the given inline area
+ */
public void renderWordArea(WordArea area);
- /** render the given inline space */
+ /**
+ * render the given inline space
+ */
public void renderInlineSpace(InlineSpace space);
- /** render the given line area */
+ /**
+ * render the given line area
+ */
public void renderLineArea(LineArea area);
- /** render the given page */
+ /**
+ * render the given page
+ */
public void renderPage(Page page);
- /** render the given leader area */
+ /**
+ * render the given leader area
+ */
public void renderLeaderArea(LeaderArea area);
}
diff --git a/src/org/apache/fop/render/awt/AWTFontMetrics.java b/src/org/apache/fop/render/awt/AWTFontMetrics.java
index 1b1c7f4db..33a79fe8b 100644
--- a/src/org/apache/fop/render/awt/AWTFontMetrics.java
+++ b/src/org/apache/fop/render/awt/AWTFontMetrics.java
@@ -1,50 +1,13 @@
/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
package org.apache.fop.render.awt;
-//FOP
+// FOP
import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.layout.FontInfo;
import org.apache.fop.layout.FontDescriptor;
@@ -63,78 +26,79 @@ import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
/**
-* This is a FontMetrics to be used for AWT rendering.
-* It instanciates a font, depening on famil and style
-* values. The java.awt.FontMetrics for this font is then
-* created to be used for the actual measurement.
-* Since layout is word by word and since it is expected that
-* two subsequent words often share the same style, the
-* Font and FontMetrics is buffered and only changed if needed.
-*
-* Since FontState and FontInfo multiply all factors by
-* size, we assume a "standard" font of FONT_SIZE.
-*/
+ * This is a FontMetrics to be used for AWT rendering.
+ * It instanciates a font, depening on famil and style
+ * values. The java.awt.FontMetrics for this font is then
+ * created to be used for the actual measurement.
+ * Since layout is word by word and since it is expected that
+ * two subsequent words often share the same style, the
+ * Font and FontMetrics is buffered and only changed if needed.
+ *
+ * Since FontState and FontInfo multiply all factors by
+ * size, we assume a "standard" font of FONT_SIZE.
+ */
public class AWTFontMetrics {
+
/**
* Font size standard used for metric measurements
*/
public static final int FONT_SIZE = 1;
/**
- * This factor multiplies the calculated values to scale
- * to FOP internal measurements
- */
+ * This factor multiplies the calculated values to scale
+ * to FOP internal measurements
+ */
public static final int FONT_FACTOR = (1000 * 1000) / FONT_SIZE;
/**
- * The width of all 256 character, if requested
- */
+ * The width of all 256 character, if requested
+ */
private int width[] = null;
/**
- * The typical height of a small cap latter
- */
+ * The typical height of a small cap latter
+ */
private int xHeight = 0;
/**
- * Buffered font.
- * f1 is bufferd for metric measurements during layout.
- * fSized is buffered for display purposes
- */
- private Font f1 = null; //, fSized = null;
+ * Buffered font.
+ * f1 is bufferd for metric measurements during layout.
+ * fSized is buffered for display purposes
+ */
+ private Font f1 = null; // , fSized = null;
/**
- * The family type of the font last used
- */
+ * The family type of the font last used
+ */
private String family = "";
/**
- * The style of the font last used
- */
+ * The style of the font last used
+ */
private int style = 0;
/**
- * The size of the font last used
- */
+ * The size of the font last used
+ */
private float size = 0;
/**
- * The FontMetrics object used to calculate character width etc.
- */
+ * The FontMetrics object used to calculate character width etc.
+ */
private FontMetrics fmt = null;
/**
- * Temp graphics object needed to get the font metrics
- */
+ * Temp graphics object needed to get the font metrics
+ */
Graphics2D graphics;
/**
- * Constructs a new Font-metrics.
- * @param parent an temp graphics object - this is needed so
- * that we can get an instance of
- * java.awt.FontMetrics
- */
+ * Constructs a new Font-metrics.
+ * @param parent an temp graphics object - this is needed so
+ * that we can get an instance of
+ * java.awt.FontMetrics
+ */
public AWTFontMetrics(Graphics2D graphics) {
this.graphics = graphics;
}
@@ -148,11 +112,12 @@ public class AWTFontMetrics {
*/
public int getAscender(String family, int style, int size) {
setFont(family, style, size);
- //return (int)(FONT_FACTOR * fmt.getAscent());
+ // return (int)(FONT_FACTOR * fmt.getAscent());
// workaround for sun bug on FontMetric.getAscent()
// http://developer.java.sun.com/developer/bugParade/bugs/4399887.html
- int realAscent = fmt.getAscent() - (fmt.getDescent() + fmt.getLeading());
+ int realAscent = fmt.getAscent()
+ - (fmt.getDescent() + fmt.getLeading());
return FONT_FACTOR * realAscent;
}
@@ -191,8 +156,8 @@ public class AWTFontMetrics {
}
/**
- * Returns width (in 1/1000ths of point size) of character at
- * code point i
+ * Returns width (in 1/1000ths of point size) of character at
+ * code point i
* @param i the character for which to get the width
* @param family font family (jave name) to use
* @param style font style (jave def.) to use
@@ -224,7 +189,7 @@ public class AWTFontMetrics {
width = new int[256];
}
setFont(family, style, size);
- for (i = 0 ; i < 256 ; i++) {
+ for (i = 0; i < 256; i++) {
width[i] = FONT_FACTOR * fmt.charWidth(i);
}
return width;
@@ -249,10 +214,10 @@ public class AWTFontMetrics {
fmt = graphics.getFontMetrics(f1);
changed = true;
} else {
- if ((this.style != style) || !this.family.equals(family) ||
- this.size != s) {
+ if ((this.style != style) ||!this.family.equals(family)
+ || this.size != s) {
if (family.equals(this.family)) {
- f1 = f1.deriveFont(style, (float) s);
+ f1 = f1.deriveFont(style, (float)s);
} else
f1 = new Font(family, style, s);
fmt = graphics.getFontMetrics(f1);
@@ -263,7 +228,7 @@ public class AWTFontMetrics {
if (changed) {
layout = new TextLayout("m", f1, graphics.getFontRenderContext());
rect = layout.getBounds();
- xHeight = (int) rect.getHeight();
+ xHeight = (int)rect.getHeight();
}
// save the family and style for later comparison
this.family = family;
@@ -279,7 +244,7 @@ public class AWTFontMetrics {
* This is here, so that the font-mapping
* of FOP-defined fonts to java-fonts can be done
* in one place and does not need to occur in
- *AWTFontRenderer.
+ * AWTFontRenderer.
* @param family font family (jave name) to use
* @param style font style (jave def.) to use
* @param size font size
@@ -290,13 +255,16 @@ public class AWTFontMetrics {
setFont(family, style, size);
return f1;
- /*if( setFont(family,style, size) ) fSized = null;
- if( fSized == null || this.size != size ) {
- fSized = f1.deriveFont( size / 1000f );
- }
- this.size = size;
- return fSized;*/
+ /*
+ * if( setFont(family,style, size) ) fSized = null;
+ * if( fSized == null || this.size != size ) {
+ * fSized = f1.deriveFont( size / 1000f );
+ * }
+ * this.size = size;
+ * return fSized;
+ */
}
+
}
diff --git a/src/org/apache/fop/render/awt/AWTRenderer.java b/src/org/apache/fop/render/awt/AWTRenderer.java
index e182c38f7..ef2ef9f63 100644
--- a/src/org/apache/fop/render/awt/AWTRenderer.java
+++ b/src/org/apache/fop/render/awt/AWTRenderer.java
@@ -1,12 +1,17 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.awt;
/*
- originally contributed by
- Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
- Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
- Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
+ * originally contributed by
+ * Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
+ * Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
+ * Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
*/
import org.apache.fop.layout.*;
@@ -86,7 +91,7 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
protected float currentBlue = 0;
/**
- * The parent component, used to set up the font.
+ * The parent component, used to set up the font.
* This is needed as FontSetup needs a live AWT component
* in order to generate valid font measures.
*/
@@ -107,20 +112,24 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
*/
private int currentAreaContainerXPosition = 0;
- /** options */
- protected Hashtable options;
+ /**
+ * options
+ */
+ protected Hashtable options;
- /** set up renderer options */
- public void setOptions(Hashtable options) {
- this.options = options;
- }
+ /**
+ * set up renderer options
+ */
+ public void setOptions(Hashtable options) {
+ this.options = options;
+ }
public AWTRenderer(Translator aRes) {
res = aRes;
}
/**
- * Sets parent component which is used to set up the font.
+ * Sets parent component which is used to set up the font.
* This is needed as FontSetup needs a live AWT component
* in order to generate valid font measures.
* @param parent the live AWT component reference
@@ -161,52 +170,48 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
* @param g the green component
* @param b the blue component
*/
-
- // corrected 7/13/01 aml,rlc to properly handle thickness
- //
- protected void addLine(int x1, int y1, int x2, int y2, int th,
- float r, float g, float b)
- {
- graphics.setColor(new Color (r, g, b));
+
+ // corrected 7/13/01 aml,rlc to properly handle thickness
+ //
+ protected void addLine(int x1, int y1, int x2, int y2, int th, float r,
+ float g, float b) {
+ graphics.setColor(new Color(r, g, b));
int x = x1;
int y = y1;
int height, width;
- if (x1 == x2) //vertical line
- {
- height = y2 - y1;
- if (height > 0) //y coordinates are reversed between fo and AWT
- {
- height = -height;
- y = y2;
- }
- width = th;
- if (width < 0)
- {
- width = -width;
- x -= width;
- }
- }
- else //horizontal line
- {
- width = x2 - x1;
- if (width < 0)
- {
- width = -width;
- x = x2;
- }
- height = th;
- if (height > 0) //y coordinates are reversed between fo and AWT
- {
- height = -height;
- y -= height;
- }
+ if (x1 == x2) // vertical line
+ {
+ height = y2 - y1;
+ if (height > 0) // y coordinates are reversed between fo and AWT
+ {
+ height = -height;
+ y = y2;
+ }
+ width = th;
+ if (width < 0) {
+ width = -width;
+ x -= width;
+ }
+ } else // horizontal line
+ {
+ width = x2 - x1;
+ if (width < 0) {
+ width = -width;
+ x = x2;
+ }
+ height = th;
+ if (height > 0) // y coordinates are reversed between fo and AWT
+ {
+ height = -height;
+ y -= height;
+ }
}
- addRect (x, y, width, height, false);
-
-// // graphics.setColor(Color.red);
-// graphics.drawLine((int)(x1 / 1000f),
-// pageHeight - (int)(y1 / 1000f), (int)(x2 / 1000f),
-// pageHeight - (int)(y2 / 1000f));
+ addRect(x, y, width, height, false);
+
+ // // graphics.setColor(Color.red);
+ // graphics.drawLine((int)(x1 / 1000f),
+ // pageHeight - (int)(y1 / 1000f), (int)(x2 / 1000f),
+ // pageHeight - (int)(y2 / 1000f));
}
@@ -221,17 +226,17 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
* @param g the green component
* @param b the blue component
*/
-
- // changed by aml/rlc to use helper function that
- // corrects for integer roundoff, and to remove 3D effect
-
- protected void addRect(int x, int y, int w, int h, float r,
- float g, float b) {
- graphics.setColor(new Color (r, g, b));
+
+ // changed by aml/rlc to use helper function that
+ // corrects for integer roundoff, and to remove 3D effect
+
+ protected void addRect(int x, int y, int w, int h, float r, float g,
+ float b) {
+ graphics.setColor(new Color(r, g, b));
// graphics.setColor(Color.green);
- addRect (x, y, w, h, true);
+ addRect(x, y, w, h, true);
}
-
+
/**
* draw a filled rectangle
*
@@ -246,16 +251,15 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
* @param fg the green component of the fill
* @param fb the blue component of the fill
*/
-
- // changed by aml/rlc to use helper function that
- // corrects for integer roundoff
- protected void addRect(int x, int y, int w, int h, float r,
- float g, float b, float fr, float fg, float fb)
- {
- graphics.setColor(new Color (r, g, b));
- addRect (x, y, w, h, true);
- graphics.setColor(new Color (fr, fg, fb));
- addRect (x, y, w, h, false);
+
+ // changed by aml/rlc to use helper function that
+ // corrects for integer roundoff
+ protected void addRect(int x, int y, int w, int h, float r, float g,
+ float b, float fr, float fg, float fb) {
+ graphics.setColor(new Color(r, g, b));
+ addRect(x, y, w, h, true);
+ graphics.setColor(new Color(fr, fg, fb));
+ addRect(x, y, w, h, false);
}
/**
@@ -267,19 +271,19 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
* @param h the height in millipoints
* @param drawAsOutline true for draw, false for fill
*/
-
- // helper function by aml/rlc to correct integer roundoff problems
- //
- protected void addRect(int x, int y, int w, int h, boolean drawAsOutline)
- {
- int startx = (x + 500)/ 1000;
+
+ // helper function by aml/rlc to correct integer roundoff problems
+ //
+ protected void addRect(int x, int y, int w, int h,
+ boolean drawAsOutline) {
+ int startx = (x + 500) / 1000;
int starty = pageHeight - ((y + 500) / 1000);
int endx = (x + w + 500) / 1000;
int endy = pageHeight - ((y + h + 500) / 1000);
if (drawAsOutline)
- graphics.drawRect(startx, starty, endx - startx, endy - starty);
+ graphics.drawRect(startx, starty, endx - startx, endy - starty);
else
- graphics.fillRect(startx, starty, endx - startx, endy - starty);
+ graphics.fillRect(startx, starty, endx - startx, endy - starty);
}
/**
@@ -288,9 +292,8 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
* Choose pages
* Zoom factor
* Page format / Landscape or Portrait
- **/
- public void transform(Graphics2D g2d, double zoomPercent,double angle)
- {
+ */
+ public void transform(Graphics2D g2d, double zoomPercent, double angle) {
AffineTransform at = g2d.getTransform();
at.rotate(angle);
at.scale(zoomPercent / 100.0, zoomPercent / 100.0);
@@ -347,16 +350,16 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
public void render(AreaTree areaTree,
int aPageNumber) throws IOException {
tree = areaTree;
- Page page = (Page) areaTree.getPages().elementAt(aPageNumber);
+ Page page = (Page)areaTree.getPages().elementAt(aPageNumber);
- pageWidth = (int)((float) page.getWidth() / 1000f + .5);
- pageHeight = (int)((float) page.getHeight() / 1000f + .5);
+ pageWidth = (int)((float)page.getWidth() / 1000f + .5);
+ pageHeight = (int)((float)page.getHeight() / 1000f + .5);
- pageImage = new BufferedImage(
- (int)((pageWidth * (int) scaleFactor) / 100),
- (int)((pageHeight * (int) scaleFactor) / 100),
- BufferedImage.TYPE_INT_RGB);
+ pageImage =
+ new BufferedImage((int)((pageWidth * (int)scaleFactor) / 100),
+ (int)((pageHeight * (int)scaleFactor) / 100),
+ BufferedImage.TYPE_INT_RGB);
graphics = pageImage.createGraphics();
@@ -389,9 +392,9 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
// SG: Wollen wir Links abbilden?
/*
- if (page.hasLinks()) {
- ....
- }
+ * if (page.hasLinks()) {
+ * ....
+ * }
*/
}
@@ -400,24 +403,24 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
int saveY = this.currentYPosition;
int saveX = this.currentAreaContainerXPosition;
- if (area.getPosition() ==
- org.apache.fop.fo.properties.Position.ABSOLUTE) {
+ if (area.getPosition()
+ == org.apache.fop.fo.properties.Position.ABSOLUTE) {
// Y position is computed assuming positive Y axis, adjust
- //for negative postscript one
- this.currentYPosition =
- area.getYPosition() - 2 * area.getPaddingTop() -
- 2 * area.getBorderTopWidth();
+ // for negative postscript one
+ this.currentYPosition = area.getYPosition()
+ - 2 * area.getPaddingTop()
+ - 2 * area.getBorderTopWidth();
this.currentAreaContainerXPosition = area.getXPosition();
- } else if (area.getPosition() ==
- org.apache.fop.fo.properties.Position.RELATIVE) {
+ } else if (area.getPosition()
+ == org.apache.fop.fo.properties.Position.RELATIVE) {
this.currentYPosition -= area.getYPosition();
this.currentAreaContainerXPosition += area.getXPosition();
- } else if (area.getPosition() ==
- org.apache.fop.fo.properties.Position.STATIC) {
- this.currentYPosition -=
- area.getPaddingTop() + area.getBorderTopWidth();
- this.currentAreaContainerXPosition +=
- area.getPaddingLeft() + area.getBorderLeftWidth();
+ } else if (area.getPosition()
+ == org.apache.fop.fo.properties.Position.STATIC) {
+ this.currentYPosition -= area.getPaddingTop()
+ + area.getBorderTopWidth();
+ this.currentAreaContainerXPosition += area.getPaddingLeft()
+ + area.getBorderLeftWidth();
}
doFrame(area);
@@ -425,12 +428,12 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
org.apache.fop.layout.Box b =
- (org.apache.fop.layout.Box) e.nextElement();
+ (org.apache.fop.layout.Box)e.nextElement();
b.render(this);
}
- if (area.getPosition() !=
- org.apache.fop.fo.properties.Position.STATIC) {
+ if (area.getPosition()
+ != org.apache.fop.fo.properties.Position.STATIC) {
this.currentYPosition = saveY;
this.currentAreaContainerXPosition = saveX;
} else {
@@ -444,12 +447,11 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
renderAreaContainer(area.getFootnoteReferenceArea());
// main reference area
- Enumeration e =
- area.getMainReferenceArea().getChildren().elements();
+ Enumeration e = area.getMainReferenceArea().getChildren().elements();
while (e.hasMoreElements()) {
org.apache.fop.layout.Box b =
- (org.apache.fop.layout.Box) e.nextElement();
- b.render(this); // span areas
+ (org.apache.fop.layout.Box)e.nextElement();
+ b.render(this); // span areas
}
}
@@ -458,8 +460,8 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
org.apache.fop.layout.Box b =
- (org.apache.fop.layout.Box) e.nextElement();
- b.render(this); // column areas
+ (org.apache.fop.layout.Box)e.nextElement();
+ b.render(this); // column areas
}
}
@@ -469,7 +471,7 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
w = area.getContentWidth();
if (area instanceof BlockArea) {
- rx += ((BlockArea) area).getStartIndent();
+ rx += ((BlockArea)area).getStartIndent();
}
h = area.getContentHeight();
@@ -484,8 +486,8 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
// I'm not sure I should have to check for bg being null
// but I do
if ((bg != null) && (bg.alpha() == 0)) {
- this.addRect(rx, ry, w, -h, bg.red(), bg.green(),
- bg.blue(), bg.red(), bg.green(), bg.blue());
+ this.addRect(rx, ry, w, -h, bg.red(), bg.green(), bg.blue(),
+ bg.red(), bg.green(), bg.blue());
}
rx = rx - area.getBorderLeftWidth();
@@ -498,7 +500,7 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
if (area.getBorderTopWidth() != 0) {
borderColor = bp.getBorderColor(BorderAndPadding.TOP);
- // addLine(rx, ry, rx + w, ry, area.getBorderTopWidth(), // corrected aml/rlc
+ // addLine(rx, ry, rx + w, ry, area.getBorderTopWidth(), // corrected aml/rlc
addLine(rx, ry, rx + w, ry, -area.getBorderTopWidth(),
borderColor.red(), borderColor.green(),
borderColor.blue());
@@ -514,16 +516,17 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
if (area.getBorderRightWidth() != 0) {
borderColor = bp.getBorderColor(BorderAndPadding.RIGHT);
addLine(rx + w, ry, rx + w, ry - h,
-// area.getBorderRightWidth(), borderColor.red(), // corrected aml/rlc
- -area.getBorderRightWidth(), borderColor.red(),
- borderColor.green(), borderColor.blue());
+ // area.getBorderRightWidth(), borderColor.red(), // corrected aml/rlc
+ -area.getBorderRightWidth(), borderColor.red(),
+ borderColor.green(),
+ borderColor.blue());
}
if (area.getBorderBottomWidth() != 0) {
borderColor = bp.getBorderColor(BorderAndPadding.BOTTOM);
- addLine(rx, ry - h, rx + w, ry - h,
- area.getBorderBottomWidth(), borderColor.red(),
- borderColor.green(), borderColor.blue());
+ addLine(rx, ry - h, rx + w, ry - h, area.getBorderBottomWidth(),
+ borderColor.red(), borderColor.green(),
+ borderColor.blue());
}
}
@@ -531,35 +534,40 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
protected Rectangle2D getBounds(org.apache.fop.layout.Area a) {
return new Rectangle2D.Double(currentAreaContainerXPosition,
- currentYPosition, a.getAllocationWidth(), a.getHeight());
+ currentYPosition,
+ a.getAllocationWidth(), a.getHeight());
}
-/*
+
+ /*
+ * public void renderBlockArea(BlockArea area) {
+ * doFrame(area);
+ * Enumeration e = area.getChildren().elements();
+ * while (e.hasMoreElements()) {
+ * org.apache.fop.layout.Box b =
+ * (org.apache.fop.layout.Box) e.nextElement();
+ * b.render(this);
+ * }
+ * }
+ */
public void renderBlockArea(BlockArea area) {
+ this.currentYPosition -= (area.getPaddingTop()
+ + area.getBorderTopWidth());
doFrame(area);
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
org.apache.fop.layout.Box b =
- (org.apache.fop.layout.Box) e.nextElement();
+ (org.apache.fop.layout.Box)e.nextElement();
b.render(this);
}
+ this.currentYPosition -= (area.getPaddingBottom()
+ + area.getBorderBottomWidth());
}
-*/
- public void renderBlockArea(BlockArea area) {
- this.currentYPosition -= (area.getPaddingTop() + area.getBorderTopWidth());
- doFrame(area);
- Enumeration e = area.getChildren().elements();
- while (e.hasMoreElements()) {
- org.apache.fop.layout.Box b =
- (org.apache.fop.layout.Box) e.nextElement();
- b.render(this);
- }
- this.currentYPosition -= (area.getPaddingBottom() + area.getBorderBottomWidth());
- }
public void setupFontInfo(FontInfo fontInfo) {
// create a temp Image to test font metrics on
- BufferedImage fontImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
+ BufferedImage fontImage =
+ new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
FontSetup.setup(fontInfo, fontImage.createGraphics());
}
@@ -571,11 +579,9 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
// correct integer roundoff (aml/rlc)
- public void renderImageArea(ImageArea area)
- {
+ public void renderImageArea(ImageArea area) {
- int x = currentAreaContainerXPosition +
- area.getXOffset();
+ int x = currentAreaContainerXPosition + area.getXOffset();
int y = currentYPosition;
int w = area.getContentWidth();
@@ -585,35 +591,34 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
if (img == null) {
MessageHandler.logln("Error while loading image : area.getImage() is null");
-
- // correct integer roundoff
- // graphics.drawRect(x / 1000, pageHeight - y / 1000,
- // w / 1000, h / 1000);
- addRect (x, y, w, h, true); // use helper function
-
-
+
+ // correct integer roundoff
+ // graphics.drawRect(x / 1000, pageHeight - y / 1000,
+ // w / 1000, h / 1000);
+ addRect(x, y, w, h, true); // use helper function
+
+
java.awt.Font f = graphics.getFont();
- java.awt.Font smallFont =
- new java.awt.Font(f.getFontName(), f.getStyle(), 8);
-
+ java.awt.Font smallFont = new java.awt.Font(f.getFontName(),
+ f.getStyle(), 8);
+
graphics.setFont(smallFont);
-
- // correct integer roundoff // aml/rlc
- // graphics.drawString("area.getImage() is null", x / 1000,
- // pageHeight - y / 1000);
-
+
+ // correct integer roundoff // aml/rlc
+ // graphics.drawString("area.getImage() is null", x / 1000,
+ // pageHeight - y / 1000);
+
graphics.drawString("area.getImage() is null", (x + 500) / 1000,
pageHeight - (y + 500) / 1000);
-
-
+
+
graphics.setFont(f);
} else {
if (img instanceof SVGImage) {
try {
- SVGDocument svg = ((SVGImage) img).getSVGDocument();
- renderSVGDocument(svg, (int) x, (int) y);
- } catch (FopImageException e) {
- }
+ SVGDocument svg = ((SVGImage)img).getSVGDocument();
+ renderSVGDocument(svg, (int)x, (int)y);
+ } catch (FopImageException e) {}
} else {
String urlString = img.getURL();
@@ -622,20 +627,21 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
ImageIcon icon = new ImageIcon(url);
Image image = icon.getImage();
-
-// correct integer roundoff aml/rlc
-// graphics.drawImage(image, x / 1000,
-// pageHeight - y / 1000, w / 1000, h / 1000,
-// null);
-
- int startx = (x + 500)/ 1000;
+
+ // correct integer roundoff aml/rlc
+ // graphics.drawImage(image, x / 1000,
+ // pageHeight - y / 1000, w / 1000, h / 1000,
+ // null);
+
+ int startx = (x + 500) / 1000;
int starty = pageHeight - ((y + 500) / 1000);
int endx = (x + w + 500) / 1000;
int endy = pageHeight - ((y + h + 500) / 1000);
-
- //reverse start and end y because h is positive
- graphics.drawImage(image, startx, starty, endx - startx, starty - endy, null);
-
+
+ // reverse start and end y because h is positive
+ graphics.drawImage(image, startx, starty, endx - startx,
+ starty - endy, null);
+
} catch (MalformedURLException mue) {
// cannot normally occur because, if URL is wrong, constructing FopImage
// will already have failed earlier on
@@ -660,21 +666,21 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
FontMetricsMapper mapper;
try {
- mapper = (FontMetricsMapper)
- area.getFontState().getFontInfo().getMetricsFor(name);
+ mapper =
+ (FontMetricsMapper)area.getFontState().getFontInfo().getMetricsFor(name);
} catch (FOPException iox) {
- mapper = new FontMetricsMapper("MonoSpaced",
- java.awt.Font.PLAIN, graphics);
+ mapper = new FontMetricsMapper("MonoSpaced", java.awt.Font.PLAIN,
+ graphics);
}
- if ((!name.equals(this.currentFontName)) ||
- (size != this.currentFontSize)) {
+ if ((!name.equals(this.currentFontName))
+ || (size != this.currentFontSize)) {
this.currentFontName = name;
this.currentFontSize = size;
}
- if ((red != this.currentRed) || (green != this.currentGreen) ||
- (blue != this.currentBlue)) {
+ if ((red != this.currentRed) || (green != this.currentGreen)
+ || (blue != this.currentBlue)) {
this.currentRed = red;
this.currentGreen = green;
this.currentBlue = blue;
@@ -684,8 +690,9 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
int bl = this.currentYPosition;
- String s;// = area.getText();
- if (area.getPageNumberID() != null) { // this text is a page number, so resolve it
+ String s; // = area.getText();
+ if (area.getPageNumberID()
+ != null) { // this text is a page number, so resolve it
s = tree.getIDReferences().getPageNumber(area.getPageNumberID());
if (s == null) {
s = "";
@@ -699,9 +706,8 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
java.awt.Font f = mapper.getFont(size);
if (saveColor != null) {
- if (saveColor.getRed() != red ||
- saveColor.getGreen() != green ||
- saveColor.getBlue() != blue) {
+ if (saveColor.getRed() != red || saveColor.getGreen() != green
+ || saveColor.getBlue() != blue) {
saveColor = new Color(red, green, blue);
}
} else {
@@ -716,11 +722,11 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
TextAttribute.UNDERLINE_ON);
}
AttributedCharacterIterator iter = ats.getIterator();
-
-// correct integer roundoff
-// graphics.drawString(iter, rx / 1000f,
-// (int)(pageHeight - bl / 1000f));
-
+
+ // correct integer roundoff
+ // graphics.drawString(iter, rx / 1000f,
+ // (int)(pageHeight - bl / 1000f));
+
graphics.drawString(iter, (rx + 500) / 1000,
(int)(pageHeight - (bl + 500) / 1000));
@@ -747,9 +753,9 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
org.apache.fop.layout.Box b =
- (org.apache.fop.layout.Box) e.nextElement();
+ (org.apache.fop.layout.Box)e.nextElement();
if (b instanceof InlineArea) {
- InlineArea ia = (InlineArea) b;
+ InlineArea ia = (InlineArea)b;
this.currentYPosition = ry - ia.getYOffset();
} else {
this.currentYPosition = ry - area.getPlacementOffset();
@@ -765,9 +771,9 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
*
* @param area area to render
*/
-
- // call to addRect corrected by aml/rlc
-
+
+ // call to addRect corrected by aml/rlc
+
public void renderLeaderArea(LeaderArea area) {
int rx = this.currentXPosition;
@@ -775,21 +781,21 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
int w = area.getLeaderLength();
int h = area.getHeight();
int th = area.getRuleThickness();
- int st = area.getRuleStyle(); //not used at the moment
+ int st = area.getRuleStyle(); // not used at the moment
float r = area.getRed();
float g = area.getGreen();
float b = area.getBlue();
Color oldColor = graphics.getColor();
graphics.setColor(new Color(r, g, b));
-
-// use helper function to correct integer roundoff - aml/rlc
-// graphics.fillRect((int)(rx / 1000f),
-// (int)(pageHeight - ry / 1000f), (int)(w / 1000f),
-// (int)(th / 1000f));
-
- addRect (rx, ry, w, -th, false); // NB addRect expects negative height
-
+
+ // use helper function to correct integer roundoff - aml/rlc
+ // graphics.fillRect((int)(rx / 1000f),
+ // (int)(pageHeight - ry / 1000f), (int)(w / 1000f),
+ // (int)(th / 1000f));
+
+ addRect(rx, ry, w, -th, false); // NB addRect expects negative height
+
graphics.setColor(oldColor);
this.currentXPosition += area.getContentWidth();
}
@@ -813,11 +819,11 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
GraphicsNodeRenderContext rc = getRenderContext();
BridgeContext ctx = new BridgeContext(userAgent, rc);
GraphicsNode root;
-
- // correct integer roundoff aml/rlc
- // graphics.translate(x / 1000f, pageHeight - y / 1000f);
+
+ // correct integer roundoff aml/rlc
+ // graphics.translate(x / 1000f, pageHeight - y / 1000f);
graphics.translate((x + 500) / 1000, pageHeight - (y + 500) / 1000);
-
+
graphics.setRenderingHints(rc.getRenderingHints());
try {
root = builder.build(ctx, doc);
@@ -825,11 +831,11 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
} catch (Exception e) {
e.printStackTrace();
}
-
- // correct integer roundoff aml/rlc
-// graphics.translate(-x / 1000f, y / 1000f - pageHeight);
+
+ // correct integer roundoff aml/rlc
+ // graphics.translate(-x / 1000f, y / 1000f - pageHeight);
graphics.translate(-(x + 500) / 1000, (y + 500) / 1000 - pageHeight);
-
+
}
public GraphicsNodeRenderContext getRenderContext() {
@@ -843,17 +849,17 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
FontRenderContext fontRenderContext =
- new FontRenderContext(new AffineTransform(), true,
- true);
+ new FontRenderContext(new AffineTransform(), true, true);
TextPainter textPainter = new StrokingTextPainter();
GraphicsNodeRableFactory gnrFactory =
- new ConcreteGraphicsNodeRableFactory();
+ new ConcreteGraphicsNodeRableFactory();
- nodeRenderContext = new GraphicsNodeRenderContext(
- new AffineTransform(), null, hints,
- fontRenderContext, textPainter, gnrFactory);
+ nodeRenderContext =
+ new GraphicsNodeRenderContext(new AffineTransform(), null,
+ hints, fontRenderContext,
+ textPainter, gnrFactory);
}
return nodeRenderContext;
@@ -872,8 +878,8 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
Graphics2D oldGraphics = graphics;
int oldPageNumber = pageNumber;
- graphics = (Graphics2D) g;
- Page aPage = (Page) tree.getPages().elementAt(pageIndex);
+ graphics = (Graphics2D)g;
+ Page aPage = (Page)tree.getPages().elementAt(pageIndex);
renderPage(aPage);
graphics = oldGraphics;
@@ -885,11 +891,11 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
}
public PageFormat getPageFormat(int pageIndex)
- throws IndexOutOfBoundsException {
+ throws IndexOutOfBoundsException {
if (pageIndex >= tree.getPages().size())
return null;
- Page page = (Page) tree.getPages().elementAt(pageIndex);
+ Page page = (Page)tree.getPages().elementAt(pageIndex);
PageFormat pageFormat = new PageFormat();
Paper paper = new Paper();
@@ -898,14 +904,11 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
// if the width is greater than the height assume lanscape mode
// and swap the width and height values in the paper format
- if(width > height)
- {
+ if (width > height) {
paper.setImageableArea(0, 0, height / 1000d, width / 1000d);
paper.setSize(height / 1000d, width / 1000d);
pageFormat.setOrientation(PageFormat.LANDSCAPE);
- }
- else
- {
+ } else {
paper.setImageableArea(0, 0, width / 1000d, height / 1000d);
paper.setSize(width / 1000d, height / 1000d);
pageFormat.setOrientation(PageFormat.PORTRAIT);
@@ -915,7 +918,7 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
}
public Printable getPrintable(int pageIndex)
- throws IndexOutOfBoundsException {
+ throws IndexOutOfBoundsException {
return this;
}
@@ -936,42 +939,40 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
* Draws an image.
* TODO: protect other image formats (JIMI)
*/
-/* public void renderImage(String href, float x, float y, float width,
- float height, Vector transform) {
- // What is with transformations?
- try {
- URL url = new URL(href);
- ImageIcon imageIcon = new ImageIcon(url);
-
- AffineTransform fullTransform = new AffineTransform();
- AffineTransform aTransform;
-
- transform = (transform == null) ? new Vector() : transform;
- for (int i = 0; i < transform.size(); i++) {
- org.w3c.dom.svg.SVGTransform t =
- (org.w3c.dom.svg.SVGTransform)
- transform.elementAt(i);
- SVGMatrix matrix = t.getMatrix();
- aTransform = new AffineTransform(matrix.getA(),
- matrix.getB(), matrix.getC(), matrix.getD(),
- matrix.getE(), matrix.getF());
- fullTransform.concatenate(aTransform);
- }
-
- BufferedImage bi = new BufferedImage((int) width, (int) height,
- BufferedImage.TYPE_INT_RGB);
- Graphics2D g2d = bi.createGraphics();
- BufferedImageOp bop = new AffineTransformOp(fullTransform,
- AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
- g2d.drawImage(imageIcon.getImage(), 0, 0, (int) width,
- (int) height, imageIcon.getImageObserver());
- graphics.drawImage(bi, bop, (int) x, (int) y);
- } catch (Exception ex) {
- MessageHandler.errorln("AWTRenderer: renderImage(): " +
- ex.getMessage());
- }
-
- }*/
+ /*
+ * public void renderImage(String href, float x, float y, float width,
+ * float height, Vector transform) {
+ * // What is with transformations?
+ * try {
+ * URL url = new URL(href);
+ * ImageIcon imageIcon = new ImageIcon(url);
+ * AffineTransform fullTransform = new AffineTransform();
+ * AffineTransform aTransform;
+ * transform = (transform == null) ? new Vector() : transform;
+ * for (int i = 0; i < transform.size(); i++) {
+ * org.w3c.dom.svg.SVGTransform t =
+ * (org.w3c.dom.svg.SVGTransform)
+ * transform.elementAt(i);
+ * SVGMatrix matrix = t.getMatrix();
+ * aTransform = new AffineTransform(matrix.getA(),
+ * matrix.getB(), matrix.getC(), matrix.getD(),
+ * matrix.getE(), matrix.getF());
+ * fullTransform.concatenate(aTransform);
+ * }
+ * BufferedImage bi = new BufferedImage((int) width, (int) height,
+ * BufferedImage.TYPE_INT_RGB);
+ * Graphics2D g2d = bi.createGraphics();
+ * BufferedImageOp bop = new AffineTransformOp(fullTransform,
+ * AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
+ * g2d.drawImage(imageIcon.getImage(), 0, 0, (int) width,
+ * (int) height, imageIcon.getImageObserver());
+ * graphics.drawImage(bi, bop, (int) x, (int) y);
+ * } catch (Exception ex) {
+ * MessageHandler.errorln("AWTRenderer: renderImage(): " +
+ * ex.getMessage());
+ * }
+ * }
+ */
public void renderForeignObjectArea(ForeignObjectArea area) {
area.getObject().render(this);
@@ -980,6 +981,7 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
protected class MUserAgent implements UserAgent {
AffineTransform currentTransform = null;
+
/**
* Creates a new SVGUserAgent.
*/
@@ -1013,14 +1015,14 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
* Returns a customized the pixel to mm factor.
*/
public float getPixelToMM() {
- return 0.264583333333333333333f; // 72 dpi
+ return 0.264583333333333333333f; // 72 dpi
}
/**
* Returns the language settings.
*/
public String getLanguages() {
- return "en";//userLanguages;
+ return "en"; // userLanguages;
}
/**
@@ -1028,7 +1030,7 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
* @return null if no user style sheet was specified.
*/
public String getUserStyleSheetURI() {
- return null;//userStyleSheetURI;
+ return null; // userStyleSheetURI;
}
/**
@@ -1044,15 +1046,14 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
* @param uri The document URI.
*/
public void openLink(SVGAElement elt) {
- //application.openLink(uri);
+ // application.openLink(uri);
}
public Point getClientAreaLocationOnScreen() {
return new Point(0, 0);
}
- public void setSVGCursor(java.awt.Cursor cursor) {
- }
+ public void setSVGCursor(java.awt.Cursor cursor) {}
public AffineTransform getTransform() {
return currentTransform;
@@ -1074,7 +1075,7 @@ public class AWTRenderer implements Renderer, Printable, Pageable {
return false;
}
- public void registerExtension(BridgeExtension be) {
- }
+ public void registerExtension(BridgeExtension be) {}
+
}
}
diff --git a/src/org/apache/fop/render/awt/FontMetricsMapper.java b/src/org/apache/fop/render/awt/FontMetricsMapper.java
index 76cee666b..2991e85a0 100644
--- a/src/org/apache/fop/render/awt/FontMetricsMapper.java
+++ b/src/org/apache/fop/render/awt/FontMetricsMapper.java
@@ -1,51 +1,13 @@
/*
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.awt;
-//FOP
+// FOP
import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.layout.FontInfo;
import org.apache.fop.layout.FontDescriptor;
@@ -59,46 +21,47 @@ import java.awt.Font;
/**
-* This class implements org.apache.fop.layout.FontMetric and
-* is added to the hash table in FontInfo. It deferes the
-* actual calculation of the metrics to
-* AWTFontMetrics. It only keeps the java name and
-* style as member varibles
-*/
+ * This class implements org.apache.fop.layout.FontMetric and
+ * is added to the hash table in FontInfo. It deferes the
+ * actual calculation of the metrics to
+ * AWTFontMetrics. It only keeps the java name and
+ * style as member varibles
+ */
public class FontMetricsMapper implements org.apache.fop.layout.FontMetric {
+
/**
- * The first and last non space-character
+ * The first and last non space-character
*/
private final static int FIRST_CHAR = 32;
private final static int LAST_CHAR = 255;
/**
- * This is a AWTFontMetrics that does the real calculation.
- * It is only one class that dynamically determines the font-size.
- */
+ * This is a AWTFontMetrics that does the real calculation.
+ * It is only one class that dynamically determines the font-size.
+ */
private static AWTFontMetrics metric = null;
/**
- * The java name of the font.
- # Make the family name immutable.
- */
+ * The java name of the font.
+ * # Make the family name immutable.
+ */
private final String family;
/**
- * The java style of the font.
- # Make the style immutable.
- */
+ * The java style of the font.
+ * # Make the style immutable.
+ */
private final int style;
/**
- * Constructs a new Font-metrics.
- * @param family the family name of the font (java value)
- * @param style the java type style value of the font
- * @param parent an AWT component - this is needed so
- * that we can get an instance of
- * java.awt.FontMetrics
- */
+ * Constructs a new Font-metrics.
+ * @param family the family name of the font (java value)
+ * @param style the java type style value of the font
+ * @param parent an AWT component - this is needed so
+ * that we can get an instance of
+ * java.awt.FontMetrics
+ */
public FontMetricsMapper(String family, int style, Graphics2D graphics) {
this.family = family;
this.style = style;
@@ -151,29 +114,30 @@ public class FontMetricsMapper implements org.apache.fop.layout.FontMetric {
}
/**
- * return width (in 1/1000ths of point size) of character at
- * code point i.
- */
+ * return width (in 1/1000ths of point size) of character at
+ * code point i.
+ */
public int width(int i, int size) {
return metric.width(i, family, style, size);
}
/**
- * return width (in 1/1000ths of point size) of all character
- */
+ * return width (in 1/1000ths of point size) of all character
+ */
public int[] getWidths(int size) {
return metric.getWidths(family, style, size);
}
/**
- * Gets a Font instance of the Font that this
- * FontMetrics describes in the desired size.
- * @return font with the desired characeristics.
- */
+ * Gets a Font instance of the Font that this
+ * FontMetrics describes in the desired size.
+ * @return font with the desired characeristics.
+ */
public Font getFont(int size) {
return metric.getFont(family, style, size);
}
+
}
diff --git a/src/org/apache/fop/render/awt/FontSetup.java b/src/org/apache/fop/render/awt/FontSetup.java
index 7fb9535ab..90e33f8f6 100644
--- a/src/org/apache/fop/render/awt/FontSetup.java
+++ b/src/org/apache/fop/render/awt/FontSetup.java
@@ -1,53 +1,10 @@
-/*-- $Id: FontSetup.java --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.render.awt;
// FOP
@@ -65,31 +22,33 @@ import java.awt.Graphics2D;
* sets up the AWT fonts. It is similar to
* org.apache.fop.render.pdf.FontSetup.
* Assigns the font (with metrics) to internal names like "F1" and
- * assigns family-style-weight triplets to the fonts
+ * assigns family-style-weight triplets to the fonts
*/
public class FontSetup {
- /** sets up the font info object.
- *
- * adds metrics for basic fonts and useful family-style-weight
- * triplets for lookup
- *
- * @param fontInfo the font info object to set up
- * @param parent needed, since a live AWT component is needed
- * to get a valid java.awt.FontMetrics object
- */
+ /**
+ * sets up the font info object.
+ *
+ * adds metrics for basic fonts and useful family-style-weight
+ * triplets for lookup
+ *
+ * @param fontInfo the font info object to set up
+ * @param parent needed, since a live AWT component is needed
+ * to get a valid java.awt.FontMetrics object
+ */
public static void setup(FontInfo fontInfo, Graphics2D graphics) {
FontMetricsMapper metric;
int normal, bold, bolditalic, italic;
MessageHandler.logln("setting up fonts");
- /* available java fonts are:
- Serif - bold, normal, italic, bold-italic
- SansSerif - bold, normal, italic, bold-italic
- MonoSpaced - bold, normal, italic, bold-italic
- */
+ /*
+ * available java fonts are:
+ * Serif - bold, normal, italic, bold-italic
+ * SansSerif - bold, normal, italic, bold-italic
+ * MonoSpaced - bold, normal, italic, bold-italic
+ */
normal = java.awt.Font.PLAIN;
bold = java.awt.Font.BOLD;
italic = java.awt.Font.ITALIC;
@@ -98,7 +57,7 @@ public class FontSetup {
metric = new FontMetricsMapper("SansSerif", normal, graphics);
// --> goes to F1
fontInfo.addMetrics("F1", metric);
- metric = new FontMetricsMapper("SansSerif",italic, graphics);
+ metric = new FontMetricsMapper("SansSerif", italic, graphics);
// --> goes to F2
fontInfo.addMetrics("F2", metric);
metric = new FontMetricsMapper("SansSerif", bold, graphics);
@@ -140,10 +99,10 @@ public class FontSetup {
fontInfo.addMetrics("F13", metric);
fontInfo.addMetrics("F14", metric);
- //Custom type 1 fonts step 1/2
- // fontInfo.addMetrics("F15", new OMEP());
- // fontInfo.addMetrics("F16", new GaramondLightCondensed());
- // fontInfo.addMetrics("F17", new BauerBodoniBoldItalic());
+ // Custom type 1 fonts step 1/2
+ // fontInfo.addMetrics("F15", new OMEP());
+ // fontInfo.addMetrics("F16", new GaramondLightCondensed());
+ // fontInfo.addMetrics("F17", new BauerBodoniBoldItalic());
/* any is treated as serif */
fontInfo.addFontProperties("F5", "any", "normal", "normal");
@@ -193,10 +152,10 @@ public class FontSetup {
fontInfo.addFontProperties("F13", "Symbol", "normal", "normal");
fontInfo.addFontProperties("F14", "ZapfDingbats", "normal", "normal");
- //Custom type 1 fonts step 2/2
- // fontInfo.addFontProperties("F15", "OMEP", "normal", "normal");
- // fontInfo.addFontProperties("F16", "Garamond-LightCondensed", "normal", "normal");
- // fontInfo.addFontProperties("F17", "BauerBodoni", "italic", "bold");
+ // Custom type 1 fonts step 2/2
+ // fontInfo.addFontProperties("F15", "OMEP", "normal", "normal");
+ // fontInfo.addFontProperties("F16", "Garamond-LightCondensed", "normal", "normal");
+ // fontInfo.addFontProperties("F17", "BauerBodoni", "italic", "bold");
/* for compatibility with PassiveTex */
fontInfo.addFontProperties("F5", "Times-Roman", "normal", "normal");
diff --git a/src/org/apache/fop/render/mif/Font.java b/src/org/apache/fop/render/mif/Font.java
index e88fe10aa..d1cbc9e7d 100644
--- a/src/org/apache/fop/render/mif/Font.java
+++ b/src/org/apache/fop/render/mif/Font.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
diff --git a/src/org/apache/fop/render/mif/FontSetup.java b/src/org/apache/fop/render/mif/FontSetup.java
index 4869543ab..4691751d9 100644
--- a/src/org/apache/fop/render/mif/FontSetup.java
+++ b/src/org/apache/fop/render/mif/FontSetup.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -12,7 +13,7 @@ import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.layout.FontInfo;
import org.apache.fop.layout.FontDescriptor;
import org.apache.fop.mif.MIFDocument;
-//import org.apache.fop.pdf.PDFResources;
+// import org.apache.fop.pdf.PDFResources;
// Java
import java.util.Enumeration;
@@ -22,7 +23,7 @@ import java.util.Hashtable;
* sets up the PDF fonts.
*
* Assigns the font (with metrics) to internal names like "F1" and
- * assigns family-style-weight triplets to the fonts
+ * assigns family-style-weight triplets to the fonts
*/
public class FontSetup {
@@ -52,10 +53,10 @@ public class FontSetup {
fontInfo.addMetrics("F13", new Symbol());
fontInfo.addMetrics("F14", new ZapfDingbats());
- //Custom type 1 fonts step 1/2
- // fontInfo.addMetrics("F15", new OMEP());
- // fontInfo.addMetrics("F16", new GaramondLightCondensed());
- // fontInfo.addMetrics("F17", new BauerBodoniBoldItalic());
+ // Custom type 1 fonts step 1/2
+ // fontInfo.addMetrics("F15", new OMEP());
+ // fontInfo.addMetrics("F16", new GaramondLightCondensed());
+ // fontInfo.addMetrics("F17", new BauerBodoniBoldItalic());
/* any is treated as serif */
fontInfo.addFontProperties("F5", "any", "normal", "normal");
@@ -105,10 +106,10 @@ public class FontSetup {
fontInfo.addFontProperties("F13", "Symbol", "normal", "normal");
fontInfo.addFontProperties("F14", "ZapfDingbats", "normal", "normal");
- //Custom type 1 fonts step 2/2
- // fontInfo.addFontProperties("F15", "OMEP", "normal", "normal");
- // fontInfo.addFontProperties("F16", "Garamond-LightCondensed", "normal", "normal");
- // fontInfo.addFontProperties("F17", "BauerBodoni", "italic", "bold");
+ // Custom type 1 fonts step 2/2
+ // fontInfo.addFontProperties("F15", "OMEP", "normal", "normal");
+ // fontInfo.addFontProperties("F16", "Garamond-LightCondensed", "normal", "normal");
+ // fontInfo.addFontProperties("F17", "BauerBodoni", "italic", "bold");
/* for compatibility with PassiveTex */
fontInfo.addFontProperties("F5", "Times-Roman", "normal", "normal");
@@ -139,18 +140,21 @@ public class FontSetup {
Hashtable fonts = fontInfo.getFonts();
Enumeration e = fonts.keys();
while (e.hasMoreElements()) {
- String f = (String) e.nextElement();
- Font font = (Font) fonts.get(f);
+ String f = (String)e.nextElement();
+ Font font = (Font)fonts.get(f);
FontDescriptor desc = null;
if (font instanceof FontDescriptor) {
- desc = (FontDescriptor) font;
+ desc = (FontDescriptor)font;
}
- /* mifDoc.makeFont(f,font.fontName(),
- font.encoding(),
- font,
- desc
- ); */
+ /*
+ * mifDoc.makeFont(f,font.fontName(),
+ * font.encoding(),
+ * font,
+ * desc
+ * );
+ */
}
}
+
}
diff --git a/src/org/apache/fop/render/mif/MIFRenderer.java b/src/org/apache/fop/render/mif/MIFRenderer.java
index e38004baa..778c992d1 100644
--- a/src/org/apache/fop/render/mif/MIFRenderer.java
+++ b/src/org/apache/fop/render/mif/MIFRenderer.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -36,6 +37,7 @@ import java.util.Enumeration;
import java.awt.Rectangle;
import java.util.Vector;
import java.util.Hashtable;
+
/**
* Renderer that renders areas to MIF
*/
@@ -46,24 +48,34 @@ public class MIFRenderer implements Renderer {
private int pageHeight;
private int pageWidth;
- /** the current vertical position in millipoints from bottom */
+ /**
+ * the current vertical position in millipoints from bottom
+ */
protected int currentYPosition = 0;
- /** the current horizontal position in millipoints from left */
+ /**
+ * the current horizontal position in millipoints from left
+ */
protected int currentXPosition = 0;
- /** the horizontal position of the current area container */
+ /**
+ * the horizontal position of the current area container
+ */
private int currentAreaContainerXPosition = 0;
- /** the MIF Document being created */
+ /**
+ * the MIF Document being created
+ */
protected MIFDocument mifDoc;
/* is a table currently open? */
private boolean inTable = false;
- /** options */
+ /**
+ * options
+ */
protected Hashtable options;
/**
@@ -73,7 +85,9 @@ public class MIFRenderer implements Renderer {
this.mifDoc = new MIFDocument();
}
- /** set up renderer options */
+ /**
+ * set up renderer options
+ */
public void setOptions(Hashtable options) {
this.options = options;
}
@@ -90,59 +104,62 @@ public class MIFRenderer implements Renderer {
MessageHandler.logln("rendering areas to MIF");
// idReferences=areaTree.getIDReferences();
- //this.pdfResources = this.pdfDoc.getResources();
- //this.pdfDoc.setIDReferences(idReferences);
+ // this.pdfResources = this.pdfDoc.getResources();
+ // this.pdfDoc.setIDReferences(idReferences);
Enumeration e = areaTree.getPages().elements();
while (e.hasMoreElements()) {
- this.renderPage((Page) e.nextElement());
+ this.renderPage((Page)e.nextElement());
}
- // MessageHandler.logln("writing out MIF");
+ // MessageHandler.logln("writing out MIF");
this.mifDoc.output(stream);
stream.close();
}
- /** set up the given FontInfo */
+ /**
+ * set up the given FontInfo
+ */
public void setupFontInfo(FontInfo fontInfo) {
FontSetup.setup(fontInfo);
- //FontSetup.addToFontFormat(this.mifDoc, fontInfo);
+ // FontSetup.addToFontFormat(this.mifDoc, fontInfo);
}
- /** set the producer of the rendering */
+ /**
+ * set the producer of the rendering
+ */
public void setProducer(String producer) {}
public void renderAreaContainer(AreaContainer area) {
- if (area.foCreator != null && area.foCreator.getName() == "fo:table") {
+ if (area.foCreator != null
+ && area.foCreator.getName() == "fo:table") {
this.mifDoc.createTable();
this.inTable = true;
- } else if (area.foCreator != null &&
- area.foCreator.getName() == "fo:table-body") {
+ } else if (area.foCreator != null
+ && area.foCreator.getName() == "fo:table-body") {
this.mifDoc.setCurrent("fo:table-body");
- } else if (area.foCreator != null &&
- area.foCreator.getName() == "fo:table-column") {
+ } else if (area.foCreator != null
+ && area.foCreator.getName() == "fo:table-column") {
- int colWidth = ((org.apache.fop.fo.flow.TableColumn)
- area.foCreator).getColumnWidth();
+ int colWidth =
+ ((org.apache.fop.fo.flow.TableColumn)area.foCreator).getColumnWidth();
this.mifDoc.setColumnProp(colWidth);
- } else if (area.foCreator != null &&
- area.foCreator.getName() == "fo:table-row") {
+ } else if (area.foCreator != null
+ && area.foCreator.getName() == "fo:table-row") {
this.mifDoc.startRow();
- } else if (area.foCreator != null &&
- area.foCreator.getName() == "fo:table-cell") {
+ } else if (area.foCreator != null
+ && area.foCreator.getName() == "fo:table-cell") {
int rowSpan =
- ((org.apache.fop.fo.flow.TableCell) area.foCreator).
- getNumRowsSpanned();
+ ((org.apache.fop.fo.flow.TableCell)area.foCreator).getNumRowsSpanned();
int colSpan =
- ((org.apache.fop.fo.flow.TableCell) area.foCreator).
- getNumColumnsSpanned();
+ ((org.apache.fop.fo.flow.TableCell)area.foCreator).getNumColumnsSpanned();
this.mifDoc.startCell(rowSpan, colSpan);
} else if (inTable) {
@@ -155,9 +172,9 @@ public class MIFRenderer implements Renderer {
if (area.getPosition() == Position.ABSOLUTE) {
// Y position is computed assuming positive Y axis, adjust for negative postscript one
- this.currentYPosition =
- area.getYPosition() - 2 * area.getPaddingTop() -
- 2 * area.getBorderTopWidth();
+ this.currentYPosition = area.getYPosition()
+ - 2 * area.getPaddingTop()
+ - 2 * area.getBorderTopWidth();
this.currentAreaContainerXPosition = area.getXPosition();
} else if (area.getPosition() == Position.RELATIVE) {
@@ -167,10 +184,10 @@ public class MIFRenderer implements Renderer {
} else if (area.getPosition() == Position.STATIC) {
- this.currentYPosition -=
- area.getPaddingTop() + area.getBorderTopWidth();
- this.currentAreaContainerXPosition +=
- area.getPaddingLeft() + area.getBorderLeftWidth();
+ this.currentYPosition -= area.getPaddingTop()
+ + area.getBorderTopWidth();
+ this.currentAreaContainerXPosition += area.getPaddingLeft()
+ + area.getBorderLeftWidth();
}
this.currentXPosition = this.currentAreaContainerXPosition;
@@ -178,7 +195,7 @@ public class MIFRenderer implements Renderer {
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
+ Box b = (Box)e.nextElement();
b.render(this);
}
if (area.getPosition() != Position.STATIC) {
@@ -212,27 +229,22 @@ public class MIFRenderer implements Renderer {
ColorType bg = area.getBackgroundColor();
/*
-
- // I'm not sure I should have to check for bg being null
- // but I do
- if ((bg != null) && (bg.alpha() == 0)) {
- this.addRect(rx, ry, w, -h, new PDFColor(bg), new PDFColor(bg));
- }
-
+ * // I'm not sure I should have to check for bg being null
+ * // but I do
+ * if ((bg != null) && (bg.alpha() == 0)) {
+ * this.addRect(rx, ry, w, -h, new PDFColor(bg), new PDFColor(bg));
+ * }
*/
/*
-
- // floats & footnotes stuff
- renderAreaContainer(area.getBeforeFloatReferenceArea());
- renderAreaContainer(area.getFootnoteReferenceArea());
-
+ * // floats & footnotes stuff
+ * renderAreaContainer(area.getBeforeFloatReferenceArea());
+ * renderAreaContainer(area.getFootnoteReferenceArea());
*/
// main reference area
- Enumeration e =
- area.getMainReferenceArea().getChildren().elements();
+ Enumeration e = area.getMainReferenceArea().getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
- b.render(this); // span areas
+ Box b = (Box)e.nextElement();
+ b.render(this); // span areas
}
if (area.getPosition() != Position.STATIC) {
@@ -249,7 +261,7 @@ public class MIFRenderer implements Renderer {
w = area.getContentWidth();
if (area instanceof BlockArea)
- rx += ((BlockArea) area).getStartIndent();
+ rx += ((BlockArea)area).getStartIndent();
h = area.getContentHeight();
int ry = this.currentYPosition;
@@ -261,14 +273,13 @@ public class MIFRenderer implements Renderer {
h = h + area.getPaddingTop() + area.getPaddingBottom();
/*
- // I'm not sure I should have to check for bg being null
- // but I do
- if ((bg != null) && (bg.alpha() == 0)) {
- this.addRect(rx, ry, w, -h,
- new PDFColor(bg),
- new PDFColor(bg));
- }
-
+ * // I'm not sure I should have to check for bg being null
+ * // but I do
+ * if ((bg != null) && (bg.alpha() == 0)) {
+ * this.addRect(rx, ry, w, -h,
+ * new PDFColor(bg),
+ * new PDFColor(bg));
+ * }
*/
rx = rx - area.getBorderLeftWidth();
@@ -276,56 +287,59 @@ public class MIFRenderer implements Renderer {
w = w + area.getBorderLeftWidth() + area.getBorderRightWidth();
h = h + area.getBorderTopWidth() + area.getBorderBottomWidth();
- //Create a textrect with these dimensions.
- //The y co-ordinate is measured +ve downwards so subtract page-height
+ // Create a textrect with these dimensions.
+ // The y co-ordinate is measured +ve downwards so subtract page-height
this.mifDoc.setTextRectProp(rx, pageHeight - ry, w, h);
/*
- BorderAndPadding bp = area.getBorderAndPadding();
- if (area.getBorderTopWidth() != 0)
- addLine(rx, ry, rx + w, ry, area.getBorderTopWidth(),
- new PDFColor(bp.getBorderColor(BorderAndPadding.TOP)));
- if (area.getBorderLeftWidth() != 0)
- addLine(rx, ry, rx, ry - h, area.getBorderLeftWidth(),
- new PDFColor(bp.getBorderColor(BorderAndPadding.LEFT)));
- if (area.getBorderRightWidth() != 0)
- addLine(rx + w, ry, rx + w, ry - h, area.getBorderRightWidth(),
- new PDFColor(bp.getBorderColor(BorderAndPadding.RIGHT)));
- if (area.getBorderBottomWidth() != 0)
- addLine(rx, ry - h, rx + w, ry - h, area.getBorderBottomWidth(),
- new PDFColor(bp.getBorderColor(BorderAndPadding.BOTTOM)));
+ * BorderAndPadding bp = area.getBorderAndPadding();
+ * if (area.getBorderTopWidth() != 0)
+ * addLine(rx, ry, rx + w, ry, area.getBorderTopWidth(),
+ * new PDFColor(bp.getBorderColor(BorderAndPadding.TOP)));
+ * if (area.getBorderLeftWidth() != 0)
+ * addLine(rx, ry, rx, ry - h, area.getBorderLeftWidth(),
+ * new PDFColor(bp.getBorderColor(BorderAndPadding.LEFT)));
+ * if (area.getBorderRightWidth() != 0)
+ * addLine(rx + w, ry, rx + w, ry - h, area.getBorderRightWidth(),
+ * new PDFColor(bp.getBorderColor(BorderAndPadding.RIGHT)));
+ * if (area.getBorderBottomWidth() != 0)
+ * addLine(rx, ry - h, rx + w, ry - h, area.getBorderBottomWidth(),
+ * new PDFColor(bp.getBorderColor(BorderAndPadding.BOTTOM)));
*/
}
public void renderSpanArea(SpanArea area) {
- //A span maps to a textframe
+ // A span maps to a textframe
this.mifDoc.createTextRect(area.getColumnCount());
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
- b.render(this); // column areas
+ Box b = (Box)e.nextElement();
+ b.render(this); // column areas
}
}
- /** render the given block area */
+ /**
+ * render the given block area
+ */
public void renderBlockArea(BlockArea area) {
- this.mifDoc.setBlockProp(area.getStartIndent(),
- area.getEndIndent());
+ this.mifDoc.setBlockProp(area.getStartIndent(), area.getEndIndent());
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
+ Box b = (Box)e.nextElement();
b.render(this);
}
}
- /** render the given display space */
+ /**
+ * render the given display space
+ */
public void renderDisplaySpace(DisplaySpace space) {
int d = space.getSize();
@@ -333,12 +347,15 @@ public class MIFRenderer implements Renderer {
}
- /** render the given SVG area */
+ /**
+ * render the given SVG area
+ */
public void renderSVGArea(SVGArea area) {}
- /** render a foreign object area */
- public void renderForeignObjectArea(ForeignObjectArea area) {
- }
+ /**
+ * render a foreign object area
+ */
+ public void renderForeignObjectArea(ForeignObjectArea area) {}
public void renderWordArea(WordArea area) {
String s;
@@ -348,7 +365,9 @@ public class MIFRenderer implements Renderer {
this.currentXPosition += area.getContentWidth();
}
- /** render the given image area */
+ /**
+ * render the given image area
+ */
public void renderImageArea(ImageArea area) {
int x = this.currentAreaContainerXPosition + area.getXOffset();
@@ -360,17 +379,19 @@ public class MIFRenderer implements Renderer {
FopImage img = area.getImage();
if (img instanceof SVGImage) {
- /* try {
- SVGSVGElement svg =
- ((SVGImage) img).getSVGDocument().getRootElement();
- currentStream.add("ET\nq\n" + (((float) w) / 1000f) +
- " 0 0 " + (((float) h) / 1000f) + " " +
- (((float) x) / 1000f) + " " +
- (((float)(y - h)) / 1000f) + " cm\n");
- // renderSVG(svg, (int) x, (int) y);
- currentStream.add("Q\nBT\n");
- } catch (FopImageException e) {
- } */
+ /*
+ * try {
+ * SVGSVGElement svg =
+ * ((SVGImage) img).getSVGDocument().getRootElement();
+ * currentStream.add("ET\nq\n" + (((float) w) / 1000f) +
+ * " 0 0 " + (((float) h) / 1000f) + " " +
+ * (((float) x) / 1000f) + " " +
+ * (((float)(y - h)) / 1000f) + " cm\n");
+ * // renderSVG(svg, (int) x, (int) y);
+ * currentStream.add("Q\nBT\n");
+ * } catch (FopImageException e) {
+ * }
+ */
MessageHandler.logln("Warning: SVG images not supported in this version");
} else {
@@ -380,20 +401,26 @@ public class MIFRenderer implements Renderer {
}
}
- /** render the given inline area */
+ /**
+ * render the given inline area
+ */
public void renderInlineArea(InlineArea area) {}
- /** render the given inline space */
+ /**
+ * render the given inline space
+ */
public void renderInlineSpace(InlineSpace space) {
// I dont need the size of space! I just need to
// leave a blank space each time
String s = " ";
- this.mifDoc.addToStream(s); // cool!
+ this.mifDoc.addToStream(s); // cool!
this.currentXPosition += space.getSize();
}
- /** render the given line area */
+ /**
+ * render the given line area
+ */
public void renderLineArea(LineArea area) {
int rx = this.currentAreaContainerXPosition + area.getStartIndent();
@@ -406,14 +433,14 @@ public class MIFRenderer implements Renderer {
int bl = this.currentYPosition;
- //The start of a new linearea corresponds to a new para in FM
+ // The start of a new linearea corresponds to a new para in FM
this.mifDoc.startLine();
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
+ Box b = (Box)e.nextElement();
this.currentYPosition = ry - area.getPlacementOffset();
b.render(this);
@@ -423,7 +450,9 @@ public class MIFRenderer implements Renderer {
}
- /** render the given page */
+ /**
+ * render the given page
+ */
public void renderPage(Page page) {
AreaContainer before, after;
@@ -450,19 +479,21 @@ public class MIFRenderer implements Renderer {
if (before != null) {
- this.mifDoc.createTextRect(1); // Create a rect with one col
+ this.mifDoc.createTextRect(1); // Create a rect with one col
renderAreaContainer(before);
}
if (after != null) {
- this.mifDoc.createTextRect(1); // Create a rect with one col
+ this.mifDoc.createTextRect(1); // Create a rect with one col
renderAreaContainer(after);
}
}
- /** render the given leader area */
+ /**
+ * render the given leader area
+ */
public void renderLeaderArea(LeaderArea area) {}
}
diff --git a/src/org/apache/fop/render/mif/fonts/Courier.java b/src/org/apache/fop/render/mif/fonts/Courier.java
index f45c1432d..ec22420a3 100644
--- a/src/org/apache/fop/render/mif/fonts/Courier.java
+++ b/src/org/apache/fop/render/mif/fonts/Courier.java
@@ -1,4 +1,9 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.mif.fonts;
@@ -245,7 +250,7 @@ public class Courier extends Font {
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
@@ -274,15 +279,18 @@ public class Courier extends Font {
return lastChar;
}
- public int width(int i,int size) {
+ public int width(int i, int size) {
return size * width[i];
}
public int[] getWidths(int size) {
- int[] arr = new int[getLastChar()-getFirstChar()+1];
- System.arraycopy(width, getFirstChar(), arr, 0, getLastChar()-getFirstChar()+1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ int[] arr = new int[getLastChar() - getFirstChar() + 1];
+ System.arraycopy(width, getFirstChar(), arr, 0,
+ getLastChar() - getFirstChar() + 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/mif/fonts/CourierBold.java b/src/org/apache/fop/render/mif/fonts/CourierBold.java
index 52f6f6d00..9f5c4a756 100644
--- a/src/org/apache/fop/render/mif/fonts/CourierBold.java
+++ b/src/org/apache/fop/render/mif/fonts/CourierBold.java
@@ -1,4 +1,9 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.mif.fonts;
@@ -245,7 +250,7 @@ public class CourierBold extends Font {
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
@@ -274,15 +279,18 @@ public class CourierBold extends Font {
return lastChar;
}
- public int width(int i,int size) {
+ public int width(int i, int size) {
return size * width[i];
}
public int[] getWidths(int size) {
- int[] arr = new int[getLastChar()-getFirstChar()+1];
- System.arraycopy(width, getFirstChar(), arr, 0, getLastChar()-getFirstChar()+1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ int[] arr = new int[getLastChar() - getFirstChar() + 1];
+ System.arraycopy(width, getFirstChar(), arr, 0,
+ getLastChar() - getFirstChar() + 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/mif/fonts/CourierBoldOblique.java b/src/org/apache/fop/render/mif/fonts/CourierBoldOblique.java
index 1b18f5bb3..89483df6b 100644
--- a/src/org/apache/fop/render/mif/fonts/CourierBoldOblique.java
+++ b/src/org/apache/fop/render/mif/fonts/CourierBoldOblique.java
@@ -1,4 +1,9 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.mif.fonts;
@@ -245,7 +250,7 @@ public class CourierBoldOblique extends Font {
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
@@ -274,15 +279,18 @@ public class CourierBoldOblique extends Font {
return lastChar;
}
- public int width(int i,int size) {
+ public int width(int i, int size) {
return size * width[i];
}
public int[] getWidths(int size) {
- int[] arr = new int[getLastChar()-getFirstChar()+1];
- System.arraycopy(width, getFirstChar(), arr, 0, getLastChar()-getFirstChar()+1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ int[] arr = new int[getLastChar() - getFirstChar() + 1];
+ System.arraycopy(width, getFirstChar(), arr, 0,
+ getLastChar() - getFirstChar() + 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/mif/fonts/CourierOblique.java b/src/org/apache/fop/render/mif/fonts/CourierOblique.java
index a3ffc9753..e5c19f20d 100644
--- a/src/org/apache/fop/render/mif/fonts/CourierOblique.java
+++ b/src/org/apache/fop/render/mif/fonts/CourierOblique.java
@@ -1,4 +1,9 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.mif.fonts;
@@ -245,7 +250,7 @@ public class CourierOblique extends Font {
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
@@ -274,15 +279,18 @@ public class CourierOblique extends Font {
return lastChar;
}
- public int width(int i,int size) {
+ public int width(int i, int size) {
return size * width[i];
}
public int[] getWidths(int size) {
- int[] arr = new int[getLastChar()-getFirstChar()+1];
- System.arraycopy(width, getFirstChar(), arr, 0, getLastChar()-getFirstChar()+1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ int[] arr = new int[getLastChar() - getFirstChar() + 1];
+ System.arraycopy(width, getFirstChar(), arr, 0,
+ getLastChar() - getFirstChar() + 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/mif/fonts/Helvetica.java b/src/org/apache/fop/render/mif/fonts/Helvetica.java
index b719f4fed..f6722774f 100644
--- a/src/org/apache/fop/render/mif/fonts/Helvetica.java
+++ b/src/org/apache/fop/render/mif/fonts/Helvetica.java
@@ -1,4 +1,9 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.mif.fonts;
@@ -240,7 +245,7 @@ public class Helvetica extends Font {
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
@@ -269,15 +274,18 @@ public class Helvetica extends Font {
return lastChar;
}
- public int width(int i,int size) {
+ public int width(int i, int size) {
return size * width[i];
}
public int[] getWidths(int size) {
- int[] arr = new int[getLastChar()-getFirstChar()+1];
- System.arraycopy(width, getFirstChar(), arr, 0, getLastChar()-getFirstChar()+1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ int[] arr = new int[getLastChar() - getFirstChar() + 1];
+ System.arraycopy(width, getFirstChar(), arr, 0,
+ getLastChar() - getFirstChar() + 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/mif/fonts/HelveticaBold.java b/src/org/apache/fop/render/mif/fonts/HelveticaBold.java
index 48c4362e9..fd66a1fc6 100644
--- a/src/org/apache/fop/render/mif/fonts/HelveticaBold.java
+++ b/src/org/apache/fop/render/mif/fonts/HelveticaBold.java
@@ -1,4 +1,9 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.mif.fonts;
@@ -240,7 +245,7 @@ public class HelveticaBold extends Font {
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
@@ -269,15 +274,18 @@ public class HelveticaBold extends Font {
return lastChar;
}
- public int width(int i,int size) {
+ public int width(int i, int size) {
return size * width[i];
}
public int[] getWidths(int size) {
- int[] arr = new int[getLastChar()-getFirstChar()+1];
- System.arraycopy(width, getFirstChar(), arr, 0, getLastChar()-getFirstChar()+1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ int[] arr = new int[getLastChar() - getFirstChar() + 1];
+ System.arraycopy(width, getFirstChar(), arr, 0,
+ getLastChar() - getFirstChar() + 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/mif/fonts/HelveticaBoldOblique.java b/src/org/apache/fop/render/mif/fonts/HelveticaBoldOblique.java
index 6437fd503..dd21f6677 100644
--- a/src/org/apache/fop/render/mif/fonts/HelveticaBoldOblique.java
+++ b/src/org/apache/fop/render/mif/fonts/HelveticaBoldOblique.java
@@ -1,4 +1,9 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.mif.fonts;
@@ -240,7 +245,7 @@ public class HelveticaBoldOblique extends Font {
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
@@ -269,15 +274,18 @@ public class HelveticaBoldOblique extends Font {
return lastChar;
}
- public int width(int i,int size) {
+ public int width(int i, int size) {
return size * width[i];
}
public int[] getWidths(int size) {
- int[] arr = new int[getLastChar()-getFirstChar()+1];
- System.arraycopy(width, getFirstChar(), arr, 0, getLastChar()-getFirstChar()+1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ int[] arr = new int[getLastChar() - getFirstChar() + 1];
+ System.arraycopy(width, getFirstChar(), arr, 0,
+ getLastChar() - getFirstChar() + 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/mif/fonts/HelveticaOblique.java b/src/org/apache/fop/render/mif/fonts/HelveticaOblique.java
index ab146e08c..81aae1bc6 100644
--- a/src/org/apache/fop/render/mif/fonts/HelveticaOblique.java
+++ b/src/org/apache/fop/render/mif/fonts/HelveticaOblique.java
@@ -1,4 +1,9 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.mif.fonts;
@@ -240,7 +245,7 @@ public class HelveticaOblique extends Font {
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
@@ -269,15 +274,18 @@ public class HelveticaOblique extends Font {
return lastChar;
}
- public int width(int i,int size) {
+ public int width(int i, int size) {
return size * width[i];
}
public int[] getWidths(int size) {
- int[] arr = new int[getLastChar()-getFirstChar()+1];
- System.arraycopy(width, getFirstChar(), arr, 0, getLastChar()-getFirstChar()+1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ int[] arr = new int[getLastChar() - getFirstChar() + 1];
+ System.arraycopy(width, getFirstChar(), arr, 0,
+ getLastChar() - getFirstChar() + 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/mif/fonts/Symbol.java b/src/org/apache/fop/render/mif/fonts/Symbol.java
index 4418542bc..3ccfcb0a3 100644
--- a/src/org/apache/fop/render/mif/fonts/Symbol.java
+++ b/src/org/apache/fop/render/mif/fonts/Symbol.java
@@ -1,4 +1,9 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.mif.fonts;
@@ -212,7 +217,7 @@ public class Symbol extends Font {
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
@@ -241,15 +246,18 @@ public class Symbol extends Font {
return lastChar;
}
- public int width(int i,int size) {
+ public int width(int i, int size) {
return size * width[i];
}
public int[] getWidths(int size) {
- int[] arr = new int[getLastChar()-getFirstChar()+1];
- System.arraycopy(width, getFirstChar(), arr, 0, getLastChar()-getFirstChar()+1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ int[] arr = new int[getLastChar() - getFirstChar() + 1];
+ System.arraycopy(width, getFirstChar(), arr, 0,
+ getLastChar() - getFirstChar() + 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/mif/fonts/TimesBold.java b/src/org/apache/fop/render/mif/fonts/TimesBold.java
index 1ad9c5834..8a3eab830 100644
--- a/src/org/apache/fop/render/mif/fonts/TimesBold.java
+++ b/src/org/apache/fop/render/mif/fonts/TimesBold.java
@@ -1,4 +1,9 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.mif.fonts;
@@ -240,7 +245,7 @@ public class TimesBold extends Font {
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
@@ -269,15 +274,18 @@ public class TimesBold extends Font {
return lastChar;
}
- public int width(int i,int size) {
+ public int width(int i, int size) {
return size * width[i];
}
public int[] getWidths(int size) {
- int[] arr = new int[getLastChar()-getFirstChar()+1];
- System.arraycopy(width, getFirstChar(), arr, 0, getLastChar()-getFirstChar()+1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ int[] arr = new int[getLastChar() - getFirstChar() + 1];
+ System.arraycopy(width, getFirstChar(), arr, 0,
+ getLastChar() - getFirstChar() + 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/mif/fonts/TimesBoldItalic.java b/src/org/apache/fop/render/mif/fonts/TimesBoldItalic.java
index e92af2c9e..938979887 100644
--- a/src/org/apache/fop/render/mif/fonts/TimesBoldItalic.java
+++ b/src/org/apache/fop/render/mif/fonts/TimesBoldItalic.java
@@ -1,4 +1,9 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.mif.fonts;
@@ -240,7 +245,7 @@ public class TimesBoldItalic extends Font {
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
@@ -269,15 +274,18 @@ public class TimesBoldItalic extends Font {
return lastChar;
}
- public int width(int i,int size) {
+ public int width(int i, int size) {
return size * width[i];
}
public int[] getWidths(int size) {
- int[] arr = new int[getLastChar()-getFirstChar()+1];
- System.arraycopy(width, getFirstChar(), arr, 0, getLastChar()-getFirstChar()+1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ int[] arr = new int[getLastChar() - getFirstChar() + 1];
+ System.arraycopy(width, getFirstChar(), arr, 0,
+ getLastChar() - getFirstChar() + 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/mif/fonts/TimesItalic.java b/src/org/apache/fop/render/mif/fonts/TimesItalic.java
index 0d2dcbaaf..cc4bfb08b 100644
--- a/src/org/apache/fop/render/mif/fonts/TimesItalic.java
+++ b/src/org/apache/fop/render/mif/fonts/TimesItalic.java
@@ -1,4 +1,9 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.mif.fonts;
@@ -240,7 +245,7 @@ public class TimesItalic extends Font {
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
@@ -269,15 +274,18 @@ public class TimesItalic extends Font {
return lastChar;
}
- public int width(int i,int size) {
+ public int width(int i, int size) {
return size * width[i];
}
public int[] getWidths(int size) {
- int[] arr = new int[getLastChar()-getFirstChar()+1];
- System.arraycopy(width, getFirstChar(), arr, 0, getLastChar()-getFirstChar()+1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ int[] arr = new int[getLastChar() - getFirstChar() + 1];
+ System.arraycopy(width, getFirstChar(), arr, 0,
+ getLastChar() - getFirstChar() + 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/mif/fonts/TimesRoman.java b/src/org/apache/fop/render/mif/fonts/TimesRoman.java
index 87c5c1a0d..ae0416cd0 100644
--- a/src/org/apache/fop/render/mif/fonts/TimesRoman.java
+++ b/src/org/apache/fop/render/mif/fonts/TimesRoman.java
@@ -1,4 +1,9 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.mif.fonts;
@@ -240,7 +245,7 @@ public class TimesRoman extends Font {
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
@@ -269,15 +274,18 @@ public class TimesRoman extends Font {
return lastChar;
}
- public int width(int i,int size) {
+ public int width(int i, int size) {
return size * width[i];
}
public int[] getWidths(int size) {
- int[] arr = new int[getLastChar()-getFirstChar()+1];
- System.arraycopy(width, getFirstChar(), arr, 0, getLastChar()-getFirstChar()+1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ int[] arr = new int[getLastChar() - getFirstChar() + 1];
+ System.arraycopy(width, getFirstChar(), arr, 0,
+ getLastChar() - getFirstChar() + 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/mif/fonts/ZapfDingbats.java b/src/org/apache/fop/render/mif/fonts/ZapfDingbats.java
index 0727484a6..bc0b81c8b 100644
--- a/src/org/apache/fop/render/mif/fonts/ZapfDingbats.java
+++ b/src/org/apache/fop/render/mif/fonts/ZapfDingbats.java
@@ -1,4 +1,9 @@
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.render.mif.fonts;
@@ -225,7 +230,7 @@ public class ZapfDingbats extends Font {
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
@@ -254,15 +259,18 @@ public class ZapfDingbats extends Font {
return lastChar;
}
- public int width(int i,int size) {
+ public int width(int i, int size) {
return size * width[i];
}
public int[] getWidths(int size) {
- int[] arr = new int[getLastChar()-getFirstChar()+1];
- System.arraycopy(width, getFirstChar(), arr, 0, getLastChar()-getFirstChar()+1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ int[] arr = new int[getLastChar() - getFirstChar() + 1];
+ System.arraycopy(width, getFirstChar(), arr, 0,
+ getLastChar() - getFirstChar() + 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/pcl/PCLRenderer.java b/src/org/apache/fop/render/pcl/PCLRenderer.java
index 9c0ed9aa9..d47da9a59 100755
--- a/src/org/apache/fop/render/pcl/PCLRenderer.java
+++ b/src/org/apache/fop/render/pcl/PCLRenderer.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -32,12 +33,14 @@ import java.util.Enumeration;
/**
* Renderer that renders areas to PCL
-
- Created by Arthur E Welch III while at M&I EastPoint Technology
- Donated by EastPoint to the Apache FOP project March 2, 2001.
+ * Created by Arthur E Welch III while at M&I EastPoint Technology
+ * Donated by EastPoint to the Apache FOP project March 2, 2001.
*/
public class PCLRenderer extends PrintRenderer {
- /** the current stream to add PCL commands to */
+
+ /**
+ * the current stream to add PCL commands to
+ */
public PCLStream currentStream;
private int pageHeight = 7920;
@@ -45,24 +48,27 @@ public class PCLRenderer extends PrintRenderer {
// These variables control the virtual paggination functionality.
public int curdiv = 0;
private int divisions = -1;
- public int paperheight = -1; // Paper height in decipoints?
- public int orientation = -1; // -1=default/unknown, 0=portrait, 1=landscape.
- public int topmargin = -1; // Top margin in decipoints?
- public int leftmargin = -1; // Left margin in decipoints?
+ public int paperheight = -1; // Paper height in decipoints?
+ public int orientation =
+ -1; // -1=default/unknown, 0=portrait, 1=landscape.
+ public int topmargin = -1; // Top margin in decipoints?
+ public int leftmargin = -1; // Left margin in decipoints?
private int fullmargin = 0;
private final boolean debug = false;
- private int xoffset = -180; // X Offset to allow for PCL implicit 1/4" left margin.
+ private int xoffset =
+ -180; // X Offset to allow for PCL implicit 1/4" left margin.
private java.util.Hashtable options;
/**
* Create the PCL renderer
*/
- public PCLRenderer() {
- }
+ public PCLRenderer() {}
- /** set up renderer options */
+ /**
+ * set up renderer options
+ */
public void setOptions(java.util.Hashtable options) {
this.options = options;
}
@@ -72,8 +78,7 @@ public class PCLRenderer extends PrintRenderer {
*
* @param producer string indicating application producing PCL
*/
- public void setProducer(String producer) {
- }
+ public void setProducer(String producer) {}
/**
* render the areas into PCL
@@ -85,8 +90,8 @@ public class PCLRenderer extends PrintRenderer {
OutputStream stream) throws IOException, FOPException {
MessageHandler.logln("rendering areas to PCL");
idReferences = areaTree.getIDReferences();
- //this.pdfResources = this.pdfDoc.getResources();
- //this.pdfDoc.setIDReferences(idReferences);
+ // this.pdfResources = this.pdfDoc.getResources();
+ // this.pdfDoc.setIDReferences(idReferences);
Enumeration e = areaTree.getPages().elements();
currentStream = new PCLStream(stream);
@@ -106,12 +111,12 @@ public class PCLRenderer extends PrintRenderer {
while (e.hasMoreElements()) {
- this.renderPage((Page) e.nextElement());
+ this.renderPage((Page)e.nextElement());
}
if (!idReferences.isEveryIdValid()) {
- //throw new FOPException("The following id's were referenced but not found: "+idReferences.getInvalidIds()+"\n");
- MessageHandler.errorln("Warning: The following id's were referenced but not found: "+
- idReferences.getInvalidIds() + "\n");
+ // throw new FOPException("The following id's were referenced but not found: "+idReferences.getInvalidIds()+"\n");
+ MessageHandler.errorln("Warning: The following id's were referenced but not found: "
+ + idReferences.getInvalidIds() + "\n");
}
MessageHandler.logln("writing out PCL");
@@ -147,24 +152,24 @@ public class PCLRenderer extends PrintRenderer {
* @param rs the rule style
* @param stroke the line color
*/
- protected void addLine(int x1, int y1, int x2, int y2, int th,
- int rs, PDFPathPaint stroke) {
+ protected void addLine(int x1, int y1, int x2, int y2, int th, int rs,
+ PDFPathPaint stroke) {
int dashon = 0;
int dashoff = 0;
- //if ( rs != null && rs.length() > 5 && rs.charAt(0) == '[' && rs.charAt(1) != ']' && rs.charAt(4) == ']' )
- //{
- // dashon = rs.charAt(1) - '0';
- // dashoff = rs.charAt(3) - '0';
- //}
+ // if ( rs != null && rs.length() > 5 && rs.charAt(0) == '[' && rs.charAt(1) != ']' && rs.charAt(4) == ']' )
+ // {
+ // dashon = rs.charAt(1) - '0';
+ // dashoff = rs.charAt(3) - '0';
+ // }
switch (rs) {
- case org.apache.fop.fo.properties.RuleStyle.DASHED:
- dashon = 3;
- dashoff = 3;
- break;
- case org.apache.fop.fo.properties.RuleStyle.DOTTED:
- dashon = 1;
- dashoff = 3;
- break;
+ case org.apache.fop.fo.properties.RuleStyle.DASHED:
+ dashon = 3;
+ dashoff = 3;
+ break;
+ case org.apache.fop.fo.properties.RuleStyle.DOTTED:
+ dashon = 1;
+ dashoff = 3;
+ break;
}
if (x1 == x2) {
if (dashon > 0 && dashoff > 0) {
@@ -202,8 +207,7 @@ public class PCLRenderer extends PrintRenderer {
* @param h the height in millipoints
* @param stroke the stroke color/gradient
*/
- protected void addRect(int x, int y, int w, int h,
- PDFPathPaint stroke) {
+ protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke) {
if (h < 0)
h *= -1;
@@ -231,23 +235,27 @@ public class PCLRenderer extends PrintRenderer {
* @param fill the fill color/gradient
* @param stroke the stroke color/gradient
*/
- protected void addRect(int x, int y, int w, int h,
- PDFPathPaint stroke, PDFPathPaint fill) {
+ protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke,
+ PDFPathPaint fill) {
if ((w == 0) || (h == 0))
return;
if (h < 0)
h *= -1;
- PDFColor sc = (PDFColor) stroke;
- PDFColor fc = (PDFColor) fill;
+ PDFColor sc = (PDFColor)stroke;
+ PDFColor fc = (PDFColor)fill;
sc.setColorSpace(ColorSpace.DEVICE_RGB);
fc.setColorSpace(ColorSpace.DEVICE_RGB);
- int lineshade = (int)(100 - ((0.3f * sc.red() + 0.59f * sc.green() +
- 0.11f * sc.blue()) * 100f));
- int fillshade = (int)(100 - ((0.3f * fc.red() + 0.59f * fc.green() +
- 0.11f * fc.blue()) * 100f));
+ int lineshade =
+ (int)(100
+ - ((0.3f * sc.red() + 0.59f * sc.green() + 0.11f * sc.blue())
+ * 100f));
+ int fillshade =
+ (int)(100
+ - ((0.3f * fc.red() + 0.59f * fc.green() + 0.11f * fc.blue())
+ * 100f));
int xpos = xoffset + (x / 100);
if (xpos < 0) {
@@ -255,21 +263,21 @@ public class PCLRenderer extends PrintRenderer {
MessageHandler.errorln("PCLRenderer.addRect() WARNING: Horizontal position out of bounds.");
}
- currentStream.add("\033*v1O\033&a" + xpos + "h" +
- (pageHeight - (y / 100)) + "V" + "\033*c" +
- (w / 100) + "h" + (h / 100) + "V" + "\033*c" +
- lineshade + "G" + "\033*c2P");
+ currentStream.add("\033*v1O\033&a" + xpos + "h"
+ + (pageHeight - (y / 100)) + "V" + "\033*c"
+ + (w / 100) + "h" + (h / 100) + "V" + "\033*c"
+ + lineshade + "G" + "\033*c2P");
if (fillshade != lineshade && (w >= 720 || h >= 720)) {
xpos = xoffset + ((x + 240) / 100);
if (xpos < 0) {
xpos = 0;
MessageHandler.errorln("PCLRenderer.addRect() WARNING: Horizontal position out of bounds.");
}
- currentStream.add("\033&a" + xpos + "h" +
- (pageHeight - ((y + 240)) / 100) + "V" +
- "\033*c" + ((w - 480) / 100) + "h" +
- ((h - 480) / 100) + "V" + "\033*c" + fillshade +
- "G" + "\033*c2P");
+ currentStream.add("\033&a" + xpos + "h"
+ + (pageHeight - ((y + 240)) / 100) + "V"
+ + "\033*c" + ((w - 480) / 100) + "h"
+ + ((h - 480) / 100) + "V" + "\033*c"
+ + fillshade + "G" + "\033*c2P");
}
// Reset pattern transparency mode.
currentStream.add("\033*v0O");
@@ -298,8 +306,8 @@ public class PCLRenderer extends PrintRenderer {
int cg = 0;
int cb = 0;
int grey = 0;
- boolean iscolor = img.getColorSpace().getColorSpace() !=
- ColorSpace.DEVICE_GRAY;
+ boolean iscolor = img.getColorSpace().getColorSpace()
+ != ColorSpace.DEVICE_GRAY;
int dcount = 0;
int xres = (iw * 72000) / w;
int yres = (ih * 72000) / h;
@@ -318,24 +326,23 @@ public class PCLRenderer extends PrintRenderer {
else
resolution = 75;
if (debug)
- System.out.println("PCLRenderer.printBMP() iscolor = " +
- iscolor);
- // Setup for graphics
+ System.out.println("PCLRenderer.printBMP() iscolor = " + iscolor);
+ // Setup for graphics
currentStream.add("\033*t" + resolution + "R\033*r0F\033*r1A");
// Transfer graphics data
- for (iy = 0 ; iy < ih ; iy++) {
+ for (iy = 0; iy < ih; iy++) {
ib = 0;
- //int padding = iw % 8;
- //if ( padding != 0 )
- // padding = 8 - padding;
- //padding = 0;
- //indx = (ih - iy - 1 + padding) * iw;
+ // int padding = iw % 8;
+ // if ( padding != 0 )
+ // padding = 8 - padding;
+ // padding = 0;
+ // indx = (ih - iy - 1 + padding) * iw;
indx = iy * iw;
if (iscolor)
indx *= 3;
- //currentStream.add("\033*b" + bytewidth + "W");
- for (ix = 0 ; ix < iw ; ix++) {
+ // currentStream.add("\033*b" + bytewidth + "W");
+ for (ix = 0; ix < iw; ix++) {
if (iscolor) {
cr = imgmap[indx++] & 0xFF;
cg = imgmap[indx++] & 0xFF;
@@ -352,7 +359,7 @@ public class PCLRenderer extends PrintRenderer {
lastcount++;
else {
ic[icwidth++] = (char)(lastcount & 0xFF);
- ic[icwidth++] = (char) lastbyte;
+ ic[icwidth++] = (char)lastbyte;
lastbyte = ib;
lastcount = 0;
}
@@ -362,12 +369,12 @@ public class PCLRenderer extends PrintRenderer {
}
if (lastcount == 255 || ((ix + 1) == iw)) {
ic[icwidth++] = (char)(lastcount & 0xFF);
- ic[icwidth++] = (char) lastbyte;
+ ic[icwidth++] = (char)lastbyte;
lastbyte = 0;
lastcount = -1;
}
}
- icu[ix / 8] = (char) ib;
+ icu[ix / 8] = (char)ib;
ib = 0;
}
}
@@ -386,7 +393,7 @@ public class PCLRenderer extends PrintRenderer {
currentStream.add("\033*rB");
- return(true);
+ return (true);
}
/**
@@ -410,76 +417,77 @@ public class PCLRenderer extends PrintRenderer {
MessageHandler.errorln("PCLRenderer.renderImageArea() WARNING: Horizontal position out of bounds.");
}
- currentStream.add("\033&a" + xpos + "h" +
- (pageHeight - (y / 100)) + "V");
+ currentStream.add("\033&a" + xpos + "h" + (pageHeight - (y / 100))
+ + "V");
try {
printBMP(img, x, y, w, h);
} catch (FopImageException e) {
- //e.printStackTrace(System.out);
- MessageHandler.errorln(
- "PCLRenderer.renderImageArea() Error printing BMP (" +
- e.toString() + ")");
+ // e.printStackTrace(System.out);
+ MessageHandler.errorln("PCLRenderer.renderImageArea() Error printing BMP ("
+ + e.toString() + ")");
}
}
- /** render a foreign object area */
+ /**
+ * render a foreign object area
+ */
public void renderForeignObjectArea(ForeignObjectArea area) {
// if necessary need to scale and align the content
this.currentXPosition = this.currentXPosition + area.getXOffset();
this.currentYPosition = this.currentYPosition;
switch (area.getAlign()) {
- case TextAlign.START:
- break;
- case TextAlign.END:
- break;
- case TextAlign.CENTER:
- case TextAlign.JUSTIFY:
- break;
+ case TextAlign.START:
+ break;
+ case TextAlign.END:
+ break;
+ case TextAlign.CENTER:
+ case TextAlign.JUSTIFY:
+ break;
}
switch (area.getVerticalAlign()) {
- case VerticalAlign.BASELINE:
- break;
- case VerticalAlign.MIDDLE:
- break;
- case VerticalAlign.SUB:
- break;
- case VerticalAlign.SUPER:
- break;
- case VerticalAlign.TEXT_TOP:
- break;
- case VerticalAlign.TEXT_BOTTOM:
- break;
- case VerticalAlign.TOP:
- break;
- case VerticalAlign.BOTTOM:
- break;
+ case VerticalAlign.BASELINE:
+ break;
+ case VerticalAlign.MIDDLE:
+ break;
+ case VerticalAlign.SUB:
+ break;
+ case VerticalAlign.SUPER:
+ break;
+ case VerticalAlign.TEXT_TOP:
+ break;
+ case VerticalAlign.TEXT_BOTTOM:
+ break;
+ case VerticalAlign.TOP:
+ break;
+ case VerticalAlign.BOTTOM:
+ break;
}
// in general the content will not be text
// align and scale
switch (area.scalingMethod()) {
- case Scaling.UNIFORM:
- break;
- case Scaling.NON_UNIFORM:
- break;
+ case Scaling.UNIFORM:
+ break;
+ case Scaling.NON_UNIFORM:
+ break;
}
// if the overflow is auto (default), scroll or visible
// then the contents should not be clipped, since this
// is considered a printing medium.
switch (area.getOverflow()) {
- case Overflow.VISIBLE:
- case Overflow.SCROLL:
- case Overflow.AUTO:
- break;
- case Overflow.HIDDEN:
- break;
+ case Overflow.VISIBLE:
+ case Overflow.SCROLL:
+ case Overflow.AUTO:
+ break;
+ case Overflow.HIDDEN:
+ break;
}
area.getObject().render(this);
this.currentXPosition += area.getEffectiveWidth();
- // this.currentYPosition -= area.getEffectiveHeight();
+ // this.currentYPosition -= area.getEffectiveHeight();
}
/**
@@ -493,7 +501,7 @@ public class PCLRenderer extends PrintRenderer {
int x = this.currentXPosition;
int y = this.currentYPosition;
SVGSVGElement svg =
- ((SVGDocument) area.getSVGDocument()).getRootElement();
+ ((SVGDocument)area.getSVGDocument()).getRootElement();
int w = (int)(svg.getWidth().getBaseVal().getValue() * 1000);
int h = (int)(svg.getHeight().getBaseVal().getValue() * 1000);
@@ -505,9 +513,9 @@ public class PCLRenderer extends PrintRenderer {
// TODO - translate and clip to viewbox
- //currentStream.add(svgRenderer.getString());
+ // currentStream.add(svgRenderer.getString());
- //currentStream.add("Q\n");
+ // currentStream.add("Q\n");
}
public void setFont(String name, float size) {
@@ -520,62 +528,70 @@ public class PCLRenderer extends PrintRenderer {
}
}
switch (fontcode) {
- case 1: // F1 = Helvetica
- //currentStream.add("\033(8U\033(s1p" + (size / 1000) + "v0s0b24580T");
- // Arial is more common among PCL5 printers than Helvetica - so use Arial
- currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v0s0b16602T");
- break;
- case 2: // F2 = Helvetica Oblique
- currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v1s0b16602T");
- break;
- case 3: // F3 = Helvetica Bold
- currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v0s3b16602T");
- break;
- case 4: // F4 = Helvetica Bold Oblique
- currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v1s3b16602T");
- break;
- case 5: // F5 = Times Roman
- //currentStream.add("\033(8U\033(s1p" + (size / 1000) + "v0s0b25093T");
- // Times New is more common among PCL5 printers than Times - so use Times New
- currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v0s0b16901T");
- break;
- case 6: // F6 = Times Italic
- currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v1s0b16901T");
- break;
- case 7: // F7 = Times Bold
- currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v0s3b16901T");
- break;
- case 8: // F8 = Times Bold Italic
- currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v1s3b16901T");
- break;
- case 9: // F9 = Courier
- currentStream.add("\033(0N\033(s0p" +
- (120.01f / (size / 1000.00f)) + "h0s0b4099T");
- break;
- case 10: // F10 = Courier Oblique
- currentStream.add("\033(0N\033(s0p" +
- (120.01f / (size / 1000.00f)) + "h1s0b4099T");
- break;
- case 11: // F11 = Courier Bold
- currentStream.add("\033(0N\033(s0p" +
- (120.01f / (size / 1000.00f)) + "h0s3b4099T");
- break;
- case 12: // F12 = Courier Bold Oblique
- currentStream.add("\033(0N\033(s0p" +
- (120.01f / (size / 1000.00f)) + "h1s3b4099T");
- break;
- case 13: // F13 = Symbol
- currentStream.add("\033(19M\033(s1p" + (size / 1000) +
- "v0s0b16686T");
- //currentStream.add("\033(9U\033(s1p" + (size / 1000) + "v0s0b25093T"); // ECMA Latin 1 Symbol Set in Times Roman???
- break;
- case 14: // F14 = Zapf Dingbats
- currentStream.add("\033(14L\033(s1p" + (size / 1000) +
- "v0s0b45101T");
- break;
- default:
- currentStream.add("\033(0N\033(s" + (size / 1000) + "V");
- break;
+ case 1: // F1 = Helvetica
+ // currentStream.add("\033(8U\033(s1p" + (size / 1000) + "v0s0b24580T");
+ // Arial is more common among PCL5 printers than Helvetica - so use Arial
+ currentStream.add("\033(0N\033(s1p" + (size / 1000)
+ + "v0s0b16602T");
+ break;
+ case 2: // F2 = Helvetica Oblique
+ currentStream.add("\033(0N\033(s1p" + (size / 1000)
+ + "v1s0b16602T");
+ break;
+ case 3: // F3 = Helvetica Bold
+ currentStream.add("\033(0N\033(s1p" + (size / 1000)
+ + "v0s3b16602T");
+ break;
+ case 4: // F4 = Helvetica Bold Oblique
+ currentStream.add("\033(0N\033(s1p" + (size / 1000)
+ + "v1s3b16602T");
+ break;
+ case 5: // F5 = Times Roman
+ // currentStream.add("\033(8U\033(s1p" + (size / 1000) + "v0s0b25093T");
+ // Times New is more common among PCL5 printers than Times - so use Times New
+ currentStream.add("\033(0N\033(s1p" + (size / 1000)
+ + "v0s0b16901T");
+ break;
+ case 6: // F6 = Times Italic
+ currentStream.add("\033(0N\033(s1p" + (size / 1000)
+ + "v1s0b16901T");
+ break;
+ case 7: // F7 = Times Bold
+ currentStream.add("\033(0N\033(s1p" + (size / 1000)
+ + "v0s3b16901T");
+ break;
+ case 8: // F8 = Times Bold Italic
+ currentStream.add("\033(0N\033(s1p" + (size / 1000)
+ + "v1s3b16901T");
+ break;
+ case 9: // F9 = Courier
+ currentStream.add("\033(0N\033(s0p"
+ + (120.01f / (size / 1000.00f)) + "h0s0b4099T");
+ break;
+ case 10: // F10 = Courier Oblique
+ currentStream.add("\033(0N\033(s0p"
+ + (120.01f / (size / 1000.00f)) + "h1s0b4099T");
+ break;
+ case 11: // F11 = Courier Bold
+ currentStream.add("\033(0N\033(s0p"
+ + (120.01f / (size / 1000.00f)) + "h0s3b4099T");
+ break;
+ case 12: // F12 = Courier Bold Oblique
+ currentStream.add("\033(0N\033(s0p"
+ + (120.01f / (size / 1000.00f)) + "h1s3b4099T");
+ break;
+ case 13: // F13 = Symbol
+ currentStream.add("\033(19M\033(s1p" + (size / 1000)
+ + "v0s0b16686T");
+ // currentStream.add("\033(9U\033(s1p" + (size / 1000) + "v0s0b25093T"); // ECMA Latin 1 Symbol Set in Times Roman???
+ break;
+ case 14: // F14 = Zapf Dingbats
+ currentStream.add("\033(14L\033(s1p" + (size / 1000)
+ + "v0s0b45101T");
+ break;
+ default:
+ currentStream.add("\033(0N\033(s" + (size / 1000) + "V");
+ break;
}
}
@@ -591,16 +607,17 @@ public class PCLRenderer extends PrintRenderer {
float red = area.getRed();
float green = area.getGreen();
float blue = area.getBlue();
- PDFColor theAreaColor = new PDFColor((double) area.getRed(),
- (double) area.getGreen(), (double) area.getBlue());
+ PDFColor theAreaColor = new PDFColor((double)area.getRed(),
+ (double)area.getGreen(),
+ (double)area.getBlue());
- //currentStream.add("\033*c" + (int)(100 - ((0.3f * red + 0.59f * green + 0.11f * blue) * 100f)) + "G\033*v2T");
- currentStream.add("\033*v1O\033*c" + (int)(100 -
- ((0.3f * red + 0.59f * green + 0.11f * blue) * 100f))
+ // currentStream.add("\033*c" + (int)(100 - ((0.3f * red + 0.59f * green + 0.11f * blue) * 100f)) + "G\033*v2T");
+ currentStream.add("\033*v1O\033*c"
+ + (int)(100 - ((0.3f * red + 0.59f * green + 0.11f * blue) * 100f))
+ "G\033*v2T");
- if ((!name.equals(this.currentFontName)) ||
- (size != this.currentFontSize)) {
+ if ((!name.equals(this.currentFontName))
+ || (size != this.currentFontSize)) {
this.currentFontName = name;
this.currentFontSize = size;
setFont(name, size);
@@ -628,8 +645,8 @@ public class PCLRenderer extends PrintRenderer {
xpos = 0;
MessageHandler.errorln("PCLRenderer.renderWordArea() WARNING: Horizontal position out of bounds.");
}
- currentStream.add("\033&a" + xpos + "h" +
- (pageHeight - (bl / 100)) + "V" + s);
+ currentStream.add("\033&a" + xpos + "h" + (pageHeight - (bl / 100))
+ + "V" + s);
this.currentXPosition += area.getContentWidth();
}
@@ -641,9 +658,8 @@ public class PCLRenderer extends PrintRenderer {
*/
public void renderPage(Page page) {
if (debug)
- System.out.println(
- "PCLRenderer.renderPage() page.Height() = " +
- page.getHeight());
+ System.out.println("PCLRenderer.renderPage() page.Height() = "
+ + page.getHeight());
BodyAreaContainer body;
AreaContainer before, after, start, end;
@@ -651,32 +667,32 @@ public class PCLRenderer extends PrintRenderer {
divisions = paperheight / (page.getHeight() / 100);
if (debug)
- System.out.println( "PCLRenderer.renderPage() paperheight=" +
- paperheight + " divisions=" + divisions);
+ System.out.println("PCLRenderer.renderPage() paperheight="
+ + paperheight + " divisions=" + divisions);
- // Set top margin.
- //float fullmargin = 0;
+ // Set top margin.
+ // float fullmargin = 0;
if (divisions > 0)
fullmargin = paperheight * curdiv / divisions;
if (topmargin > 0)
fullmargin += topmargin;
if (debug)
- System.out.println("PCLRenderer.renderPage() curdiv=" +
- curdiv + " fullmargin=" + fullmargin);
- //if ( fullmargin > 0 )
- // currentStream.add("\033&l" + (fullmargin / 15f) + "c1e8C");
- //this.currentYPosition = fullmargin * 100;
+ System.out.println("PCLRenderer.renderPage() curdiv=" + curdiv
+ + " fullmargin=" + fullmargin);
+ // if ( fullmargin > 0 )
+ // currentStream.add("\033&l" + (fullmargin / 15f) + "c1e8C");
+ // this.currentYPosition = fullmargin * 100;
if (paperheight > 0)
pageHeight = (paperheight / divisions) + fullmargin;
else
pageHeight = page.getHeight() / 100;
if (debug)
- System.out.println(
- "PCLRenderer.renderPage() Set currentYPosition=" +
- this.currentYPosition);
+ System.out.println("PCLRenderer.renderPage() Set currentYPosition="
+ + this.currentYPosition);
if (leftmargin > 0 && curdiv == 0)
- currentStream.add("\033&k" + (leftmargin / 6f) + "H\033&a1L\033&k12H");
+ currentStream.add("\033&k" + (leftmargin / 6f)
+ + "H\033&a1L\033&k12H");
body = page.getBody();
before = page.getBefore();
@@ -701,7 +717,7 @@ public class PCLRenderer extends PrintRenderer {
if (end != null)
renderAreaContainer(end);
- // End page.
+ // End page.
if (++curdiv == divisions || divisions == -1) {
curdiv = 0;
currentStream.add("\f");
@@ -709,31 +725,29 @@ public class PCLRenderer extends PrintRenderer {
// Links, etc not implemented...
/*
- currentPage = this.pdfDoc.makePage(this.pdfResources, currentStream,
- page.getWidth()/1000, page.getHeight()/1000, page);
-
- if (page.hasLinks()) {
- currentAnnotList = this.pdfDoc.makeAnnotList();
- currentPage.setAnnotList(currentAnnotList);
-
- Enumeration e = page.getLinkSets().elements();
- while (e.hasMoreElements()) {
- LinkSet linkSet = (LinkSet) e.nextElement();
-
- linkSet.align();
- String dest = linkSet.getDest();
- int linkType = linkSet.getLinkType();
- Enumeration f = linkSet.getRects().elements();
- while (f.hasMoreElements()) {
- LinkedRectangle lrect = (LinkedRectangle) f.nextElement();
- currentAnnotList.addLink(
- this.pdfDoc.makeLink(lrect.getRectangle(), dest, linkType));
- }
- }
- } else {
- // just to be on the safe side
- currentAnnotList = null;
- }
+ * currentPage = this.pdfDoc.makePage(this.pdfResources, currentStream,
+ * page.getWidth()/1000, page.getHeight()/1000, page);
+ * if (page.hasLinks()) {
+ * currentAnnotList = this.pdfDoc.makeAnnotList();
+ * currentPage.setAnnotList(currentAnnotList);
+ * Enumeration e = page.getLinkSets().elements();
+ * while (e.hasMoreElements()) {
+ * LinkSet linkSet = (LinkSet) e.nextElement();
+ * linkSet.align();
+ * String dest = linkSet.getDest();
+ * int linkType = linkSet.getLinkType();
+ * Enumeration f = linkSet.getRects().elements();
+ * while (f.hasMoreElements()) {
+ * LinkedRectangle lrect = (LinkedRectangle) f.nextElement();
+ * currentAnnotList.addLink(
+ * this.pdfDoc.makeLink(lrect.getRectangle(), dest, linkType));
+ * }
+ * }
+ * } else {
+ * // just to be on the safe side
+ * currentAnnotList = null;
+ * }
*/
}
+
}
diff --git a/src/org/apache/fop/render/pcl/PCLStream.java b/src/org/apache/fop/render/pcl/PCLStream.java
index dadc3a984..fdc714b7b 100755
--- a/src/org/apache/fop/render/pcl/PCLStream.java
+++ b/src/org/apache/fop/render/pcl/PCLStream.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -23,13 +24,13 @@ public class PCLStream {
byte buff[] = new byte[str.length()];
int countr;
int len = str.length();
- for (countr = 0 ; countr < len ; countr++)
- buff[countr] = (byte) str.charAt(countr);
+ for (countr = 0; countr < len; countr++)
+ buff[countr] = (byte)str.charAt(countr);
try {
out.write(buff);
} catch (IOException e) {
- //e.printStackTrace();
- //e.printStackTrace(System.out);
+ // e.printStackTrace();
+ // e.printStackTrace(System.out);
throw new RuntimeException(e.toString());
}
}
@@ -37,4 +38,5 @@ public class PCLStream {
public void setDoOutput(boolean doout) {
doOutput = doout;
}
+
}
diff --git a/src/org/apache/fop/render/pdf/CIDFont.java b/src/org/apache/fop/render/pdf/CIDFont.java
index a8eff598b..0e5c089ac 100644
--- a/src/org/apache/fop/render/pdf/CIDFont.java
+++ b/src/org/apache/fop/render/pdf/CIDFont.java
@@ -1,29 +1,45 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.render.pdf;
import org.apache.fop.pdf.PDFWArray;
public abstract class CIDFont extends Font {
- // Required
- public abstract String getCidBaseFont();
- public abstract byte getCidType();
- public abstract String getCharEncoding();
- public abstract String getRegistry();
- public abstract String getOrdering();
- public abstract int getSupplement();
- // Optional
- public int getDefaultWidth() { return 0; }
- public PDFWArray getWidths() { return null; }
- // public int getWinCharSet() { return 0; }
-
- // Need For FOP
-
- /**
- *Returns CMap Object .
- *
- *If this method does not return null , the mapping from character codes
- *to a font number is performed in FOP . When the getCidType() method
- *returns CIDFontType2 , this method must not return null .
- */
- public CMap getCMap() { return null; }
+ // Required
+ public abstract String getCidBaseFont();
+ public abstract byte getCidType();
+ public abstract String getCharEncoding();
+ public abstract String getRegistry();
+ public abstract String getOrdering();
+ public abstract int getSupplement();
+ // Optional
+ public int getDefaultWidth() {
+ return 0;
+ }
+
+ public PDFWArray getWidths() {
+ return null;
+ }
+
+ // public int getWinCharSet() { return 0; }
+
+ // Need For FOP
+
+ /**
+ * Returns CMap Object .
+ *
+ * If this method does not return null , the mapping from character codes
+ * to a font number is performed in FOP . When the getCidType() method
+ * returns CIDFontType2 , this method must not return null .
+ */
+ public CMap getCMap() {
+ return null;
+ }
+
}
diff --git a/src/org/apache/fop/render/pdf/CMap.java b/src/org/apache/fop/render/pdf/CMap.java
index 8b40e3ec3..e7e018a50 100644
--- a/src/org/apache/fop/render/pdf/CMap.java
+++ b/src/org/apache/fop/render/pdf/CMap.java
@@ -1,55 +1,12 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.render.pdf;
public interface CMap {
- public abstract char mapping(char ch);
+ public abstract char mapping(char ch);
}
diff --git a/src/org/apache/fop/render/pdf/Font.java b/src/org/apache/fop/render/pdf/Font.java
index 3bb151a04..d0142ef87 100644
--- a/src/org/apache/fop/render/pdf/Font.java
+++ b/src/org/apache/fop/render/pdf/Font.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.render.pdf;
// FOP
@@ -58,28 +15,28 @@ import org.apache.fop.layout.FontMetric;
*/
public abstract class Font implements FontMetric {
- /**
- * get the encoding of the font
- */
+ /**
+ * get the encoding of the font
+ */
public abstract String encoding();
- /**
- * get the base font name
- */
+ /**
+ * get the base font name
+ */
public abstract String fontName();
-
- /**
- * get the subtype of the font, default is TYPE1
- */
+
+ /**
+ * get the subtype of the font, default is TYPE1
+ */
public byte getSubType() {
return org.apache.fop.pdf.PDFFont.TYPE1;
}
- /**
- * Provide a default mapping
- */
+ /**
+ * Provide a default mapping
+ */
public char mapChar(char c) {
- // Use default CodePointMapping
+ // Use default CodePointMapping
if (c > 127) {
char d = org.apache.fop.render.pdf.CodePointMapping.map[c];
if (d != 0) {
@@ -90,6 +47,7 @@ public abstract class Font implements FontMetric {
}
return c;
}
+
}
diff --git a/src/org/apache/fop/render/pdf/FontReader.java b/src/org/apache/fop/render/pdf/FontReader.java
index e8430d399..132030d92 100644
--- a/src/org/apache/fop/render/pdf/FontReader.java
+++ b/src/org/apache/fop/render/pdf/FontReader.java
@@ -1,8 +1,8 @@
-/*-- $Id$ --
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.render.pdf;
@@ -25,20 +25,20 @@ import org.apache.fop.apps.FOPException;
/**
* Class for reading a metric.xml file and creating a font object.
* Typical usage:
-
- FontReader reader = new FontReader();
- reader.setFontEmbedPath();
- reader.useKerning(true);
- Font f = reader.getFont();
-
-*/
+ *
+ * FontReader reader = new FontReader();
+ * reader.setFontEmbedPath();
+ * reader.useKerning(true);
+ * Font f = reader.getFont();
+ *
+ */
public class FontReader extends DefaultHandler {
private Locator locator = null;
private boolean isCID = false;
private MultiByteFont multiFont = null;
private SingleByteFont singleFont = null;
private Font returnFont = null;
- //private SingleByteFont singleFont = null;
+ // private SingleByteFont singleFont = null;
private String text = null;
private Vector cidWidths = null;
@@ -57,8 +57,8 @@ public class FontReader extends DefaultHandler {
parser.setFeature("http://xml.org/sax/features/namespace-prefixes",
false);
} catch (SAXException e) {
- throw new FOPException (
- "You need a SAX parser which supports SAX version 2",e);
+ throw new FOPException("You need a SAX parser which supports SAX version 2",
+ e);
}
parser.setContentHandler(this);
@@ -67,16 +67,15 @@ public class FontReader extends DefaultHandler {
parser.parse(path);
} catch (SAXException e) {
throw new FOPException(e);
+ } catch (IOException e) {
+ throw new FOPException(e);
}
- catch (IOException e) {
- throw new FOPException(e);
- }
-
+
}
/**
- * Sets the path to embed a font. a null value disables font embedding
- */
+ * Sets the path to embed a font. a null value disables font embedding
+ */
public void setFontEmbedPath(String path) {
if (isCID)
multiFont.embedFileName = path;
@@ -85,8 +84,8 @@ public class FontReader extends DefaultHandler {
}
/**
- * Enable/disable use of kerning for the font
- */
+ * Enable/disable use of kerning for the font
+ */
public void useKerning(boolean kern) {
if (isCID)
multiFont.useKerning = true;
@@ -96,29 +95,28 @@ public class FontReader extends DefaultHandler {
/**
- * Get the generated font object
- */
+ * Get the generated font object
+ */
public Font getFont() {
return returnFont;
}
/**
- * Construct a FontReader object from a path to a metric.xml file
- * and read metric data
- */
+ * Construct a FontReader object from a path to a metric.xml file
+ * and read metric data
+ */
public FontReader(String path) throws FOPException {
createFont(path);
}
- public void startDocument() {
- }
+ public void startDocument() {}
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
- public void startElement(String uri, String localName,
- String qName, Attributes attributes) {
+ public void startElement(String uri, String localName, String qName,
+ Attributes attributes) {
if (localName.equals("font-metrics")) {
if ("TYPE0".equals(attributes.getValue("type"))) {
multiFont = new MultiByteFont();
@@ -151,13 +149,11 @@ public class FontReader extends DefaultHandler {
} else if ("kerning".equals(localName)) {
currentKerning = new Hashtable();
if (isCID)
- multiFont.kerning.put(
- new Integer(attributes.getValue("kpx1")),
- currentKerning);
+ multiFont.kerning.put(new Integer(attributes.getValue("kpx1")),
+ currentKerning);
else
- singleFont.kerning.put(
- new Integer(attributes.getValue("kpx1")),
- currentKerning);
+ singleFont.kerning.put(new Integer(attributes.getValue("kpx1")),
+ currentKerning);
} else if ("bfranges".equals(localName)) {
bfranges = new Vector();
} else if ("bf".equals(localName)) {
@@ -172,16 +168,15 @@ public class FontReader extends DefaultHandler {
singleFont.width = new int[256];
} else if ("char".equals(localName)) {
try {
- singleFont.width[
- Integer.parseInt(attributes.getValue("idx"))] =
+ singleFont.width[Integer.parseInt(attributes.getValue("idx"))] =
Integer.parseInt(attributes.getValue("wdt"));
} catch (NumberFormatException ne) {
- System.out.println("Malformed width in metric file: " +
- ne.getMessage());
+ System.out.println("Malformed width in metric file: "
+ + ne.getMessage());
}
} else if ("pair".equals(localName)) {
- currentKerning.put( new Integer(attributes.getValue("kpx2")),
- new Integer(attributes.getValue("kern")));
+ currentKerning.put(new Integer(attributes.getValue("kpx2")),
+ new Integer(attributes.getValue("kern")));
}
}
@@ -274,8 +269,8 @@ public class FontReader extends DefaultHandler {
int[] wds = new int[cidWidths.size()];
int j = 0;
for (Enumeration e = cidWidths.elements();
- e.hasMoreElements();) {
- Integer i = (Integer) e.nextElement();
+ e.hasMoreElements(); ) {
+ Integer i = (Integer)e.nextElement();
wds[j++] = i.intValue();
}
diff --git a/src/org/apache/fop/render/pdf/FontSetup.java b/src/org/apache/fop/render/pdf/FontSetup.java
index 6f28b1c54..81b6b0d58 100644
--- a/src/org/apache/fop/render/pdf/FontSetup.java
+++ b/src/org/apache/fop/render/pdf/FontSetup.java
@@ -1,53 +1,10 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.render.pdf;
// FOP
@@ -69,7 +26,7 @@ import java.util.Vector;
* sets up the PDF fonts.
*
* Assigns the font (with metrics) to internal names like "F1" and
- * assigns family-style-weight triplets to the fonts
+ * assigns family-style-weight triplets to the fonts
*/
public class FontSetup {
@@ -82,186 +39,147 @@ public class FontSetup {
* @param fontInfo the font info object to set up
*/
public static void setup(FontInfo fontInfo) {
- MessageHandler.logln("setting up fonts");
-
- fontInfo.addMetrics("F1", new Helvetica());
- fontInfo.addMetrics("F2", new HelveticaOblique());
- fontInfo.addMetrics("F3", new HelveticaBold());
- fontInfo.addMetrics("F4", new HelveticaBoldOblique());
- fontInfo.addMetrics("F5", new TimesRoman());
- fontInfo.addMetrics("F6", new TimesItalic());
- fontInfo.addMetrics("F7", new TimesBold());
- fontInfo.addMetrics("F8", new TimesBoldItalic());
- fontInfo.addMetrics("F9", new Courier());
- fontInfo.addMetrics("F10", new CourierOblique());
- fontInfo.addMetrics("F11", new CourierBold());
- fontInfo.addMetrics("F12", new CourierBoldOblique());
- fontInfo.addMetrics("F13", new Symbol());
- fontInfo.addMetrics("F14", new ZapfDingbats());
-
- //Custom type 1 fonts step 1/2
-// fontInfo.addMetrics("F15", new OMEP());
-// fontInfo.addMetrics("F16", new GaramondLightCondensed());
-// fontInfo.addMetrics("F17", new BauerBodoniBoldItalic());
+ MessageHandler.logln("setting up fonts");
+
+ fontInfo.addMetrics("F1", new Helvetica());
+ fontInfo.addMetrics("F2", new HelveticaOblique());
+ fontInfo.addMetrics("F3", new HelveticaBold());
+ fontInfo.addMetrics("F4", new HelveticaBoldOblique());
+ fontInfo.addMetrics("F5", new TimesRoman());
+ fontInfo.addMetrics("F6", new TimesItalic());
+ fontInfo.addMetrics("F7", new TimesBold());
+ fontInfo.addMetrics("F8", new TimesBoldItalic());
+ fontInfo.addMetrics("F9", new Courier());
+ fontInfo.addMetrics("F10", new CourierOblique());
+ fontInfo.addMetrics("F11", new CourierBold());
+ fontInfo.addMetrics("F12", new CourierBoldOblique());
+ fontInfo.addMetrics("F13", new Symbol());
+ fontInfo.addMetrics("F14", new ZapfDingbats());
+
+ // Custom type 1 fonts step 1/2
+ // fontInfo.addMetrics("F15", new OMEP());
+ // fontInfo.addMetrics("F16", new GaramondLightCondensed());
+ // fontInfo.addMetrics("F17", new BauerBodoniBoldItalic());
- /* any is treated as serif */
- fontInfo.addFontProperties("F5", "any", "normal", "normal");
- fontInfo.addFontProperties("F6", "any", "italic", "normal");
- fontInfo.addFontProperties("F6", "any", "oblique", "normal");
- fontInfo.addFontProperties("F7", "any", "normal", "bold");
- fontInfo.addFontProperties("F8", "any", "italic", "bold");
- fontInfo.addFontProperties("F8", "any", "oblique", "bold");
+ /* any is treated as serif */
+ fontInfo.addFontProperties("F5", "any", "normal", "normal");
+ fontInfo.addFontProperties("F6", "any", "italic", "normal");
+ fontInfo.addFontProperties("F6", "any", "oblique", "normal");
+ fontInfo.addFontProperties("F7", "any", "normal", "bold");
+ fontInfo.addFontProperties("F8", "any", "italic", "bold");
+ fontInfo.addFontProperties("F8", "any", "oblique", "bold");
- fontInfo.addFontProperties("F1", "sans-serif", "normal",
- "normal");
- fontInfo.addFontProperties("F2", "sans-serif", "oblique",
- "normal");
- fontInfo.addFontProperties("F2", "sans-serif", "italic",
- "normal");
- fontInfo.addFontProperties("F3", "sans-serif", "normal",
- "bold");
- fontInfo.addFontProperties("F4", "sans-serif", "oblique",
- "bold");
- fontInfo.addFontProperties("F4", "sans-serif", "italic",
- "bold");
- fontInfo.addFontProperties("F5", "serif", "normal", "normal");
- fontInfo.addFontProperties("F6", "serif", "oblique",
- "normal");
- fontInfo.addFontProperties("F6", "serif", "italic", "normal");
- fontInfo.addFontProperties("F7", "serif", "normal", "bold");
- fontInfo.addFontProperties("F8", "serif", "oblique", "bold");
- fontInfo.addFontProperties("F8", "serif", "italic", "bold");
- fontInfo.addFontProperties("F9", "monospace", "normal",
- "normal");
- fontInfo.addFontProperties("F10", "monospace", "oblique",
- "normal");
- fontInfo.addFontProperties("F10", "monospace", "italic",
- "normal");
- fontInfo.addFontProperties("F11", "monospace", "normal",
- "bold");
- fontInfo.addFontProperties("F12", "monospace", "oblique",
- "bold");
- fontInfo.addFontProperties("F12", "monospace", "italic",
- "bold");
+ fontInfo.addFontProperties("F1", "sans-serif", "normal", "normal");
+ fontInfo.addFontProperties("F2", "sans-serif", "oblique", "normal");
+ fontInfo.addFontProperties("F2", "sans-serif", "italic", "normal");
+ fontInfo.addFontProperties("F3", "sans-serif", "normal", "bold");
+ fontInfo.addFontProperties("F4", "sans-serif", "oblique", "bold");
+ fontInfo.addFontProperties("F4", "sans-serif", "italic", "bold");
+ fontInfo.addFontProperties("F5", "serif", "normal", "normal");
+ fontInfo.addFontProperties("F6", "serif", "oblique", "normal");
+ fontInfo.addFontProperties("F6", "serif", "italic", "normal");
+ fontInfo.addFontProperties("F7", "serif", "normal", "bold");
+ fontInfo.addFontProperties("F8", "serif", "oblique", "bold");
+ fontInfo.addFontProperties("F8", "serif", "italic", "bold");
+ fontInfo.addFontProperties("F9", "monospace", "normal", "normal");
+ fontInfo.addFontProperties("F10", "monospace", "oblique", "normal");
+ fontInfo.addFontProperties("F10", "monospace", "italic", "normal");
+ fontInfo.addFontProperties("F11", "monospace", "normal", "bold");
+ fontInfo.addFontProperties("F12", "monospace", "oblique", "bold");
+ fontInfo.addFontProperties("F12", "monospace", "italic", "bold");
- fontInfo.addFontProperties("F1", "Helvetica", "normal",
- "normal");
- fontInfo.addFontProperties("F2", "Helvetica", "oblique",
- "normal");
- fontInfo.addFontProperties("F2", "Helvetica", "italic",
- "normal");
- fontInfo.addFontProperties("F3", "Helvetica", "normal",
- "bold");
- fontInfo.addFontProperties("F4", "Helvetica", "oblique",
- "bold");
- fontInfo.addFontProperties("F4", "Helvetica", "italic",
- "bold");
- fontInfo.addFontProperties("F5", "Times", "normal", "normal");
- fontInfo.addFontProperties("F6", "Times", "oblique",
- "normal");
- fontInfo.addFontProperties("F6", "Times", "italic", "normal");
- fontInfo.addFontProperties("F7", "Times", "normal", "bold");
- fontInfo.addFontProperties("F8", "Times", "oblique", "bold");
- fontInfo.addFontProperties("F8", "Times", "italic", "bold");
- fontInfo.addFontProperties("F9", "Courier", "normal",
- "normal");
- fontInfo.addFontProperties("F10", "Courier", "oblique",
- "normal");
- fontInfo.addFontProperties("F10", "Courier", "italic",
- "normal");
- fontInfo.addFontProperties("F11", "Courier", "normal",
- "bold");
- fontInfo.addFontProperties("F12", "Courier", "oblique",
- "bold");
- fontInfo.addFontProperties("F12", "Courier", "italic",
- "bold");
- fontInfo.addFontProperties("F13", "Symbol", "normal",
- "normal");
- fontInfo.addFontProperties("F14", "ZapfDingbats", "normal",
- "normal");
+ fontInfo.addFontProperties("F1", "Helvetica", "normal", "normal");
+ fontInfo.addFontProperties("F2", "Helvetica", "oblique", "normal");
+ fontInfo.addFontProperties("F2", "Helvetica", "italic", "normal");
+ fontInfo.addFontProperties("F3", "Helvetica", "normal", "bold");
+ fontInfo.addFontProperties("F4", "Helvetica", "oblique", "bold");
+ fontInfo.addFontProperties("F4", "Helvetica", "italic", "bold");
+ fontInfo.addFontProperties("F5", "Times", "normal", "normal");
+ fontInfo.addFontProperties("F6", "Times", "oblique", "normal");
+ fontInfo.addFontProperties("F6", "Times", "italic", "normal");
+ fontInfo.addFontProperties("F7", "Times", "normal", "bold");
+ fontInfo.addFontProperties("F8", "Times", "oblique", "bold");
+ fontInfo.addFontProperties("F8", "Times", "italic", "bold");
+ fontInfo.addFontProperties("F9", "Courier", "normal", "normal");
+ fontInfo.addFontProperties("F10", "Courier", "oblique", "normal");
+ fontInfo.addFontProperties("F10", "Courier", "italic", "normal");
+ fontInfo.addFontProperties("F11", "Courier", "normal", "bold");
+ fontInfo.addFontProperties("F12", "Courier", "oblique", "bold");
+ fontInfo.addFontProperties("F12", "Courier", "italic", "bold");
+ fontInfo.addFontProperties("F13", "Symbol", "normal", "normal");
+ fontInfo.addFontProperties("F14", "ZapfDingbats", "normal", "normal");
- //Custom type 1 fonts step 2/2
-// fontInfo.addFontProperties("F15", "OMEP", "normal", "normal");
-// fontInfo.addFontProperties("F16", "Garamond-LightCondensed", "normal", "normal");
-// fontInfo.addFontProperties("F17", "BauerBodoni", "italic", "bold");
+ // Custom type 1 fonts step 2/2
+ // fontInfo.addFontProperties("F15", "OMEP", "normal", "normal");
+ // fontInfo.addFontProperties("F16", "Garamond-LightCondensed", "normal", "normal");
+ // fontInfo.addFontProperties("F17", "BauerBodoni", "italic", "bold");
- /* for compatibility with PassiveTex */
- fontInfo.addFontProperties("F5", "Times-Roman", "normal",
- "normal");
- fontInfo.addFontProperties("F6", "Times-Roman", "oblique",
- "normal");
- fontInfo.addFontProperties("F6", "Times-Roman", "italic",
- "normal");
- fontInfo.addFontProperties("F7", "Times-Roman", "normal",
- "bold");
- fontInfo.addFontProperties("F8", "Times-Roman", "oblique",
- "bold");
- fontInfo.addFontProperties("F8", "Times-Roman", "italic",
- "bold");
- fontInfo.addFontProperties("F5", "Times Roman", "normal",
- "normal");
- fontInfo.addFontProperties("F6", "Times Roman", "oblique",
- "normal");
- fontInfo.addFontProperties("F6", "Times Roman", "italic",
- "normal");
- fontInfo.addFontProperties("F7", "Times Roman", "normal",
- "bold");
- fontInfo.addFontProperties("F8", "Times Roman", "oblique",
- "bold");
- fontInfo.addFontProperties("F8", "Times Roman", "italic",
- "bold");
- fontInfo.addFontProperties("F9", "Computer-Modern-Typewriter",
- "normal", "normal");
+ /* for compatibility with PassiveTex */
+ fontInfo.addFontProperties("F5", "Times-Roman", "normal", "normal");
+ fontInfo.addFontProperties("F6", "Times-Roman", "oblique", "normal");
+ fontInfo.addFontProperties("F6", "Times-Roman", "italic", "normal");
+ fontInfo.addFontProperties("F7", "Times-Roman", "normal", "bold");
+ fontInfo.addFontProperties("F8", "Times-Roman", "oblique", "bold");
+ fontInfo.addFontProperties("F8", "Times-Roman", "italic", "bold");
+ fontInfo.addFontProperties("F5", "Times Roman", "normal", "normal");
+ fontInfo.addFontProperties("F6", "Times Roman", "oblique", "normal");
+ fontInfo.addFontProperties("F6", "Times Roman", "italic", "normal");
+ fontInfo.addFontProperties("F7", "Times Roman", "normal", "bold");
+ fontInfo.addFontProperties("F8", "Times Roman", "oblique", "bold");
+ fontInfo.addFontProperties("F8", "Times Roman", "italic", "bold");
+ fontInfo.addFontProperties("F9", "Computer-Modern-Typewriter",
+ "normal", "normal");
/* Add configured fonts */
- addConfiguredFonts(fontInfo, 15);
+ addConfiguredFonts(fontInfo, 15);
}
- /**
- * Add fonts from configuration file starting with
- * internalnames F
- */
+ /**
+ * Add fonts from configuration file starting with
+ * internalnames F
+ */
public static void addConfiguredFonts(FontInfo fontInfo, int num) {
- String internalName=null;
+ String internalName = null;
FontReader reader = null;
Vector fontInfos = Configuration.getFonts();
if (fontInfos == null)
- return;
-
- for (Enumeration e = fontInfos.elements(); e.hasMoreElements();) {
+ return;
+
+ for (Enumeration e = fontInfos.elements(); e.hasMoreElements(); ) {
org.apache.fop.configuration.FontInfo configFontInfo =
(org.apache.fop.configuration.FontInfo)e.nextElement();
-
- try {
- String metricsFile = configFontInfo.getMetricsFile();
- if (metricsFile != null) {
- internalName = "F"+num;
- num++;
- reader = new FontReader(metricsFile);
- reader.useKerning(configFontInfo.getKerning());
- reader.setFontEmbedPath(configFontInfo.getEmbedFile());
- fontInfo.addMetrics(internalName, reader.getFont());
-
- Vector triplets = configFontInfo.getFontTriplets();
- for (Enumeration t = triplets.elements(); t.hasMoreElements();) {
- FontTriplet triplet = (FontTriplet)t.nextElement();
-
- fontInfo.addFontProperties(internalName,
- triplet.getName(),
- triplet.getStyle(),
- triplet.getWeight());
+
+ try {
+ String metricsFile = configFontInfo.getMetricsFile();
+ if (metricsFile != null) {
+ internalName = "F" + num;
+ num++;
+ reader = new FontReader(metricsFile);
+ reader.useKerning(configFontInfo.getKerning());
+ reader.setFontEmbedPath(configFontInfo.getEmbedFile());
+ fontInfo.addMetrics(internalName, reader.getFont());
+
+ Vector triplets = configFontInfo.getFontTriplets();
+ for (Enumeration t = triplets.elements();
+ t.hasMoreElements(); ) {
+ FontTriplet triplet = (FontTriplet)t.nextElement();
+
+ fontInfo.addFontProperties(internalName,
+ triplet.getName(),
+ triplet.getStyle(),
+ triplet.getWeight());
+ }
}
+ } catch (Exception ex) {
+ MessageHandler.error("Failed to read font metrics file "
+ + configFontInfo.getMetricsFile()
+ + " : " + ex.getMessage());
}
- } catch (Exception ex) {
- MessageHandler.error("Failed to read font metrics file " +
- configFontInfo.getMetricsFile() +
- " : " + ex.getMessage());
- }
}
}
-
+
/**
* add the fonts in the font info to the PDF document
*
@@ -269,23 +187,19 @@ public class FontSetup {
* @param fontInfo font info object to get font information from
*/
public static void addToResources(PDFDocument doc, FontInfo fontInfo) {
- Hashtable fonts = fontInfo.getUsedFonts();
- Enumeration e = fonts.keys();
- PDFResources resources = doc.getResources();
- while (e.hasMoreElements()) {
- String f = (String) e.nextElement();
- Font font = (Font)fonts.get(f);
- FontDescriptor desc = null;
- if (font instanceof FontDescriptor) {
- desc = (FontDescriptor)font;
+ Hashtable fonts = fontInfo.getUsedFonts();
+ Enumeration e = fonts.keys();
+ PDFResources resources = doc.getResources();
+ while (e.hasMoreElements()) {
+ String f = (String)e.nextElement();
+ Font font = (Font)fonts.get(f);
+ FontDescriptor desc = null;
+ if (font instanceof FontDescriptor) {
+ desc = (FontDescriptor)font;
+ }
+ resources.addFont(doc.makeFont(f, font.fontName(),
+ font.encoding(), font, desc));
}
- resources.addFont(doc.makeFont(f,
- font.fontName(),
- font.encoding(),
- font,
- desc
- )
- );
- }
}
+
}
diff --git a/src/org/apache/fop/render/pdf/PDFRenderer.java b/src/org/apache/fop/render/pdf/PDFRenderer.java
index 8ad9c1a8f..7d9e27381 100644
--- a/src/org/apache/fop/render/pdf/PDFRenderer.java
+++ b/src/org/apache/fop/render/pdf/PDFRenderer.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.render.pdf;
@@ -53,44 +54,66 @@ import java.awt.Dimension;
*/
public class PDFRenderer extends PrintRenderer {
- /** the PDF Document being created */
+ /**
+ * the PDF Document being created
+ */
protected PDFDocument pdfDoc;
- /** the /Resources object of the PDF document being created */
+ /**
+ * the /Resources object of the PDF document being created
+ */
protected PDFResources pdfResources;
- /** the current stream to add PDF commands to */
+ /**
+ * the current stream to add PDF commands to
+ */
PDFStream currentStream;
- /** the current annotation list to add annotations to */
+ /**
+ * the current annotation list to add annotations to
+ */
PDFAnnotList currentAnnotList;
- /** the current page to add annotations to */
+ /**
+ * the current page to add annotations to
+ */
PDFPage currentPage;
PDFColor currentColor;
- /** true if a TJ command is left to be written */
+ /**
+ * true if a TJ command is left to be written
+ */
boolean textOpen = false;
- /** the previous Y coordinate of the last word written.
- Used to decide if we can draw the next word on the same line. */
+ /**
+ * the previous Y coordinate of the last word written.
+ * Used to decide if we can draw the next word on the same line.
+ */
int prevWordY = 0;
- /** the previous X coordinate of the last word written.
- used to calculate how much space between two words */
+ /**
+ * the previous X coordinate of the last word written.
+ * used to calculate how much space between two words
+ */
int prevWordX = 0;
- /** The width of the previous word. Used to calculate space between */
+ /**
+ * The width of the previous word. Used to calculate space between
+ */
int prevWordWidth = 0;
private PDFOutline rootOutline;
- /** reusable word area string buffer to reduce memory usage */
+ /**
+ * reusable word area string buffer to reduce memory usage
+ */
private StringBuffer _wordAreaPDF = new StringBuffer();
- /** options */
- protected Hashtable options;
+ /**
+ * options
+ */
+ protected Hashtable options;
/**
* create the PDF renderer
@@ -99,11 +122,13 @@ public class PDFRenderer extends PrintRenderer {
this.pdfDoc = new PDFDocument();
}
- /** set up renderer options */
- public void setOptions(Hashtable options) {
- this.options = options;
- }
-
+ /**
+ * set up renderer options
+ */
+ public void setOptions(Hashtable options) {
+ this.options = options;
+ }
+
/**
* set the PDF document's producer
*
@@ -127,13 +152,13 @@ public class PDFRenderer extends PrintRenderer {
this.pdfDoc.setIDReferences(idReferences);
Enumeration e = areaTree.getPages().elements();
while (e.hasMoreElements()) {
- this.renderPage((Page) e.nextElement());
+ this.renderPage((Page)e.nextElement());
}
if (!idReferences.isEveryIdValid()) {
- // throw new FOPException("The following id's were referenced but not found: "+idReferences.getInvalidIds()+"\n");
- MessageHandler.errorln("WARNING: The following id's were referenced but not found: "+
- idReferences.getInvalidIds() + "\n");
+ // throw new FOPException("The following id's were referenced but not found: "+idReferences.getInvalidIds()+"\n");
+ MessageHandler.errorln("WARNING: The following id's were referenced but not found: "
+ + idReferences.getInvalidIds() + "\n");
}
renderRootExtensions(areaTree);
@@ -160,10 +185,10 @@ public class PDFRenderer extends PrintRenderer {
PDFPathPaint stroke) {
closeText();
- currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) +
- (x1 / 1000f) + " "+ (y1 / 1000f) + " m " +
- (x2 / 1000f) + " "+ (y2 / 1000f) + " l " +
- (th / 1000f) + " w S\n" + "Q\nBT\n");
+ currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false)
+ + (x1 / 1000f) + " " + (y1 / 1000f) + " m "
+ + (x2 / 1000f) + " " + (y2 / 1000f) + " l "
+ + (th / 1000f) + " w S\n" + "Q\nBT\n");
}
/**
@@ -179,13 +204,14 @@ public class PDFRenderer extends PrintRenderer {
* @param g the green component
* @param b the blue component
*/
- protected void addLine(int x1, int y1, int x2, int y2, int th,
- int rs, PDFPathPaint stroke) {
+ protected void addLine(int x1, int y1, int x2, int y2, int th, int rs,
+ PDFPathPaint stroke) {
closeText();
- currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) +
- setRuleStylePattern(rs) + (x1 / 1000f) + " "+
- (y1 / 1000f) + " m " + (x2 / 1000f) + " "+
- (y2 / 1000f) + " l " + (th / 1000f) + " w S\n" + "Q\nBT\n");
+ currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false)
+ + setRuleStylePattern(rs) + (x1 / 1000f) + " "
+ + (y1 / 1000f) + " m " + (x2 / 1000f) + " "
+ + (y2 / 1000f) + " l " + (th / 1000f) + " w S\n"
+ + "Q\nBT\n");
}
/**
@@ -197,12 +223,12 @@ public class PDFRenderer extends PrintRenderer {
* @param h the height in millipoints
* @param stroke the stroke color/gradient
*/
- protected void addRect(int x, int y, int w, int h,
- PDFPathPaint stroke) {
+ protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke) {
closeText();
- currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) +
- (x / 1000f) + " " + (y / 1000f) + " " + (w / 1000f) +
- " " + (h / 1000f) + " re s\n" + "Q\nBT\n");
+ currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false)
+ + (x / 1000f) + " " + (y / 1000f) + " "
+ + (w / 1000f) + " " + (h / 1000f) + " re s\n"
+ + "Q\nBT\n");
}
/**
@@ -215,31 +241,31 @@ public class PDFRenderer extends PrintRenderer {
* @param fill the fill color/gradient
* @param stroke the stroke color/gradient
*/
- protected void addRect(int x, int y, int w, int h,
- PDFPathPaint stroke, PDFPathPaint fill) {
+ protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke,
+ PDFPathPaint fill) {
closeText();
- currentStream.add("ET\nq\n" + fill.getColorSpaceOut(true) +
- stroke.getColorSpaceOut(false) + (x / 1000f) + " " +
- (y / 1000f) + " " + (w / 1000f) + " " + (h / 1000f) +
- " re b\n" + "Q\nBT\n");
+ currentStream.add("ET\nq\n" + fill.getColorSpaceOut(true)
+ + stroke.getColorSpaceOut(false) + (x / 1000f)
+ + " " + (y / 1000f) + " " + (w / 1000f) + " "
+ + (h / 1000f) + " re b\n" + "Q\nBT\n");
}
/**
- * add a filled rectangle to the current stream
- *
- * @param x the x position of left edge in millipoints
- * @param y the y position of top edge in millipoints
- * @param w the width in millipoints
- * @param h the height in millipoints
- * @param fill the fill color/gradient
- */
+ * add a filled rectangle to the current stream
+ *
+ * @param x the x position of left edge in millipoints
+ * @param y the y position of top edge in millipoints
+ * @param w the width in millipoints
+ * @param h the height in millipoints
+ * @param fill the fill color/gradient
+ */
protected void addFilledRect(int x, int y, int w, int h,
- PDFPathPaint fill) {
+ PDFPathPaint fill) {
closeText();
- currentStream.add("ET\nq\n" + fill.getColorSpaceOut(true) +
- (x / 1000f) + " " +
- (y / 1000f) + " " + (w / 1000f) + " " + (h / 1000f) +
- " re f\n" + "Q\nBT\n");
+ currentStream.add("ET\nq\n" + fill.getColorSpaceOut(true)
+ + (x / 1000f) + " " + (y / 1000f) + " "
+ + (w / 1000f) + " " + (h / 1000f) + " re f\n"
+ + "Q\nBT\n");
}
/**
@@ -261,57 +287,57 @@ public class PDFRenderer extends PrintRenderer {
try {
closeText();
- SVGDocument svg =
- ((SVGImage) img).getSVGDocument();
+ SVGDocument svg = ((SVGImage)img).getSVGDocument();
currentStream.add("ET\nq\n");
- renderSVGDocument(svg, (int) x, (int) y, area.getFontState());
+ renderSVGDocument(svg, (int)x, (int)y, area.getFontState());
currentStream.add("Q\nBT\n");
- } catch (FopImageException e) {
- }
+ } catch (FopImageException e) {}
} else {
int xObjectNum = this.pdfDoc.addImage(img);
closeText();
- currentStream.add("ET\nq\n" + (((float) w) / 1000f) +
- " 0 0 " + (((float) h) / 1000f) + " " +
- (((float) x) / 1000f) + " " +
- (((float)(y - h)) / 1000f) + " cm\n" + "/Im" +
- xObjectNum + " Do\nQ\nBT\n");
+ currentStream.add("ET\nq\n" + (((float)w) / 1000f) + " 0 0 "
+ + (((float)h) / 1000f) + " "
+ + (((float)x) / 1000f) + " "
+ + (((float)(y - h)) / 1000f) + " cm\n" + "/Im"
+ + xObjectNum + " Do\nQ\nBT\n");
}
- this.currentXPosition += area.getContentWidth();
+ this.currentXPosition += area.getContentWidth();
}
- /** render a foreign object area */
+ /**
+ * render a foreign object area
+ */
public void renderForeignObjectArea(ForeignObjectArea area) {
// if necessary need to scale and align the content
this.currentXPosition = this.currentXPosition + area.getXOffset();
this.currentYPosition = this.currentYPosition;
switch (area.getAlign()) {
- case TextAlign.START:
- break;
- case TextAlign.END:
- break;
- case TextAlign.CENTER:
- case TextAlign.JUSTIFY:
- break;
+ case TextAlign.START:
+ break;
+ case TextAlign.END:
+ break;
+ case TextAlign.CENTER:
+ case TextAlign.JUSTIFY:
+ break;
}
switch (area.getVerticalAlign()) {
- case VerticalAlign.BASELINE:
- break;
- case VerticalAlign.MIDDLE:
- break;
- case VerticalAlign.SUB:
- break;
- case VerticalAlign.SUPER:
- break;
- case VerticalAlign.TEXT_TOP:
- break;
- case VerticalAlign.TEXT_BOTTOM:
- break;
- case VerticalAlign.TOP:
- break;
- case VerticalAlign.BOTTOM:
- break;
+ case VerticalAlign.BASELINE:
+ break;
+ case VerticalAlign.MIDDLE:
+ break;
+ case VerticalAlign.SUB:
+ break;
+ case VerticalAlign.SUPER:
+ break;
+ case VerticalAlign.TEXT_TOP:
+ break;
+ case VerticalAlign.TEXT_BOTTOM:
+ break;
+ case VerticalAlign.TOP:
+ break;
+ case VerticalAlign.BOTTOM:
+ break;
}
closeText();
@@ -320,28 +346,28 @@ public class PDFRenderer extends PrintRenderer {
// align and scale
currentStream.add("q\n");
switch (area.scalingMethod()) {
- case Scaling.UNIFORM:
- break;
- case Scaling.NON_UNIFORM:
- break;
+ case Scaling.UNIFORM:
+ break;
+ case Scaling.NON_UNIFORM:
+ break;
}
// if the overflow is auto (default), scroll or visible
// then the contents should not be clipped, since this
// is considered a printing medium.
switch (area.getOverflow()) {
- case Overflow.VISIBLE:
- case Overflow.SCROLL:
- case Overflow.AUTO:
- break;
- case Overflow.HIDDEN:
- break;
+ case Overflow.VISIBLE:
+ case Overflow.SCROLL:
+ case Overflow.AUTO:
+ break;
+ case Overflow.HIDDEN:
+ break;
}
area.getObject().render(this);
currentStream.add("Q\n");
currentStream.add("BT\n");
this.currentXPosition += area.getEffectiveWidth();
- // this.currentYPosition -= area.getEffectiveHeight();
+ // this.currentYPosition -= area.getEffectiveHeight();
}
/**
@@ -356,7 +382,8 @@ public class PDFRenderer extends PrintRenderer {
renderSVGDocument(area.getSVGDocument(), x, y, area.getFontState());
}
- protected void renderSVGDocument(Document doc, int x, int y, FontState fs) {
+ protected void renderSVGDocument(Document doc, int x, int y,
+ FontState fs) {
SVGSVGElement svg = ((SVGDocument)doc).getRootElement();
int w = (int)(svg.getWidth().getBaseVal().getValue() * 1000);
int h = (int)(svg.getHeight().getBaseVal().getValue() * 1000);
@@ -372,8 +399,8 @@ public class PDFRenderer extends PrintRenderer {
if (w != 0 && h != 0) {
currentStream.add(x / 1000f + " " + y / 1000f + " m\n");
currentStream.add((x + w) / 1000f + " " + y / 1000f + " l\n");
- currentStream.add((x + w) / 1000f + " " + (y - h) / 1000f +
- " l\n");
+ currentStream.add((x + w) / 1000f + " " + (y - h) / 1000f
+ + " l\n");
currentStream.add(x / 1000f + " " + (y - h) / 1000f + " l\n");
currentStream.add("h\n");
currentStream.add("W\n");
@@ -382,8 +409,8 @@ public class PDFRenderer extends PrintRenderer {
// transform so that the coordinates (0,0) is from the top left
// and positive is down and to the right. (0,0) is where the
// viewBox puts it.
- currentStream.add(sx + " 0 0 " + sy + " " + xOffset / 1000f +
- " " + yOffset / 1000f + " cm\n");
+ currentStream.add(sx + " 0 0 " + sy + " " + xOffset / 1000f + " "
+ + yOffset / 1000f + " cm\n");
UserAgent userAgent = new MUserAgent(new AffineTransform());
@@ -394,12 +421,12 @@ public class PDFRenderer extends PrintRenderer {
PDFAElementBridge aBridge = new PDFAElementBridge();
ctx.putBridge(aBridge);
GraphicsNode root;
- PDFGraphics2D graphics =
- new PDFGraphics2D(true, fs, pdfDoc,
- currentFontName, currentFontSize, currentXPosition,
- currentYPosition);
- graphics.setGraphicContext(
- new org.apache.batik.ext.awt.g2d.GraphicContext());
+ PDFGraphics2D graphics = new PDFGraphics2D(true, fs, pdfDoc,
+ currentFontName,
+ currentFontSize,
+ currentXPosition,
+ currentYPosition);
+ graphics.setGraphicContext(new org.apache.batik.ext.awt.g2d.GraphicContext());
graphics.setRenderingHints(rc.getRenderingHints());
aBridge.setPDFGraphics2D(graphics);
try {
@@ -407,7 +434,8 @@ public class PDFRenderer extends PrintRenderer {
root.paint(graphics, rc);
currentStream.add(graphics.getString());
} catch (Exception e) {
- MessageHandler.errorln("Error: svg graphic could not be rendered: " + e.getMessage());
+ MessageHandler.errorln("Error: svg graphic could not be rendered: "
+ + e.getMessage());
}
currentStream.add("Q\n");
@@ -424,22 +452,23 @@ public class PDFRenderer extends PrintRenderer {
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
FontRenderContext fontRenderContext =
- new FontRenderContext(new AffineTransform(), true,
- true);
+ new FontRenderContext(new AffineTransform(), true, true);
TextPainter textPainter = null;
- Boolean bl = org.apache.fop.configuration.Configuration.getBooleanValue("strokeSVGText");
- if(bl == null || bl.booleanValue()) {
+ Boolean bl =
+ org.apache.fop.configuration.Configuration.getBooleanValue("strokeSVGText");
+ if (bl == null || bl.booleanValue()) {
textPainter = new StrokingTextPainter();
} else {
textPainter = new PDFTextPainter(fs);
}
GraphicsNodeRableFactory gnrFactory =
- new ConcreteGraphicsNodeRableFactory();
+ new ConcreteGraphicsNodeRableFactory();
- nodeRenderContext = new GraphicsNodeRenderContext(
- new AffineTransform(), null, hints,
- fontRenderContext, textPainter, gnrFactory);
+ nodeRenderContext =
+ new GraphicsNodeRenderContext(new AffineTransform(), null,
+ hints, fontRenderContext,
+ textPainter, gnrFactory);
nodeRenderContext.setTextPainter(textPainter);
}
@@ -460,7 +489,7 @@ public class PDFRenderer extends PrintRenderer {
boolean kerningAvailable = false;
kerning = area.getFontState().getKerning();
- if (kerning != null && !kerning.isEmpty()) {
+ if (kerning != null &&!kerning.isEmpty()) {
kerningAvailable = true;
}
@@ -469,16 +498,16 @@ public class PDFRenderer extends PrintRenderer {
// This assumes that *all* CIDFonts use a /ToUnicode mapping
boolean useMultiByte = false;
- Font f = (Font) area.getFontState().getFontInfo().getFonts().
- get(name);
+ Font f =
+ (Font)area.getFontState().getFontInfo().getFonts().get(name);
if (f instanceof CIDFont)
useMultiByte = true;
- //String startText = useMultiByte ? " " : ") ";
- if ((!name.equals(this.currentFontName)) ||
- (size != this.currentFontSize)) {
+ if ((!name.equals(this.currentFontName))
+ || (size != this.currentFontSize)) {
closeText();
this.currentFontName = name;
@@ -488,16 +517,16 @@ public class PDFRenderer extends PrintRenderer {
PDFColor areaColor = null;
if (this.currentFill instanceof PDFColor) {
- areaColor = (PDFColor) this.currentFill;
+ areaColor = (PDFColor)this.currentFill;
}
- if (areaColor == null ||
- areaColor.red() != (double) area.getRed() ||
- areaColor.green() != (double) area.getGreen() ||
- areaColor.blue() != (double) area.getBlue()) {
+ if (areaColor == null || areaColor.red() != (double)area.getRed()
+ || areaColor.green() != (double)area.getGreen()
+ || areaColor.blue() != (double)area.getBlue()) {
- areaColor = new PDFColor((double) area.getRed(),
- (double) area.getGreen(), (double) area.getBlue());
+ areaColor = new PDFColor((double)area.getRed(),
+ (double)area.getGreen(),
+ (double)area.getBlue());
closeText();
@@ -515,22 +544,21 @@ public class PDFRenderer extends PrintRenderer {
if (!textOpen || bl != prevWordY) {
closeText();
- pdf.append("1 0 0 1 " +(rx / 1000f) + " " +
- (bl / 1000f) + " Tm [" + startText);
+ pdf.append("1 0 0 1 " + (rx / 1000f) + " " + (bl / 1000f)
+ + " Tm [" + startText);
prevWordY = bl;
textOpen = true;
} else {
// express the space between words in thousandths of an em
int space = prevWordX - rx + prevWordWidth;
- float emDiff =
- (float) space / (float) currentFontSize * 1000f;
+ float emDiff = (float)space / (float)currentFontSize * 1000f;
// this prevents a problem in Acrobat Reader where large
// numbers cause text to disappear or default to a limit
- if(emDiff < -33000) {
+ if (emDiff < -33000) {
closeText();
- pdf.append("1 0 0 1 " +(rx / 1000f) + " " +
- (bl / 1000f) + " Tm [" + startText);
+ pdf.append("1 0 0 1 " + (rx / 1000f) + " " + (bl / 1000f)
+ + " Tm [" + startText);
textOpen = true;
} else {
pdf.append(Float.toString(emDiff));
@@ -543,7 +571,8 @@ public class PDFRenderer extends PrintRenderer {
String s;
- if (area.getPageNumberID() != null) { // this text is a page number, so resolve it
+ if (area.getPageNumberID()
+ != null) { // this text is a page number, so resolve it
s = idReferences.getPageNumber(area.getPageNumberID());
if (s == null) {
s = "";
@@ -560,15 +589,15 @@ public class PDFRenderer extends PrintRenderer {
if (!useMultiByte) {
if (ch > 127) {
pdf.append("\\");
- pdf.append(Integer.toOctalString((int) ch));
+ pdf.append(Integer.toOctalString((int)ch));
} else {
switch (ch) {
- case '(':
- case ')':
- case '\\':
- pdf.append("\\");
- break;
+ case '(':
+ case ')':
+ case '\\':
+ pdf.append("\\");
+ break;
}
pdf.append(ch);
}
@@ -577,8 +606,8 @@ public class PDFRenderer extends PrintRenderer {
}
if (kerningAvailable && (i + 1) < l) {
- addKerning(pdf, (new Integer((int) ch)),
- (new Integer((int) area.getFontState().mapChar(s.charAt(i + 1)))),
+ addKerning(pdf, (new Integer((int)ch)),
+ (new Integer((int)area.getFontState().mapChar(s.charAt(i + 1)))),
kerning, startText, endText);
}
@@ -602,19 +631,21 @@ public class PDFRenderer extends PrintRenderer {
byte[] uniBytes = null;
try {
- char[] a = {c};
+ char[] a = {
+ c
+ };
uniBytes = new String(a).getBytes("UnicodeBigUnmarked");
} catch (Exception e) {
// This should never fail
}
for (int i = 0; i < uniBytes.length; i++) {
- int b = (uniBytes[i] < 0) ? (int)(256 + uniBytes[i]) :
- (int) uniBytes[i];
+ int b = (uniBytes[i] < 0) ? (int)(256 + uniBytes[i])
+ : (int)uniBytes[i];
String hexString = Integer.toHexString(b);
if (hexString.length() == 1)
- buf = buf.append("0"+hexString);
+ buf = buf.append("0" + hexString);
else
buf = buf.append(hexString);
}
@@ -624,7 +655,8 @@ public class PDFRenderer extends PrintRenderer {
}
- /** Checks to see if we have some text rendering commands open
+ /**
+ * Checks to see if we have some text rendering commands open
* still and writes out the TJ command to the stream if we do
*/
private void closeText() {
@@ -637,14 +669,14 @@ public class PDFRenderer extends PrintRenderer {
}
private void addKerning(StringBuffer buf, Integer ch1, Integer ch2,
- Hashtable kerning, String startText, String endText) {
- Hashtable kernPair = (Hashtable) kerning.get(ch1);
+ Hashtable kerning, String startText,
+ String endText) {
+ Hashtable kernPair = (Hashtable)kerning.get(ch1);
if (kernPair != null) {
- Integer width = (Integer) kernPair.get(ch2);
+ Integer width = (Integer)kernPair.get(ch2);
if (width != null) {
- buf.append(endText).append(-
- (width.intValue())).append(' ').append(startText);
+ buf.append(endText).append(-(width.intValue())).append(' ').append(startText);
}
}
}
@@ -692,7 +724,8 @@ public class PDFRenderer extends PrintRenderer {
currentStream.add("ET\n");
currentPage = this.pdfDoc.makePage(this.pdfResources, currentStream,
- page.getWidth() / 1000, page.getHeight() / 1000, page);
+ page.getWidth() / 1000,
+ page.getHeight() / 1000, page);
if (page.hasLinks()) {
currentAnnotList = this.pdfDoc.makeAnnotList();
@@ -700,18 +733,16 @@ public class PDFRenderer extends PrintRenderer {
Enumeration e = page.getLinkSets().elements();
while (e.hasMoreElements()) {
- LinkSet linkSet = (LinkSet) e.nextElement();
+ LinkSet linkSet = (LinkSet)e.nextElement();
linkSet.align();
String dest = linkSet.getDest();
int linkType = linkSet.getLinkType();
Enumeration f = linkSet.getRects().elements();
while (f.hasMoreElements()) {
- LinkedRectangle lrect =
- (LinkedRectangle) f.nextElement();
- currentAnnotList.addLink(
- this.pdfDoc.makeLink(lrect.getRectangle(),
- dest, linkType));
+ LinkedRectangle lrect = (LinkedRectangle)f.nextElement();
+ currentAnnotList.addLink(this.pdfDoc.makeLink(lrect.getRectangle(),
+ dest, linkType));
}
}
} else {
@@ -726,23 +757,23 @@ public class PDFRenderer extends PrintRenderer {
/**
* defines a string containing dashArray and dashPhase for the rule style
*/
- private String setRuleStylePattern (int style) {
+ private String setRuleStylePattern(int style) {
String rs = "";
switch (style) {
- case org.apache.fop.fo.properties.RuleStyle.SOLID:
- rs = "[] 0 d ";
- break;
- case org.apache.fop.fo.properties.RuleStyle.DASHED:
- rs = "[3 3] 0 d ";
- break;
- case org.apache.fop.fo.properties.RuleStyle.DOTTED:
- rs = "[1 3] 0 d ";
- break;
- case org.apache.fop.fo.properties.RuleStyle.DOUBLE:
- rs = "[] 0 d ";
- break;
- default:
- rs = "[] 0 d ";
+ case org.apache.fop.fo.properties.RuleStyle.SOLID:
+ rs = "[] 0 d ";
+ break;
+ case org.apache.fop.fo.properties.RuleStyle.DASHED:
+ rs = "[3 3] 0 d ";
+ break;
+ case org.apache.fop.fo.properties.RuleStyle.DOTTED:
+ rs = "[1 3] 0 d ";
+ break;
+ case org.apache.fop.fo.properties.RuleStyle.DOUBLE:
+ rs = "[] 0 d ";
+ break;
+ default:
+ rs = "[] 0 d ";
}
return rs;
}
@@ -752,9 +783,9 @@ public class PDFRenderer extends PrintRenderer {
if (v != null) {
Enumeration e = v.elements();
while (e.hasMoreElements()) {
- ExtensionObj ext = (ExtensionObj) e.nextElement();
+ ExtensionObj ext = (ExtensionObj)e.nextElement();
if (ext instanceof Outline) {
- renderOutline((Outline) ext);
+ renderOutline((Outline)ext);
}
}
}
@@ -768,18 +799,20 @@ public class PDFRenderer extends PrintRenderer {
PDFOutline pdfOutline = null;
Outline parent = outline.getParentOutline();
if (parent == null) {
- pdfOutline = this.pdfDoc.makeOutline(rootOutline,
- outline.getLabel().toString(),
- outline.getInternalDestination());
+ pdfOutline =
+ this.pdfDoc.makeOutline(rootOutline,
+ outline.getLabel().toString(),
+ outline.getInternalDestination());
} else {
PDFOutline pdfParentOutline =
- (PDFOutline) parent.getRendererObject();
+ (PDFOutline)parent.getRendererObject();
if (pdfParentOutline == null) {
MessageHandler.errorln("Error: pdfParentOutline is null");
} else {
- pdfOutline = this.pdfDoc.makeOutline(pdfParentOutline,
- outline.getLabel().toString(),
- outline.getInternalDestination());
+ pdfOutline =
+ this.pdfDoc.makeOutline(pdfParentOutline,
+ outline.getLabel().toString(),
+ outline.getInternalDestination());
}
}
@@ -789,12 +822,13 @@ public class PDFRenderer extends PrintRenderer {
Vector v = outline.getOutlines();
Enumeration e = v.elements();
while (e.hasMoreElements()) {
- renderOutline((Outline) e.nextElement());
+ renderOutline((Outline)e.nextElement());
}
}
protected class MUserAgent implements UserAgent {
AffineTransform currentTransform = null;
+
/**
* Creates a new SVGUserAgent.
*/
@@ -828,14 +862,14 @@ public class PDFRenderer extends PrintRenderer {
* Returns a customized the pixel to mm factor.
*/
public float getPixelToMM() {
- return 0.264583333333333333333f; // 72 dpi
+ return 0.264583333333333333333f; // 72 dpi
}
/**
* Returns the language settings.
*/
public String getLanguages() {
- return "en";//userLanguages;
+ return "en"; // userLanguages;
}
/**
@@ -843,7 +877,7 @@ public class PDFRenderer extends PrintRenderer {
* @return null if no user style sheet was specified.
*/
public String getUserStyleSheetURI() {
- return null;//userStyleSheetURI;
+ return null; // userStyleSheetURI;
}
/**
@@ -859,15 +893,14 @@ public class PDFRenderer extends PrintRenderer {
* @param uri The document URI.
*/
public void openLink(SVGAElement elt) {
- //application.openLink(uri);
+ // application.openLink(uri);
}
public Point getClientAreaLocationOnScreen() {
return new Point(0, 0);
}
- public void setSVGCursor(java.awt.Cursor cursor) {
- }
+ public void setSVGCursor(java.awt.Cursor cursor) {}
public AffineTransform getTransform() {
return currentTransform;
@@ -889,7 +922,7 @@ public class PDFRenderer extends PrintRenderer {
return false;
}
- public void registerExtension(BridgeExtension be) {
- }
+ public void registerExtension(BridgeExtension be) {}
+
}
}
diff --git a/src/org/apache/fop/render/pdf/fonts/BFEntry.java b/src/org/apache/fop/render/pdf/fonts/BFEntry.java
index a0f8f198c..4f3fc2376 100644
--- a/src/org/apache/fop/render/pdf/fonts/BFEntry.java
+++ b/src/org/apache/fop/render/pdf/fonts/BFEntry.java
@@ -1,52 +1,8 @@
-/*-- $Id$ --
-
- ============================================================================
- The Apache Software License, Version 1.1
- ============================================================================
-
- Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modifica-
- tion, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- 3. The end-user documentation included with the redistribution, if any, must
- include the following acknowledgment: "This product includes software
- developed by the Apache Software Foundation (http://www.apache.org/)."
- Alternately, this acknowledgment may appear in the software itself, if
- and wherever such third-party acknowledgments normally appear.
-
- 4. The names "Fop" and "Apache Software Foundation" must not be used to
- endorse or promote products derived from this software without prior
- written permission. For written permission, please contact
- apache@apache.org.
-
- 5. Products derived from this software may not be called "Apache", nor may
- "Apache" appear in their name, without prior written permission of the
- Apache Software Foundation.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- This software consists of voluntary contributions made by many individuals
- on behalf of the Apache Software Foundation and was originally created by
- James Tauber . For more information on the Apache
- Software Foundation, please see .
-
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.render.pdf.fonts;
@@ -58,16 +14,13 @@ public class BFEntry {
public int unicodeStart;
public int unicodeEnd;
public int glyphStartIndex;
-
- public BFEntry() {
- }
- public BFEntry (int unicodeStart,
- int unicodeEnd,
- int glyphStartIndex) {
+ public BFEntry() {}
+
+ public BFEntry(int unicodeStart, int unicodeEnd, int glyphStartIndex) {
this.unicodeStart = unicodeStart;
this.unicodeEnd = unicodeEnd;
this.glyphStartIndex = glyphStartIndex;
}
-
+
}
diff --git a/src/org/apache/fop/render/pdf/fonts/MultiByteFont.java b/src/org/apache/fop/render/pdf/fonts/MultiByteFont.java
index 2fb09b1b8..7a667d79b 100644
--- a/src/org/apache/fop/render/pdf/fonts/MultiByteFont.java
+++ b/src/org/apache/fop/render/pdf/fonts/MultiByteFont.java
@@ -1,8 +1,8 @@
-/* $Id$
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.render.pdf.fonts;
@@ -38,7 +38,9 @@ public class MultiByteFont extends CIDFont implements FontDescriptor {
public int xHeight = 0;
public int ascender = 0;
public int descender = 0;
- public int[] fontBBox = {0, 0, 0, 0};
+ public int[] fontBBox = {
+ 0, 0, 0, 0
+ };
public String embedFileName = null;
public String embedResourceName = null;
@@ -53,7 +55,7 @@ public class MultiByteFont extends CIDFont implements FontDescriptor {
public Hashtable kerning = new Hashtable();
public boolean useKerning = true;
- private String namePrefix = null; // Quasi unique prefix
+ private String namePrefix = null; // Quasi unique prefix
private static int uniqueCounter = 1;
public PDFWArray warray = new PDFWArray();
public int width[] = null;
@@ -61,9 +63,14 @@ public class MultiByteFont extends CIDFont implements FontDescriptor {
public BFEntry[] bfentries = null;
- /** usedGlyphs contains orginal, new glyph index */
+ /**
+ * usedGlyphs contains orginal, new glyph index
+ */
private Hashtable usedGlyphs = new Hashtable();
- /** usedGlyphsIndex contains new glyph, original index */
+
+ /**
+ * usedGlyphsIndex contains new glyph, original index
+ */
private Hashtable usedGlyphsIndex = new Hashtable();
int usedGlyphsCount = 0;
@@ -85,12 +92,13 @@ public class MultiByteFont extends CIDFont implements FontDescriptor {
cnt = uniqueCounter++;
}
int ctm = (int)(System.currentTimeMillis() & 0xffff);
- namePrefix = new String(cnt + "E"+ Integer.toHexString(ctm));
+ namePrefix = new String(cnt + "E" + Integer.toHexString(ctm));
}
public final boolean hasKerningInfo() {
return (useKerning & kerning.isEmpty());
}
+
public final java.util.Hashtable getKerningInfo() {
if (useKerning)
return kerning;
@@ -105,42 +113,55 @@ public class MultiByteFont extends CIDFont implements FontDescriptor {
public String getLang() {
return null;
}
+
public String getPanose() {
return null;
}
+
public int getAvgWidth() {
return -1;
}
+
public int getMinWidth() {
return -1;
}
+
public int getMaxWidth() {
return -1;
}
+
public int getleading() {
return -1;
}
+
public int getStemH() {
return 0;
}
+
public int getMissingWidth() {
return missingWidth;
}
+
public int getDefaultWidth() {
return defaultWidth;
}
+
public String getRegistry() {
return "Adobe";
}
+
public String getOrdering() {
return "UCS";
}
+
public int getSupplement() {
return 0;
}
+
public byte getCidType() {
return cidType;
}
+
public String getCidBaseFont() {
return isEmbeddable() ? namePrefix + fontName : fontName;
}
@@ -156,7 +177,7 @@ public class MultiByteFont extends CIDFont implements FontDescriptor {
int[] tmpWidth = new int[usedGlyphsCount];
for (int i = 0; i < usedGlyphsCount; i++) {
- Integer nw = (Integer) usedGlyphsIndex.get(new Integer(i));
+ Integer nw = (Integer)usedGlyphsIndex.get(new Integer(i));
int nwx = (nw == null) ? 0 : nw.intValue();
tmpWidth[i] = width[nwx];
}
@@ -166,8 +187,8 @@ public class MultiByteFont extends CIDFont implements FontDescriptor {
}
public boolean isEmbeddable() {
- return (embedFileName == null && embedResourceName == null) ?
- false : true;
+ return (embedFileName == null && embedResourceName == null) ? false
+ : true;
}
@@ -176,8 +197,7 @@ public class MultiByteFont extends CIDFont implements FontDescriptor {
FontFileReader reader = new FontFileReader(embedFileName);
TTFSubSetFile subset = new TTFSubSetFile();
- byte[] subsetFont =
- subset.readFont(reader, ttcName, usedGlyphs);
+ byte[] subsetFont = subset.readFont(reader, ttcName, usedGlyphs);
// Only TrueType CID fonts are supported now
embeddedFont = new PDFTTFStream(i, subsetFont.length);
@@ -185,12 +205,12 @@ public class MultiByteFont extends CIDFont implements FontDescriptor {
embeddedFont.addFilter("ascii-85");
embeddedFont.setData(subsetFont, subsetFont.length);
} catch (IOException ioe) {
- MessageHandler.errorln("Failed to embed font ["+i+"] " + fontName +
- ": " + ioe.getMessage());
- return (PDFStream) null;
+ MessageHandler.errorln("Failed to embed font [" + i + "] "
+ + fontName + ": " + ioe.getMessage());
+ return (PDFStream)null;
}
- return (PDFStream) embeddedFont;
+ return (PDFStream)embeddedFont;
}
public String encoding() {
@@ -204,9 +224,11 @@ public class MultiByteFont extends CIDFont implements FontDescriptor {
public int getAscender() {
return ascender;
}
+
public int getDescender() {
return descender;
}
+
public int getCapHeight() {
return capHeight;
}
@@ -253,7 +275,7 @@ public class MultiByteFont extends CIDFont implements FontDescriptor {
public int width(int i, int size) {
if (isEmbeddable()) {
- Integer idx = (Integer) usedGlyphsIndex.get(new Integer(i));
+ Integer idx = (Integer)usedGlyphsIndex.get(new Integer(i));
return size * width[idx.intValue()];
} else {
return size * width[i];
@@ -270,7 +292,7 @@ public class MultiByteFont extends CIDFont implements FontDescriptor {
public Integer reMap(Integer i) {
if (isEmbeddable()) {
- Integer ret = (Integer) usedGlyphsIndex.get(i);
+ Integer ret = (Integer)usedGlyphsIndex.get(i);
if (ret == null)
ret = i;
return ret;
@@ -281,36 +303,37 @@ public class MultiByteFont extends CIDFont implements FontDescriptor {
}
public char mapChar(char c) {
- int idx = (int) c;
+ int idx = (int)c;
int retIdx = 0;
for (int i = 0; (i < bfentries.length) && retIdx == 0; i++) {
- if (bfentries[i].unicodeStart <= idx &&
- bfentries[i].unicodeEnd >= idx) {
- retIdx = bfentries[i].glyphStartIndex + idx -
- bfentries[i].unicodeStart;
+ if (bfentries[i].unicodeStart <= idx
+ && bfentries[i].unicodeEnd >= idx) {
+ retIdx = bfentries[i].glyphStartIndex + idx
+ - bfentries[i].unicodeStart;
}
}
if (isEmbeddable()) {
// Reencode to a new subset font or get
// the reencoded value
- Integer newIdx = (Integer) usedGlyphs.get(new Integer(retIdx));
+ Integer newIdx = (Integer)usedGlyphs.get(new Integer(retIdx));
if (newIdx == null) {
usedGlyphs.put(new Integer(retIdx),
new Integer(usedGlyphsCount));
usedGlyphsIndex.put(new Integer(usedGlyphsCount),
new Integer(retIdx));
retIdx = usedGlyphsCount;
- //System.out.println(c+"("+(int)c+") = "+retIdx);
+ // System.out.println(c+"("+(int)c+") = "+retIdx);
usedGlyphsCount++;
} else {
retIdx = newIdx.intValue();
}
}
- return (char) retIdx;
+ return (char)retIdx;
}
+
}
diff --git a/src/org/apache/fop/render/pdf/fonts/SingleByteFont.java b/src/org/apache/fop/render/pdf/fonts/SingleByteFont.java
index 8a847e2c5..e780594f0 100644
--- a/src/org/apache/fop/render/pdf/fonts/SingleByteFont.java
+++ b/src/org/apache/fop/render/pdf/fonts/SingleByteFont.java
@@ -1,8 +1,8 @@
-/* $Id$
- *
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.render.pdf.fonts;
@@ -24,132 +24,165 @@ import java.util.Hashtable;
public class SingleByteFont extends Font implements FontDescriptor {
public String fontName = null;
public String encoding = "WinAnsiEncoding";
-
+
public int capHeight = 0;
public int xHeight = 0;
public int ascender = 0;
public int descender = 0;
- public int[] fontBBox = {0, 0, 0, 0};
-
+ public int[] fontBBox = {
+ 0, 0, 0, 0
+ };
+
public String embedFileName = null;
public String embedResourceName = null;
- public PDFStream embeddedFont=null;
-
+ public PDFStream embeddedFont = null;
+
public int firstChar = 0;
public int lastChar = 255;
public int flags = 4;
public int stemV = 0;
public int italicAngle = 0;
public int missingWidth = 0;
-
- public Hashtable kerning=new Hashtable();
+
+ public Hashtable kerning = new Hashtable();
public boolean useKerning = true;
-
+
public int width[] = null;
public byte subType = 0;
-
+
public final boolean hasKerningInfo() {
return (useKerning & kerning.isEmpty());
}
-
+
public final java.util.Hashtable getKerningInfo() {
- if (useKerning)
- return kerning;
- else
- return new Hashtable();
+ if (useKerning)
+ return kerning;
+ else
+ return new Hashtable();
}
public byte getSubType() {
return subType;
}
- public int getAvgWidth() {return -1;}
- public int getMinWidth() {return -1;}
- public int getMaxWidth() {return -1;}
- public int getleading() {return -1;}
- public int getStemH() {return 0;}
- public int getMissingWidth() {return missingWidth;}
+ public int getAvgWidth() {
+ return -1;
+ }
- public String getCharEncoding() {return encoding;}
+ public int getMinWidth() {
+ return -1;
+ }
+
+ public int getMaxWidth() {
+ return -1;
+ }
+
+ public int getleading() {
+ return -1;
+ }
+
+ public int getStemH() {
+ return 0;
+ }
+
+ public int getMissingWidth() {
+ return missingWidth;
+ }
+
+ public String getCharEncoding() {
+ return encoding;
+ }
public boolean isEmbeddable() {
- return (embedFileName==null && embedResourceName==null) ? false : true;
+ return (embedFileName == null && embedResourceName == null) ? false
+ : true;
}
-
+
public PDFStream getFontFile(int i) {
- InputStream instream=null;
-
+ InputStream instream = null;
+
// Get file first
- if (embedFileName!=null)
- try {
- instream=new FileInputStream(embedFileName);
- } catch (Exception e) {
- System.out.println("Failed to embed fontfile: "+embedFileName);
- }
-
- // Get resource
- if (instream==null && embedResourceName!=null)
- try {
- instream=new BufferedInputStream(this.getClass().getResourceAsStream(embedResourceName));
- } catch (Exception e) {
- System.out.println("Failed to embed fontresource: "+embedResourceName);
- }
-
- if (instream==null)
+ if (embedFileName != null)
+ try {
+ instream = new FileInputStream(embedFileName);
+ } catch (Exception e) {
+ System.out.println("Failed to embed fontfile: "
+ + embedFileName);
+ }
+
+ // Get resource
+ if (instream == null && embedResourceName != null)
+ try {
+ instream =
+ new BufferedInputStream(this.getClass().getResourceAsStream(embedResourceName));
+ } catch (Exception e) {
+ System.out.println("Failed to embed fontresource: "
+ + embedResourceName);
+ }
+
+ if (instream == null)
return (PDFStream)null;
-
- // Read fontdata
+
+ // Read fontdata
byte[] file = new byte[128000];
int fsize = 0;
try {
- int l = instream.read(file, 0, 128000);
- fsize += l;
-
- if (l==128000) {
- // More to read - needs to extend
- byte[] tmpbuf;
-
- while (l > 0) {
- tmpbuf = new byte[file.length + 64000];
- System.arraycopy(file, 0, tmpbuf, 0, file.length);
- l=instream.read(tmpbuf, file.length, 64000);
- fsize += l;
- file = tmpbuf;
-
- if (l < 64000) // whole file read. No need to loop again
- l=0;
- }
- }
-
- if (subType == org.apache.fop.pdf.PDFFont.TYPE1) {
- embeddedFont=new PDFT1Stream(i, fsize);
- ((PDFT1Stream)embeddedFont).setData(file, fsize);
- } else {
- embeddedFont=new PDFTTFStream(i, fsize);
- ((PDFTTFStream)embeddedFont).setData(file, fsize);
- }
-
- embeddedFont.addFilter("flate");
- embeddedFont.addFilter("ascii-85");
- instream.close();
- } catch (Exception e) {}
-
- return (PDFStream) embeddedFont;
- }
-
+ int l = instream.read(file, 0, 128000);
+ fsize += l;
+
+ if (l == 128000) {
+ // More to read - needs to extend
+ byte[] tmpbuf;
+
+ while (l > 0) {
+ tmpbuf = new byte[file.length + 64000];
+ System.arraycopy(file, 0, tmpbuf, 0, file.length);
+ l = instream.read(tmpbuf, file.length, 64000);
+ fsize += l;
+ file = tmpbuf;
+
+ if (l < 64000) // whole file read. No need to loop again
+ l = 0;
+ }
+ }
+
+ if (subType == org.apache.fop.pdf.PDFFont.TYPE1) {
+ embeddedFont = new PDFT1Stream(i, fsize);
+ ((PDFT1Stream)embeddedFont).setData(file, fsize);
+ } else {
+ embeddedFont = new PDFTTFStream(i, fsize);
+ ((PDFTTFStream)embeddedFont).setData(file, fsize);
+ }
+
+ embeddedFont.addFilter("flate");
+ embeddedFont.addFilter("ascii-85");
+ instream.close();
+ } catch (Exception e) {}
+
+ return (PDFStream)embeddedFont;
+ }
+
public String encoding() {
return encoding;
}
-
+
public String fontName() {
return fontName;
}
- public int getAscender() {return ascender;}
- public int getDescender() {return descender;}
- public int getCapHeight() {return capHeight;}
+ public int getAscender() {
+ return ascender;
+ }
+
+ public int getDescender() {
+ return descender;
+ }
+
+ public int getCapHeight() {
+ return capHeight;
+ }
public int getAscender(int size) {
return size * ascender;
@@ -185,7 +218,7 @@ public class SingleByteFont extends Font implements FontDescriptor {
public int getFirstChar() {
return 0;
- //return firstChar;
+ // return firstChar;
}
public int getLastChar() {
@@ -198,9 +231,11 @@ public class SingleByteFont extends Font implements FontDescriptor {
public int[] getWidths(int size) {
int[] arr = new int[width.length];
- System.arraycopy(width, 0, arr, 0, width.length-1);
- for( int i = 0; i < arr.length; i++) arr[i] *= size;
+ System.arraycopy(width, 0, arr, 0, width.length - 1);
+ for (int i = 0; i < arr.length; i++)
+ arr[i] *= size;
return arr;
}
+
}
diff --git a/src/org/apache/fop/render/ps/ASCII85EncodeFilter.java b/src/org/apache/fop/render/ps/ASCII85EncodeFilter.java
index 1ba0f615c..887598868 100644
--- a/src/org/apache/fop/render/ps/ASCII85EncodeFilter.java
+++ b/src/org/apache/fop/render/ps/ASCII85EncodeFilter.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -21,12 +22,11 @@ public class ASCII85EncodeFilter implements Filter {
private static final long base85_2 = base85_3 * base85_4;
private static final long base85_1 = base85_2 * base85_4;
- protected ASCII85EncodeFilter() {
- }
+ protected ASCII85EncodeFilter() {}
public long write(OutputStream out, byte[] buf, int len,
long bw) throws IOException {
- //Assumption: len<80
+ // Assumption: len<80
int line = (int)(bw % 80) + len;
if (line >= 80) {
int first = len - (line - 80);
@@ -50,10 +50,11 @@ public class ASCII85EncodeFilter implements Filter {
byte[] data = new byte[4];
int bytes_read;
while ((bytes_read = in.read(data)) == data.length) {
- long val = ((data[0] << 24) & 0xff000000L)// note: must have the L at the
- + ((data[1] << 16) & 0xff0000L)// end, otherwise you get into
- + ((data[2] << 8) & 0xff00L)// weird signed value problems
- + (data[3] & 0xffL); // cause we're using a full 32 bits
+ long val = ((data[0] << 24)
+ & 0xff000000L) // note: must have the L at the
+ + ((data[1] << 16) & 0xff0000L) // end, otherwise you get into
+ + ((data[2] << 8) & 0xff00L) // weird signed value problems
+ + (data[3] & 0xffL); // cause we're using a full 32 bits
byte[] conv = convertWord(val);
bw = write(out, conv, conv.length, bw);
@@ -75,9 +76,10 @@ public class ASCII85EncodeFilter implements Filter {
}
}
- long val = ((lastdata[0] << 24) & 0xff000000L) +
- ((lastdata[1] << 16) & 0xff0000L) +
- ((lastdata[2] << 8) & 0xff00L) + (lastdata[3] & 0xffL);
+ long val = ((lastdata[0] << 24) & 0xff000000L)
+ + ((lastdata[1] << 16) & 0xff0000L)
+ + ((lastdata[2] << 8) & 0xff00L)
+ + (lastdata[3] & 0xffL);
byte[] conv;
// special rule for handling zeros at the end
@@ -115,26 +117,33 @@ public class ASCII85EncodeFilter implements Filter {
}
if (word == 0) {
- byte[] result = { (byte) ASCII85_ZERO };
+ byte[] result = {
+ (byte)ASCII85_ZERO
+ };
return result;
} else {
byte c1 = (byte)((word / base85_1) & 0xFF);
byte c2 = (byte)(((word - (c1 * base85_1)) / base85_2) & 0xFF);
- byte c3 = (byte)( ((word - (c1 * base85_1) - (c2 * base85_2)) /
- base85_3) & 0xFF);
- byte c4 = (byte)( ((word - (c1 * base85_1) - (c2 * base85_2) -
- (c3 * base85_3)) / base85_4) & 0xFF);
- byte c5 = (byte)( ((word - (c1 * base85_1) - (c2 * base85_2) -
- (c3 * base85_3) - (c4 * base85_4))) & 0xFF);
-
- byte[] ret = {(byte)(c1 + ASCII85_START),
- (byte)(c2 + ASCII85_START), (byte)(c3 + ASCII85_START),
- (byte)(c4 + ASCII85_START), (byte)(c5 + ASCII85_START)};
+ byte c3 =
+ (byte)(((word - (c1 * base85_1) - (c2 * base85_2)) / base85_3)
+ & 0xFF);
+ byte c4 =
+ (byte)(((word - (c1 * base85_1) - (c2 * base85_2) - (c3 * base85_3)) / base85_4)
+ & 0xFF);
+ byte c5 =
+ (byte)(((word - (c1 * base85_1) - (c2 * base85_2) - (c3 * base85_3) - (c4 * base85_4)))
+ & 0xFF);
+
+ byte[] ret = {
+ (byte)(c1 + ASCII85_START), (byte)(c2 + ASCII85_START),
+ (byte)(c3 + ASCII85_START), (byte)(c4 + ASCII85_START),
+ (byte)(c5 + ASCII85_START)
+ };
for (int i = 0; i < ret.length; i++) {
if (ret[i] < 33 || ret[i] > 117) {
- System.out.println("Illegal char value "+
- new Integer(ret[i]));
+ System.out.println("Illegal char value "
+ + new Integer(ret[i]));
}
}
return ret;
@@ -146,4 +155,5 @@ public class ASCII85EncodeFilter implements Filter {
ASCII85EncodeFilter myfilter = new ASCII85EncodeFilter();
return FilterThread.filter(in, myfilter);
}
+
}
diff --git a/src/org/apache/fop/render/ps/ASCIIHexEncodeFilter.java b/src/org/apache/fop/render/ps/ASCIIHexEncodeFilter.java
index ab447ae62..8a8c2d837 100644
--- a/src/org/apache/fop/render/ps/ASCIIHexEncodeFilter.java
+++ b/src/org/apache/fop/render/ps/ASCIIHexEncodeFilter.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -14,8 +15,7 @@ public class ASCIIHexEncodeFilter implements Filter {
private static final String ASCIIHEX_EOD = ">";
private static final String ENCODING = "US-ASCII";
- protected ASCIIHexEncodeFilter() {
- }
+ protected ASCIIHexEncodeFilter() {}
public long write(OutputStream out, byte[] buf, int len,
long bw) throws IOException {
@@ -25,7 +25,7 @@ public class ASCIIHexEncodeFilter implements Filter {
while (rest > 0) {
int restofline = 80 - (int)((bw + pos) % 80);
if (rest < restofline) {
- //last line
+ // last line
restofline = rest;
last = true;
}
@@ -54,8 +54,8 @@ public class ASCIIHexEncodeFilter implements Filter {
sb.append("0");
sb.append(Integer.toHexString(val));
}
- bw = write(out, sb.toString().getBytes(ENCODING),
- bytes_read * 2, bw);
+ bw = write(out, sb.toString().getBytes(ENCODING), bytes_read * 2,
+ bw);
}
byte[] eod = ASCIIHEX_EOD.getBytes(ENCODING);
bw = write(out, eod, eod.length, bw);
@@ -65,4 +65,5 @@ public class ASCIIHexEncodeFilter implements Filter {
ASCIIHexEncodeFilter myfilter = new ASCIIHexEncodeFilter();
return FilterThread.filter(in, myfilter);
}
+
}
diff --git a/src/org/apache/fop/render/ps/Filter.java b/src/org/apache/fop/render/ps/Filter.java
index bf5b17a2c..3d6f0034c 100644
--- a/src/org/apache/fop/render/ps/Filter.java
+++ b/src/org/apache/fop/render/ps/Filter.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -12,7 +13,6 @@ import java.io.IOException;
public interface Filter {
- public void doFilter(InputStream in,
- OutputStream out) throws IOException;
+ public void doFilter(InputStream in, OutputStream out) throws IOException;
}
diff --git a/src/org/apache/fop/render/ps/FilterThread.java b/src/org/apache/fop/render/ps/FilterThread.java
index e69f80274..b690c3225 100644
--- a/src/org/apache/fop/render/ps/FilterThread.java
+++ b/src/org/apache/fop/render/ps/FilterThread.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -29,10 +30,12 @@ public class FilterThread extends Thread {
e.printStackTrace();
}
}
- finally { this.filter = null;
- this.in = null;
- this.out = null;
- } }
+ finally {
+ this.filter = null;
+ this.in = null;
+ this.out = null;
+ }
+ }
public static InputStream filter(InputStream in,
Filter filter) throws IOException {
@@ -42,4 +45,5 @@ public class FilterThread extends Thread {
thread.start();
return pin;
}
+
}
diff --git a/src/org/apache/fop/render/ps/FlateEncodeFilter.java b/src/org/apache/fop/render/ps/FlateEncodeFilter.java
index 1e93f3825..bde626713 100644
--- a/src/org/apache/fop/render/ps/FlateEncodeFilter.java
+++ b/src/org/apache/fop/render/ps/FlateEncodeFilter.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -11,8 +12,7 @@ import java.util.zip.DeflaterOutputStream;
public class FlateEncodeFilter implements Filter {
- protected FlateEncodeFilter() {
- }
+ protected FlateEncodeFilter() {}
private long copyStream(InputStream in, OutputStream out,
int bufferSize) throws IOException {
@@ -30,7 +30,7 @@ public class FlateEncodeFilter implements Filter {
OutputStream out) throws IOException {
DeflaterOutputStream dout = new DeflaterOutputStream(out);
copyStream(in, dout, 2048);
- //dout.flush();
+ // dout.flush();
dout.close();
}
@@ -38,4 +38,5 @@ public class FlateEncodeFilter implements Filter {
FlateEncodeFilter myfilter = new FlateEncodeFilter();
return FilterThread.filter(in, myfilter);
}
+
}
diff --git a/src/org/apache/fop/render/ps/PSGraphics2D.java b/src/org/apache/fop/render/ps/PSGraphics2D.java
index c107405cc..67859e351 100644
--- a/src/org/apache/fop/render/ps/PSGraphics2D.java
+++ b/src/org/apache/fop/render/ps/PSGraphics2D.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.render.ps;
@@ -44,24 +45,36 @@ import java.util.Vector;
public class PSGraphics2D extends AbstractGraphics2D {
boolean standalone = false;
- /** the PDF Document being created */
+ /**
+ * the PDF Document being created
+ */
protected PSRenderer psRenderer;
protected FontState fontState;
- /** the current (internal) font name */
+ /**
+ * the current (internal) font name
+ */
protected String currentFontName;
- /** the current font size in millipoints */
+ /**
+ * the current font size in millipoints
+ */
protected int currentFontSize;
- /** the current vertical position in millipoints from bottom */
+ /**
+ * the current vertical position in millipoints from bottom
+ */
protected int currentYPosition = 0;
- /** the current horizontal position in millipoints from left */
+ /**
+ * the current horizontal position in millipoints from left
+ */
protected int currentXPosition = 0;
- /** the current colour for use in svg */
+ /**
+ * the current colour for use in svg
+ */
PDFColor currentColour = new PDFColor(0, 0, 0);
FontInfo fontInfo;
@@ -71,8 +84,8 @@ public class PSGraphics2D extends AbstractGraphics2D {
* This is used to create a Graphics object for use inside an already
* existing document.
*/
- public PSGraphics2D(boolean textAsShapes, FontState fs,
- PSRenderer ren, String font, int size, int xpos, int ypos) {
+ public PSGraphics2D(boolean textAsShapes, FontState fs, PSRenderer ren,
+ String font, int size, int xpos, int ypos) {
super(textAsShapes);
psRenderer = ren;
currentFontName = font;
@@ -101,7 +114,7 @@ public class PSGraphics2D extends AbstractGraphics2D {
* Creates a new Graphics object that is
* a copy of this Graphics object.
* @return a new graphics context that is a copy of
- * this graphics context.
+ * this graphics context.
*/
public Graphics create() {
return new PSGraphics2D(this);
@@ -126,14 +139,14 @@ public class PSGraphics2D extends AbstractGraphics2D {
* @param x the x coordinate.
* @param y the y coordinate.
* @param observer object to be notified as more of
- * the image is converted.
+ * the image is converted.
* @see java.awt.Image
* @see java.awt.image.ImageObserver
* @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
*/
public boolean drawImage(Image img, int x, int y,
ImageObserver observer) {
- //System.err.println("drawImage:x, y");
+ // System.err.println("drawImage:x, y");
final int width = img.getWidth(observer);
final int height = img.getHeight(observer);
@@ -156,10 +169,8 @@ public class PSGraphics2D extends AbstractGraphics2D {
}
g.dispose();
- final byte[] result =
- new byte[buf.getWidth() * buf.getHeight() * 3];
- final byte[] mask =
- new byte[buf.getWidth() * buf.getHeight()];
+ final byte[] result = new byte[buf.getWidth() * buf.getHeight() * 3];
+ final byte[] mask = new byte[buf.getWidth() * buf.getHeight()];
Raster raster = buf.getData();
DataBuffer bd = raster.getDataBuffer();
@@ -167,28 +178,26 @@ public class PSGraphics2D extends AbstractGraphics2D {
int count = 0;
int maskpos = 0;
switch (bd.getDataType()) {
- case DataBuffer.TYPE_INT:
- int[][] idata = ((DataBufferInt) bd).getBankData();
- for (int i = 0; i < idata.length; i++) {
- for (int j = 0; j < idata[i].length; j++) {
- //mask[maskpos++] = (byte)((idata[i][j] >> 24) & 0xFF);
- if(((idata[i][j] >> 24) & 0xFF) != 255) {
- result[count++] = (byte)0xFF;
- result[count++] = (byte)0xFF;
- result[count++] = (byte)0xFF;
- } else {
- result[count++] =
- (byte)((idata[i][j] >> 16) & 0xFF);
- result[count++] =
- (byte)((idata[i][j] >> 8) & 0xFF);
- result[count++] = (byte)((idata[i][j]) & 0xFF);
- }
+ case DataBuffer.TYPE_INT:
+ int[][] idata = ((DataBufferInt)bd).getBankData();
+ for (int i = 0; i < idata.length; i++) {
+ for (int j = 0; j < idata[i].length; j++) {
+ // mask[maskpos++] = (byte)((idata[i][j] >> 24) & 0xFF);
+ if (((idata[i][j] >> 24) & 0xFF) != 255) {
+ result[count++] = (byte)0xFF;
+ result[count++] = (byte)0xFF;
+ result[count++] = (byte)0xFF;
+ } else {
+ result[count++] = (byte)((idata[i][j] >> 16) & 0xFF);
+ result[count++] = (byte)((idata[i][j] >> 8) & 0xFF);
+ result[count++] = (byte)((idata[i][j]) & 0xFF);
}
}
- break;
- default:
- // error
- break;
+ }
+ break;
+ default:
+ // error
+ break;
}
try {
@@ -197,12 +206,12 @@ public class PSGraphics2D extends AbstractGraphics2D {
double[] matrix = new double[6];
at.getMatrix(matrix);
psRenderer.write("gsave");
- Shape imclip = getClip();
- writeClip(imclip);
- //psRenderer.write("" + matrix[0] + " " + matrix[1] +
- // " " + matrix[2] + " " + matrix[3] + " " +
- // matrix[4] + " " + matrix[5] + " cm\n");
-psRenderer.renderBitmap(fopimg, x, y, width, height);
+ Shape imclip = getClip();
+ writeClip(imclip);
+ // psRenderer.write("" + matrix[0] + " " + matrix[1] +
+ // " " + matrix[2] + " " + matrix[3] + " " +
+ // matrix[4] + " " + matrix[5] + " cm\n");
+ psRenderer.renderBitmap(fopimg, x, y, width, height);
psRenderer.write("grestore");
} catch (Exception e) {
e.printStackTrace();
@@ -225,14 +234,14 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
byte[] m_mask;
PDFColor transparent = new PDFColor(255, 255, 255);
- TempImage(int width, int height,
- byte[] result, byte[] mask) throws FopImageException {
+ TempImage(int width, int height, byte[] result,
+ byte[] mask) throws FopImageException {
this.m_height = height;
this.m_width = width;
this.m_bitsPerPixel = 8;
this.m_colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
- //this.m_isTransparent = false;
- //this.m_bitmapsSize = this.m_width * this.m_height * 3;
+ // this.m_isTransparent = false;
+ // this.m_bitmapsSize = this.m_width * this.m_height * 3;
this.m_bitmaps = result;
this.m_mask = mask;
}
@@ -264,18 +273,22 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
public boolean isTransparent() throws FopImageException {
return transparent != null;
}
+
public PDFColor getTransparentColor() throws FopImageException {
return transparent;
}
- public byte[] getMask() throws FopImageException {
+
+ public byte[] getMask() throws FopImageException {
return m_mask;
}
+
// get the image bytes, and bytes properties
// get uncompressed image bytes
public byte[] getBitmaps() throws FopImageException {
return m_bitmaps;
}
+
// width * (bitsPerPixel / 8) * height, no ?
public int getBitmapsSize() throws FopImageException {
return m_width * m_height * 3;
@@ -287,9 +300,11 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
public byte[] getRessourceBytes() throws FopImageException {
return null;
}
+
public int getRessourceBytesSize() throws FopImageException {
return 0;
}
+
// return null if no corresponding PDFFilter
public PDFFilter getPDFFilter() throws FopImageException {
return null;
@@ -329,13 +344,13 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
* @param width the width of the rectangle.
* @param height the height of the rectangle.
* @param observer object to be notified as more of
- * the image is converted.
+ * the image is converted.
* @see java.awt.Image
* @see java.awt.image.ImageObserver
* @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
*/
- public boolean drawImage(Image img, int x, int y, int width,
- int height, ImageObserver observer) {
+ public boolean drawImage(Image img, int x, int y, int width, int height,
+ ImageObserver observer) {
System.out.println("drawImage");
return true;
}
@@ -368,7 +383,7 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
* @see java.awt.Graphics#create
*/
public void dispose() {
- //System.out.println("dispose");
+ // System.out.println("dispose");
psRenderer = null;
fontState = null;
currentFontName = null;
@@ -393,12 +408,13 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
* @see #setComposite
*/
public void draw(Shape s) {
- //System.out.println("draw(Shape)");
- psRenderer.write("gsave");
- Shape imclip = getClip();
- writeClip(imclip);
+ // System.out.println("draw(Shape)");
+ psRenderer.write("gsave");
+ Shape imclip = getClip();
+ writeClip(imclip);
Color c = getColor();
- psRenderer.write(c.getRed() + " " + c.getGreen() + " " + c.getBlue() + " setrgbcolor");
+ psRenderer.write(c.getRed() + " " + c.getGreen() + " " + c.getBlue()
+ + " setrgbcolor");
applyPaint(getPaint(), false);
applyStroke(getStroke());
@@ -409,38 +425,41 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
double vals[] = new double[6];
int type = iter.currentSegment(vals);
switch (type) {
- case PathIterator.SEG_CUBICTO:
- psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) +
- " " + PDFNumber.doubleOut(1000 * vals[1]) + " " +
- PDFNumber.doubleOut(1000 * vals[2]) + " " +
- PDFNumber.doubleOut(1000 * vals[3]) + " " +
- PDFNumber.doubleOut(1000 * vals[4]) + " " +
- PDFNumber.doubleOut(1000 * vals[5]) + " curveto");
- break;
- case PathIterator.SEG_LINETO:
- psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) +
- " " + PDFNumber.doubleOut(1000 * vals[1]) + " lineto");
- break;
- case PathIterator.SEG_MOVETO:
- psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) +
- " " + PDFNumber.doubleOut(1000 * vals[1]) + " M");
- break;
- case PathIterator.SEG_QUADTO:
-// psRenderer.write((1000 * PDFNumber.doubleOut(vals[0])) +
-// " " + (1000 * PDFNumber.doubleOut(vals[1])) + " " +
-// (1000 * PDFNumber.doubleOut(vals[2])) + " " +
-// (1000 * PDFNumber.doubleOut(vals[3])) + " y\n");
- break;
- case PathIterator.SEG_CLOSE:
- psRenderer.write("closepath");
- break;
- default:
- break;
+ case PathIterator.SEG_CUBICTO:
+ psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) + " "
+ + PDFNumber.doubleOut(1000 * vals[1]) + " "
+ + PDFNumber.doubleOut(1000 * vals[2]) + " "
+ + PDFNumber.doubleOut(1000 * vals[3]) + " "
+ + PDFNumber.doubleOut(1000 * vals[4]) + " "
+ + PDFNumber.doubleOut(1000 * vals[5])
+ + " curveto");
+ break;
+ case PathIterator.SEG_LINETO:
+ psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) + " "
+ + PDFNumber.doubleOut(1000 * vals[1])
+ + " lineto");
+ break;
+ case PathIterator.SEG_MOVETO:
+ psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) + " "
+ + PDFNumber.doubleOut(1000 * vals[1])
+ + " M");
+ break;
+ case PathIterator.SEG_QUADTO:
+ // psRenderer.write((1000 * PDFNumber.doubleOut(vals[0])) +
+ // " " + (1000 * PDFNumber.doubleOut(vals[1])) + " " +
+ // (1000 * PDFNumber.doubleOut(vals[2])) + " " +
+ // (1000 * PDFNumber.doubleOut(vals[3])) + " y\n");
+ break;
+ case PathIterator.SEG_CLOSE:
+ psRenderer.write("closepath");
+ break;
+ default:
+ break;
}
iter.next();
}
doDrawing(false, true, false);
- psRenderer.write("grestore");
+ psRenderer.write("grestore");
}
protected void writeClip(Shape s) {
@@ -450,42 +469,45 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
double vals[] = new double[6];
int type = iter.currentSegment(vals);
switch (type) {
- case PathIterator.SEG_CUBICTO:
- psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) +
- " " + PDFNumber.doubleOut(1000 * vals[1]) + " " +
- PDFNumber.doubleOut(1000 * vals[2]) + " " +
- PDFNumber.doubleOut(1000 * vals[3]) + " " +
- PDFNumber.doubleOut(1000 * vals[4]) + " " +
- PDFNumber.doubleOut(1000 * vals[5]) + " curveto");
- break;
- case PathIterator.SEG_LINETO:
- psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) +
- " " + PDFNumber.doubleOut(1000 * vals[1]) + " lineto");
- break;
- case PathIterator.SEG_MOVETO:
- psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) +
- " " + PDFNumber.doubleOut(1000 * vals[1]) + " M");
- break;
- case PathIterator.SEG_QUADTO:
-// psRenderer.write(1000 * PDFNumber.doubleOut(vals[0]) +
-// " " + 1000 * PDFNumber.doubleOut(vals[1]) + " " +
-// 1000 * PDFNumber.doubleOut(vals[2]) + " " +
-// 1000 * PDFNumber.doubleOut(vals[3]) + " y\n");
- break;
- case PathIterator.SEG_CLOSE:
- psRenderer.write("closepath");
- break;
- default:
- break;
+ case PathIterator.SEG_CUBICTO:
+ psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) + " "
+ + PDFNumber.doubleOut(1000 * vals[1]) + " "
+ + PDFNumber.doubleOut(1000 * vals[2]) + " "
+ + PDFNumber.doubleOut(1000 * vals[3]) + " "
+ + PDFNumber.doubleOut(1000 * vals[4]) + " "
+ + PDFNumber.doubleOut(1000 * vals[5])
+ + " curveto");
+ break;
+ case PathIterator.SEG_LINETO:
+ psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) + " "
+ + PDFNumber.doubleOut(1000 * vals[1])
+ + " lineto");
+ break;
+ case PathIterator.SEG_MOVETO:
+ psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) + " "
+ + PDFNumber.doubleOut(1000 * vals[1])
+ + " M");
+ break;
+ case PathIterator.SEG_QUADTO:
+ // psRenderer.write(1000 * PDFNumber.doubleOut(vals[0]) +
+ // " " + 1000 * PDFNumber.doubleOut(vals[1]) + " " +
+ // 1000 * PDFNumber.doubleOut(vals[2]) + " " +
+ // 1000 * PDFNumber.doubleOut(vals[3]) + " y\n");
+ break;
+ case PathIterator.SEG_CLOSE:
+ psRenderer.write("closepath");
+ break;
+ default:
+ break;
}
iter.next();
}
// clip area
- psRenderer.write("clippath");
+ psRenderer.write("clippath");
}
protected void applyPaint(Paint paint, boolean fill) {
- if(paint instanceof GradientPaint) {
+ if (paint instanceof GradientPaint) {
GradientPaint gp = (GradientPaint)paint;
Color c1 = gp.getColor1();
Color c2 = gp.getColor2();
@@ -493,54 +515,55 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
Point2D p2 = gp.getPoint2();
boolean cyclic = gp.isCyclic();
- Vector theCoords = new Vector();
- theCoords.addElement( new Double(p1.getX()));
- theCoords.addElement( new Double(p1.getY()));
- theCoords.addElement( new Double(p2.getX()));
- theCoords.addElement( new Double(p2.getY()));
+ Vector theCoords = new Vector();
+ theCoords.addElement(new Double(p1.getX()));
+ theCoords.addElement(new Double(p1.getY()));
+ theCoords.addElement(new Double(p2.getX()));
+ theCoords.addElement(new Double(p2.getY()));
- Vector theExtend = new Vector();
- theExtend.addElement(new Boolean(true));
- theExtend.addElement(new Boolean(true));
+ Vector theExtend = new Vector();
+ theExtend.addElement(new Boolean(true));
+ theExtend.addElement(new Boolean(true));
- Vector theDomain = new Vector();
- theDomain.addElement(new Double(0));
- theDomain.addElement(new Double(1));
+ Vector theDomain = new Vector();
+ theDomain.addElement(new Double(0));
+ theDomain.addElement(new Double(1));
- Vector theEncode = new Vector();
- theEncode.addElement(new Double(0));
- theEncode.addElement(new Double(1));
- theEncode.addElement(new Double(0));
- theEncode.addElement(new Double(1));
+ Vector theEncode = new Vector();
+ theEncode.addElement(new Double(0));
+ theEncode.addElement(new Double(1));
+ theEncode.addElement(new Double(0));
+ theEncode.addElement(new Double(1));
- Vector theBounds = new Vector();
- theBounds.addElement(new Double(0));
- theBounds.addElement(new Double(1));
+ Vector theBounds = new Vector();
+ theBounds.addElement(new Double(0));
+ theBounds.addElement(new Double(1));
- Vector theFunctions = new Vector();
+ Vector theFunctions = new Vector();
Vector someColors = new Vector();
- PDFColor color1 = new PDFColor(c1.getRed(), c1.getGreen(), c1.getBlue());
+ PDFColor color1 = new PDFColor(c1.getRed(), c1.getGreen(),
+ c1.getBlue());
someColors.addElement(color1);
- PDFColor color2 = new PDFColor(c2.getRed(), c2.getGreen(), c2.getBlue());
+ PDFColor color2 = new PDFColor(c2.getRed(), c2.getGreen(),
+ c2.getBlue());
someColors.addElement(color2);
ColorSpace aColorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
- } else if(paint instanceof TexturePaint) {
- }
+ } else if (paint instanceof TexturePaint) {}
}
protected void applyStroke(Stroke stroke) {
- if(stroke instanceof BasicStroke) {
+ if (stroke instanceof BasicStroke) {
BasicStroke bs = (BasicStroke)stroke;
float[] da = bs.getDashArray();
- if(da != null) {
+ if (da != null) {
psRenderer.write("[");
- for(int count = 0; count < da.length; count++) {
+ for (int count = 0; count < da.length; count++) {
psRenderer.write("" + (1000 * (int)da[count]));
- if(count < da.length - 1) {
+ if (count < da.length - 1) {
psRenderer.write(" ");
}
}
@@ -549,35 +572,37 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
psRenderer.write((1000 * (int)offset) + " setdash");
}
int ec = bs.getEndCap();
- switch(ec) {
- case BasicStroke.CAP_BUTT:
- psRenderer.write(0 + " setlinecap");
+ switch (ec) {
+ case BasicStroke.CAP_BUTT:
+ psRenderer.write(0 + " setlinecap");
break;
- case BasicStroke.CAP_ROUND:
- psRenderer.write(1 + " setlinecap");
+ case BasicStroke.CAP_ROUND:
+ psRenderer.write(1 + " setlinecap");
break;
- case BasicStroke.CAP_SQUARE:
- psRenderer.write(2 + " setlinecap");
+ case BasicStroke.CAP_SQUARE:
+ psRenderer.write(2 + " setlinecap");
break;
}
int lj = bs.getLineJoin();
- switch(lj) {
- case BasicStroke.JOIN_MITER:
- psRenderer.write(0 + " setlinejoin");
+ switch (lj) {
+ case BasicStroke.JOIN_MITER:
+ psRenderer.write(0 + " setlinejoin");
break;
- case BasicStroke.JOIN_ROUND:
- psRenderer.write(1 + " setlinejoin");
+ case BasicStroke.JOIN_ROUND:
+ psRenderer.write(1 + " setlinejoin");
break;
- case BasicStroke.JOIN_BEVEL:
- psRenderer.write(2 + " setlinejoin");
+ case BasicStroke.JOIN_BEVEL:
+ psRenderer.write(2 + " setlinejoin");
break;
}
float lw = bs.getLineWidth();
- psRenderer.write(PDFNumber.doubleOut(1000 * lw) + " setlinewidth");
+ psRenderer.write(PDFNumber.doubleOut(1000 * lw)
+ + " setlinewidth");
float ml = bs.getMiterLimit();
- psRenderer.write(PDFNumber.doubleOut(1000 * ml) + " setmiterlimit");
+ psRenderer.write(PDFNumber.doubleOut(1000 * ml)
+ + " setmiterlimit");
}
}
@@ -601,8 +626,7 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
* @see #clip
* @see #setClip
*/
- public void drawRenderedImage(RenderedImage img,
- AffineTransform xform) {
+ public void drawRenderedImage(RenderedImage img, AffineTransform xform) {
System.out.println("drawRenderedImage");
}
@@ -619,7 +643,7 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
* Transform , and Composite attributes. Note
* that no rendering is done if the specified transform is
* noninvertible.
- *
+ *
* Rendering hints set on the Graphics2D object might
* be used in rendering the RenderableImage .
* If explicit control is required over specific hints recognized by a
@@ -627,7 +651,7 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
* are used is required, then a RenderedImage should be
* obtained directly from the RenderableImage
* and rendered using
- *{@link #drawRenderedImage(RenderedImage, AffineTransform) drawRenderedImage}.
+ * {@link #drawRenderedImage(RenderedImage, AffineTransform) drawRenderedImage}.
* @param img the image to be rendered
* @param xform the transformation from image space into user space
* @see #transform
@@ -667,20 +691,24 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
public void drawString(String s, float x, float y) {
System.out.println("drawString(String)");
psRenderer.write("BT");
- Shape imclip = getClip();
- writeClip(imclip);
+ Shape imclip = getClip();
+ writeClip(imclip);
Color c = getColor();
- psRenderer.write(c.getRed() + " " + c.getGreen() + " " + c.getBlue() + " setrgbcolor");
+ psRenderer.write(c.getRed() + " " + c.getGreen() + " " + c.getBlue()
+ + " setrgbcolor");
AffineTransform trans = getTransform();
trans.translate(x, y);
double[] vals = new double[6];
trans.getMatrix(vals);
- psRenderer.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " "
-+ PDFNumber.doubleOut(vals[2]) + " " + PDFNumber.doubleOut(vals[3]) + " " + PDFNumber.doubleOut(vals[4])
-+ " " + PDFNumber.doubleOut(vals[5]) + " " +
- PDFNumber.doubleOut(vals[6]) + " Tm [" + s + "]");
+ psRenderer.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " "
+ + PDFNumber.doubleOut(vals[2]) + " "
+ + PDFNumber.doubleOut(vals[3]) + " "
+ + PDFNumber.doubleOut(vals[4]) + " "
+ + PDFNumber.doubleOut(vals[5]) + " "
+ + PDFNumber.doubleOut(vals[6]) + " Tm [" + s + "]");
psRenderer.write("ET");
}
@@ -708,13 +736,13 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
* @see #setComposite
* @see #setClip
*/
- public void drawString(AttributedCharacterIterator iterator,
- float x, float y) {
+ public void drawString(AttributedCharacterIterator iterator, float x,
+ float y) {
System.err.println("drawString(AttributedCharacterIterator)");
psRenderer.write("BT");
- Shape imclip = getClip();
- writeClip(imclip);
+ Shape imclip = getClip();
+ writeClip(imclip);
Color c = getColor();
currentColour = new PDFColor(c.getRed(), c.getGreen(), c.getBlue());
psRenderer.write(currentColour.getColorSpaceOut(true));
@@ -727,13 +755,18 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
double[] vals = new double[6];
trans.getMatrix(vals);
- for(char ch = iterator.first(); ch != CharacterIterator.DONE; ch = iterator.next()) {
+ for (char ch = iterator.first(); ch != CharacterIterator.DONE;
+ ch = iterator.next()) {
Map attr = iterator.getAttributes();
- psRenderer.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " "
-+ PDFNumber.doubleOut(vals[2]) + " " + PDFNumber.doubleOut(vals[3]) + " " + PDFNumber.doubleOut(vals[4])
-+ " " + PDFNumber.doubleOut(vals[5]) + " " +
- PDFNumber.doubleOut(vals[6]) + " Tm [" + ch + "]");
+ psRenderer.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " "
+ + PDFNumber.doubleOut(vals[2]) + " "
+ + PDFNumber.doubleOut(vals[3]) + " "
+ + PDFNumber.doubleOut(vals[4]) + " "
+ + PDFNumber.doubleOut(vals[5]) + " "
+ + PDFNumber.doubleOut(vals[6]) + " Tm [" + ch
+ + "]");
}
psRenderer.write("ET");
@@ -754,12 +787,13 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
* @see #setClip
*/
public void fill(Shape s) {
- //System.err.println("fill");
- psRenderer.write("gsave");
- Shape imclip = getClip();
- writeClip(imclip);
+ // System.err.println("fill");
+ psRenderer.write("gsave");
+ Shape imclip = getClip();
+ writeClip(imclip);
Color c = getColor();
- psRenderer.write(c.getRed() + " " + c.getGreen() + " " + c.getBlue() + " setrgbcolor");
+ psRenderer.write(c.getRed() + " " + c.getGreen() + " " + c.getBlue()
+ + " setrgbcolor");
applyPaint(getPaint(), true);
@@ -769,43 +803,45 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
double vals[] = new double[6];
int type = iter.currentSegment(vals);
switch (type) {
- case PathIterator.SEG_CUBICTO:
- psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) +
- " " + PDFNumber.doubleOut(1000 * vals[1]) + " " +
- PDFNumber.doubleOut(1000 * vals[2]) + " " +
- PDFNumber.doubleOut(1000 * vals[3]) + " " +
- PDFNumber.doubleOut(1000 * vals[4]) + " " +
- PDFNumber.doubleOut(1000 * vals[5]) + " curveto");
- break;
- case PathIterator.SEG_LINETO:
- psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) +
- " " + PDFNumber.doubleOut(1000 * vals[1]) + " lineto");
- break;
- case PathIterator.SEG_MOVETO:
- psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) +
- " " + PDFNumber.doubleOut(1000 * vals[1]) + " M");
- break;
- case PathIterator.SEG_QUADTO:
- //psRenderer.write(1000 * PDFNumber.doubleOut(vals[0]) +
- // " " + 1000 * PDFNumber.doubleOut(vals[1]) + " " +
- // 1000 * PDFNumber.doubleOut(vals[2]) + " " +
- // 1000 * PDFNumber.doubleOut(vals[3]) + " y\n");
- break;
- case PathIterator.SEG_CLOSE:
- psRenderer.write("closepath");
- break;
- default:
- break;
+ case PathIterator.SEG_CUBICTO:
+ psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) + " "
+ + PDFNumber.doubleOut(1000 * vals[1]) + " "
+ + PDFNumber.doubleOut(1000 * vals[2]) + " "
+ + PDFNumber.doubleOut(1000 * vals[3]) + " "
+ + PDFNumber.doubleOut(1000 * vals[4]) + " "
+ + PDFNumber.doubleOut(1000 * vals[5])
+ + " curveto");
+ break;
+ case PathIterator.SEG_LINETO:
+ psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) + " "
+ + PDFNumber.doubleOut(1000 * vals[1])
+ + " lineto");
+ break;
+ case PathIterator.SEG_MOVETO:
+ psRenderer.write(PDFNumber.doubleOut(1000 * vals[0]) + " "
+ + PDFNumber.doubleOut(1000 * vals[1])
+ + " M");
+ break;
+ case PathIterator.SEG_QUADTO:
+ // psRenderer.write(1000 * PDFNumber.doubleOut(vals[0]) +
+ // " " + 1000 * PDFNumber.doubleOut(vals[1]) + " " +
+ // 1000 * PDFNumber.doubleOut(vals[2]) + " " +
+ // 1000 * PDFNumber.doubleOut(vals[3]) + " y\n");
+ break;
+ case PathIterator.SEG_CLOSE:
+ psRenderer.write("closepath");
+ break;
+ default:
+ break;
}
iter.next();
}
doDrawing(true, false,
iter.getWindingRule() == PathIterator.WIND_EVEN_ODD);
- psRenderer.write("grestore");
+ psRenderer.write("grestore");
}
- protected void doDrawing(boolean fill, boolean stroke,
- boolean nonzero) {
+ protected void doDrawing(boolean fill, boolean stroke, boolean nonzero) {
if (fill) {
if (stroke) {
if (!nonzero)
@@ -819,7 +855,7 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
psRenderer.write("fill");
}
} else {
- //if(stroke)
+ // if(stroke)
psRenderer.write("stroke");
}
}
@@ -829,9 +865,8 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
* Graphics2D .
*/
public GraphicsConfiguration getDeviceConfiguration() {
- //System.out.println("getDeviceConviguration");
- return GraphicsEnvironment.getLocalGraphicsEnvironment().
- getDefaultScreenDevice().getDefaultConfiguration();
+ // System.out.println("getDeviceConviguration");
+ return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
}
/**
@@ -840,8 +875,8 @@ psRenderer.renderBitmap(fopimg, x, y, width, height);
private Graphics2D fmg;
{
- BufferedImage bi =
- new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
+ BufferedImage bi = new BufferedImage(1, 1,
+ BufferedImage.TYPE_INT_ARGB);
fmg = bi.createGraphics();
}
diff --git a/src/org/apache/fop/render/ps/PSRenderer.java b/src/org/apache/fop/render/ps/PSRenderer.java
index be0f66b03..16ed11fac 100644
--- a/src/org/apache/fop/render/ps/PSRenderer.java
+++ b/src/org/apache/fop/render/ps/PSRenderer.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -73,14 +74,18 @@ import java.awt.Dimension;
*/
public class PSRenderer implements Renderer {
- /** the application producing the PostScript */
+ /**
+ * the application producing the PostScript
+ */
protected String producer;
- int imagecount = 0; //DEBUG
+ int imagecount = 0; // DEBUG
private boolean enableComments = true;
- /** the stream used to output the PostScript */
+ /**
+ * the stream used to output the PostScript
+ */
protected PSStream out;
private boolean ioTrouble = false;
@@ -108,7 +113,9 @@ public class PSRenderer implements Renderer {
}
- /** set up renderer options */
+ /**
+ * set up renderer options
+ */
public void setOptions(Hashtable options) {
this.options = options;
}
@@ -125,8 +132,8 @@ public class PSRenderer implements Renderer {
MessageHandler.logln("rendering areas to PostScript");
this.out = new PSStream(stream);
write("%!PS-Adobe-3.0");
- write("%%Creator: "+this.producer);
- write("%%Pages: "+areaTree.getPages().size());
+ write("%%Creator: " + this.producer);
+ write("%%Pages: " + areaTree.getPages().size());
write("%%DocumentProcessColors: Black");
write("%%DocumentSuppliedResources: procset FOPFonts");
write("%%EndComments");
@@ -142,7 +149,7 @@ public class PSRenderer implements Renderer {
comment("% --- AreaTree begin");
Enumeration e = areaTree.getPages().elements();
while (e.hasMoreElements()) {
- this.renderPage((Page) e.nextElement());
+ this.renderPage((Page)e.nextElement());
}
comment("% --- AreaTree end");
write("%%Trailer");
@@ -187,13 +194,13 @@ public class PSRenderer implements Renderer {
write("/ux 0.0 def");
write("/uy 0.0 def");
- //write("/cf /Helvetica def");
- //write("/cs 12000 def");
+ // write("/cf /Helvetica def");
+ // write("/cs 12000 def");
- // F
+ // F
write("/F {");
write(" /Tp exch def");
- //write(" currentdict exch get");
+ // write(" currentdict exch get");
write(" /Tf exch def");
write(" Tf findfont Tp scalefont setfont");
write(" /cf Tf def /cs Tp def /cw ( ) stringwidth pop def");
@@ -241,33 +248,33 @@ public class PSRenderer implements Renderer {
- //write("/gfF1{/Helvetica findfont} bd");
- //write("/gfF3{/Helvetica-Bold findfont} bd");
+ // write("/gfF1{/Helvetica findfont} bd");
+ // write("/gfF3{/Helvetica-Bold findfont} bd");
Hashtable fonts = fontInfo.getFonts();
Enumeration enum = fonts.keys();
while (enum.hasMoreElements()) {
- String key = (String) enum.nextElement();
- Font fm = (Font) fonts.get(key);
- write("/"+key + " /"+fm.fontName() + " def");
+ String key = (String)enum.nextElement();
+ Font fm = (Font)fonts.get(key);
+ write("/" + key + " /" + fm.fontName() + " def");
}
write("end def");
write("%%EndResource");
enum = fonts.keys();
while (enum.hasMoreElements()) {
- String key = (String) enum.nextElement();
- Font fm = (Font) fonts.get(key);
- write("/"+fm.fontName() + " findfont");
+ String key = (String)enum.nextElement();
+ Font fm = (Font)fonts.get(key);
+ write("/" + fm.fontName() + " findfont");
write("dup length dict begin");
write(" {1 index /FID ne {def} {pop pop} ifelse} forall");
write(" /Encoding ISOLatin1Encoding def");
write(" currentdict");
write("end");
- write("/"+fm.fontName() + " exch definefont pop");
+ write("/" + fm.fontName() + " exch definefont pop");
}
}
protected void movetoCurrPosition() {
- write(this.currentXPosition + " "+this.currentYPosition + " M");
+ write(this.currentXPosition + " " + this.currentYPosition + " M");
}
/**
@@ -290,30 +297,30 @@ public class PSRenderer implements Renderer {
int saveX = this.currentAreaContainerXPosition;
if (area.getPosition() == Position.ABSOLUTE) {
// Y position is computed assuming positive Y axis, adjust for negative postscript one
- this.currentYPosition =
- area.getYPosition() - 2 * area.getPaddingTop() -
- 2 * area.getBorderTopWidth();
+ this.currentYPosition = area.getYPosition()
+ - 2 * area.getPaddingTop()
+ - 2 * area.getBorderTopWidth();
this.currentAreaContainerXPosition = area.getXPosition();
} else if (area.getPosition() == Position.RELATIVE) {
this.currentYPosition -= area.getYPosition();
this.currentAreaContainerXPosition += area.getXPosition();
} else if (area.getPosition() == Position.STATIC) {
- this.currentYPosition -=
- area.getPaddingTop() + area.getBorderTopWidth();
- this.currentAreaContainerXPosition +=
- area.getPaddingLeft() + area.getBorderLeftWidth();
+ this.currentYPosition -= area.getPaddingTop()
+ + area.getBorderTopWidth();
+ this.currentAreaContainerXPosition += area.getPaddingLeft()
+ + area.getBorderLeftWidth();
}
this.currentXPosition = this.currentAreaContainerXPosition;
- //comment("% --- AreaContainer begin");
+ // comment("% --- AreaContainer begin");
doFrame(area);
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
+ Box b = (Box)e.nextElement();
b.render(this);
}
- //comment("% --- AreaContainer end");
+ // comment("% --- AreaContainer end");
if (area.getPosition() != Position.STATIC) {
this.currentYPosition = saveY;
@@ -348,16 +355,16 @@ public class PSRenderer implements Renderer {
h = area.getContentHeight();
int ry = this.currentYPosition;
- //comment("% --- BodyAreaContainer begin");
+ // comment("% --- BodyAreaContainer begin");
doFrame(area);
- //movetoCurrPosition();
+ // movetoCurrPosition();
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
+ Box b = (Box)e.nextElement();
b.render(this);
}
- //comment("% --- BodyAreaContainer end");
+ // comment("% --- BodyAreaContainer end");
if (area.getPosition() != Position.STATIC) {
this.currentYPosition = saveY;
@@ -373,13 +380,13 @@ public class PSRenderer implements Renderer {
* @param area the span area to render
*/
public void renderSpanArea(SpanArea area) {
- //comment("% --- SpanArea begin");
+ // comment("% --- SpanArea begin");
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
+ Box b = (Box)e.nextElement();
b.render(this);
}
- //comment("% --- SpanArea end");
+ // comment("% --- SpanArea end");
}
/**
@@ -388,14 +395,14 @@ public class PSRenderer implements Renderer {
* @param area the block area to render
*/
public void renderBlockArea(BlockArea area) {
- //comment("% --- BlockArea begin");
+ // comment("% --- BlockArea begin");
doFrame(area);
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
+ Box b = (Box)e.nextElement();
b.render(this);
}
- //comment("% --- BlockArea end");
+ // comment("% --- BlockArea end");
}
/**
@@ -404,12 +411,14 @@ public class PSRenderer implements Renderer {
* @param space the space to render
*/
public void renderDisplaySpace(DisplaySpace space) {
- //write("% --- DisplaySpace size="+space.getSize());
+ // write("% --- DisplaySpace size="+space.getSize());
this.currentYPosition -= space.getSize();
movetoCurrPosition();
}
- /** render a foreign object area */
+ /**
+ * render a foreign object area
+ */
public void renderForeignObjectArea(ForeignObjectArea area) {
// if necessary need to scale and align the content
area.getObject().render(this);
@@ -441,8 +450,7 @@ public class PSRenderer implements Renderer {
write("newpath");
write(x / 1000f + " " + y / 1000f + " M");
write((x + w) / 1000f + " " + y / 1000f + " rlineto");
- write((x + w) / 1000f + " " + (y - h) / 1000f +
- " rlineto");
+ write((x + w) / 1000f + " " + (y - h) / 1000f + " rlineto");
write(x / 1000f + " " + (y - h) / 1000f + " rlineto");
write("closepath");
write("clippath");
@@ -450,8 +458,7 @@ public class PSRenderer implements Renderer {
// transform so that the coordinates (0,0) is from the top left
// and positive is down and to the right. (0,0) is where the
// viewBox puts it.
- write(xOffset +
- " " + yOffset + " translate");
+ write(xOffset + " " + yOffset + " translate");
write(sx + " " + sy + " " + " scale");
@@ -461,19 +468,20 @@ public class PSRenderer implements Renderer {
GraphicsNodeRenderContext rc = getRenderContext();
BridgeContext ctx = new BridgeContext(userAgent, rc);
GraphicsNode root;
- PSGraphics2D graphics =
- new PSGraphics2D(false, area.getFontState(), this,
- currentFontName, currentFontSize, currentXPosition,
- currentYPosition);
- graphics.setGraphicContext(
- new org.apache.batik.ext.awt.g2d.GraphicContext());
+ PSGraphics2D graphics = new PSGraphics2D(false, area.getFontState(),
+ this, currentFontName,
+ currentFontSize,
+ currentXPosition,
+ currentYPosition);
+ graphics.setGraphicContext(new org.apache.batik.ext.awt.g2d.GraphicContext());
graphics.setRenderingHints(rc.getRenderingHints());
try {
root = builder.build(ctx, doc);
root.paint(graphics, rc);
} catch (Exception e) {
- MessageHandler.errorln("Error: svg graphic could not be rendered: " + e.getMessage());
- //e.printStackTrace();
+ MessageHandler.errorln("Error: svg graphic could not be rendered: "
+ + e.getMessage());
+ // e.printStackTrace();
}
write("grestore");
@@ -493,18 +501,18 @@ public class PSRenderer implements Renderer {
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
FontRenderContext fontRenderContext =
- new FontRenderContext(new AffineTransform(), true,
- true);
+ new FontRenderContext(new AffineTransform(), true, true);
TextPainter textPainter = new StrokingTextPainter();
- //TextPainter textPainter = new PDFTextPainter();
+ // TextPainter textPainter = new PDFTextPainter();
GraphicsNodeRableFactory gnrFactory =
- new ConcreteGraphicsNodeRableFactory();
+ new ConcreteGraphicsNodeRableFactory();
- nodeRenderContext = new GraphicsNodeRenderContext(
- new AffineTransform(), null, hints,
- fontRenderContext, textPainter, gnrFactory);
+ nodeRenderContext =
+ new GraphicsNodeRenderContext(new AffineTransform(), null,
+ hints, fontRenderContext,
+ textPainter, gnrFactory);
nodeRenderContext.setTextPainter(textPainter);
}
@@ -513,59 +521,60 @@ public class PSRenderer implements Renderer {
public void renderBitmap(FopImage img, int x, int y, int w, int h) {
try {
- boolean iscolor = img.getColorSpace().getColorSpace() !=
- ColorSpace.DEVICE_GRAY;
+ boolean iscolor = img.getColorSpace().getColorSpace()
+ != ColorSpace.DEVICE_GRAY;
byte[] imgmap = img.getBitmaps();
write("gsave");
write("/DeviceRGB setcolorspace");
- write(x + " "+(y - h) + " translate");
- write(w + " "+h + " scale");
+ write(x + " " + (y - h) + " translate");
+ write(w + " " + h + " scale");
write("<<");
write(" /ImageType 1");
- write(" /Width "+img.getWidth());
- write(" /Height "+img.getHeight());
+ write(" /Width " + img.getWidth());
+ write(" /Height " + img.getHeight());
write(" /BitsPerComponent 8");
if (iscolor) {
write(" /Decode [0 1 0 1 0 1]");
} else {
write(" /Decode [0 1]");
}
- //Setup scanning for left-to-right and top-to-bottom
- write(" /ImageMatrix ["+img.getWidth() + " 0 0 -"+
- img.getHeight() + " 0 "+img.getHeight() + "]");
+ // Setup scanning for left-to-right and top-to-bottom
+ write(" /ImageMatrix [" + img.getWidth() + " 0 0 -"
+ + img.getHeight() + " 0 " + img.getHeight() + "]");
write(" /DataSource currentfile /ASCII85Decode filter /FlateDecode filter");
- //write(" /DataSource currentfile /ASCIIHexDecode filter /FlateDecode filter");
- //write(" /DataSource currentfile /ASCII85Decode filter /RunLengthDecode filter");
- //write(" /DataSource currentfile /ASCIIHexDecode filter /RunLengthDecode filter");
- //write(" /DataSource currentfile /ASCIIHexDecode filter");
- //write(" /DataSource currentfile /ASCII85Decode filter");
- //write(" /DataSource currentfile /RunLengthDecode filter");
+ // write(" /DataSource currentfile /ASCIIHexDecode filter /FlateDecode filter");
+ // write(" /DataSource currentfile /ASCII85Decode filter /RunLengthDecode filter");
+ // write(" /DataSource currentfile /ASCIIHexDecode filter /RunLengthDecode filter");
+ // write(" /DataSource currentfile /ASCIIHexDecode filter");
+ // write(" /DataSource currentfile /ASCII85Decode filter");
+ // write(" /DataSource currentfile /RunLengthDecode filter");
write(">>");
write("image");
/*
- for (int y=0; y 127) {
- sb = sb.append("\\"+Integer.toOctalString(mch));
+ sb = sb.append("\\" + Integer.toOctalString(mch));
} else {
String escape = "\\()[]{}";
if (escape.indexOf(mch) >= 0) {
@@ -650,15 +657,15 @@ public class PSRenderer implements Renderer {
sb = sb.append(mch);
}
}
- //System.out.println("["+s+"] --> ["+sb.toString()+"]");
+ // System.out.println("["+s+"] --> ["+sb.toString()+"]");
- //comment("% --- InlineArea font-weight="+fontWeight+": " + sb.toString());
+ // comment("% --- InlineArea font-weight="+fontWeight+": " + sb.toString());
useFont(fs.getFontName(), fs.getFontSize());
useColor(area.getRed(), area.getGreen(), area.getBlue());
- if (area.getUnderlined() || area.getLineThrough() ||
- area.getOverlined())
+ if (area.getUnderlined() || area.getLineThrough()
+ || area.getOverlined())
write("ULS");
- write("("+sb.toString() + ") t");
+ write("(" + sb.toString() + ") t");
if (area.getUnderlined())
write("ULE");
if (area.getLineThrough())
@@ -670,7 +677,7 @@ public class PSRenderer implements Renderer {
public void useFont(String name, int size) {
if ((currentFontName != name) || (currentFontSize != size)) {
- write(name + " "+size + " F");
+ write(name + " " + size + " F");
currentFontName = name;
currentFontSize = size;
}
@@ -682,10 +689,10 @@ public class PSRenderer implements Renderer {
* @param space the space to render
*/
public void renderInlineSpace(InlineSpace space) {
- //write("% --- InlineSpace size="+space.getSize());
+ // write("% --- InlineSpace size="+space.getSize());
this.currentXPosition += space.getSize();
- if (space.getUnderlined() || space.getLineThrough() ||
- space.getOverlined())
+ if (space.getUnderlined() || space.getLineThrough()
+ || space.getOverlined())
write("ULS");
write(space.getSize() + " 0 RM");
if (space.getUnderlined())
@@ -714,14 +721,14 @@ public class PSRenderer implements Renderer {
movetoCurrPosition();
String fontWeight = area.getFontState().getFontWeight();
- //comment("% --- LineArea begin font-weight="+fontWeight);
+ // comment("% --- LineArea begin font-weight="+fontWeight);
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
+ Box b = (Box)e.nextElement();
this.currentYPosition = ry - area.getPlacementOffset();
b.render(this);
}
- //comment("% --- LineArea end");
+ // comment("% --- LineArea end");
this.currentYPosition = ry - h;
this.currentXPosition = rx;
@@ -735,7 +742,7 @@ public class PSRenderer implements Renderer {
public void renderPage(Page page) {
BodyAreaContainer body;
AreaContainer before, after;
- write("%%Page: "+page.getNumber() + " "+page.getNumber());
+ write("%%Page: " + page.getNumber() + " " + page.getNumber());
write("%%BeginPageSetup");
write("FOPFonts begin");
write("0.001 0.001 scale");
@@ -770,95 +777,89 @@ public class PSRenderer implements Renderer {
int th4 = th / 4;
switch (area.getLeaderPattern()) {
- case LeaderPattern.SPACE:
- //NOP
+ case LeaderPattern.SPACE:
+ // NOP
+ break;
+ case LeaderPattern.RULE:
+ if (area.getRuleStyle() == RuleStyle.NONE)
break;
- case LeaderPattern.RULE:
- if (area.getRuleStyle() == RuleStyle.NONE)
- break;
+ useColor(area.getRed(), area.getGreen(), area.getBlue());
+ write("gsave");
+ write("0 setlinecap");
+ switch (area.getRuleStyle()) {
+ case RuleStyle.DOTTED:
+ write("newpath");
+ write("[1000 3000] 0 setdash");
+ write(th + " setlinewidth");
+ write(rx + " " + ry + " M");
+ write(w + " 0 rlineto");
useColor(area.getRed(), area.getGreen(), area.getBlue());
- write("gsave");
- write("0 setlinecap");
- switch (area.getRuleStyle()) {
- case RuleStyle.DOTTED:
- write("newpath");
- write("[1000 3000] 0 setdash");
- write(th + " setlinewidth");
- write(rx + " "+ry + " M");
- write(w + " 0 rlineto");
- useColor(area.getRed(), area.getGreen(),
- area.getBlue());
- write("stroke");
- break;
- case RuleStyle.DASHED:
- write("newpath");
- write("[3000 3000] 0 setdash");
- write(th + " setlinewidth");
- write(rx + " "+ry + " M");
- write(w + " 0 rlineto");
- useColor(area.getRed(), area.getGreen(),
- area.getBlue());
- write("stroke");
- break;
- case RuleStyle.SOLID:
- write("newpath");
- write(th + " setlinewidth");
- write(rx + " "+ry + " M");
- write(w + " 0 rlineto");
- useColor(area.getRed(), area.getGreen(),
- area.getBlue());
- write("stroke");
- break;
- case RuleStyle.DOUBLE:
- write("newpath");
- write(th3 + " setlinewidth");
- write(rx + " "+(ry - th3) + " M");
- write(w + " 0 rlineto");
- write(rx + " "+(ry + th3) + " M");
- write(w + " 0 rlineto");
- useColor(area.getRed(), area.getGreen(),
- area.getBlue());
- write("stroke");
- break;
- case RuleStyle.GROOVE:
- write(th2 + " setlinewidth");
- write("newpath");
- write(rx + " "+(ry - th4) + " M");
- write(w + " 0 rlineto");
- useColor(area.getRed(), area.getGreen(),
- area.getBlue());
- write("stroke");
- write("newpath");
- write(rx + " "+(ry + th4) + " M");
- write(w + " 0 rlineto");
- useColor(1, 1, 1); //white
- write("stroke");
- break;
- case RuleStyle.RIDGE:
- write(th2 + " setlinewidth");
- write("newpath");
- write(rx + " "+(ry - th4) + " M");
- write(w + " 0 rlineto");
- useColor(1, 1, 1); //white
- write("stroke");
- write("newpath");
- write(rx + " "+(ry + th4) + " M");
- write(w + " 0 rlineto");
- useColor(area.getRed(), area.getGreen(),
- area.getBlue());
- write("stroke");
- break;
- }
- write("grestore");
+ write("stroke");
break;
- case LeaderPattern.DOTS:
- comment("% --- Leader dots NYI");
- MessageHandler.errorln("Leader dots: Not yet implemented");
+ case RuleStyle.DASHED:
+ write("newpath");
+ write("[3000 3000] 0 setdash");
+ write(th + " setlinewidth");
+ write(rx + " " + ry + " M");
+ write(w + " 0 rlineto");
+ useColor(area.getRed(), area.getGreen(), area.getBlue());
+ write("stroke");
+ break;
+ case RuleStyle.SOLID:
+ write("newpath");
+ write(th + " setlinewidth");
+ write(rx + " " + ry + " M");
+ write(w + " 0 rlineto");
+ useColor(area.getRed(), area.getGreen(), area.getBlue());
+ write("stroke");
+ break;
+ case RuleStyle.DOUBLE:
+ write("newpath");
+ write(th3 + " setlinewidth");
+ write(rx + " " + (ry - th3) + " M");
+ write(w + " 0 rlineto");
+ write(rx + " " + (ry + th3) + " M");
+ write(w + " 0 rlineto");
+ useColor(area.getRed(), area.getGreen(), area.getBlue());
+ write("stroke");
+ break;
+ case RuleStyle.GROOVE:
+ write(th2 + " setlinewidth");
+ write("newpath");
+ write(rx + " " + (ry - th4) + " M");
+ write(w + " 0 rlineto");
+ useColor(area.getRed(), area.getGreen(), area.getBlue());
+ write("stroke");
+ write("newpath");
+ write(rx + " " + (ry + th4) + " M");
+ write(w + " 0 rlineto");
+ useColor(1, 1, 1); // white
+ write("stroke");
break;
- case LeaderPattern.USECONTENT:
- comment("% --- Leader use-content NYI");
- MessageHandler.errorln("Leader use-content: Not yet implemented");
+ case RuleStyle.RIDGE:
+ write(th2 + " setlinewidth");
+ write("newpath");
+ write(rx + " " + (ry - th4) + " M");
+ write(w + " 0 rlineto");
+ useColor(1, 1, 1); // white
+ write("stroke");
+ write("newpath");
+ write(rx + " " + (ry + th4) + " M");
+ write(w + " 0 rlineto");
+ useColor(area.getRed(), area.getGreen(), area.getBlue());
+ write("stroke");
break;
+ }
+ write("grestore");
+ break;
+ case LeaderPattern.DOTS:
+ comment("% --- Leader dots NYI");
+ MessageHandler.errorln("Leader dots: Not yet implemented");
+ break;
+ case LeaderPattern.USECONTENT:
+ comment("% --- Leader use-content NYI");
+ MessageHandler.errorln("Leader use-content: Not yet implemented");
+ break;
}
this.currentXPosition += area.getContentWidth();
write(area.getContentWidth() + " 0 RM");
@@ -871,7 +872,7 @@ public class PSRenderer implements Renderer {
BorderAndPadding bap = area.getBorderAndPadding();
if (area instanceof BlockArea)
- rx += ((BlockArea) area).getStartIndent();
+ rx += ((BlockArea)area).getStartIndent();
h = area.getContentHeight();
int ry = this.currentYPosition;
@@ -886,17 +887,17 @@ public class PSRenderer implements Renderer {
w = w + area.getBorderLeftWidth() + area.getBorderRightWidth();
h = h + area.getBorderTopWidth() + area.getBorderBottomWidth();
- //Create a textrect with these dimensions.
- //The y co-ordinate is measured +ve downwards so subtract page-height
+ // Create a textrect with these dimensions.
+ // The y co-ordinate is measured +ve downwards so subtract page-height
ColorType bg = area.getBackgroundColor();
if ((bg != null) && (bg.alpha() == 0)) {
write("newpath");
- write(rx + " "+ry + " M");
+ write(rx + " " + ry + " M");
write(w + " 0 rlineto");
- write("0 "+(-h) + " rlineto");
+ write("0 " + (-h) + " rlineto");
write((-w) + " 0 rlineto");
- write("0 "+h + " rlineto");
+ write("0 " + h + " rlineto");
write("closepath");
useColor(bg);
write("fill");
@@ -905,7 +906,7 @@ public class PSRenderer implements Renderer {
if (area.getBorderTopWidth() != 0) {
write("newpath");
- write(rx + " "+ry + " M");
+ write(rx + " " + ry + " M");
write(w + " 0 rlineto");
write(area.getBorderTopWidth() + " setlinewidth");
write("0 setlinecap");
@@ -914,8 +915,8 @@ public class PSRenderer implements Renderer {
}
if (area.getBorderLeftWidth() != 0) {
write("newpath");
- write(rx + " "+ry + " M");
- write("0 "+(-h) + " rlineto");
+ write(rx + " " + ry + " M");
+ write("0 " + (-h) + " rlineto");
write(area.getBorderLeftWidth() + " setlinewidth");
write("0 setlinecap");
useColor(bap.getBorderColor(BorderAndPadding.LEFT));
@@ -923,8 +924,8 @@ public class PSRenderer implements Renderer {
}
if (area.getBorderRightWidth() != 0) {
write("newpath");
- write((rx + w) + " "+ry + " M");
- write("0 "+(-h) + " rlineto");
+ write((rx + w) + " " + ry + " M");
+ write("0 " + (-h) + " rlineto");
write(area.getBorderRightWidth() + " setlinewidth");
write("0 setlinecap");
useColor(bap.getBorderColor(BorderAndPadding.RIGHT));
@@ -932,7 +933,7 @@ public class PSRenderer implements Renderer {
}
if (area.getBorderBottomWidth() != 0) {
write("newpath");
- write(rx + " "+(ry - h) + " M");
+ write(rx + " " + (ry - h) + " M");
write(w + " 0 rlineto");
write(area.getBorderBottomWidth() + " setlinewidth");
write("0 setlinecap");
@@ -946,9 +947,8 @@ public class PSRenderer implements Renderer {
}
private void useColor(float red, float green, float blue) {
- if ((red != currRed) || (green != currGreen) ||
- (blue != currBlue)) {
- write(red + " "+green + " "+blue + " setrgbcolor");
+ if ((red != currRed) || (green != currGreen) || (blue != currBlue)) {
+ write(red + " " + green + " " + blue + " setrgbcolor");
currRed = red;
currGreen = green;
currBlue = blue;
@@ -957,6 +957,7 @@ public class PSRenderer implements Renderer {
protected class MUserAgent implements UserAgent {
AffineTransform currentTransform = null;
+
/**
* Creates a new SVGUserAgent.
*/
@@ -990,14 +991,14 @@ public class PSRenderer implements Renderer {
* Returns a customized the pixel to mm factor.
*/
public float getPixelToMM() {
- return 0.264583333333333333333f; // 72 dpi
+ return 0.264583333333333333333f; // 72 dpi
}
/**
* Returns the language settings.
*/
public String getLanguages() {
- return "en";//userLanguages;
+ return "en"; // userLanguages;
}
/**
@@ -1005,7 +1006,7 @@ public class PSRenderer implements Renderer {
* @return null if no user style sheet was specified.
*/
public String getUserStyleSheetURI() {
- return null;//userStyleSheetURI;
+ return null; // userStyleSheetURI;
}
/**
@@ -1021,15 +1022,14 @@ public class PSRenderer implements Renderer {
* @param uri The document URI.
*/
public void openLink(SVGAElement elt) {
- //application.openLink(uri);
+ // application.openLink(uri);
}
public Point getClientAreaLocationOnScreen() {
return new Point(0, 0);
}
- public void setSVGCursor(java.awt.Cursor cursor) {
- }
+ public void setSVGCursor(java.awt.Cursor cursor) {}
public AffineTransform getTransform() {
return currentTransform;
@@ -1051,7 +1051,7 @@ public class PSRenderer implements Renderer {
return false;
}
- public void registerExtension(BridgeExtension be) {
- }
+ public void registerExtension(BridgeExtension be) {}
+
}
}
diff --git a/src/org/apache/fop/render/ps/PSStream.java b/src/org/apache/fop/render/ps/PSStream.java
index 6f0fb0e45..9b03c11fd 100644
--- a/src/org/apache/fop/render/ps/PSStream.java
+++ b/src/org/apache/fop/render/ps/PSStream.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
diff --git a/src/org/apache/fop/render/txt/TXTRenderer.java b/src/org/apache/fop/render/txt/TXTRenderer.java
index f971800d0..eaff0eb88 100755
--- a/src/org/apache/fop/render/txt/TXTRenderer.java
+++ b/src/org/apache/fop/render/txt/TXTRenderer.java
@@ -1,10 +1,11 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
-//package com.eastpoint.chrysalis;
+// package com.eastpoint.chrysalis;
package org.apache.fop.render.txt;
// FOP
@@ -35,55 +36,62 @@ import java.util.Hashtable;
/**
* Renderer that renders areas to plain text
*/
-public class TXTRenderer extends PrintRenderer
-{
- /** the current stream to add Text commands to */
+public class TXTRenderer extends PrintRenderer {
+
+ /**
+ * the current stream to add Text commands to
+ */
PCLStream currentStream;
- private int pageHeight = 7920;
-
- // These variables control the virtual paggination functionality.
- public int curdiv = 0;
- private int divisions = -1;
- private int paperheight = -1; // Paper height in decipoints?
- public int orientation = -1; // -1=default/unknown, 0=portrait, 1=landscape.
- public int topmargin = -1; // Top margin in decipoints?
- public int leftmargin = -1; // Left margin in decipoints?
- private int fullmargin = 0;
- final boolean debug = false;
-
- // Variables for rendering text.
- StringBuffer charData[];
- StringBuffer decoData[];
- public float textCPI = 16.67f;
- public float textLPI = 8;
- int maxX = (int)(8.5f * textCPI + 1);
- int maxY = (int)(11f * textLPI + 1);
- float xFactor;
- float yFactor;
- public String lineEnding = "\r\n"; // Every line except the last line on a page (which will end with pageEnding) will be terminated with this string.
- public String pageEnding = "\f"; // Every page except the last one will end with this string.
- public boolean suppressGraphics = false; // If true then graphics/decorations will not be rendered - text only.
-
- /** options */
- protected Hashtable options;
-
- public TXTRenderer() {
- }
-
- /** set up renderer options */
- public void setOptions(Hashtable options) {
- this.options = options;
- }
-
+ private int pageHeight = 7920;
+
+ // These variables control the virtual paggination functionality.
+ public int curdiv = 0;
+ private int divisions = -1;
+ private int paperheight = -1; // Paper height in decipoints?
+ public int orientation =
+ -1; // -1=default/unknown, 0=portrait, 1=landscape.
+ public int topmargin = -1; // Top margin in decipoints?
+ public int leftmargin = -1; // Left margin in decipoints?
+ private int fullmargin = 0;
+ final boolean debug = false;
+
+ // Variables for rendering text.
+ StringBuffer charData[];
+ StringBuffer decoData[];
+ public float textCPI = 16.67f;
+ public float textLPI = 8;
+ int maxX = (int)(8.5f * textCPI + 1);
+ int maxY = (int)(11f * textLPI + 1);
+ float xFactor;
+ float yFactor;
+ public String lineEnding =
+ "\r\n"; // Every line except the last line on a page (which will end with pageEnding) will be terminated with this string.
+ public String pageEnding =
+ "\f"; // Every page except the last one will end with this string.
+ public boolean suppressGraphics =
+ false; // If true then graphics/decorations will not be rendered - text only.
+
+ /**
+ * options
+ */
+ protected Hashtable options;
+
+ public TXTRenderer() {}
+
+ /**
+ * set up renderer options
+ */
+ public void setOptions(Hashtable options) {
+ this.options = options;
+ }
+
/**
* set the TXT document's producer
*
* @param producer string indicating application producing PDF
*/
- public void setProducer(String producer)
- {
- }
+ public void setProducer(String producer) {}
/**
* render the areas into text
@@ -91,79 +99,77 @@ public class TXTRenderer extends PrintRenderer
* @param areaTree the laid-out area tree
* @param writer the PrintWriter to write the PDF with
*/
- public void render(AreaTree areaTree, OutputStream stream) throws IOException, FOPException
- {
- MessageHandler.logln("rendering areas to TEXT");
- idReferences=areaTree.getIDReferences();
- Enumeration e = areaTree.getPages().elements();
- currentStream = new PCLStream(stream);
-
- boolean first = true;
-
- while (e.hasMoreElements())
- {
- if ( first )
- first = false;
- else
- currentStream.add(pageEnding);
- this.renderPage((Page) e.nextElement());
- }
- currentStream.add(lineEnding);
- if ( !idReferences.isEveryIdValid() )
- {
- //throw new FOPException("The following id's were referenced but not found: "+idReferences.getInvalidIds()+"\n");
- MessageHandler.errorln("Warning: The following id's were referenced but not found: "+idReferences.getInvalidIds()+"\n");
+ public void render(AreaTree areaTree,
+ OutputStream stream) throws IOException, FOPException {
+ MessageHandler.logln("rendering areas to TEXT");
+ idReferences = areaTree.getIDReferences();
+ Enumeration e = areaTree.getPages().elements();
+ currentStream = new PCLStream(stream);
+
+ boolean first = true;
+
+ while (e.hasMoreElements()) {
+ if (first)
+ first = false;
+ else
+ currentStream.add(pageEnding);
+ this.renderPage((Page)e.nextElement());
+ }
+ currentStream.add(lineEnding);
+ if (!idReferences.isEveryIdValid()) {
+ // throw new FOPException("The following id's were referenced but not found: "+idReferences.getInvalidIds()+"\n");
+ MessageHandler.errorln("Warning: The following id's were referenced but not found: "
+ + idReferences.getInvalidIds() + "\n");
}
MessageHandler.logln("writing out TEXT");
- stream.flush();
+ stream.flush();
}
- void addStr(int row, int col, String str, boolean ischar)
- {
-if ( debug )
-System.out.println("TXTRenderer.addStr(" + row + ", " + col + ", \"" + str + "\", " + ischar + ")");
- if ( suppressGraphics && ! ischar )
- return;
- StringBuffer sb;
- if ( row < 0 )
- row = 0;
- if ( ischar )
- sb = charData[row];
- else
- sb = decoData[row];
- if ( sb == null )
- sb = new StringBuffer();
- if ( (col + str.length()) > maxX )
- col = maxX - str.length();
- if ( col < 0 )
- {
- col = 0;
- if ( str.length() > maxX )
- str = str.substring(0, maxX);
- }
- // Pad to col
- for ( int countr = sb.length() ; countr < col ; countr++ )
- sb.append(' ');
-if ( debug )
-System.out.println("TXTRenderer.addStr() sb.length()=" + sb.length());
- for ( int countr = col ; countr < (col + str.length()) ; countr++ )
- {
- if ( countr >= sb.length() )
- sb.append(str.charAt(countr - col));
- else
- {
-if ( debug )
-System.out.println("TXTRenderer.addStr() sb.length()=" + sb.length() + " countr=" + countr);
- sb.setCharAt(countr, str.charAt(countr - col));
- }
- }
-
- if ( ischar )
- charData[row] = sb;
- else
- decoData[row] = sb;
- }
+ void addStr(int row, int col, String str, boolean ischar) {
+ if (debug)
+ System.out.println("TXTRenderer.addStr(" + row + ", " + col
+ + ", \"" + str + "\", " + ischar + ")");
+ if (suppressGraphics &&!ischar)
+ return;
+ StringBuffer sb;
+ if (row < 0)
+ row = 0;
+ if (ischar)
+ sb = charData[row];
+ else
+ sb = decoData[row];
+ if (sb == null)
+ sb = new StringBuffer();
+ if ((col + str.length()) > maxX)
+ col = maxX - str.length();
+ if (col < 0) {
+ col = 0;
+ if (str.length() > maxX)
+ str = str.substring(0, maxX);
+ }
+ // Pad to col
+ for (int countr = sb.length(); countr < col; countr++)
+ sb.append(' ');
+ if (debug)
+ System.out.println("TXTRenderer.addStr() sb.length()="
+ + sb.length());
+ for (int countr = col; countr < (col + str.length()); countr++) {
+ if (countr >= sb.length())
+ sb.append(str.charAt(countr - col));
+ else {
+ if (debug)
+ System.out.println("TXTRenderer.addStr() sb.length()="
+ + sb.length() + " countr=" + countr);
+ sb.setCharAt(countr, str.charAt(countr - col));
+ }
+ }
+
+ if (ischar)
+ charData[row] = sb;
+ else
+ decoData[row] = sb;
+ }
/**
* add a line to the current stream
@@ -175,16 +181,13 @@ System.out.println("TXTRenderer.addStr() sb.length()=" + sb.length() + " countr=
* @param th the thickness in millipoints
* @param stroke the line color
*/
- protected void addLine(int x1, int y1, int x2, int y2, int th, PDFPathPaint stroke)
- {
- if ( x1 == x2 )
- {
- addRect(x1, y1, th, y2 - y1 + 1, stroke, stroke);
- }
- else if ( y1 == y2 )
- {
- addRect(x1, y1, x2 - x1 + 1, th, stroke, stroke);
- }
+ protected void addLine(int x1, int y1, int x2, int y2, int th,
+ PDFPathPaint stroke) {
+ if (x1 == x2) {
+ addRect(x1, y1, th, y2 - y1 + 1, stroke, stroke);
+ } else if (y1 == y2) {
+ addRect(x1, y1, x2 - x1 + 1, th, stroke, stroke);
+ }
}
/**
@@ -198,257 +201,239 @@ System.out.println("TXTRenderer.addStr() sb.length()=" + sb.length() + " countr=
* @param rs the rule style
* @param stroke the line color
*/
- protected void addLine(int x1, int y1, int x2, int y2, int th, int rs, PDFPathPaint stroke)
- {
- PDFColor lstroke = null;
- if ( rs == org.apache.fop.fo.properties.RuleStyle.DOTTED )
- lstroke = new PDFColor(0.7f, 0.7f, 0.7f);
- else
- lstroke = (PDFColor)stroke;
- if ( x1 == x2 )
- {
- addRect(x1, y1, th, y2 - y1 + 1, lstroke, lstroke);
- }
- else if ( y1 == y2 )
- {
- addRect(x1, y1, x2 - x1 + 1, th, lstroke, lstroke);
- }
+ protected void addLine(int x1, int y1, int x2, int y2, int th, int rs,
+ PDFPathPaint stroke) {
+ PDFColor lstroke = null;
+ if (rs == org.apache.fop.fo.properties.RuleStyle.DOTTED)
+ lstroke = new PDFColor(0.7f, 0.7f, 0.7f);
+ else
+ lstroke = (PDFColor)stroke;
+ if (x1 == x2) {
+ addRect(x1, y1, th, y2 - y1 + 1, lstroke, lstroke);
+ } else if (y1 == y2) {
+ addRect(x1, y1, x2 - x1 + 1, th, lstroke, lstroke);
+ }
}
- protected void addLine(float x1, float y1, float x2, float y2, PDFColor sc, float sw)
- {
-/* SVG - Not yet implemented
-if ( debug )
-System.out.println("TXTRenderer.addLine(" + x1 + ", " + y1 + ", " + x2 + ", " + y2 + ", " + sc + ", " + sw + ")");
- if ( x1 == x2 )
- {
- addRect(x1 - sw/2, y1, sw, y2 - y1 + 1, 0, 0, sc, null, 0);
- }
- else if ( y1 == y2 || (Math.abs(y1 - y2) <= 0.24) ) // 72/300=0.24
- {
- addRect(x1, y1 - sw/2, x2 - x1 + 1, sw, 0, 0, sc, null, 0);
- }
- else if ( sc != null )
- {
- // Convert dimensions to characters.
- //float cfact = 300f / 72f; // 300 dpi, 1pt=1/72in
- int ix1 = (int)(x1 * xFactor);
- int iy1 = (int)(y1 * yFactor);
- int ix2 = (int)(x2 * xFactor);
- int iy2 = (int)(y2 * yFactor);
- int isw = (int)(sw * xFactor);
- int origix;
-
- // Normalize
- if ( iy1 > iy2 )
- {
- int tmp = ix1;
- ix1 = ix2;
- ix2 = tmp;
- tmp = iy1;
- iy1 = iy2;
- iy2 = tmp;
- }
- if ( ix1 > ix2 )
- {
- origix = ix2;
- ix1 -=ix2;
- ix2 = 0;
- }
- else
- {
- origix = ix1;
- ix2 -= ix1;
- ix1 = 0;
- }
-
- // Convert line width to a pixel run length.
-//System.out.println("TXTRenderer.addLine(" + ix1 + ", " + iy1 + ", " + ix2 + ", " + iy2 + ", " + isw + ")");
- int runlen = (int)Math.sqrt(Math.pow(isw, 2) * (1 + Math.pow((ix1 - ix2) / (iy1 - iy2), 2)));
- if ( runlen < 1 )
- runlen = 1;
- StringBuffer rlbuff = new StringBuffer();
- for ( int countr = 0 ; countr < runlen ; countr++ )
- rlbuff.append('*');
- String rlstr = rlbuff.toString();
-//System.out.println("TXTRenderer.addLine: runlen = " + runlen);
-
- // Draw the line.
- int d, dx, dy;
- int Aincr, Bincr;
- int xincr = 1;
- int x, y;
-
-
- dx = Math.abs(ix2 - ix1);
- dy = iy2 - iy1;
-
- if ( dx > dy )
- {
- xincr = dx / dy;
-
- // Move to starting position.
- //currentStream.add("\033*p" + origix + "x" + iy1 + "Y");
- x = ix1 - runlen / 2;
- iy2 += (isw / 2);
- // Start raster graphics
- //currentStream.add("\033*t300R\033*r" + dx + "s1A\033*b1M");
- }
- else
- {
- // Move to starting position.
- //currentStream.add("\033*p" + (origix - runlen / 2) + "x" + iy1 + "Y");
- x = ix1;
- // Start raster graphics
- //currentStream.add("\033*t300R\033*r1A\033*b1M");
- }
-
- if ( ix1 > ix2 )
- xincr *= -1;
- d = 2 * dx - dy;
- Aincr = 2 * (dx - dy);
- Bincr = 2 * dx;
-
- y = iy1;
-
- xferLineBytes(x, runlen, null, -1);
-
- for ( y = iy1 + 1 ; y <= iy2 ; y++ )
- {
- if ( d >= 0 )
- {
- x += xincr;
- d += Aincr;
- }
- else
- d += Bincr;
- xferLineBytes(x, runlen, null, -1);
- }
-
- // End raster graphics
- //currentStream.add("\033*rB");
- // Return to regular print mode.
- //currentStream.add("\033*v0t0n0O");
- }
-*/
+ protected void addLine(float x1, float y1, float x2, float y2,
+ PDFColor sc, float sw) {
+ /*
+ * SVG - Not yet implemented
+ * if ( debug )
+ * System.out.println("TXTRenderer.addLine(" + x1 + ", " + y1 + ", " + x2 + ", " + y2 + ", " + sc + ", " + sw + ")");
+ * if ( x1 == x2 )
+ * {
+ * addRect(x1 - sw/2, y1, sw, y2 - y1 + 1, 0, 0, sc, null, 0);
+ * }
+ * else if ( y1 == y2 || (Math.abs(y1 - y2) <= 0.24) ) // 72/300=0.24
+ * {
+ * addRect(x1, y1 - sw/2, x2 - x1 + 1, sw, 0, 0, sc, null, 0);
+ * }
+ * else if ( sc != null )
+ * {
+ * // Convert dimensions to characters.
+ * //float cfact = 300f / 72f; // 300 dpi, 1pt=1/72in
+ * int ix1 = (int)(x1 * xFactor);
+ * int iy1 = (int)(y1 * yFactor);
+ * int ix2 = (int)(x2 * xFactor);
+ * int iy2 = (int)(y2 * yFactor);
+ * int isw = (int)(sw * xFactor);
+ * int origix;
+ * // Normalize
+ * if ( iy1 > iy2 )
+ * {
+ * int tmp = ix1;
+ * ix1 = ix2;
+ * ix2 = tmp;
+ * tmp = iy1;
+ * iy1 = iy2;
+ * iy2 = tmp;
+ * }
+ * if ( ix1 > ix2 )
+ * {
+ * origix = ix2;
+ * ix1 -=ix2;
+ * ix2 = 0;
+ * }
+ * else
+ * {
+ * origix = ix1;
+ * ix2 -= ix1;
+ * ix1 = 0;
+ * }
+ * // Convert line width to a pixel run length.
+ * //System.out.println("TXTRenderer.addLine(" + ix1 + ", " + iy1 + ", " + ix2 + ", " + iy2 + ", " + isw + ")");
+ * int runlen = (int)Math.sqrt(Math.pow(isw, 2) * (1 + Math.pow((ix1 - ix2) / (iy1 - iy2), 2)));
+ * if ( runlen < 1 )
+ * runlen = 1;
+ * StringBuffer rlbuff = new StringBuffer();
+ * for ( int countr = 0 ; countr < runlen ; countr++ )
+ * rlbuff.append('*');
+ * String rlstr = rlbuff.toString();
+ * //System.out.println("TXTRenderer.addLine: runlen = " + runlen);
+ * // Draw the line.
+ * int d, dx, dy;
+ * int Aincr, Bincr;
+ * int xincr = 1;
+ * int x, y;
+ * dx = Math.abs(ix2 - ix1);
+ * dy = iy2 - iy1;
+ * if ( dx > dy )
+ * {
+ * xincr = dx / dy;
+ * // Move to starting position.
+ * //currentStream.add("\033*p" + origix + "x" + iy1 + "Y");
+ * x = ix1 - runlen / 2;
+ * iy2 += (isw / 2);
+ * // Start raster graphics
+ * //currentStream.add("\033*t300R\033*r" + dx + "s1A\033*b1M");
+ * }
+ * else
+ * {
+ * // Move to starting position.
+ * //currentStream.add("\033*p" + (origix - runlen / 2) + "x" + iy1 + "Y");
+ * x = ix1;
+ * // Start raster graphics
+ * //currentStream.add("\033*t300R\033*r1A\033*b1M");
+ * }
+ * if ( ix1 > ix2 )
+ * xincr *= -1;
+ * d = 2 * dx - dy;
+ * Aincr = 2 * (dx - dy);
+ * Bincr = 2 * dx;
+ * y = iy1;
+ * xferLineBytes(x, runlen, null, -1);
+ *
+ * for ( y = iy1 + 1 ; y <= iy2 ; y++ )
+ * {
+ * if ( d >= 0 )
+ * {
+ * x += xincr;
+ * d += Aincr;
+ * }
+ * else
+ * d += Bincr;
+ * xferLineBytes(x, runlen, null, -1);
+ * }
+ * // End raster graphics
+ * //currentStream.add("\033*rB");
+ * // Return to regular print mode.
+ * //currentStream.add("\033*v0t0n0O");
+ * }
+ */
}
- private void xferLineBytes(int startpos, int bitcount, Vector save, int start2)
- {
-/* Not yet implemented
-//System.out.println("TXTRenderer.xferLineBytes(" + startpos + ", " + bitcount + ")");
- int curbitpos = 0;
- if ( start2 > 0 && start2 <= (startpos + bitcount) )
- {
- bitcount += (start2 - startpos);
- start2 = 0;
- }
-
- char bytes[] = new char[((start2>startpos?start2:startpos) + bitcount) / 4 + 2];
- int dlen = 0;
- byte dbyte = 0;
- int bytepos = 0;
-
- do
- {
- int bits2set;
- if ( startpos < 0 )
- {
- bits2set = bitcount + startpos;
- startpos = 0;
- }
- else
- bits2set = bitcount;
-
- byte bittype = 0;
- do
- {
- if ( bytepos > 0 )
- {
- int inc = startpos - curbitpos;
- if ( (inc) >= (8 - bytepos) )
- {
- curbitpos += (8 - bytepos);
- bytepos = 0;
- bytes[dlen++] = (char)0;
- bytes[dlen++] = (char)dbyte;
- dbyte = 0;
- }
- else
- {
- bytepos += inc;
- dbyte = (byte)(dbyte ^ (byte)(Math.pow(2, 8 - bytepos) - 1));
- curbitpos += inc;
- }
- }
-
- // Set runs of whole bytes.
- int setbytes = (startpos - curbitpos) / 8;
- if ( setbytes > 0 )
- {
- curbitpos += setbytes * 8;
- while ( setbytes > 0 )
- {
- if ( setbytes > 256 )
- {
- bytes[dlen++] = 0xFF;
- setbytes -= 256;
- }
- else
- {
- bytes[dlen++] = (char)((setbytes - 1) & 0xFF);
- setbytes = 0;
- }
- bytes[dlen++] = (char)bittype;
- }
- }
- // move to position in the first byte.
- if ( curbitpos < startpos )
- {
- if ( bytepos == 0 )
- dbyte = bittype;
- bytepos += startpos - curbitpos;
- dbyte = (byte)(dbyte ^ (byte)(Math.pow(2, 8 - bytepos) - 1));
- curbitpos += bytepos;
- startpos += bits2set;
- }
- else
- {
- startpos += bits2set;
- }
-
- if ( bittype == 0 )
- bittype = (byte)0xFF;
- else
- bittype = 7;
- } while ( bittype != 7 );
-
- if ( start2 > 0 )
- {
- startpos = start2;
- start2 = -1;
- }
- else
- startpos = -1;
- } while ( startpos >= 0 );
- if ( bytepos > 0 )
- {
- bytes[dlen++] = (char)0;
- bytes[dlen++] = (char)dbyte;
- }
- if ( save == null )
- {
- //currentStream.add("\033*b" + dlen + "W");
- //currentStream.add(new String(bytes, 0, dlen));
- }
- else
- {
- String line = "\033*b" + dlen + "W" + new String(bytes, 0, dlen);
- //currentStream.add(line);
- save.addElement(line);
- }
-*/
- }
+ private void xferLineBytes(int startpos, int bitcount, Vector save,
+ int start2) {
+ /*
+ * Not yet implemented
+ * //System.out.println("TXTRenderer.xferLineBytes(" + startpos + ", " + bitcount + ")");
+ * int curbitpos = 0;
+ * if ( start2 > 0 && start2 <= (startpos + bitcount) )
+ * {
+ * bitcount += (start2 - startpos);
+ * start2 = 0;
+ * }
+ * char bytes[] = new char[((start2>startpos?start2:startpos) + bitcount) / 4 + 2];
+ * int dlen = 0;
+ * byte dbyte = 0;
+ * int bytepos = 0;
+ * do
+ * {
+ * int bits2set;
+ * if ( startpos < 0 )
+ * {
+ * bits2set = bitcount + startpos;
+ * startpos = 0;
+ * }
+ * else
+ * bits2set = bitcount;
+ * byte bittype = 0;
+ * do
+ * {
+ * if ( bytepos > 0 )
+ * {
+ * int inc = startpos - curbitpos;
+ * if ( (inc) >= (8 - bytepos) )
+ * {
+ * curbitpos += (8 - bytepos);
+ * bytepos = 0;
+ * bytes[dlen++] = (char)0;
+ * bytes[dlen++] = (char)dbyte;
+ * dbyte = 0;
+ * }
+ * else
+ * {
+ * bytepos += inc;
+ * dbyte = (byte)(dbyte ^ (byte)(Math.pow(2, 8 - bytepos) - 1));
+ * curbitpos += inc;
+ * }
+ * }
+ * // Set runs of whole bytes.
+ * int setbytes = (startpos - curbitpos) / 8;
+ * if ( setbytes > 0 )
+ * {
+ * curbitpos += setbytes * 8;
+ * while ( setbytes > 0 )
+ * {
+ * if ( setbytes > 256 )
+ * {
+ * bytes[dlen++] = 0xFF;
+ * setbytes -= 256;
+ * }
+ * else
+ * {
+ * bytes[dlen++] = (char)((setbytes - 1) & 0xFF);
+ * setbytes = 0;
+ * }
+ * bytes[dlen++] = (char)bittype;
+ * }
+ * }
+ * // move to position in the first byte.
+ * if ( curbitpos < startpos )
+ * {
+ * if ( bytepos == 0 )
+ * dbyte = bittype;
+ * bytepos += startpos - curbitpos;
+ * dbyte = (byte)(dbyte ^ (byte)(Math.pow(2, 8 - bytepos) - 1));
+ * curbitpos += bytepos;
+ * startpos += bits2set;
+ * }
+ * else
+ * {
+ * startpos += bits2set;
+ * }
+ * if ( bittype == 0 )
+ * bittype = (byte)0xFF;
+ * else
+ * bittype = 7;
+ * } while ( bittype != 7 );
+ * if ( start2 > 0 )
+ * {
+ * startpos = start2;
+ * start2 = -1;
+ * }
+ * else
+ * startpos = -1;
+ * } while ( startpos >= 0 );
+ * if ( bytepos > 0 )
+ * {
+ * bytes[dlen++] = (char)0;
+ * bytes[dlen++] = (char)dbyte;
+ * }
+ * if ( save == null )
+ * {
+ * //currentStream.add("\033*b" + dlen + "W");
+ * //currentStream.add(new String(bytes, 0, dlen));
+ * }
+ * else
+ * {
+ * String line = "\033*b" + dlen + "W" + new String(bytes, 0, dlen);
+ * //currentStream.add(line);
+ * save.addElement(line);
+ * }
+ */
+ }
/**
* add a rectangle to the current stream
@@ -459,26 +444,22 @@ System.out.println("TXTRenderer.addLine(" + x1 + ", " + y1 + ", " + x2 + ", " +
* @param h the height in millipoints
* @param stroke the stroke color/gradient
*/
- protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke)
- {
- if ( h < 0 )
- h *= -1;
-
- if (h < 720 || w < 720)
- {
- if ( w < 720 )
- w = 720;
- if ( h < 720 )
- h = 720;
- addRect(x, y, w, h, stroke, stroke);
- }
- else
- {
- addRect(x, y, w, 720, stroke, stroke);
- addRect(x, y, 720, h, stroke, stroke);
- addRect(x + w - 720, y, 720, h, stroke, stroke);
- addRect(x, y - h + 720, w, 720, stroke, stroke);
- }
+ protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke) {
+ if (h < 0)
+ h *= -1;
+
+ if (h < 720 || w < 720) {
+ if (w < 720)
+ w = 720;
+ if (h < 720)
+ h = 720;
+ addRect(x, y, w, h, stroke, stroke);
+ } else {
+ addRect(x, y, w, 720, stroke, stroke);
+ addRect(x, y, 720, h, stroke, stroke);
+ addRect(x + w - 720, y, 720, h, stroke, stroke);
+ addRect(x, y - h + 720, w, 720, stroke, stroke);
+ }
}
/**
@@ -491,108 +472,108 @@ System.out.println("TXTRenderer.addLine(" + x1 + ", " + y1 + ", " + x2 + ", " +
* @param fill the fill color/gradient
* @param stroke the stroke color/gradient
*/
- protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke, PDFPathPaint fill)
- {
-//System.out.println("TXTRenderer.addRect(" + x + ", " + y + ", " + w + ", " + h + ", " + r + ", " + g + ", " + b + ", " + fr + ", " + fg + ", " + fb + ")");
- if ((w == 0) || (h == 0))
- return;
- if ( h < 0 )
- h *= -1;
-
- int row = (int)((pageHeight - (y / 100))* 100 * yFactor);
- int col = (int)(x * xFactor);
-
- PDFColor sc = (PDFColor)stroke;
- PDFColor fc = (PDFColor)fill;
-
- sc.setColorSpace(ColorSpace.DEVICE_RGB);
- fc.setColorSpace(ColorSpace.DEVICE_RGB);
-
- int lineshade = (int)(100 - ((0.3f * sc.red() + 0.59f * sc.green() + 0.11f * sc.blue()) * 100f));
- int fillshade = (int)(100 - ((0.3f * fc.red() + 0.59f * fc.green() + 0.11f * fc.blue()) * 100f));
-if ( debug )
-System.out.println("TXTRenderer.addRect(" + x + ", " + y + ", " + w + ", " + h + ", " + stroke + ", " + fill + ") fillshade=" + fillshade);
- char fillchar = ' ';
- if ( fillshade >= 75 )
- fillchar = '#';
- else if ( fillshade >= 50 )
- fillchar = '*';
- else if ( fillshade >= 25 )
- fillchar = ':';
-
-
- if ( fillchar != ' ' )
- {
- StringBuffer linefill = new StringBuffer();
- int sw = (int)(w * xFactor);
- int sh = (int)(h * yFactor);
- if ( sw == 0 || sh == 0 )
- {
- if ( fillshade >= 50 )
- {
- if ( h > w )
- fillchar = '|';
- else
- fillchar = '-';
- }
- else
- {
- if ( h > w )
- fillchar = ':';
- else
- fillchar = '.';
- }
- }
- if ( sw == 0 )
- linefill.append(fillchar);
- else
- for ( int countr = 0 ; countr < sw ; countr++ )
- linefill.append(fillchar);
- if ( sh == 0 )
- addStr(row, col, linefill.toString(), false);
- else
- for ( int countr = 0 ; countr < sh ; countr++ )
- addStr(row + countr, col, linefill.toString(), false);
- }
-
- if ( lineshade >= 25 )
- {
- char vlinechar = '|';
- char hlinechar = '-';
- if ( lineshade < 50 )
- {
- vlinechar = ':';
- hlinechar = '.';
- }
- StringBuffer linefill = new StringBuffer();
- int sw = (int)(w * xFactor);
- for ( int countr = 0 ; countr < sw ; countr++ )
- linefill.append(hlinechar);
- int sh = (int)(h * yFactor);
-
- if ( w > h )
- {
- for ( int countr = 1 ; countr < (sh - 1); countr++ )
- {
- addStr(row + countr, col, String.valueOf(vlinechar), false);
- addStr(row + countr, col + sw, String.valueOf(vlinechar), false);
- }
- addStr(row, col, linefill.toString(), false);
- addStr(row + sh, col, linefill.toString(), false);
-
- }
- else
- {
- addStr(row, col, linefill.toString(), false);
- addStr(row + sh, col, linefill.toString(), false);
- for ( int countr = 1 ; countr < (sh - 1); countr++ )
- {
- addStr(row + countr, col, String.valueOf(vlinechar), false);
- addStr(row + countr, col + sw, String.valueOf(vlinechar), false);
- }
-
- }
- }
+ protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke,
+ PDFPathPaint fill) {
+ // System.out.println("TXTRenderer.addRect(" + x + ", " + y + ", " + w + ", " + h + ", " + r + ", " + g + ", " + b + ", " + fr + ", " + fg + ", " + fb + ")");
+ if ((w == 0) || (h == 0))
+ return;
+ if (h < 0)
+ h *= -1;
+
+ int row = (int)((pageHeight - (y / 100)) * 100 * yFactor);
+ int col = (int)(x * xFactor);
+
+ PDFColor sc = (PDFColor)stroke;
+ PDFColor fc = (PDFColor)fill;
+
+ sc.setColorSpace(ColorSpace.DEVICE_RGB);
+ fc.setColorSpace(ColorSpace.DEVICE_RGB);
+
+ int lineshade =
+ (int)(100
+ - ((0.3f * sc.red() + 0.59f * sc.green() + 0.11f * sc.blue())
+ * 100f));
+ int fillshade =
+ (int)(100
+ - ((0.3f * fc.red() + 0.59f * fc.green() + 0.11f * fc.blue())
+ * 100f));
+ if (debug)
+ System.out.println("TXTRenderer.addRect(" + x + ", " + y + ", "
+ + w + ", " + h + ", " + stroke + ", " + fill
+ + ") fillshade=" + fillshade);
+ char fillchar = ' ';
+ if (fillshade >= 75)
+ fillchar = '#';
+ else if (fillshade >= 50)
+ fillchar = '*';
+ else if (fillshade >= 25)
+ fillchar = ':';
+
+
+ if (fillchar != ' ') {
+ StringBuffer linefill = new StringBuffer();
+ int sw = (int)(w * xFactor);
+ int sh = (int)(h * yFactor);
+ if (sw == 0 || sh == 0) {
+ if (fillshade >= 50) {
+ if (h > w)
+ fillchar = '|';
+ else
+ fillchar = '-';
+ } else {
+ if (h > w)
+ fillchar = ':';
+ else
+ fillchar = '.';
+ }
+ }
+ if (sw == 0)
+ linefill.append(fillchar);
+ else
+ for (int countr = 0; countr < sw; countr++)
+ linefill.append(fillchar);
+ if (sh == 0)
+ addStr(row, col, linefill.toString(), false);
+ else
+ for (int countr = 0; countr < sh; countr++)
+ addStr(row + countr, col, linefill.toString(), false);
+ }
+
+ if (lineshade >= 25) {
+ char vlinechar = '|';
+ char hlinechar = '-';
+ if (lineshade < 50) {
+ vlinechar = ':';
+ hlinechar = '.';
+ }
+ StringBuffer linefill = new StringBuffer();
+ int sw = (int)(w * xFactor);
+ for (int countr = 0; countr < sw; countr++)
+ linefill.append(hlinechar);
+ int sh = (int)(h * yFactor);
+
+ if (w > h) {
+ for (int countr = 1; countr < (sh - 1); countr++) {
+ addStr(row + countr, col, String.valueOf(vlinechar),
+ false);
+ addStr(row + countr, col + sw, String.valueOf(vlinechar),
+ false);
+ }
+ addStr(row, col, linefill.toString(), false);
+ addStr(row + sh, col, linefill.toString(), false);
+
+ } else {
+ addStr(row, col, linefill.toString(), false);
+ addStr(row + sh, col, linefill.toString(), false);
+ for (int countr = 1; countr < (sh - 1); countr++) {
+ addStr(row + countr, col, String.valueOf(vlinechar),
+ false);
+ addStr(row + countr, col + sw, String.valueOf(vlinechar),
+ false);
+ }
+
+ }
+ }
}
@@ -610,1018 +591,987 @@ System.out.println("TXTRenderer.addRect(" + x + ", " + y + ", " + w + ", " + h +
* @param fg the green component of the fill
* @param fb the blue component of the fill
*/
- protected void addRect(float x, float y, float w, float h, float rx, float ry,
- PDFColor fc, PDFColor sc, float sw)
- {
-/* SVG - Not yet implemented
-if ( debug )
-System.out.println("TXTRenderer.addRect(" + x + ", " + y + ", " + w + ", " + h + ", " + rx + ", " + ry + ", " + fc + ", " + sc + ", " + sw + ")");
-
- float sr = 1;
- float sg = 1;
- float sb = 1;
- float fr = 1;
- float fg = 1;
- float fb = 1;
- if ( sc != null && sw > 0 )
- {
- sr = (float)sc.red();
- sg = (float)sc.green();
- sb = (float)sc.blue();
- }
- if ( fc != null )
- {
- fr = (float)fc.red();
- fg = (float)fc.green();
- fb = (float)fc.blue();
- }
- addRect((int)(x * 1000), (int)(pageHeight * 100 - y * 1000), (int)(w * 1000), (int)(h * 1000), sr, sg, sb, fr, fg, fb);
-
- fc = null;
- sc = null;
-
- if ( rx == 0 || ry == 0 )
- {
- if ( fc != null )
- {
- int fillshade = (int)(100 - ((0.3f * fc.red() + 0.59f * fc.green() + 0.11f * fc.blue()) * 100f));
- currentStream.add("\033*v0n1O\033&a" + (x * 10) + "h" + ((y * 10)) + "V"
- + "\033*c" + (w * 10) + "h" + (h * 10) + "v" + fillshade + "g2P\033*v0n0O");
- }
- if ( sc != null && sw > 0 )
- {
- String lend = "v" + String.valueOf((int)(100 - ((0.3f * sc.red() + 0.59f * sc.green() + 0.11f * sc.blue()) * 100f))) + "g2P";
- currentStream.add("\033*v0n1O");
- currentStream.add("\033&a" + ((x - sw/2) * 10) + "h" + (((y - sw/2)) * 10) + "V"
- + "\033*c" + ((w + sw) * 10) + "h" + ((sw) * 10) + lend);
- currentStream.add("\033&a" + ((x - sw/2) * 10) + "h" + (((y - sw/2)) * 10) + "V"
- + "\033*c" + ((sw) * 10) + "h" + ((h + sw) * 10) + lend);
- currentStream.add("\033&a" + ((x + w - sw/2) * 10) + "h" + (((y - sw/2)) * 10) + "V"
- + "\033*c" + ((sw) * 10) + "h" + ((h + sw) * 10) + lend);
- currentStream.add("\033&a" + ((x - sw/2) * 10) + "h" + (((y + h - sw/2)) * 10) + "V"
- + "\033*c" + ((w + sw) * 10) + "h" + ((sw) * 10) + lend);
- currentStream.add("\033*v0n0O");
- }
- }
- else
- {
- // Convert dimensions to pixels.
- float cfact = 300f / 72f; // 300 dpi, 1pt=1/72in
- int ix = (int)(x * cfact);
- int iy = (int)(y * cfact);
- int iw = (int)(w * cfact);
- int ih = (int)(h * cfact);
- int irx = (int)(rx * cfact);
- int iry = (int)(ry * cfact);
- int isw = (int)(sw * cfact);
- int longwidth = 0;
- int pass = 0;
- PDFColor thecolor = null;
-
- do
- {
- if ( pass == 0 && fc != null )
- {
- thecolor = fc;
- }
- else if ( pass == 1 && sc != null )
- {
- int iswdiv2 = isw / 2;
- thecolor = sc;
- ix -= iswdiv2;
- iy -= iswdiv2;
- irx += iswdiv2;
- iry += iswdiv2;
- iw += isw;
- ih += isw;
- longwidth = (int)(isw * 1.414);
- }
- else
- thecolor = null;
-
-
- if ( thecolor != null )
- {
- int tx = 0;
- int ty = iry;
- long a = irx;
- long b = iry;
- long Asquared = (long)Math.pow(a, 2);
- long TwoAsquared = 2 * Asquared;
- long Bsquared = (long)Math.pow(b, 2);
- long TwoBsquared = 2 * Bsquared;
- long d = Bsquared - Asquared * b + Asquared / 4;
- long dx = 0;
- long dy = TwoAsquared * b;
- int rectlen = iw - 2 * irx;
- Vector bottomlines = new Vector();
-
- int x0 = tx;
-
- // Set Transparency modes and select shading.
- currentStream.add("\033*v0n1O\033*c" + (int)(100 - ((0.3f * thecolor.red() + 0.59f * thecolor.green() + 0.11f * thecolor.blue()) * 100f)) + "G\033*v2T");
- // Move to starting position.
- currentStream.add("\033*p" + ix + "x" + iy + "Y");
- // Start raster graphics
- currentStream.add("\033*t300R\033*r" + iw + "s1A\033*b1M");
-
- while ( dx < dy )
- {
- if ( d > 0 )
- {
- if ( pass == 0 || ty > (iry - isw) )
- xferLineBytes(irx - x0, rectlen + 2 * x0, bottomlines, -1);
- else
- xferLineBytes(irx - x0, longwidth, bottomlines, iw - irx + x0 - longwidth);
- x0 = tx + 1;
- ty--;
- dy -= TwoAsquared;
- d -= dy;
- }
- tx++;
- dx += TwoBsquared;
- d += Bsquared + dx;
- }
-
- d += (3 * (Asquared - Bsquared) / 2 - (dx + dy)) / 2;
-
- while ( ty > 0 )
- {
- if ( pass == 0 || ty >= (iry - isw) )
- xferLineBytes(irx - tx, rectlen + 2 * tx, bottomlines, -1);
- else
- xferLineBytes(irx - tx, isw, bottomlines, iw - irx + tx - isw);
-
- if ( d < 0 )
- {
- tx++;
- dx += TwoBsquared;
- d += dx;
- }
- ty--;
- dy -= TwoAsquared;
- d += Asquared - dy;
- }
-
- // Draw the middle part of the rectangle
- int midlen = ih - 2 * iry;
- if ( midlen > 0 )
- {
- if ( pass == 0 )
- xferLineBytes(0, iw, null, -1);
- else
- xferLineBytes(0, isw, null, iw - isw);
- currentStream.add("\033*b3M");
- for ( int countr = midlen - 1 ; countr > 0 ; countr-- )
- currentStream.add("\033*b0W");
- currentStream.add("\033*b1M");
- }
-
- // Draw the bottom.
- for ( int countr = bottomlines.size() - 1 ; countr >= 0 ; countr-- )
- currentStream.add((String)bottomlines.elementAt(countr));
-
- // End raster graphics
- currentStream.add("\033*rB");
- // Return to regular print mode.
- currentStream.add("\033*v0t0n0O");
- }
- pass++;
- } while ( pass < 2 );
- }
-*/
+ protected void addRect(float x, float y, float w, float h, float rx,
+ float ry, PDFColor fc, PDFColor sc, float sw) {
+ /*
+ * SVG - Not yet implemented
+ * if ( debug )
+ * System.out.println("TXTRenderer.addRect(" + x + ", " + y + ", " + w + ", " + h + ", " + rx + ", " + ry + ", " + fc + ", " + sc + ", " + sw + ")");
+ * float sr = 1;
+ * float sg = 1;
+ * float sb = 1;
+ * float fr = 1;
+ * float fg = 1;
+ * float fb = 1;
+ * if ( sc != null && sw > 0 )
+ * {
+ * sr = (float)sc.red();
+ * sg = (float)sc.green();
+ * sb = (float)sc.blue();
+ * }
+ * if ( fc != null )
+ * {
+ * fr = (float)fc.red();
+ * fg = (float)fc.green();
+ * fb = (float)fc.blue();
+ * }
+ * addRect((int)(x * 1000), (int)(pageHeight * 100 - y * 1000), (int)(w * 1000), (int)(h * 1000), sr, sg, sb, fr, fg, fb);
+ * fc = null;
+ * sc = null;
+ * if ( rx == 0 || ry == 0 )
+ * {
+ * if ( fc != null )
+ * {
+ * int fillshade = (int)(100 - ((0.3f * fc.red() + 0.59f * fc.green() + 0.11f * fc.blue()) * 100f));
+ * currentStream.add("\033*v0n1O\033&a" + (x * 10) + "h" + ((y * 10)) + "V"
+ * + "\033*c" + (w * 10) + "h" + (h * 10) + "v" + fillshade + "g2P\033*v0n0O");
+ * }
+ * if ( sc != null && sw > 0 )
+ * {
+ * String lend = "v" + String.valueOf((int)(100 - ((0.3f * sc.red() + 0.59f * sc.green() + 0.11f * sc.blue()) * 100f))) + "g2P";
+ * currentStream.add("\033*v0n1O");
+ * currentStream.add("\033&a" + ((x - sw/2) * 10) + "h" + (((y - sw/2)) * 10) + "V"
+ * + "\033*c" + ((w + sw) * 10) + "h" + ((sw) * 10) + lend);
+ * currentStream.add("\033&a" + ((x - sw/2) * 10) + "h" + (((y - sw/2)) * 10) + "V"
+ * + "\033*c" + ((sw) * 10) + "h" + ((h + sw) * 10) + lend);
+ * currentStream.add("\033&a" + ((x + w - sw/2) * 10) + "h" + (((y - sw/2)) * 10) + "V"
+ * + "\033*c" + ((sw) * 10) + "h" + ((h + sw) * 10) + lend);
+ * currentStream.add("\033&a" + ((x - sw/2) * 10) + "h" + (((y + h - sw/2)) * 10) + "V"
+ * + "\033*c" + ((w + sw) * 10) + "h" + ((sw) * 10) + lend);
+ * currentStream.add("\033*v0n0O");
+ * }
+ * }
+ * else
+ * {
+ * // Convert dimensions to pixels.
+ * float cfact = 300f / 72f; // 300 dpi, 1pt=1/72in
+ * int ix = (int)(x * cfact);
+ * int iy = (int)(y * cfact);
+ * int iw = (int)(w * cfact);
+ * int ih = (int)(h * cfact);
+ * int irx = (int)(rx * cfact);
+ * int iry = (int)(ry * cfact);
+ * int isw = (int)(sw * cfact);
+ * int longwidth = 0;
+ * int pass = 0;
+ * PDFColor thecolor = null;
+ * do
+ * {
+ * if ( pass == 0 && fc != null )
+ * {
+ * thecolor = fc;
+ * }
+ * else if ( pass == 1 && sc != null )
+ * {
+ * int iswdiv2 = isw / 2;
+ * thecolor = sc;
+ * ix -= iswdiv2;
+ * iy -= iswdiv2;
+ * irx += iswdiv2;
+ * iry += iswdiv2;
+ * iw += isw;
+ * ih += isw;
+ * longwidth = (int)(isw * 1.414);
+ * }
+ * else
+ * thecolor = null;
+ * if ( thecolor != null )
+ * {
+ * int tx = 0;
+ * int ty = iry;
+ * long a = irx;
+ * long b = iry;
+ * long Asquared = (long)Math.pow(a, 2);
+ * long TwoAsquared = 2 * Asquared;
+ * long Bsquared = (long)Math.pow(b, 2);
+ * long TwoBsquared = 2 * Bsquared;
+ * long d = Bsquared - Asquared * b + Asquared / 4;
+ * long dx = 0;
+ * long dy = TwoAsquared * b;
+ * int rectlen = iw - 2 * irx;
+ * Vector bottomlines = new Vector();
+ * int x0 = tx;
+ * // Set Transparency modes and select shading.
+ * currentStream.add("\033*v0n1O\033*c" + (int)(100 - ((0.3f * thecolor.red() + 0.59f * thecolor.green() + 0.11f * thecolor.blue()) * 100f)) + "G\033*v2T");
+ * // Move to starting position.
+ * currentStream.add("\033*p" + ix + "x" + iy + "Y");
+ * // Start raster graphics
+ * currentStream.add("\033*t300R\033*r" + iw + "s1A\033*b1M");
+ * while ( dx < dy )
+ * {
+ * if ( d > 0 )
+ * {
+ * if ( pass == 0 || ty > (iry - isw) )
+ * xferLineBytes(irx - x0, rectlen + 2 * x0, bottomlines, -1);
+ * else
+ * xferLineBytes(irx - x0, longwidth, bottomlines, iw - irx + x0 - longwidth);
+ * x0 = tx + 1;
+ * ty--;
+ * dy -= TwoAsquared;
+ * d -= dy;
+ * }
+ * tx++;
+ * dx += TwoBsquared;
+ * d += Bsquared + dx;
+ * }
+ * d += (3 * (Asquared - Bsquared) / 2 - (dx + dy)) / 2;
+ * while ( ty > 0 )
+ * {
+ * if ( pass == 0 || ty >= (iry - isw) )
+ * xferLineBytes(irx - tx, rectlen + 2 * tx, bottomlines, -1);
+ * else
+ * xferLineBytes(irx - tx, isw, bottomlines, iw - irx + tx - isw);
+ *
+ * if ( d < 0 )
+ * {
+ * tx++;
+ * dx += TwoBsquared;
+ * d += dx;
+ * }
+ * ty--;
+ * dy -= TwoAsquared;
+ * d += Asquared - dy;
+ * }
+ * // Draw the middle part of the rectangle
+ * int midlen = ih - 2 * iry;
+ * if ( midlen > 0 )
+ * {
+ * if ( pass == 0 )
+ * xferLineBytes(0, iw, null, -1);
+ * else
+ * xferLineBytes(0, isw, null, iw - isw);
+ * currentStream.add("\033*b3M");
+ * for ( int countr = midlen - 1 ; countr > 0 ; countr-- )
+ * currentStream.add("\033*b0W");
+ * currentStream.add("\033*b1M");
+ * }
+ * // Draw the bottom.
+ * for ( int countr = bottomlines.size() - 1 ; countr >= 0 ; countr-- )
+ * currentStream.add((String)bottomlines.elementAt(countr));
+ * // End raster graphics
+ * currentStream.add("\033*rB");
+ * // Return to regular print mode.
+ * currentStream.add("\033*v0t0n0O");
+ * }
+ * pass++;
+ * } while ( pass < 2 );
+ * }
+ */
}
- // Add a polyline or polygon. Does not support fills yet!!!
- protected void addPolyline(Vector points, int posx, int posy, PDFColor fc, PDFColor sc, float sw, boolean close)
- {
+ // Add a polyline or polygon. Does not support fills yet!!!
+ protected void addPolyline(Vector points, int posx, int posy,
+ PDFColor fc, PDFColor sc, float sw,
+ boolean close) {}
+
+ boolean printBMP(FopImage img, int x, int y, int w,
+ int h) throws FopImageException {
+ if (debug)
+ System.out.println("TXTRenderer.printBMP(" + img + ", " + x
+ + ", " + y + ", " + w + ", " + h + ")");
+ addRect(x, y, w, h, new PDFColor(1f, 1f, 1f),
+ new PDFColor(0f, 0f, 0f));
+ int nameh = (int)(h * yFactor / 2);
+ if (nameh > 0) {
+ int namew = (int)(w * xFactor);
+
+ if (namew > 4) {
+ String iname = img.getURL();
+ if (iname.length() >= namew)
+ addStr((int)((pageHeight - (y / 100)) * 100 * yFactor)
+ + nameh, (int)(x * xFactor),
+ iname.substring(iname.length() - namew),
+ true);
+ else
+ addStr((int)((pageHeight - (y / 100)) * 100 * yFactor)
+ + nameh, (int)(x * xFactor
+ + (namew - iname.length())
+ / 2), iname, true);
+
+ }
+ }
+ return (true);
}
- boolean printBMP(FopImage img, int x, int y, int w, int h) throws FopImageException
- {
- if ( debug )
- System.out.println("TXTRenderer.printBMP(" + img + ", " + x + ", "
- + y + ", " + w + ", " + h + ")");
- addRect(x, y, w, h, new PDFColor(1f, 1f, 1f), new PDFColor(0f, 0f, 0f));
- int nameh = (int)(h * yFactor / 2);
- if ( nameh > 0 )
- {
- int namew = (int)(w * xFactor);
-
- if ( namew > 4 )
- {
- String iname = img.getURL();
- if ( iname.length() >= namew )
- addStr((int)((pageHeight - (y / 100))* 100 * yFactor) + nameh, (int)(x * xFactor), iname.substring(iname.length() - namew), true);
- else
- addStr((int)((pageHeight - (y / 100))* 100 * yFactor) + nameh, (int)(x * xFactor + (namew - iname.length()) / 2), iname, true);
-
- }
- }
- return(true);
- }
-
/**
* render image area to PCL
*
* @param area the image area to render
*/
- public void renderImageArea(ImageArea area)
- {
- int x = this.currentAreaContainerXPosition + area.getXOffset();
- int y = this.currentYPosition;
- int w = area.getContentWidth();
- int h = area.getHeight();
-
- this.currentYPosition -= h;
-
- FopImage img = area.getImage();
-
- try
- {
- printBMP(img, x, y, w, h);
- }
- catch ( FopImageException e )
- {
- //e.printStackTrace(System.out);
- MessageHandler.errorln("TXTRenderer.renderImageArea() Error printing BMP (" + e.toString() + ").");
- }
+ public void renderImageArea(ImageArea area) {
+ int x = this.currentAreaContainerXPosition + area.getXOffset();
+ int y = this.currentYPosition;
+ int w = area.getContentWidth();
+ int h = area.getHeight();
+
+ this.currentYPosition -= h;
+
+ FopImage img = area.getImage();
+
+ try {
+ printBMP(img, x, y, w, h);
+ } catch (FopImageException e) {
+ // e.printStackTrace(System.out);
+ MessageHandler.errorln("TXTRenderer.renderImageArea() Error printing BMP ("
+ + e.toString() + ").");
+ }
}
- public void renderImage(FontState fontState, String href, float x, float y, float width, float height)
- {
- try
- {
- if ( href.indexOf(":") == -1 )
- href = "file:" + href;
- FopImage img = FopImageFactory.Make(href);
- if(img != null)
- {
- if ( img instanceof SVGImage )
- {
- SVGSVGElement svg = ((SVGImage)img).getSVGDocument().getRootElement();
- renderSVG(fontState, svg, (int)x * 1000, (int)y * 1000);
- }
- else
- {
- printBMP(img, (int)x, (int)y, (int)width, (int)height);
- }
- }
- }
- catch(Exception e)
- {
- MessageHandler.errorln("could not add image to SVG: " + href);
- }
- }
-
- /** render a foreign object area */
- public void renderForeignObjectArea(ForeignObjectArea area)
- {
+ public void renderImage(FontState fontState, String href, float x,
+ float y, float width, float height) {
+ try {
+ if (href.indexOf(":") == -1)
+ href = "file:" + href;
+ FopImage img = FopImageFactory.Make(href);
+ if (img != null) {
+ if (img instanceof SVGImage) {
+ SVGSVGElement svg =
+ ((SVGImage)img).getSVGDocument().getRootElement();
+ renderSVG(fontState, svg, (int)x * 1000, (int)y * 1000);
+ } else {
+ printBMP(img, (int)x, (int)y, (int)width, (int)height);
+ }
+ }
+ } catch (Exception e) {
+ MessageHandler.errorln("could not add image to SVG: " + href);
+ }
+ }
+
+ /**
+ * render a foreign object area
+ */
+ public void renderForeignObjectArea(ForeignObjectArea area) {
// if necessary need to scale and align the content
this.currentXPosition = this.currentXPosition + area.getXOffset();
this.currentYPosition = this.currentYPosition;
- switch (area.getAlign())
- {
- case TextAlign.START:
- break;
- case TextAlign.END:
- break;
- case TextAlign.CENTER:
- case TextAlign.JUSTIFY:
- break;
+ switch (area.getAlign()) {
+ case TextAlign.START:
+ break;
+ case TextAlign.END:
+ break;
+ case TextAlign.CENTER:
+ case TextAlign.JUSTIFY:
+ break;
}
- switch (area.getVerticalAlign())
- {
- case VerticalAlign.BASELINE:
- break;
- case VerticalAlign.MIDDLE:
- break;
- case VerticalAlign.SUB:
- break;
- case VerticalAlign.SUPER:
- break;
- case VerticalAlign.TEXT_TOP:
- break;
- case VerticalAlign.TEXT_BOTTOM:
- break;
- case VerticalAlign.TOP:
- break;
- case VerticalAlign.BOTTOM:
- break;
+ switch (area.getVerticalAlign()) {
+ case VerticalAlign.BASELINE:
+ break;
+ case VerticalAlign.MIDDLE:
+ break;
+ case VerticalAlign.SUB:
+ break;
+ case VerticalAlign.SUPER:
+ break;
+ case VerticalAlign.TEXT_TOP:
+ break;
+ case VerticalAlign.TEXT_BOTTOM:
+ break;
+ case VerticalAlign.TOP:
+ break;
+ case VerticalAlign.BOTTOM:
+ break;
}
// in general the content will not be text
// align and scale
- switch (area.scalingMethod())
- {
- case Scaling.UNIFORM:
- break;
- case Scaling.NON_UNIFORM:
- break;
+ switch (area.scalingMethod()) {
+ case Scaling.UNIFORM:
+ break;
+ case Scaling.NON_UNIFORM:
+ break;
}
// if the overflow is auto (default), scroll or visible
// then the contents should not be clipped, since this
// is considered a printing medium.
- switch (area.getOverflow())
- {
- case Overflow.VISIBLE:
- case Overflow.SCROLL:
- case Overflow.AUTO:
- break;
- case Overflow.HIDDEN:
- break;
+ switch (area.getOverflow()) {
+ case Overflow.VISIBLE:
+ case Overflow.SCROLL:
+ case Overflow.AUTO:
+ break;
+ case Overflow.HIDDEN:
+ break;
}
area.getObject().render(this);
this.currentXPosition += area.getEffectiveWidth();
- // this.currentYPosition -= area.getEffectiveHeight();
+ // this.currentYPosition -= area.getEffectiveHeight();
}
- void renderSVG(FontState fontState, SVGSVGElement svg, int x, int y)
- {
-/* SVG - Not yet implemented
- NodeList nl = svg.getChildNodes();
- for(int count = 0; count < nl.getLength(); count++) {
- Node n = nl.item(count);
- if(n instanceof SVGElement) {
- renderElement(fontState, (SVGElement)n, x, y);
- }
- }
-*/
- }
+ void renderSVG(FontState fontState, SVGSVGElement svg, int x, int y) {
+ /*
+ * SVG - Not yet implemented
+ * NodeList nl = svg.getChildNodes();
+ * for(int count = 0; count < nl.getLength(); count++) {
+ * Node n = nl.item(count);
+ * if(n instanceof SVGElement) {
+ * renderElement(fontState, (SVGElement)n, x, y);
+ * }
+ * }
+ */
+ }
/**
* render SVG area to Text
*
* @param area the SVG area to render
*/
- public void renderSVGArea(SVGArea area)
- {
-if ( debug )
-System.out.println("TXTRenderer.renderSVGArea(" + area + ")");
- int x = this.currentAreaContainerXPosition;
- int y = this.currentYPosition;
- SVGSVGElement svg = ((SVGDocument)area.getSVGDocument()).getRootElement();
- int w = (int)(svg.getWidth().getBaseVal().getValue() * 1000);
- int h = (int)(svg.getHeight().getBaseVal().getValue() * 1000);
-
- //currentStream.add("ET\n");
- /*
- * Clip to the svg area.
- * Note: To have the svg overlay (under) a text area then use
- * an fo:block-container
- */
- //currentStream.add("q\n");
- //currentStream.add(x / 1000f + " " + y / 1000f + " m\n");
- //currentStream.add((x + w) / 1000f + " " + y / 1000f + " l\n");
- //currentStream.add((x + w) / 1000f + " " + (y - h) / 1000f + " l\n");
- //currentStream.add(x / 1000f + " " + (y - h) / 1000f + " l\n");
- //currentStream.add("h\n");
- //currentStream.add("W\n");
- //currentStream.add("n\n");
- // transform so that the coordinates (0,0) is from the top left
- // and positive is down and to the right
- //currentStream.add(1 + " " + 0 + " " + 0 + " " + (-1) + " " + x / 1000f + " " + y / 1000f + " cm\n");
-
- // TODO - translate and clip to viewbox
-
- renderSVG(area.getFontState(), svg, x, y);
-
- //Enumeration e = area.getChildren().elements();
- //while (e.hasMoreElements()) {
- // Object o = e.nextElement();
- // if(o instanceof GraphicImpl) {
- // renderElement(area, (GraphicImpl)o, x, y);
- // }
- //}
-
- //currentStream.add("Q\n");
- //currentStream.add("BT\n");
- //this.currentYPosition -= h;
- }
-
-/* SVG - Not yet implemented
- public void renderElement(FontState fontState, SVGElement area, int posx, int posy)
- {
-if ( debug )
-System.out.println("TXTRenderer.renderElement(" + fontState + ", " + area + ", " + posx + ", " + posy + ")");
- int x = posx;
- int y = posy;
- CSSStyleDeclaration style = null;
- if ( area instanceof SVGStylable )
- style = ((SVGStylable)area).getStyle();
- PDFColor fillColour = null;
- PDFColor strokeColour = null;
- float strokeWidth = 0;
-
- //currentStream.add("q\n");
- //if( area instanceof SVGTransformable )
- //{
- // SVGTransformable tf = (SVGTransformable)area;
- // SVGAnimatedTransformList trans = tf.getTransform();
- // SVGRect bbox = tf.getBBox();
- // if(trans != null) {
- // applyTransform(trans, bbox);
- // }
- //}
-
- if(style != null)
- {
- CSSValue sp = style.getPropertyCSSValue("fill");
- if(sp != null)
- {
- if( sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
- {
- if( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_RGBCOLOR )
- {
- RGBColor col = ((CSSPrimitiveValue)sp).getRGBColorValue();
- CSSPrimitiveValue val;
- val = col.getRed();
- float red = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
- val = col.getGreen();
- float green = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
- val = col.getBlue();
- float blue = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
- fillColour = new PDFColor(red, green, blue);
- }
- }
- //if(sp instanceof ColorType)
- //{
- // ColorType ct = (ColorType)sp;
- // fillColour = new PDFColor(ct.red(), ct.green(), ct.blue());
- //}
- }
- else
- fillColour = new PDFColor(0, 0, 0);
- sp = style.getPropertyCSSValue("stroke");
- if(sp != null)
- {
- if( sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
- {
- if( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_RGBCOLOR )
- {
- RGBColor col = ((CSSPrimitiveValue)sp).getRGBColorValue();
- CSSPrimitiveValue val;
- val = col.getRed();
- float red = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
- val = col.getGreen();
- float green = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
- val = col.getBlue();
- float blue = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
- strokeColour = new PDFColor(red, green, blue);
- }
- }
- //if(sp instanceof ColorType)
- //{
- // ColorType ct = (ColorType)sp;
- // strokeColour = new PDFColor(ct.red(), ct.green(), ct.blue());
- //}
- }
- sp = style.getPropertyCSSValue("stroke-width");
- if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE)
- {
- strokeWidth = ((CSSPrimitiveValue)sp).getFloatValue(CSSPrimitiveValue.CSS_PT);
- //PDFNumber pdfNumber = new PDFNumber();
- //currentStream.add(pdfNumber.doubleOut(width) + " w\n");
- //strokeWidth = ((SVGLengthImpl)sp).getValue();
- }
- else
- strokeWidth = 1;
- }
-
- if (area instanceof SVGRectElement)
- {
- SVGRectElement rg = (SVGRectElement)area;
- float rectx = rg.getX().getBaseVal().getValue() + posx / 1000;
- float recty = ((pageHeight / 10) - posy/1000) + rg.getY().getBaseVal().getValue();
- float rx = rg.getRx().getBaseVal().getValue();
- float ry = rg.getRy().getBaseVal().getValue();
- float rw = rg.getWidth().getBaseVal().getValue();
- float rh = rg.getHeight().getBaseVal().getValue();
- addRect(rectx, recty, rw, rh, rx, ry, fillColour, strokeColour, strokeWidth);
- }
- else if (area instanceof SVGLineElement)
- {
- SVGLineElement lg = (SVGLineElement)area;
- float x1 = lg.getX1().getBaseVal().getValue() + posx / 1000;
- float y1 = ((pageHeight / 10) - posy/1000) + lg.getY1().getBaseVal().getValue();
- float x2 = lg.getX2().getBaseVal().getValue() + posx / 1000;
- float y2 = ((pageHeight / 10) - posy/1000) + lg.getY2().getBaseVal().getValue();
- addLine(x1,y1,x2,y2, strokeColour, strokeWidth);
- }
- else if (area instanceof SVGTextElementImpl)
- {
- //currentStream.add("BT\n");
- renderText(fontState, (SVGTextElementImpl)area, posx / 1000f, ((float)(pageHeight / 10) - posy/1000f));
- //currentStream.add("ET\n");
- }
- else if (area instanceof SVGCircleElement)
- {
- SVGCircleElement cg = (SVGCircleElement)area;
- float cx = cg.getCx().getBaseVal().getValue() + posx / 1000;
- float cy = ((pageHeight / 10) - posy/1000) + cg.getCy().getBaseVal().getValue();
- float r = cg.getR().getBaseVal().getValue();
- //addCircle(cx,cy,r, di);
- addRect(cx - r, cy - r, 2 * r, 2 * r, r, r, fillColour, strokeColour, strokeWidth);
- }
- else if (area instanceof SVGEllipseElement)
- {
- SVGEllipseElement cg = (SVGEllipseElement)area;
- float cx = cg.getCx().getBaseVal().getValue() + posx / 1000;
- float cy = ((pageHeight / 10) - posy/1000) + cg.getCy().getBaseVal().getValue();
- float rx = cg.getRx().getBaseVal().getValue();
- float ry = cg.getRy().getBaseVal().getValue();
- //addEllipse(cx,cy,rx,ry, di);
- addRect(cx - rx, cy - ry, 2 * rx, 2 * ry, rx, ry, fillColour, strokeColour, strokeWidth);
- }
- else if (area instanceof SVGPathElementImpl)
- {
- //addPath(((SVGPathElementImpl)area).pathElements, posx, posy, di);
- }
- else if (area instanceof SVGPolylineElementImpl)
- {
- addPolyline(((SVGPolylineElementImpl)area).points, posx, posy, fillColour, strokeColour, strokeWidth, false);
- }
- else if (area instanceof SVGPolygonElementImpl)
- {
- addPolyline(((SVGPolylineElementImpl)area).points, posx, posy, fillColour, strokeColour, strokeWidth, true);
- }
- else if (area instanceof SVGGElementImpl)
- {
- renderGArea(fontState, (SVGGElementImpl)area, x, y);
- }
- else if(area instanceof SVGUseElementImpl)
- {
- SVGUseElementImpl ug = (SVGUseElementImpl)area;
- String ref = ug.link;
- ref = ref.substring(1, ref.length());
- SVGElement graph = null;
- //GraphicImpl graph = null;
- //graph = area.locateDef(ref);
- if(graph != null) {
- // probably not the best way to do this, should be able
- // to render without the style being set.
- //GraphicImpl parent = graph.getGraphicParent();
- //graph.setParent(area);
- // need to clip (if necessary) to the use area
- // the style of the linked element is as if is was
- // a direct descendant of the use element.
- renderElement(fontState, graph, posx, posy);
- //graph.setParent(parent);
- }
- }
- else if (area instanceof SVGImageElementImpl)
- {
- SVGImageElementImpl ig = (SVGImageElementImpl)area;
- renderImage(fontState, ig.link, ig.x, ig.y, ig.width, ig.height);
- }
- else if (area instanceof SVGSVGElement)
- {
- // the x and y pos will be wrong!
- renderSVG(fontState, (SVGSVGElement)area, x, y);
- }
- else if (area instanceof SVGAElement)
- {
- SVGAElement ael = (SVGAElement)area;
- org.w3c.dom.NodeList nl = ael.getChildNodes();
- for ( int count = 0 ; count < nl.getLength() ; count++ )
- {
- org.w3c.dom.Node n = nl.item(count);
- if ( n instanceof SVGElement )
- {
- if ( n instanceof GraphicElement )
- {
- SVGRect rect = ((GraphicElement)n).getBBox();
- if ( rect != null )
- {
-// currentAnnotList = this.pdfDoc.makeAnnotList();
-// currentPage.setAnnotList(currentAnnotList);
-// String dest = linkSet.getDest();
-// int linkType = linkSet.getLinkType();
-// currentAnnotList.addLink(
-// this.pdfDoc.makeLink(lrect.getRectangle(), dest, linkType));
-// currentAnnotList = null;
-// }
- }
- renderElement(fontState, (SVGElement)n, posx, posy);
- }
- }
- }
- else if ( area instanceof SVGSwitchElement )
- {
- handleSwitchElement(fontState, posx, posy, (SVGSwitchElement)area);
- }
- // should be done with some cleanup code, so only
- // required values are reset.
- //currentStream.add("Q\n");
- }
-*/
-
- private void setFont(String name, float size)
- {
- return;
- }
-
-/* SVG - Not implemented yet.
- public void renderText(FontState fontState, SVGTextElementImpl tg, float x, float y)
- {
- PDFNumber pdfNumber = new PDFNumber();
-
- CSSStyleDeclaration styles;
- styles = tg.getStyle();
- //applyStyle(tg, styles);
- // apply transform
- // text has a Tm and need to handle each element
- SVGTransformList trans = tg.getTransform().getBaseVal();
- SVGMatrix matrix = trans.consolidate().getMatrix();
- String transstr = (pdfNumber.doubleOut(matrix.getA())
- + " " + pdfNumber.doubleOut(matrix.getB())
- + " " + pdfNumber.doubleOut(matrix.getC())
- + " " + pdfNumber.doubleOut(-matrix.getD()) + " ");
-
- String fontFamily = null;
- CSSValue sp = styles.getPropertyCSSValue("font-family");
- if ( sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
- {
- if ( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING )
- fontFamily = sp.getCssText();
- }
- if ( fontFamily == null )
- fontFamily = fontState.getFontFamily();
- String fontStyle = null;
- sp = styles.getPropertyCSSValue("font-style");
- if ( sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
- {
- if ( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING )
- fontStyle = sp.getCssText();
- }
- if ( fontStyle == null )
- fontStyle = fontState.getFontStyle();
- String fontWeight = null;
- sp = styles.getPropertyCSSValue("font-weight");
- if( sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
- {
- if ( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING )
- fontWeight = sp.getCssText();
- }
- if( fontWeight == null )
- fontWeight = fontState.getFontWeight();
- float fontSize;
- sp = styles.getPropertyCSSValue("font-size");
- if( sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
- {
-// if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_NUMBER) {
- fontSize = ((CSSPrimitiveValue)sp).getFloatValue(CSSPrimitiveValue.CSS_PT);
-// }
- }
- else
- {
- fontSize = fontState.getFontSize() / 1000f;
- }
- FontState fs = fontState;
- try
- {
- fs = new FontState(fontState.getFontInfo(), fontFamily, fontStyle,
- fontWeight, (int)(fontSize * 1000));
- }
- catch( Exception fope )
- {
-// fope.printStackTrace();
- }
-
- //currentStream.add("/" + fs.getFontName() + " " + fontSize + " Tf\n");
- setFont(fs.getFontName(), fontSize * 1000);
-
- float tx = tg.x;
- float ty = tg.y;
- float currentX = x + tx;
- float currentY = y + ty;
- Vector list = tg.textList;
- for ( Enumeration e = list.elements() ; e.hasMoreElements() ; )
- {
- Object o = e.nextElement();
- styles = tg.getStyle();
- //applyStyle(tg, styles);
- if( o instanceof String )
- {
- String str = (String)o;
- //currentStream.add(transstr
- // + (currentX + matrix.getE()) + " "
- // + (y+ty + matrix.getF()) + " Tm "
- // + "(");
- boolean spacing = "preserve".equals(tg.getXMLspace());
- //currentX = addSVGStr(fs, currentX, str, spacing);
- //currentStream.add(") Tj\n");
-// for(int count = 0; count < str.length(); count++) {
-// }
-// currentX += fs.width(' ') / 1000f;
- currentStream.add("\033&a" + (currentX + matrix.getE())*10 + "h" + (y+ty + matrix.getF())*10 + "V" + str);
- for ( int count = 0; count < str.length(); count++ )
- {
- currentX += fs.width(str.charAt(count)) / 1000f;
- }
- currentX += fs.width(' ') / 1000f;
- } else if(o instanceof SVGTextPathElementImpl) {
- SVGTextPathElementImpl tpg = (SVGTextPathElementImpl)o;
- String ref = tpg.str;
- SVGElement graph = null;
-// graph = tpg.locateDef(ref);
- if(graph != null && graph instanceof SVGPathElementImpl) {
- // probably not the best way to do this, should be able
- // to render without the style being set.
-// GraphicImpl parent = graph.getGraphicParent();
-// graph.setParent(tpg);
- // set text path??
- // how should this work
-// graph.setParent(parent);
- }
- } else if(o instanceof SVGTRefElementImpl) {
- SVGTRefElementImpl trg = (SVGTRefElementImpl)o;
- String ref = trg.ref;
- ref = ref.substring(1, ref.length());
- SVGElement graph = null;
-// graph = trg.locateDef(ref);
- if(graph != null && graph instanceof SVGTextElementImpl) {
-// GraphicImpl parent = graph.getGraphicParent();
-// graph.setParent(trg);
- SVGTextElementImpl te = (SVGTextElementImpl)graph;
- renderText(fs, te, (int)(x + tx), (int)(y + ty));
-// graph.setParent(parent);
- }
- } else if(o instanceof SVGTSpanElementImpl) {
- SVGTSpanElementImpl tsg = (SVGTSpanElementImpl)o;
- styles = tsg.getStyle();
- //applyStyle(tsg, styles);
- boolean changed = false;
-
- String newprop = null;
- sp = styles.getPropertyCSSValue("font-family");
- if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
- if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING) {
- newprop = sp.getCssText();
- }
- }
- if(newprop != null && !newprop.equals(fontFamily)) {
- fontFamily = newprop;
- changed = true;
- }
- sp = styles.getPropertyCSSValue("font-style");
- if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
- if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING) {
- newprop = sp.getCssText();
- }
- }
- if(newprop != null && !newprop.equals(fontStyle)) {
- fontStyle = newprop;
- changed = true;
- }
- sp = styles.getPropertyCSSValue("font-weight");
- if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
- if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING) {
- newprop = sp.getCssText();
- }
- }
- if(newprop != null && !newprop.equals(fontWeight)) {
- fontWeight = newprop;
- changed = true;
- }
- float newSize = fontSize;
- sp = styles.getPropertyCSSValue("font-size");
- if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
-// if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_NUMBER) {
- newSize = ((CSSPrimitiveValue)sp).getFloatValue(CSSPrimitiveValue.CSS_PT);
-// }
- }
- if ( fontSize != newSize )
- {
- fontSize = newSize;
- changed = true;
- }
- FontState oldfs = null;
- if ( changed )
- {
- oldfs = fs;
- try
- {
- fs = new FontState(fontState.getFontInfo(), fontFamily, fontStyle,
- fontWeight, (int)(fontSize * 1000));
- }
- catch(Exception fope)
- {
- }
-
- setFont(fs.getFontName(), fontSize * 1000);
- //currentStream.add("/" + fs.getFontName() + " " + fontSize + " Tf\n");
- }
-
- float baseX;
- float baseY;
-
- StringBuffer pdf = new StringBuffer();
- boolean spacing = "preserve".equals(tsg.getXMLspace());
- boolean inbetween = false;
- boolean addedspace = false;
- int charPos = 0;
- float xpos = currentX;
- float ypos = currentY;
- for ( int i=0 ; i < tsg.str.length() ; i++ )
- {
- char ch = tsg.str.charAt(i);
- xpos = currentX;
- ypos = currentY;
- if ( tsg.ylist.size() > charPos )
- ypos = y + ty + ((Float)tsg.ylist.elementAt(charPos)).floatValue();
- if ( tsg.dylist.size() > charPos )
- ypos = ypos + ((Float)tsg.dylist.elementAt(charPos)).floatValue();
- if ( tsg.xlist.size() > charPos )
- xpos = x + tx + ((Float)tsg.xlist.elementAt(charPos)).floatValue();
- if ( tsg.dxlist.size() > charPos )
- xpos = xpos + ((Float)tsg.dxlist.elementAt(charPos)).floatValue();
- switch (ch)
- {
- case ' ':
- case ' ':
- if ( spacing )
- {
- currentX = xpos + fs.width(' ') / 1000f;
- currentY = ypos;
- charPos++;
- }
- else
- {
- if ( inbetween && !addedspace)
- {
- addedspace = true;
- currentX = xpos + fs.width(' ') / 1000f;
- currentY = ypos;
- charPos++;
- }
- }
- break;
- case '\n':
- case '\r':
- if ( spacing )
- {
- currentX = xpos + fs.width(' ') / 1000f;
- currentY = ypos;
- charPos++;
- }
- break;
- default:
- addedspace = false;
- pdf = pdf.append(transstr
- + (xpos + matrix.getE()) + " "
- + (ypos + matrix.getF()) + " Tm "
- + "(" + ch + ") Tj\n");
- pdf = pdf.append("\033&a" + (xpos + matrix.getE())*10 + "h" + (ypos + matrix.getF())*10 + "V" + ch);
- currentX = xpos + fs.width(ch) / 1000f;
- currentY = ypos;
- charPos++;
- inbetween = true;
- break;
- }
- //currentStream.add(pdf.toString());
- }
-// currentX += fs.width(' ') / 1000f;
- if ( changed )
- {
- fs = oldfs;
- setFont(fs.getFontName(), fs.getFontSize() * 1000);
- //currentStream.add("/" + fs.getFontName() + " " + fs.getFontSize() / 1000f + " Tf\n");
- }
- }
- else
- {
- System.err.println("Error: unknown text element " + o);
- }
- }
- }
-*/
-
-/* SVG - Not yet implemented
- public void renderGArea(FontState fontState, SVGGElement area, int posx, int posy)
- {
- NodeList nl = area.getChildNodes();
- for ( int count = 0 ; count < nl.getLength() ; count++ )
- {
- Node n = nl.item(count);
- if ( n instanceof SVGElement )
- renderElement(fontState, (SVGElement)n, posx, posy);
- }
- }
-*/
-
-/* SVG - Not yet implemented
- void handleSwitchElement(FontState fontState, int posx, int posy, SVGSwitchElement ael)
- {
- SVGList relist = ael.getRequiredExtensions();
- SVGList rflist = ael.getRequiredFeatures();
- SVGList sllist = ael.getSystemLanguage();
- org.w3c.dom.NodeList nl = ael.getChildNodes();
- for(int count = 0; count < nl.getLength(); count++) {
- org.w3c.dom.Node n = nl.item(count);
- // only render the first child that has a valid
- // test data
- if(n instanceof GraphicElement) {
- GraphicElement graphic = (GraphicElement)n;
- SVGList grelist = graphic.getRequiredExtensions();
- // if null it evaluates to true
- if(grelist != null) {
- for(int i = 0; i < grelist.getNumberOfItems(); i++) {
- String str = (String)grelist.getItem(i);
- if(relist == null) {
- // use default extension set
- // currently no extensions are supported
-// if(!(str.equals("http:// ??"))) {
- continue;
-// }
- } else {
- }
- }
- }
- SVGList grflist = graphic.getRequiredFeatures();
- if(grflist != null) {
- for(int i = 0; i < grflist.getNumberOfItems(); i++) {
- String str = (String)grflist.getItem(i);
- if(rflist == null) {
- // use default feature set
- if(!(str.equals("org.w3c.svg.static")
- || str.equals("org.w3c.dom.svg.all"))) {
- continue;
- }
- } else {
- boolean found = false;
- for(int j = 0; j < rflist.getNumberOfItems(); j++) {
- if(rflist.getItem(j).equals(str)) {
- found = true;
- break;
- }
- }
- if(!found)
- continue;
- }
- }
- }
- SVGList gsllist = graphic.getSystemLanguage();
- if(gsllist != null) {
- for(int i = 0; i < gsllist.getNumberOfItems(); i++) {
- String str = (String)gsllist.getItem(i);
- if(sllist == null) {
- // use default feature set
- if(!(str.equals("en"))) {
- continue;
- }
- } else {
- boolean found = false;
- for(int j = 0; j < sllist.getNumberOfItems(); j++) {
- if(sllist.getItem(j).equals(str)) {
- found = true;
- break;
- }
- }
- if(!found)
- continue;
- }
- }
- }
- renderElement(fontState, (SVGElement)n, posx, posy);
- // only render the first valid one
- break;
- }
- }
- }
-*/
+ public void renderSVGArea(SVGArea area) {
+ if (debug)
+ System.out.println("TXTRenderer.renderSVGArea(" + area + ")");
+ int x = this.currentAreaContainerXPosition;
+ int y = this.currentYPosition;
+ SVGSVGElement svg =
+ ((SVGDocument)area.getSVGDocument()).getRootElement();
+ int w = (int)(svg.getWidth().getBaseVal().getValue() * 1000);
+ int h = (int)(svg.getHeight().getBaseVal().getValue() * 1000);
+
+ // currentStream.add("ET\n");
+ /*
+ * Clip to the svg area.
+ * Note: To have the svg overlay (under) a text area then use
+ * an fo:block-container
+ */
+ // currentStream.add("q\n");
+ // currentStream.add(x / 1000f + " " + y / 1000f + " m\n");
+ // currentStream.add((x + w) / 1000f + " " + y / 1000f + " l\n");
+ // currentStream.add((x + w) / 1000f + " " + (y - h) / 1000f + " l\n");
+ // currentStream.add(x / 1000f + " " + (y - h) / 1000f + " l\n");
+ // currentStream.add("h\n");
+ // currentStream.add("W\n");
+ // currentStream.add("n\n");
+ // transform so that the coordinates (0,0) is from the top left
+ // and positive is down and to the right
+ // currentStream.add(1 + " " + 0 + " " + 0 + " " + (-1) + " " + x / 1000f + " " + y / 1000f + " cm\n");
+
+ // TODO - translate and clip to viewbox
+
+ renderSVG(area.getFontState(), svg, x, y);
+
+ // Enumeration e = area.getChildren().elements();
+ // while (e.hasMoreElements()) {
+ // Object o = e.nextElement();
+ // if(o instanceof GraphicImpl) {
+ // renderElement(area, (GraphicImpl)o, x, y);
+ // }
+ // }
+
+ // currentStream.add("Q\n");
+ // currentStream.add("BT\n");
+ // this.currentYPosition -= h;
+ }
+
+ /*
+ * SVG - Not yet implemented
+ * public void renderElement(FontState fontState, SVGElement area, int posx, int posy)
+ * {
+ * if ( debug )
+ * System.out.println("TXTRenderer.renderElement(" + fontState + ", " + area + ", " + posx + ", " + posy + ")");
+ * int x = posx;
+ * int y = posy;
+ * CSSStyleDeclaration style = null;
+ * if ( area instanceof SVGStylable )
+ * style = ((SVGStylable)area).getStyle();
+ * PDFColor fillColour = null;
+ * PDFColor strokeColour = null;
+ * float strokeWidth = 0;
+ * //currentStream.add("q\n");
+ * //if( area instanceof SVGTransformable )
+ * //{
+ * // SVGTransformable tf = (SVGTransformable)area;
+ * // SVGAnimatedTransformList trans = tf.getTransform();
+ * // SVGRect bbox = tf.getBBox();
+ * // if(trans != null) {
+ * // applyTransform(trans, bbox);
+ * // }
+ * //}
+ * if(style != null)
+ * {
+ * CSSValue sp = style.getPropertyCSSValue("fill");
+ * if(sp != null)
+ * {
+ * if( sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
+ * {
+ * if( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_RGBCOLOR )
+ * {
+ * RGBColor col = ((CSSPrimitiveValue)sp).getRGBColorValue();
+ * CSSPrimitiveValue val;
+ * val = col.getRed();
+ * float red = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
+ * val = col.getGreen();
+ * float green = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
+ * val = col.getBlue();
+ * float blue = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
+ * fillColour = new PDFColor(red, green, blue);
+ * }
+ * }
+ * //if(sp instanceof ColorType)
+ * //{
+ * // ColorType ct = (ColorType)sp;
+ * // fillColour = new PDFColor(ct.red(), ct.green(), ct.blue());
+ * //}
+ * }
+ * else
+ * fillColour = new PDFColor(0, 0, 0);
+ * sp = style.getPropertyCSSValue("stroke");
+ * if(sp != null)
+ * {
+ * if( sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
+ * {
+ * if( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_RGBCOLOR )
+ * {
+ * RGBColor col = ((CSSPrimitiveValue)sp).getRGBColorValue();
+ * CSSPrimitiveValue val;
+ * val = col.getRed();
+ * float red = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
+ * val = col.getGreen();
+ * float green = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
+ * val = col.getBlue();
+ * float blue = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
+ * strokeColour = new PDFColor(red, green, blue);
+ * }
+ * }
+ * //if(sp instanceof ColorType)
+ * //{
+ * // ColorType ct = (ColorType)sp;
+ * // strokeColour = new PDFColor(ct.red(), ct.green(), ct.blue());
+ * //}
+ * }
+ * sp = style.getPropertyCSSValue("stroke-width");
+ * if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE)
+ * {
+ * strokeWidth = ((CSSPrimitiveValue)sp).getFloatValue(CSSPrimitiveValue.CSS_PT);
+ * //PDFNumber pdfNumber = new PDFNumber();
+ * //currentStream.add(pdfNumber.doubleOut(width) + " w\n");
+ * //strokeWidth = ((SVGLengthImpl)sp).getValue();
+ * }
+ * else
+ * strokeWidth = 1;
+ * }
+ * if (area instanceof SVGRectElement)
+ * {
+ * SVGRectElement rg = (SVGRectElement)area;
+ * float rectx = rg.getX().getBaseVal().getValue() + posx / 1000;
+ * float recty = ((pageHeight / 10) - posy/1000) + rg.getY().getBaseVal().getValue();
+ * float rx = rg.getRx().getBaseVal().getValue();
+ * float ry = rg.getRy().getBaseVal().getValue();
+ * float rw = rg.getWidth().getBaseVal().getValue();
+ * float rh = rg.getHeight().getBaseVal().getValue();
+ * addRect(rectx, recty, rw, rh, rx, ry, fillColour, strokeColour, strokeWidth);
+ * }
+ * else if (area instanceof SVGLineElement)
+ * {
+ * SVGLineElement lg = (SVGLineElement)area;
+ * float x1 = lg.getX1().getBaseVal().getValue() + posx / 1000;
+ * float y1 = ((pageHeight / 10) - posy/1000) + lg.getY1().getBaseVal().getValue();
+ * float x2 = lg.getX2().getBaseVal().getValue() + posx / 1000;
+ * float y2 = ((pageHeight / 10) - posy/1000) + lg.getY2().getBaseVal().getValue();
+ * addLine(x1,y1,x2,y2, strokeColour, strokeWidth);
+ * }
+ * else if (area instanceof SVGTextElementImpl)
+ * {
+ * //currentStream.add("BT\n");
+ * renderText(fontState, (SVGTextElementImpl)area, posx / 1000f, ((float)(pageHeight / 10) - posy/1000f));
+ * //currentStream.add("ET\n");
+ * }
+ * else if (area instanceof SVGCircleElement)
+ * {
+ * SVGCircleElement cg = (SVGCircleElement)area;
+ * float cx = cg.getCx().getBaseVal().getValue() + posx / 1000;
+ * float cy = ((pageHeight / 10) - posy/1000) + cg.getCy().getBaseVal().getValue();
+ * float r = cg.getR().getBaseVal().getValue();
+ * //addCircle(cx,cy,r, di);
+ * addRect(cx - r, cy - r, 2 * r, 2 * r, r, r, fillColour, strokeColour, strokeWidth);
+ * }
+ * else if (area instanceof SVGEllipseElement)
+ * {
+ * SVGEllipseElement cg = (SVGEllipseElement)area;
+ * float cx = cg.getCx().getBaseVal().getValue() + posx / 1000;
+ * float cy = ((pageHeight / 10) - posy/1000) + cg.getCy().getBaseVal().getValue();
+ * float rx = cg.getRx().getBaseVal().getValue();
+ * float ry = cg.getRy().getBaseVal().getValue();
+ * //addEllipse(cx,cy,rx,ry, di);
+ * addRect(cx - rx, cy - ry, 2 * rx, 2 * ry, rx, ry, fillColour, strokeColour, strokeWidth);
+ * }
+ * else if (area instanceof SVGPathElementImpl)
+ * {
+ * //addPath(((SVGPathElementImpl)area).pathElements, posx, posy, di);
+ * }
+ * else if (area instanceof SVGPolylineElementImpl)
+ * {
+ * addPolyline(((SVGPolylineElementImpl)area).points, posx, posy, fillColour, strokeColour, strokeWidth, false);
+ * }
+ * else if (area instanceof SVGPolygonElementImpl)
+ * {
+ * addPolyline(((SVGPolylineElementImpl)area).points, posx, posy, fillColour, strokeColour, strokeWidth, true);
+ * }
+ * else if (area instanceof SVGGElementImpl)
+ * {
+ * renderGArea(fontState, (SVGGElementImpl)area, x, y);
+ * }
+ * else if(area instanceof SVGUseElementImpl)
+ * {
+ * SVGUseElementImpl ug = (SVGUseElementImpl)area;
+ * String ref = ug.link;
+ * ref = ref.substring(1, ref.length());
+ * SVGElement graph = null;
+ * //GraphicImpl graph = null;
+ * //graph = area.locateDef(ref);
+ * if(graph != null) {
+ * // probably not the best way to do this, should be able
+ * // to render without the style being set.
+ * //GraphicImpl parent = graph.getGraphicParent();
+ * //graph.setParent(area);
+ * // need to clip (if necessary) to the use area
+ * // the style of the linked element is as if is was
+ * // a direct descendant of the use element.
+ * renderElement(fontState, graph, posx, posy);
+ * //graph.setParent(parent);
+ * }
+ * }
+ * else if (area instanceof SVGImageElementImpl)
+ * {
+ * SVGImageElementImpl ig = (SVGImageElementImpl)area;
+ * renderImage(fontState, ig.link, ig.x, ig.y, ig.width, ig.height);
+ * }
+ * else if (area instanceof SVGSVGElement)
+ * {
+ * // the x and y pos will be wrong!
+ * renderSVG(fontState, (SVGSVGElement)area, x, y);
+ * }
+ * else if (area instanceof SVGAElement)
+ * {
+ * SVGAElement ael = (SVGAElement)area;
+ * org.w3c.dom.NodeList nl = ael.getChildNodes();
+ * for ( int count = 0 ; count < nl.getLength() ; count++ )
+ * {
+ * org.w3c.dom.Node n = nl.item(count);
+ * if ( n instanceof SVGElement )
+ * {
+ * if ( n instanceof GraphicElement )
+ * {
+ * SVGRect rect = ((GraphicElement)n).getBBox();
+ * if ( rect != null )
+ * {
+ * // currentAnnotList = this.pdfDoc.makeAnnotList();
+ * // currentPage.setAnnotList(currentAnnotList);
+ * // String dest = linkSet.getDest();
+ * // int linkType = linkSet.getLinkType();
+ * // currentAnnotList.addLink(
+ * // this.pdfDoc.makeLink(lrect.getRectangle(), dest, linkType));
+ * // currentAnnotList = null;
+ * // }
+ * }
+ * renderElement(fontState, (SVGElement)n, posx, posy);
+ * }
+ * }
+ * }
+ * else if ( area instanceof SVGSwitchElement )
+ * {
+ * handleSwitchElement(fontState, posx, posy, (SVGSwitchElement)area);
+ * }
+ * // should be done with some cleanup code, so only
+ * // required values are reset.
+ * //currentStream.add("Q\n");
+ * }
+ */
+
+ private void setFont(String name, float size) {
+ return;
+ }
+
+ /*
+ * SVG - Not implemented yet.
+ * public void renderText(FontState fontState, SVGTextElementImpl tg, float x, float y)
+ * {
+ * PDFNumber pdfNumber = new PDFNumber();
+ * CSSStyleDeclaration styles;
+ * styles = tg.getStyle();
+ * //applyStyle(tg, styles);
+ * // apply transform
+ * // text has a Tm and need to handle each element
+ * SVGTransformList trans = tg.getTransform().getBaseVal();
+ * SVGMatrix matrix = trans.consolidate().getMatrix();
+ * String transstr = (pdfNumber.doubleOut(matrix.getA())
+ * + " " + pdfNumber.doubleOut(matrix.getB())
+ * + " " + pdfNumber.doubleOut(matrix.getC())
+ * + " " + pdfNumber.doubleOut(-matrix.getD()) + " ");
+ * String fontFamily = null;
+ * CSSValue sp = styles.getPropertyCSSValue("font-family");
+ * if ( sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
+ * {
+ * if ( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING )
+ * fontFamily = sp.getCssText();
+ * }
+ * if ( fontFamily == null )
+ * fontFamily = fontState.getFontFamily();
+ * String fontStyle = null;
+ * sp = styles.getPropertyCSSValue("font-style");
+ * if ( sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
+ * {
+ * if ( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING )
+ * fontStyle = sp.getCssText();
+ * }
+ * if ( fontStyle == null )
+ * fontStyle = fontState.getFontStyle();
+ * String fontWeight = null;
+ * sp = styles.getPropertyCSSValue("font-weight");
+ * if( sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
+ * {
+ * if ( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING )
+ * fontWeight = sp.getCssText();
+ * }
+ * if( fontWeight == null )
+ * fontWeight = fontState.getFontWeight();
+ * float fontSize;
+ * sp = styles.getPropertyCSSValue("font-size");
+ * if( sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
+ * {
+ * // if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_NUMBER) {
+ * fontSize = ((CSSPrimitiveValue)sp).getFloatValue(CSSPrimitiveValue.CSS_PT);
+ * // }
+ * }
+ * else
+ * {
+ * fontSize = fontState.getFontSize() / 1000f;
+ * }
+ * FontState fs = fontState;
+ * try
+ * {
+ * fs = new FontState(fontState.getFontInfo(), fontFamily, fontStyle,
+ * fontWeight, (int)(fontSize * 1000));
+ * }
+ * catch( Exception fope )
+ * {
+ * // fope.printStackTrace();
+ * }
+ * //currentStream.add("/" + fs.getFontName() + " " + fontSize + " Tf\n");
+ * setFont(fs.getFontName(), fontSize * 1000);
+ * float tx = tg.x;
+ * float ty = tg.y;
+ * float currentX = x + tx;
+ * float currentY = y + ty;
+ * Vector list = tg.textList;
+ * for ( Enumeration e = list.elements() ; e.hasMoreElements() ; )
+ * {
+ * Object o = e.nextElement();
+ * styles = tg.getStyle();
+ * //applyStyle(tg, styles);
+ * if( o instanceof String )
+ * {
+ * String str = (String)o;
+ * //currentStream.add(transstr
+ * // + (currentX + matrix.getE()) + " "
+ * // + (y+ty + matrix.getF()) + " Tm "
+ * // + "(");
+ * boolean spacing = "preserve".equals(tg.getXMLspace());
+ * //currentX = addSVGStr(fs, currentX, str, spacing);
+ * //currentStream.add(") Tj\n");
+ * // for(int count = 0; count < str.length(); count++) {
+ * // }
+ * // currentX += fs.width(' ') / 1000f;
+ * currentStream.add("\033&a" + (currentX + matrix.getE())*10 + "h" + (y+ty + matrix.getF())*10 + "V" + str);
+ * for ( int count = 0; count < str.length(); count++ )
+ * {
+ * currentX += fs.width(str.charAt(count)) / 1000f;
+ * }
+ * currentX += fs.width(' ') / 1000f;
+ * } else if(o instanceof SVGTextPathElementImpl) {
+ * SVGTextPathElementImpl tpg = (SVGTextPathElementImpl)o;
+ * String ref = tpg.str;
+ * SVGElement graph = null;
+ * // graph = tpg.locateDef(ref);
+ * if(graph != null && graph instanceof SVGPathElementImpl) {
+ * // probably not the best way to do this, should be able
+ * // to render without the style being set.
+ * // GraphicImpl parent = graph.getGraphicParent();
+ * // graph.setParent(tpg);
+ * // set text path??
+ * // how should this work
+ * // graph.setParent(parent);
+ * }
+ * } else if(o instanceof SVGTRefElementImpl) {
+ * SVGTRefElementImpl trg = (SVGTRefElementImpl)o;
+ * String ref = trg.ref;
+ * ref = ref.substring(1, ref.length());
+ * SVGElement graph = null;
+ * // graph = trg.locateDef(ref);
+ * if(graph != null && graph instanceof SVGTextElementImpl) {
+ * // GraphicImpl parent = graph.getGraphicParent();
+ * // graph.setParent(trg);
+ * SVGTextElementImpl te = (SVGTextElementImpl)graph;
+ * renderText(fs, te, (int)(x + tx), (int)(y + ty));
+ * // graph.setParent(parent);
+ * }
+ * } else if(o instanceof SVGTSpanElementImpl) {
+ * SVGTSpanElementImpl tsg = (SVGTSpanElementImpl)o;
+ * styles = tsg.getStyle();
+ * //applyStyle(tsg, styles);
+ * boolean changed = false;
+ * String newprop = null;
+ * sp = styles.getPropertyCSSValue("font-family");
+ * if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
+ * if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING) {
+ * newprop = sp.getCssText();
+ * }
+ * }
+ * if(newprop != null && !newprop.equals(fontFamily)) {
+ * fontFamily = newprop;
+ * changed = true;
+ * }
+ * sp = styles.getPropertyCSSValue("font-style");
+ * if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
+ * if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING) {
+ * newprop = sp.getCssText();
+ * }
+ * }
+ * if(newprop != null && !newprop.equals(fontStyle)) {
+ * fontStyle = newprop;
+ * changed = true;
+ * }
+ * sp = styles.getPropertyCSSValue("font-weight");
+ * if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
+ * if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING) {
+ * newprop = sp.getCssText();
+ * }
+ * }
+ * if(newprop != null && !newprop.equals(fontWeight)) {
+ * fontWeight = newprop;
+ * changed = true;
+ * }
+ * float newSize = fontSize;
+ * sp = styles.getPropertyCSSValue("font-size");
+ * if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
+ * // if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_NUMBER) {
+ * newSize = ((CSSPrimitiveValue)sp).getFloatValue(CSSPrimitiveValue.CSS_PT);
+ * // }
+ * }
+ * if ( fontSize != newSize )
+ * {
+ * fontSize = newSize;
+ * changed = true;
+ * }
+ * FontState oldfs = null;
+ * if ( changed )
+ * {
+ * oldfs = fs;
+ * try
+ * {
+ * fs = new FontState(fontState.getFontInfo(), fontFamily, fontStyle,
+ * fontWeight, (int)(fontSize * 1000));
+ * }
+ * catch(Exception fope)
+ * {
+ * }
+ * setFont(fs.getFontName(), fontSize * 1000);
+ * //currentStream.add("/" + fs.getFontName() + " " + fontSize + " Tf\n");
+ * }
+ * float baseX;
+ * float baseY;
+ * StringBuffer pdf = new StringBuffer();
+ * boolean spacing = "preserve".equals(tsg.getXMLspace());
+ * boolean inbetween = false;
+ * boolean addedspace = false;
+ * int charPos = 0;
+ * float xpos = currentX;
+ * float ypos = currentY;
+ * for ( int i=0 ; i < tsg.str.length() ; i++ )
+ * {
+ * char ch = tsg.str.charAt(i);
+ * xpos = currentX;
+ * ypos = currentY;
+ * if ( tsg.ylist.size() > charPos )
+ * ypos = y + ty + ((Float)tsg.ylist.elementAt(charPos)).floatValue();
+ * if ( tsg.dylist.size() > charPos )
+ * ypos = ypos + ((Float)tsg.dylist.elementAt(charPos)).floatValue();
+ * if ( tsg.xlist.size() > charPos )
+ * xpos = x + tx + ((Float)tsg.xlist.elementAt(charPos)).floatValue();
+ * if ( tsg.dxlist.size() > charPos )
+ * xpos = xpos + ((Float)tsg.dxlist.elementAt(charPos)).floatValue();
+ * switch (ch)
+ * {
+ * case ' ':
+ * case ' ':
+ * if ( spacing )
+ * {
+ * currentX = xpos + fs.width(' ') / 1000f;
+ * currentY = ypos;
+ * charPos++;
+ * }
+ * else
+ * {
+ * if ( inbetween && !addedspace)
+ * {
+ * addedspace = true;
+ * currentX = xpos + fs.width(' ') / 1000f;
+ * currentY = ypos;
+ * charPos++;
+ * }
+ * }
+ * break;
+ * case '\n':
+ * case '\r':
+ * if ( spacing )
+ * {
+ * currentX = xpos + fs.width(' ') / 1000f;
+ * currentY = ypos;
+ * charPos++;
+ * }
+ * break;
+ * default:
+ * addedspace = false;
+ * pdf = pdf.append(transstr
+ * + (xpos + matrix.getE()) + " "
+ * + (ypos + matrix.getF()) + " Tm "
+ * + "(" + ch + ") Tj\n");
+ * pdf = pdf.append("\033&a" + (xpos + matrix.getE())*10 + "h" + (ypos + matrix.getF())*10 + "V" + ch);
+ * currentX = xpos + fs.width(ch) / 1000f;
+ * currentY = ypos;
+ * charPos++;
+ * inbetween = true;
+ * break;
+ * }
+ * //currentStream.add(pdf.toString());
+ * }
+ * // currentX += fs.width(' ') / 1000f;
+ * if ( changed )
+ * {
+ * fs = oldfs;
+ * setFont(fs.getFontName(), fs.getFontSize() * 1000);
+ * //currentStream.add("/" + fs.getFontName() + " " + fs.getFontSize() / 1000f + " Tf\n");
+ * }
+ * }
+ * else
+ * {
+ * System.err.println("Error: unknown text element " + o);
+ * }
+ * }
+ * }
+ */
+
+ /*
+ * SVG - Not yet implemented
+ * public void renderGArea(FontState fontState, SVGGElement area, int posx, int posy)
+ * {
+ * NodeList nl = area.getChildNodes();
+ * for ( int count = 0 ; count < nl.getLength() ; count++ )
+ * {
+ * Node n = nl.item(count);
+ * if ( n instanceof SVGElement )
+ * renderElement(fontState, (SVGElement)n, posx, posy);
+ * }
+ * }
+ */
+
+ /*
+ * SVG - Not yet implemented
+ * void handleSwitchElement(FontState fontState, int posx, int posy, SVGSwitchElement ael)
+ * {
+ * SVGList relist = ael.getRequiredExtensions();
+ * SVGList rflist = ael.getRequiredFeatures();
+ * SVGList sllist = ael.getSystemLanguage();
+ * org.w3c.dom.NodeList nl = ael.getChildNodes();
+ * for(int count = 0; count < nl.getLength(); count++) {
+ * org.w3c.dom.Node n = nl.item(count);
+ * // only render the first child that has a valid
+ * // test data
+ * if(n instanceof GraphicElement) {
+ * GraphicElement graphic = (GraphicElement)n;
+ * SVGList grelist = graphic.getRequiredExtensions();
+ * // if null it evaluates to true
+ * if(grelist != null) {
+ * for(int i = 0; i < grelist.getNumberOfItems(); i++) {
+ * String str = (String)grelist.getItem(i);
+ * if(relist == null) {
+ * // use default extension set
+ * // currently no extensions are supported
+ * // if(!(str.equals("http:// ??"))) {
+ * continue;
+ * // }
+ * } else {
+ * }
+ * }
+ * }
+ * SVGList grflist = graphic.getRequiredFeatures();
+ * if(grflist != null) {
+ * for(int i = 0; i < grflist.getNumberOfItems(); i++) {
+ * String str = (String)grflist.getItem(i);
+ * if(rflist == null) {
+ * // use default feature set
+ * if(!(str.equals("org.w3c.svg.static")
+ * || str.equals("org.w3c.dom.svg.all"))) {
+ * continue;
+ * }
+ * } else {
+ * boolean found = false;
+ * for(int j = 0; j < rflist.getNumberOfItems(); j++) {
+ * if(rflist.getItem(j).equals(str)) {
+ * found = true;
+ * break;
+ * }
+ * }
+ * if(!found)
+ * continue;
+ * }
+ * }
+ * }
+ * SVGList gsllist = graphic.getSystemLanguage();
+ * if(gsllist != null) {
+ * for(int i = 0; i < gsllist.getNumberOfItems(); i++) {
+ * String str = (String)gsllist.getItem(i);
+ * if(sllist == null) {
+ * // use default feature set
+ * if(!(str.equals("en"))) {
+ * continue;
+ * }
+ * } else {
+ * boolean found = false;
+ * for(int j = 0; j < sllist.getNumberOfItems(); j++) {
+ * if(sllist.getItem(j).equals(str)) {
+ * found = true;
+ * break;
+ * }
+ * }
+ * if(!found)
+ * continue;
+ * }
+ * }
+ * }
+ * renderElement(fontState, (SVGElement)n, posx, posy);
+ * // only render the first valid one
+ * break;
+ * }
+ * }
+ * }
+ */
/**
* render inline area to Text
*
* @param area inline area to render
*/
- public void renderWordArea(WordArea area)
- {
-//System.out.println("TXTRenderer.renderInlineArea: currentXPosition=" + this.currentXPosition + " currentYPosition=" + this.currentYPosition + " text=" + area.getText());
- int rx = this.currentXPosition;
- int bl = this.currentYPosition;
-
- String s;
- if ( area.getPageNumberID()!=null )
- {
- // this text is a page number, so resolve it
- s = idReferences.getPageNumber(area.getPageNumberID());
- if(s==null)
- s="";
- }
- else
- {
- s = area.getText();
- }
-
-if ( debug )
-System.out.println("TXTRenderer.renderInlineArea: rx=" + rx + " bl=" + bl + " pageHeight=" + pageHeight);
- addStr((int)((pageHeight - (bl / 100))* 100 * yFactor) - 1, (int)(rx * xFactor), s, true);
-
- this.currentXPosition += area.getContentWidth();
+ public void renderWordArea(WordArea area) {
+ // System.out.println("TXTRenderer.renderInlineArea: currentXPosition=" + this.currentXPosition + " currentYPosition=" + this.currentYPosition + " text=" + area.getText());
+ int rx = this.currentXPosition;
+ int bl = this.currentYPosition;
+
+ String s;
+ if (area.getPageNumberID() != null) {
+ // this text is a page number, so resolve it
+ s = idReferences.getPageNumber(area.getPageNumberID());
+ if (s == null)
+ s = "";
+ } else {
+ s = area.getText();
+ }
+
+ if (debug)
+ System.out.println("TXTRenderer.renderInlineArea: rx=" + rx
+ + " bl=" + bl + " pageHeight=" + pageHeight);
+ addStr((int)((pageHeight - (bl / 100)) * 100 * yFactor) - 1,
+ (int)(rx * xFactor), s, true);
+
+ this.currentXPosition += area.getContentWidth();
}
/**
@@ -1629,9 +1579,8 @@ System.out.println("TXTRenderer.renderInlineArea: rx=" + rx + " bl=" + bl + " pa
*
* @param space space to render
*/
- public void renderInlineSpace(InlineSpace space)
- {
- this.currentXPosition += space.getSize();
+ public void renderInlineSpace(InlineSpace space) {
+ this.currentXPosition += space.getSize();
}
/**
@@ -1639,121 +1588,119 @@ System.out.println("TXTRenderer.renderInlineArea: rx=" + rx + " bl=" + bl + " pa
*
* @param page page to render
*/
- public void renderPage(Page page)
- {
-if ( debug )
-System.out.println("TXTRenderer.renderPage() page.getHeight() = " + page.getHeight());
- BodyAreaContainer body;
- AreaContainer before, after, start, end;
-
- maxX = (int)(textCPI * page.getWidth() / 72000 + 1);
- maxY = (int)(textLPI * page.getHeight() / 72000 + 1);
- xFactor = (float)(maxX - 1) / (float)page.getWidth();
- yFactor = (float)(maxY - 1) / (float)page.getHeight();
- charData = new StringBuffer[maxY + 1];
- decoData = new StringBuffer[maxY + 1];
-
- if ( paperheight > 0 )
- pageHeight = paperheight;
- else
- pageHeight = page.getHeight() / 100;
-
-if ( debug )
-System.out.println("TXTRenderer.renderPage() maxX=" + maxX + " maxY=" + maxY + " xFactor=" + xFactor + " yFactor=" + yFactor + " paperHeight=" + pageHeight);
-
- body = page.getBody();
- before = page.getBefore();
- after = page.getAfter();
- start = page.getStart();
- end = page.getEnd();
-
- this.currentFontName = "";
- this.currentFontSize = 0;
-
- //currentStream.add("BT\n");
- renderBodyAreaContainer(body);
-
- if (before != null)
- renderAreaContainer(before);
-
- if (after != null)
- renderAreaContainer(after);
-
- if (start != null)
- renderAreaContainer(start);
-
- if (end != null)
- renderAreaContainer(end);
-
- // Write out the buffers.
- for ( int row = 0 ; row <= maxY ; row++ )
- {
- StringBuffer cr = charData[row];
- StringBuffer dr = decoData[row];
- StringBuffer outr = null;
-
- if ( cr != null && dr == null )
- outr = cr;
- else if ( dr != null && cr == null )
- outr = dr;
- else if ( cr != null && dr != null )
- {
- int len = dr.length();
- if ( cr.length() > len )
- len = cr.length();
- outr = new StringBuffer();
- for ( int countr = 0 ; countr < len ; countr++ )
- {
- if ( countr < cr.length() && cr.charAt(countr) != ' ' )
- outr.append(cr.charAt(countr));
- else if ( countr < dr.length() )
- outr.append(dr.charAt(countr));
- else
- outr.append(' ');
- }
- }
-
- if ( outr != null )
- currentStream.add(outr.toString());
- if ( row < maxY )
- currentStream.add(lineEnding);
- }
-
- // End page.
- //if ( ++curdiv == divisions || divisions == -1 )
- //{
- // curdiv = 0;
- // currentStream.add("\f");
- //}
-
- // Links, etc not implemented...
- /*
- currentPage = this.pdfDoc.makePage(this.pdfResources, currentStream,
- page.getWidth()/1000,
- page.getHeight()/1000, page);
-
- if (page.hasLinks()) {
- currentAnnotList = this.pdfDoc.makeAnnotList();
- currentPage.setAnnotList(currentAnnotList);
-
- Enumeration e = page.getLinkSets().elements();
- while (e.hasMoreElements()) {
- LinkSet linkSet = (LinkSet) e.nextElement();
-
- linkSet.align();
- String dest = linkSet.getDest();
- int linkType = linkSet.getLinkType();
- Enumeration f = linkSet.getRects().elements();
- while (f.hasMoreElements()) {
- LinkedRectangle lrect = (LinkedRectangle) f.nextElement();
- currentAnnotList.addLink(
- this.pdfDoc.makeLink(lrect.getRectangle(), dest, linkType));
- }
- }
- } else {
- // just to be on the safe side
- currentAnnotList = null;
- }
- */
+ public void renderPage(Page page) {
+ if (debug)
+ System.out.println("TXTRenderer.renderPage() page.getHeight() = "
+ + page.getHeight());
+ BodyAreaContainer body;
+ AreaContainer before, after, start, end;
+
+ maxX = (int)(textCPI * page.getWidth() / 72000 + 1);
+ maxY = (int)(textLPI * page.getHeight() / 72000 + 1);
+ xFactor = (float)(maxX - 1) / (float)page.getWidth();
+ yFactor = (float)(maxY - 1) / (float)page.getHeight();
+ charData = new StringBuffer[maxY + 1];
+ decoData = new StringBuffer[maxY + 1];
+
+ if (paperheight > 0)
+ pageHeight = paperheight;
+ else
+ pageHeight = page.getHeight() / 100;
+
+ if (debug)
+ System.out.println("TXTRenderer.renderPage() maxX=" + maxX
+ + " maxY=" + maxY + " xFactor=" + xFactor
+ + " yFactor=" + yFactor + " paperHeight="
+ + pageHeight);
+
+ body = page.getBody();
+ before = page.getBefore();
+ after = page.getAfter();
+ start = page.getStart();
+ end = page.getEnd();
+
+ this.currentFontName = "";
+ this.currentFontSize = 0;
+
+ // currentStream.add("BT\n");
+ renderBodyAreaContainer(body);
+
+ if (before != null)
+ renderAreaContainer(before);
+
+ if (after != null)
+ renderAreaContainer(after);
+
+ if (start != null)
+ renderAreaContainer(start);
+
+ if (end != null)
+ renderAreaContainer(end);
+
+ // Write out the buffers.
+ for (int row = 0; row <= maxY; row++) {
+ StringBuffer cr = charData[row];
+ StringBuffer dr = decoData[row];
+ StringBuffer outr = null;
+
+ if (cr != null && dr == null)
+ outr = cr;
+ else if (dr != null && cr == null)
+ outr = dr;
+ else if (cr != null && dr != null) {
+ int len = dr.length();
+ if (cr.length() > len)
+ len = cr.length();
+ outr = new StringBuffer();
+ for (int countr = 0; countr < len; countr++) {
+ if (countr < cr.length() && cr.charAt(countr) != ' ')
+ outr.append(cr.charAt(countr));
+ else if (countr < dr.length())
+ outr.append(dr.charAt(countr));
+ else
+ outr.append(' ');
+ }
+ }
+
+ if (outr != null)
+ currentStream.add(outr.toString());
+ if (row < maxY)
+ currentStream.add(lineEnding);
+ }
+
+ // End page.
+ // if ( ++curdiv == divisions || divisions == -1 )
+ // {
+ // curdiv = 0;
+ // currentStream.add("\f");
+ // }
+
+ // Links, etc not implemented...
+ /*
+ * currentPage = this.pdfDoc.makePage(this.pdfResources, currentStream,
+ * page.getWidth()/1000,
+ * page.getHeight()/1000, page);
+ * if (page.hasLinks()) {
+ * currentAnnotList = this.pdfDoc.makeAnnotList();
+ * currentPage.setAnnotList(currentAnnotList);
+ * Enumeration e = page.getLinkSets().elements();
+ * while (e.hasMoreElements()) {
+ * LinkSet linkSet = (LinkSet) e.nextElement();
+ * linkSet.align();
+ * String dest = linkSet.getDest();
+ * int linkType = linkSet.getLinkType();
+ * Enumeration f = linkSet.getRects().elements();
+ * while (f.hasMoreElements()) {
+ * LinkedRectangle lrect = (LinkedRectangle) f.nextElement();
+ * currentAnnotList.addLink(
+ * this.pdfDoc.makeLink(lrect.getRectangle(), dest, linkType));
+ * }
+ * }
+ * } else {
+ * // just to be on the safe side
+ * currentAnnotList = null;
+ * }
+ */
}
+
}
diff --git a/src/org/apache/fop/render/xml/XMLRenderer.java b/src/org/apache/fop/render/xml/XMLRenderer.java
index 557c7e6a5..b249f523f 100644
--- a/src/org/apache/fop/render/xml/XMLRenderer.java
+++ b/src/org/apache/fop/render/xml/XMLRenderer.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.render.xml;
@@ -28,22 +29,31 @@ import java.util.Hashtable;
*/
public class XMLRenderer implements Renderer {
- /** indentation to use for pretty-printing the XML */
+ /**
+ * indentation to use for pretty-printing the XML
+ */
protected int indent = 0;
- /** the application producing the XML */
+ /**
+ * the application producing the XML
+ */
protected String producer;
- /** the writer used to output the XML */
+ /**
+ * the writer used to output the XML
+ */
protected PrintWriter writer;
- /** options */
+ /**
+ * options
+ */
protected Hashtable options;
- public XMLRenderer() {
- }
+ public XMLRenderer() {}
- /** set up renderer options */
+ /**
+ * set up renderer options
+ */
public void setOptions(Hashtable options) {
this.options = options;
}
@@ -67,12 +77,12 @@ public class XMLRenderer implements Renderer {
OutputStream stream) throws IOException {
MessageHandler.logln("rendering areas to XML");
this.writer = new PrintWriter(stream);
- this.writer.write( "\n\n");
+ this.writer.write("\n\n");
writeStartTag("");
Enumeration e = areaTree.getPages().elements();
while (e.hasMoreElements()) {
- this.renderPage((Page) e.nextElement());
+ this.renderPage((Page)e.nextElement());
}
writeEndTag("");
this.writer.flush();
@@ -152,7 +162,7 @@ public class XMLRenderer implements Renderer {
writeStartTag("");
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
+ Box b = (Box)e.nextElement();
b.render(this);
}
writeEndTag("");
@@ -167,7 +177,7 @@ public class XMLRenderer implements Renderer {
writeStartTag("");
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
+ Box b = (Box)e.nextElement();
b.render(this);
}
writeEndTag("");
@@ -182,7 +192,7 @@ public class XMLRenderer implements Renderer {
writeStartTag("");
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
+ Box b = (Box)e.nextElement();
b.render(this);
}
writeEndTag("");
@@ -194,80 +204,83 @@ public class XMLRenderer implements Renderer {
* @param area the block area to render
*/
public void renderBlockArea(BlockArea area) {
- StringBuffer baText = new StringBuffer();
- baText.append("");
+ StringBuffer baText = new StringBuffer();
+ baText.append("");
writeStartTag(baText.toString());
-
- // write out marker info
- java.util.Vector markers = area.getMarkers();
- if (!markers.isEmpty()) {
- writeStartTag("");
- for (int m = 0; m < markers.size(); m++) {
- org.apache.fop.fo.flow.Marker marker =
- (org.apache.fop.fo.flow.Marker)markers.elementAt(m);
- StringBuffer maText = new StringBuffer();
- maText.append("");
- writeEmptyElementTag(maText.toString());
- }
- writeEndTag("");
- }
-
+
+ // write out marker info
+ java.util.Vector markers = area.getMarkers();
+ if (!markers.isEmpty()) {
+ writeStartTag("");
+ for (int m = 0; m < markers.size(); m++) {
+ org.apache.fop.fo.flow.Marker marker =
+ (org.apache.fop.fo.flow.Marker)markers.elementAt(m);
+ StringBuffer maText = new StringBuffer();
+ maText.append("");
+ writeEmptyElementTag(maText.toString());
+ }
+ writeEndTag("");
+ }
+
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
+ Box b = (Box)e.nextElement();
b.render(this);
}
writeEndTag("");
}
- public void renderInlineArea(InlineArea area) {
- StringBuffer iaText = new StringBuffer();
- iaText.append("");
+ public void renderInlineArea(InlineArea area) {
+ StringBuffer iaText = new StringBuffer();
+ iaText.append("");
writeStartTag(iaText.toString());
-
- // write out marker info
- java.util.Vector markers = area.getMarkers();
- if (!markers.isEmpty()) {
- writeStartTag("");
- for (int m = 0; m < markers.size(); m++) {
- org.apache.fop.fo.flow.Marker marker =
- (org.apache.fop.fo.flow.Marker)markers.elementAt(m);
- StringBuffer maText = new StringBuffer();
- maText.append("");
- writeEmptyElementTag(maText.toString());
- }
- writeEndTag("");
- }
-
+
+ // write out marker info
+ java.util.Vector markers = area.getMarkers();
+ if (!markers.isEmpty()) {
+ writeStartTag("");
+ for (int m = 0; m < markers.size(); m++) {
+ org.apache.fop.fo.flow.Marker marker =
+ (org.apache.fop.fo.flow.Marker)markers.elementAt(m);
+ StringBuffer maText = new StringBuffer();
+ maText.append("");
+ writeEmptyElementTag(maText.toString());
+ }
+ writeEndTag("");
+ }
+
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
+ Box b = (Box)e.nextElement();
b.render(this);
}
writeEndTag("");
- }
-
+ }
+
/**
* render a display space to XML
*
@@ -275,11 +288,13 @@ public class XMLRenderer implements Renderer {
*/
public void renderDisplaySpace(DisplaySpace space) {
if (!isCoarseXml())
- writeEmptyElementTag("");
+ writeEmptyElementTag("");
}
- /** render a foreign object area */
+ /**
+ * render a foreign object area
+ */
public void renderForeignObjectArea(ForeignObjectArea area) {
// if necessary need to scale and align the content
area.getObject().render(this);
@@ -316,16 +331,16 @@ public class XMLRenderer implements Renderer {
for (int i = 0; i < l; i++) {
char ch = s.charAt(i);
if (ch > 127)
- sb = sb.append(""+(int) ch + ";");
+ sb = sb.append("" + (int)ch + ";");
else
sb = sb.append(ch);
}
if (!isCoarseXml()) {
- writeElement("" +
- sb.toString() + "");
+ writeElement(""
+ + sb.toString() + "");
} else {
this.writer.write(sb.toString());
}
@@ -338,8 +353,8 @@ public class XMLRenderer implements Renderer {
*/
public void renderInlineSpace(InlineSpace space) {
if (!isCoarseXml())
- writeEmptyElementTag("");
+ writeEmptyElementTag("");
else
this.writer.write(" ");
}
@@ -356,7 +371,7 @@ public class XMLRenderer implements Renderer {
}
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
- Box b = (Box) e.nextElement();
+ Box b = (Box)e.nextElement();
b.render(this);
}
if (!isCoarseXml())
@@ -397,30 +412,32 @@ public class XMLRenderer implements Renderer {
return;
String leaderPattern = "";
switch (area.getLeaderPattern()) {
- case LeaderPattern.SPACE:
- leaderPattern = "space";
- break;
- case LeaderPattern.RULE:
- leaderPattern = "rule";
- break;
- case LeaderPattern.DOTS:
- leaderPattern = "dots";
- break;
- case LeaderPattern.USECONTENT:
- leaderPattern = "use-content";
- break;
+ case LeaderPattern.SPACE:
+ leaderPattern = "space";
+ break;
+ case LeaderPattern.RULE:
+ leaderPattern = "rule";
+ break;
+ case LeaderPattern.DOTS:
+ leaderPattern = "dots";
+ break;
+ case LeaderPattern.USECONTENT:
+ leaderPattern = "use-content";
+ break;
}
- writeEmptyElementTag("");
+ writeEmptyElementTag("");
}
private boolean isCoarseXml() {
- return ((Boolean) options.get("fineDetail")).booleanValue();
+ return ((Boolean)options.get("fineDetail")).booleanValue();
}
+
}
diff --git a/src/org/apache/fop/svg/PDFAElementBridge.java b/src/org/apache/fop/svg/PDFAElementBridge.java
index 116b27e0a..560e8fb13 100644
--- a/src/org/apache/fop/svg/PDFAElementBridge.java
+++ b/src/org/apache/fop/svg/PDFAElementBridge.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -62,7 +63,7 @@ public class PDFAElementBridge extends AbstractGraphicsNodeBridge {
* @param node the graphics node to build
*/
public GraphicsNode createGraphicsNode(BridgeContext ctx, Element e) {
- PDFANode aNode = (PDFANode) super.createGraphicsNode(ctx, e);
+ PDFANode aNode = (PDFANode)super.createGraphicsNode(ctx, e);
return aNode;
}
diff --git a/src/org/apache/fop/svg/PDFANode.java b/src/org/apache/fop/svg/PDFANode.java
index 1d25071cb..e604e74d0 100644
--- a/src/org/apache/fop/svg/PDFANode.java
+++ b/src/org/apache/fop/svg/PDFANode.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
diff --git a/src/org/apache/fop/svg/PDFDocumentGraphics2D.java b/src/org/apache/fop/svg/PDFDocumentGraphics2D.java
index d0921dbd7..ae790ad9a 100644
--- a/src/org/apache/fop/svg/PDFDocumentGraphics2D.java
+++ b/src/org/apache/fop/svg/PDFDocumentGraphics2D.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -54,8 +55,8 @@ public class PDFDocumentGraphics2D extends PDFGraphics2D {
* @param width the width of the document
* @param height the height of the document
*/
- public PDFDocumentGraphics2D(boolean textAsShapes,
- OutputStream stream, int width, int height) {
+ public PDFDocumentGraphics2D(boolean textAsShapes, OutputStream stream,
+ int width, int height) {
super(textAsShapes);
if (!textAsShapes) {
@@ -64,8 +65,7 @@ public class PDFDocumentGraphics2D extends PDFGraphics2D {
try {
fontState = new FontState(fontInfo, "Helvetica", "normal",
"normal", 12, 0);
- } catch (FOPException e) {
- }
+ } catch (FOPException e) {}
}
standalone = true;
this.stream = stream;
@@ -99,8 +99,8 @@ public class PDFDocumentGraphics2D extends PDFGraphics2D {
* The result is scaled so that the svg fits correctly inside the pdf document.
*/
public void setSVGDimension(float w, float h) {
- currentStream.write("" + PDFNumber.doubleOut(width / w) +
- " 0 0 " + PDFNumber.doubleOut(height / h) + " 0 0 cm\n");
+ currentStream.write("" + PDFNumber.doubleOut(width / w) + " 0 0 "
+ + PDFNumber.doubleOut(height / h) + " 0 0 cm\n");
}
/**
@@ -129,9 +129,8 @@ public class PDFDocumentGraphics2D extends PDFGraphics2D {
public void finish() throws IOException {
pdfStream.add(getString());
PDFResources pdfResources = this.pdfDoc.getResources();
- PDFPage currentPage =
- this.pdfDoc.makePage(pdfResources, pdfStream, width,
- height, null);
+ PDFPage currentPage = this.pdfDoc.makePage(pdfResources, pdfStream,
+ width, height, null);
if (fontInfo != null) {
FontSetup.addToResources(this.pdfDoc, fontInfo);
}
@@ -154,7 +153,7 @@ public class PDFDocumentGraphics2D extends PDFGraphics2D {
* Creates a new Graphics object that is
* a copy of this Graphics object.
* @return a new graphics context that is a copy of
- * this graphics context.
+ * this graphics context.
*/
public Graphics create() {
return new PDFDocumentGraphics2D(this);
@@ -171,5 +170,6 @@ public class PDFDocumentGraphics2D extends PDFGraphics2D {
super.drawString(s, x, y);
}
}
+
}
diff --git a/src/org/apache/fop/svg/PDFGraphics2D.java b/src/org/apache/fop/svg/PDFGraphics2D.java
index 5239b0f58..530e25fc5 100644
--- a/src/org/apache/fop/svg/PDFGraphics2D.java
+++ b/src/org/apache/fop/svg/PDFGraphics2D.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.svg;
@@ -45,27 +46,41 @@ import java.util.Vector;
public class PDFGraphics2D extends AbstractGraphics2D {
boolean standalone = false;
- /** the PDF Document being created */
+ /**
+ * the PDF Document being created
+ */
protected PDFDocument pdfDoc;
protected FontState fontState;
- /** the current stream to add PDF commands to */
+ /**
+ * the current stream to add PDF commands to
+ */
StringWriter currentStream = new StringWriter();
- /** the current (internal) font name */
+ /**
+ * the current (internal) font name
+ */
protected String currentFontName;
- /** the current font size in millipoints */
+ /**
+ * the current font size in millipoints
+ */
protected int currentFontSize;
- /** the current vertical position in millipoints from bottom */
+ /**
+ * the current vertical position in millipoints from bottom
+ */
protected int currentYPosition = 0;
- /** the current horizontal position in millipoints from left */
+ /**
+ * the current horizontal position in millipoints from left
+ */
protected int currentXPosition = 0;
- /** the current colour for use in svg */
+ /**
+ * the current colour for use in svg
+ */
PDFColor currentColour = new PDFColor(0, 0, 0);
/**
@@ -73,8 +88,8 @@ public class PDFGraphics2D extends AbstractGraphics2D {
* This is used to create a Graphics object for use inside an already
* existing document.
*/
- public PDFGraphics2D(boolean textAsShapes, FontState fs,
- PDFDocument doc, String font, int size, int xpos, int ypos) {
+ public PDFGraphics2D(boolean textAsShapes, FontState fs, PDFDocument doc,
+ String font, int size, int xpos, int ypos) {
super(textAsShapes);
pdfDoc = doc;
currentFontName = font;
@@ -107,7 +122,7 @@ public class PDFGraphics2D extends AbstractGraphics2D {
* Creates a new Graphics object that is
* a copy of this Graphics object.
* @return a new graphics context that is a copy of
- * this graphics context.
+ * this graphics context.
*/
public Graphics create() {
return new PDFGraphics2D(this);
@@ -132,14 +147,14 @@ public class PDFGraphics2D extends AbstractGraphics2D {
* @param x the x coordinate.
* @param y the y coordinate.
* @param observer object to be notified as more of
- * the image is converted.
+ * the image is converted.
* @see java.awt.Image
* @see java.awt.image.ImageObserver
* @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
*/
public boolean drawImage(Image img, int x, int y,
ImageObserver observer) {
- //System.err.println("drawImage:x, y");
+ // System.err.println("drawImage:x, y");
final int width = img.getWidth(observer);
final int height = img.getHeight(observer);
@@ -162,8 +177,7 @@ public class PDFGraphics2D extends AbstractGraphics2D {
}
g.dispose();
- final byte[] result =
- new byte[buf.getWidth() * buf.getHeight() * 3];
+ final byte[] result = new byte[buf.getWidth() * buf.getHeight() * 3];
final byte[] mask = new byte[buf.getWidth() * buf.getHeight()];
Raster raster = buf.getData();
@@ -171,39 +185,42 @@ public class PDFGraphics2D extends AbstractGraphics2D {
int count = 0;
int maskpos = 0;
- int [] iarray;
+ int[] iarray;
int i, j, val, alpha, add, mult;
switch (bd.getDataType()) {
- case DataBuffer.TYPE_INT:
- int[][] idata = ((DataBufferInt) bd).getBankData();
- for (i = 0; i < idata.length; i++) {
- iarray = idata[i];
- for (j = 0; j < iarray.length; j++) {
- val = iarray[j];
- alpha = val >>> 24;
- //mask[maskpos++] = (byte)((idata[i][j] >> 24) & 0xFF);
- if (alpha != 255) {
- // System.out.println("Alpha: " + alpha);
- // Composite with opaque white...
- add = (255 - alpha);
- mult = (alpha << 16) / 255;
- result[count++] = (byte)(add +
- ((((val >> 16) & 0xFF) * mult) >> 16));
- result[count++] = (byte)(add +
- ((((val >> 8) & 0xFF) * mult) >> 16));
- result[count++] = (byte)(add +
- ((((val) & 0xFF) * mult) >>16));
- } else {
- result[count++] = (byte)((val >> 16) & 0xFF);
- result[count++] = (byte)((val >> 8) & 0xFF);
- result[count++] = (byte)((val) & 0xFF);
- }
+ case DataBuffer.TYPE_INT:
+ int[][] idata = ((DataBufferInt)bd).getBankData();
+ for (i = 0; i < idata.length; i++) {
+ iarray = idata[i];
+ for (j = 0; j < iarray.length; j++) {
+ val = iarray[j];
+ alpha = val >>> 24;
+ // mask[maskpos++] = (byte)((idata[i][j] >> 24) & 0xFF);
+ if (alpha != 255) {
+ // System.out.println("Alpha: " + alpha);
+ // Composite with opaque white...
+ add = (255 - alpha);
+ mult = (alpha << 16) / 255;
+ result[count++] =
+ (byte)(add
+ + ((((val >> 16) & 0xFF) * mult) >> 16));
+ result[count++] =
+ (byte)(add
+ + ((((val >> 8) & 0xFF) * mult) >> 16));
+ result[count++] = (byte)(add
+ + ((((val) & 0xFF) * mult)
+ >> 16));
+ } else {
+ result[count++] = (byte)((val >> 16) & 0xFF);
+ result[count++] = (byte)((val >> 8) & 0xFF);
+ result[count++] = (byte)((val) & 0xFF);
}
}
- break;
- default:
- // error
- break;
+ }
+ break;
+ default:
+ // error
+ break;
}
try {
@@ -215,12 +232,12 @@ public class PDFGraphics2D extends AbstractGraphics2D {
currentStream.write("q\n");
Shape imclip = getClip();
writeClip(imclip);
- currentStream.write("" + matrix[0] + " " + matrix[1] +
- " " + matrix[2] + " " + matrix[3] + " " +
- matrix[4] + " " + matrix[5] + " cm\n");
- currentStream.write("" + width + " 0 0 " + (-height) +
- " " + x + " " + (y + height) + " cm\n" + "/Im" +
- xObjectNum + " Do\nQ\n");
+ currentStream.write("" + matrix[0] + " " + matrix[1] + " "
+ + matrix[2] + " " + matrix[3] + " "
+ + matrix[4] + " " + matrix[5] + " cm\n");
+ currentStream.write("" + width + " 0 0 " + (-height) + " " + x
+ + " " + (y + height) + " cm\n" + "/Im"
+ + xObjectNum + " Do\nQ\n");
} catch (Exception e) {
e.printStackTrace();
}
@@ -248,8 +265,8 @@ public class PDFGraphics2D extends AbstractGraphics2D {
this.m_width = width;
this.m_bitsPerPixel = 8;
this.m_colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
- //this.m_isTransparent = false;
- //this.m_bitmapsSize = this.m_width * this.m_height * 3;
+ // this.m_isTransparent = false;
+ // this.m_bitmapsSize = this.m_width * this.m_height * 3;
this.m_bitmaps = result;
this.m_mask = mask;
}
@@ -281,18 +298,22 @@ public class PDFGraphics2D extends AbstractGraphics2D {
public boolean isTransparent() throws FopImageException {
return transparent != null;
}
+
public PDFColor getTransparentColor() throws FopImageException {
return transparent;
}
+
public byte[] getMask() throws FopImageException {
return m_mask;
}
+
// get the image bytes, and bytes properties
// get uncompressed image bytes
public byte[] getBitmaps() throws FopImageException {
return m_bitmaps;
}
+
// width * (bitsPerPixel / 8) * height, no ?
public int getBitmapsSize() throws FopImageException {
return m_width * m_height * 3;
@@ -304,9 +325,11 @@ public class PDFGraphics2D extends AbstractGraphics2D {
public byte[] getRessourceBytes() throws FopImageException {
return null;
}
+
public int getRessourceBytesSize() throws FopImageException {
return 0;
}
+
// return null if no corresponding PDFFilter
public PDFFilter getPDFFilter() throws FopImageException {
return null;
@@ -346,13 +369,13 @@ public class PDFGraphics2D extends AbstractGraphics2D {
* @param width the width of the rectangle.
* @param height the height of the rectangle.
* @param observer object to be notified as more of
- * the image is converted.
+ * the image is converted.
* @see java.awt.Image
* @see java.awt.image.ImageObserver
* @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
*/
- public boolean drawImage(Image img, int x, int y, int width,
- int height, ImageObserver observer) {
+ public boolean drawImage(Image img, int x, int y, int width, int height,
+ ImageObserver observer) {
System.out.println("drawImage");
return true;
}
@@ -385,7 +408,7 @@ public class PDFGraphics2D extends AbstractGraphics2D {
* @see java.awt.Graphics#create
*/
public void dispose() {
- //System.out.println("dispose");
+ // System.out.println("dispose");
pdfDoc = null;
fontState = null;
currentStream = null;
@@ -410,7 +433,7 @@ public class PDFGraphics2D extends AbstractGraphics2D {
* @see #setComposite
*/
public void draw(Shape s) {
- //System.out.println("draw(Shape)");
+ // System.out.println("draw(Shape)");
currentStream.write("q\n");
Shape imclip = getClip();
writeClip(imclip);
@@ -425,33 +448,33 @@ public class PDFGraphics2D extends AbstractGraphics2D {
double vals[] = new double[6];
int type = iter.currentSegment(vals);
switch (type) {
- case PathIterator.SEG_CUBICTO:
- currentStream.write(PDFNumber.doubleOut(vals[0]) +
- " " + PDFNumber.doubleOut(vals[1]) + " " +
- PDFNumber.doubleOut(vals[2]) + " " +
- PDFNumber.doubleOut(vals[3]) + " " +
- PDFNumber.doubleOut(vals[4]) + " " +
- PDFNumber.doubleOut(vals[5]) + " c\n");
- break;
- case PathIterator.SEG_LINETO:
- currentStream.write(PDFNumber.doubleOut(vals[0]) +
- " " + PDFNumber.doubleOut(vals[1]) + " l\n");
- break;
- case PathIterator.SEG_MOVETO:
- currentStream.write(PDFNumber.doubleOut(vals[0]) +
- " " + PDFNumber.doubleOut(vals[1]) + " m\n");
- break;
- case PathIterator.SEG_QUADTO:
- currentStream.write(PDFNumber.doubleOut(vals[0]) +
- " " + PDFNumber.doubleOut(vals[1]) + " " +
- PDFNumber.doubleOut(vals[2]) + " " +
- PDFNumber.doubleOut(vals[3]) + " y\n");
- break;
- case PathIterator.SEG_CLOSE:
- currentStream.write("h\n");
- break;
- default:
- break;
+ case PathIterator.SEG_CUBICTO:
+ currentStream.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " "
+ + PDFNumber.doubleOut(vals[2]) + " "
+ + PDFNumber.doubleOut(vals[3]) + " "
+ + PDFNumber.doubleOut(vals[4]) + " "
+ + PDFNumber.doubleOut(vals[5]) + " c\n");
+ break;
+ case PathIterator.SEG_LINETO:
+ currentStream.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " l\n");
+ break;
+ case PathIterator.SEG_MOVETO:
+ currentStream.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " m\n");
+ break;
+ case PathIterator.SEG_QUADTO:
+ currentStream.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " "
+ + PDFNumber.doubleOut(vals[2]) + " "
+ + PDFNumber.doubleOut(vals[3]) + " y\n");
+ break;
+ case PathIterator.SEG_CLOSE:
+ currentStream.write("h\n");
+ break;
+ default:
+ break;
}
iter.next();
}
@@ -468,33 +491,33 @@ public class PDFGraphics2D extends AbstractGraphics2D {
double vals[] = new double[6];
int type = iter.currentSegment(vals);
switch (type) {
- case PathIterator.SEG_CUBICTO:
- currentStream.write(PDFNumber.doubleOut(vals[0]) +
- " " + PDFNumber.doubleOut(vals[1]) + " " +
- PDFNumber.doubleOut(vals[2]) + " " +
- PDFNumber.doubleOut(vals[3]) + " " +
- PDFNumber.doubleOut(vals[4]) + " " +
- PDFNumber.doubleOut(vals[5]) + " c\n");
- break;
- case PathIterator.SEG_LINETO:
- currentStream.write(PDFNumber.doubleOut(vals[0]) +
- " " + PDFNumber.doubleOut(vals[1]) + " l\n");
- break;
- case PathIterator.SEG_MOVETO:
- currentStream.write(PDFNumber.doubleOut(vals[0]) +
- " " + PDFNumber.doubleOut(vals[1]) + " m\n");
- break;
- case PathIterator.SEG_QUADTO:
- currentStream.write(PDFNumber.doubleOut(vals[0]) +
- " " + PDFNumber.doubleOut(vals[1]) + " " +
- PDFNumber.doubleOut(vals[2]) + " " +
- PDFNumber.doubleOut(vals[3]) + " y\n");
- break;
- case PathIterator.SEG_CLOSE:
- currentStream.write("h\n");
- break;
- default:
- break;
+ case PathIterator.SEG_CUBICTO:
+ currentStream.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " "
+ + PDFNumber.doubleOut(vals[2]) + " "
+ + PDFNumber.doubleOut(vals[3]) + " "
+ + PDFNumber.doubleOut(vals[4]) + " "
+ + PDFNumber.doubleOut(vals[5]) + " c\n");
+ break;
+ case PathIterator.SEG_LINETO:
+ currentStream.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " l\n");
+ break;
+ case PathIterator.SEG_MOVETO:
+ currentStream.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " m\n");
+ break;
+ case PathIterator.SEG_QUADTO:
+ currentStream.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " "
+ + PDFNumber.doubleOut(vals[2]) + " "
+ + PDFNumber.doubleOut(vals[3]) + " y\n");
+ break;
+ case PathIterator.SEG_CLOSE:
+ currentStream.write("h\n");
+ break;
+ default:
+ break;
}
iter.next();
}
@@ -505,41 +528,39 @@ public class PDFGraphics2D extends AbstractGraphics2D {
protected void applyColor(Color col, boolean fill) {
Color c = col;
- if (c.getColorSpace().getType() ==
- java.awt.color.ColorSpace.TYPE_RGB) {
- currentColour =
- new PDFColor(c.getRed(), c.getGreen(), c.getBlue());
+ if (c.getColorSpace().getType()
+ == java.awt.color.ColorSpace.TYPE_RGB) {
+ currentColour = new PDFColor(c.getRed(), c.getGreen(),
+ c.getBlue());
currentStream.write(currentColour.getColorSpaceOut(fill));
- } else if (c.getColorSpace().getType() ==
- java.awt.color.ColorSpace.TYPE_CMYK) {
+ } else if (c.getColorSpace().getType()
+ == java.awt.color.ColorSpace.TYPE_CMYK) {
float[] cComps = c.getColorComponents(new float[3]);
double[] cmyk = new double[3];
for (int i = 0; i < 3; i++) {
// convert the float elements to doubles for pdf
cmyk[i] = cComps[i];
}
- currentColour =
- new PDFColor(cmyk[0], cmyk[1], cmyk[2], cmyk[3]);
+ currentColour = new PDFColor(cmyk[0], cmyk[1], cmyk[2], cmyk[3]);
currentStream.write(currentColour.getColorSpaceOut(fill));
- } else if (c.getColorSpace().getType() ==
- java.awt.color.ColorSpace.TYPE_2CLR) {
+ } else if (c.getColorSpace().getType()
+ == java.awt.color.ColorSpace.TYPE_2CLR) {
// used for black/magenta
float[] cComps = c.getColorComponents(new float[1]);
double[] blackMagenta = new double[1];
for (int i = 0; i < 1; i++) {
blackMagenta[i] = cComps[i];
}
- //currentColour = new PDFColor(blackMagenta[0], blackMagenta[1]);
+ // currentColour = new PDFColor(blackMagenta[0], blackMagenta[1]);
currentStream.write(currentColour.getColorSpaceOut(fill));
- }
- else {
+ } else {
System.err.println("Color Space not supported by PDFGraphics2D");
}
}
protected void applyPaint(Paint paint, boolean fill) {
if (paint instanceof GradientPaint) {
- GradientPaint gp = (GradientPaint) paint;
+ GradientPaint gp = (GradientPaint)paint;
Color c1 = gp.getColor1();
Color c2 = gp.getColor2();
Point2D p1 = gp.getPoint1();
@@ -581,61 +602,58 @@ public class PDFGraphics2D extends AbstractGraphics2D {
c2.getBlue());
someColors.addElement(color2);
- PDFFunction myfunc =
- this.pdfDoc.makeFunction(2, theDomain, null,
- color1.getVector(), color2.getVector(), 1.0);
+ PDFFunction myfunc = this.pdfDoc.makeFunction(2, theDomain, null,
+ color1.getVector(), color2.getVector(), 1.0);
ColorSpace aColorSpace = new ColorSpace(ColorSpace.DEVICE_RGB);
- PDFPattern myPat =
- this.pdfDoc.createGradient(false, aColorSpace,
- someColors, null, theCoords);
+ PDFPattern myPat = this.pdfDoc.createGradient(false, aColorSpace,
+ someColors, null, theCoords);
currentStream.write(myPat.getColorSpaceOut(fill));
- } else if (paint instanceof TexturePaint) {
- }
+ } else if (paint instanceof TexturePaint) {}
}
protected void applyStroke(Stroke stroke) {
if (stroke instanceof BasicStroke) {
- BasicStroke bs = (BasicStroke) stroke;
+ BasicStroke bs = (BasicStroke)stroke;
float[] da = bs.getDashArray();
if (da != null) {
currentStream.write("[");
for (int count = 0; count < da.length; count++) {
- currentStream.write("" + ((int) da[count]));
+ currentStream.write("" + ((int)da[count]));
if (count < da.length - 1) {
currentStream.write(" ");
}
}
currentStream.write("] ");
float offset = bs.getDashPhase();
- currentStream.write(((int) offset) + " d\n");
+ currentStream.write(((int)offset) + " d\n");
}
int ec = bs.getEndCap();
switch (ec) {
- case BasicStroke.CAP_BUTT:
- currentStream.write(0 + " J\n");
- break;
- case BasicStroke.CAP_ROUND:
- currentStream.write(1 + " J\n");
- break;
- case BasicStroke.CAP_SQUARE:
- currentStream.write(2 + " J\n");
- break;
+ case BasicStroke.CAP_BUTT:
+ currentStream.write(0 + " J\n");
+ break;
+ case BasicStroke.CAP_ROUND:
+ currentStream.write(1 + " J\n");
+ break;
+ case BasicStroke.CAP_SQUARE:
+ currentStream.write(2 + " J\n");
+ break;
}
int lj = bs.getLineJoin();
switch (lj) {
- case BasicStroke.JOIN_MITER:
- currentStream.write(0 + " j\n");
- break;
- case BasicStroke.JOIN_ROUND:
- currentStream.write(1 + " j\n");
- break;
- case BasicStroke.JOIN_BEVEL:
- currentStream.write(2 + " j\n");
- break;
+ case BasicStroke.JOIN_MITER:
+ currentStream.write(0 + " j\n");
+ break;
+ case BasicStroke.JOIN_ROUND:
+ currentStream.write(1 + " j\n");
+ break;
+ case BasicStroke.JOIN_BEVEL:
+ currentStream.write(2 + " j\n");
+ break;
}
float lw = bs.getLineWidth();
currentStream.write(PDFNumber.doubleOut(lw) + " w\n");
@@ -665,8 +683,7 @@ public class PDFGraphics2D extends AbstractGraphics2D {
* @see #clip
* @see #setClip
*/
- public void drawRenderedImage(RenderedImage img,
- AffineTransform xform) {
+ public void drawRenderedImage(RenderedImage img, AffineTransform xform) {
System.out.println("drawRenderedImage");
}
@@ -683,7 +700,7 @@ public class PDFGraphics2D extends AbstractGraphics2D {
* Transform , and Composite attributes. Note
* that no rendering is done if the specified transform is
* noninvertible.
- *
+ *
* Rendering hints set on the Graphics2D object might
* be used in rendering the RenderableImage .
* If explicit control is required over specific hints recognized by a
@@ -691,7 +708,7 @@ public class PDFGraphics2D extends AbstractGraphics2D {
* are used is required, then a RenderedImage should be
* obtained directly from the RenderableImage
* and rendered using
- *{@link #drawRenderedImage(RenderedImage, AffineTransform) drawRenderedImage}.
+ * {@link #drawRenderedImage(RenderedImage, AffineTransform) drawRenderedImage}.
* @param img the image to be rendered
* @param xform the transformation from image space into user space
* @see #transform
@@ -729,7 +746,7 @@ public class PDFGraphics2D extends AbstractGraphics2D {
* @see #setClip
*/
public void drawString(String s, float x, float y) {
- //System.out.println("drawString(String)");
+ // System.out.println("drawString(String)");
currentStream.write("BT\n");
Shape imclip = getClip();
@@ -748,18 +765,18 @@ public class PDFGraphics2D extends AbstractGraphics2D {
String style = gFont.isItalic() ? "italic" : "normal";
String weight = gFont.isBold() ? "bold" : "normal";
try {
- fontState = new FontState(fontState.getFontInfo(), name,
- style, weight, size * 1000, 0);
+ fontState = new FontState(fontState.getFontInfo(), name, style,
+ weight, size * 1000, 0);
} catch (org.apache.fop.apps.FOPException fope) {
fope.printStackTrace();
}
name = fontState.getFontName();
size = fontState.getFontSize() / 1000;
- //System.out.println("ffn:" + gFont.getFontName() + "fn:" + gFont.getName() + " ff:" + gFont.getFamily() + " fs:" + fontState.getFontName());
+ // System.out.println("ffn:" + gFont.getFontName() + "fn:" + gFont.getName() + " ff:" + gFont.getFamily() + " fs:" + fontState.getFontName());
- if ((!name.equals(this.currentFontName)) ||
- (size != this.currentFontSize)) {
+ if ((!name.equals(this.currentFontName))
+ || (size != this.currentFontSize)) {
this.currentFontName = name;
this.currentFontSize = size;
currentStream.write("/" + name + " " + size + " Tf\n");
@@ -770,12 +787,13 @@ public class PDFGraphics2D extends AbstractGraphics2D {
double[] vals = new double[6];
trans.getMatrix(vals);
- currentStream.write(PDFNumber.doubleOut(vals[0]) + " " +
- PDFNumber.doubleOut(vals[1]) + " " +
- PDFNumber.doubleOut(vals[2]) + " " +
- PDFNumber.doubleOut(-vals[3]) + " " +
- PDFNumber.doubleOut(vals[4]) + " " +
- PDFNumber.doubleOut(vals[5]) + " Tm (" + s + ") Tj\n");
+ currentStream.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " "
+ + PDFNumber.doubleOut(vals[2]) + " "
+ + PDFNumber.doubleOut(-vals[3]) + " "
+ + PDFNumber.doubleOut(vals[4]) + " "
+ + PDFNumber.doubleOut(vals[5]) + " Tm (" + s
+ + ") Tj\n");
currentStream.write("ET\n");
}
@@ -803,8 +821,8 @@ public class PDFGraphics2D extends AbstractGraphics2D {
* @see #setComposite
* @see #setClip
*/
- public void drawString(AttributedCharacterIterator iterator,
- float x, float y) {
+ public void drawString(AttributedCharacterIterator iterator, float x,
+ float y) {
System.err.println("drawString(AttributedCharacterIterator)");
currentStream.write("BT\n");
@@ -826,21 +844,22 @@ public class PDFGraphics2D extends AbstractGraphics2D {
String name = fontState.getFontName();
int size = fontState.getFontSize();
- if ((!name.equals(this.currentFontName)) ||
- (size != this.currentFontSize)) {
+ if ((!name.equals(this.currentFontName))
+ || (size != this.currentFontSize)) {
this.currentFontName = name;
this.currentFontSize = size;
- currentStream.write("/" + name + " " + (size / 1000) +
- " Tf\n");
+ currentStream.write("/" + name + " " + (size / 1000)
+ + " Tf\n");
}
- currentStream.write(PDFNumber.doubleOut(vals[0]) + " " +
- PDFNumber.doubleOut(vals[1]) + " " +
- PDFNumber.doubleOut(vals[2]) + " " +
- PDFNumber.doubleOut(vals[3]) + " " +
- PDFNumber.doubleOut(vals[4]) + " " +
- PDFNumber.doubleOut(vals[5]) + " Tm (" + ch + ") Tj\n");
+ currentStream.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " "
+ + PDFNumber.doubleOut(vals[2]) + " "
+ + PDFNumber.doubleOut(vals[3]) + " "
+ + PDFNumber.doubleOut(vals[4]) + " "
+ + PDFNumber.doubleOut(vals[5]) + " Tm (" + ch
+ + ") Tj\n");
}
currentStream.write("ET\n");
@@ -861,7 +880,7 @@ public class PDFGraphics2D extends AbstractGraphics2D {
* @see #setClip
*/
public void fill(Shape s) {
- //System.err.println("fill");
+ // System.err.println("fill");
currentStream.write("q\n");
Shape imclip = getClip();
writeClip(imclip);
@@ -877,33 +896,33 @@ public class PDFGraphics2D extends AbstractGraphics2D {
double vals[] = new double[6];
int type = iter.currentSegment(vals);
switch (type) {
- case PathIterator.SEG_CUBICTO:
- currentStream.write(PDFNumber.doubleOut(vals[0]) +
- " " + PDFNumber.doubleOut(vals[1]) + " " +
- PDFNumber.doubleOut(vals[2]) + " " +
- PDFNumber.doubleOut(vals[3]) + " " +
- PDFNumber.doubleOut(vals[4]) + " " +
- PDFNumber.doubleOut(vals[5]) + " c\n");
- break;
- case PathIterator.SEG_LINETO:
- currentStream.write(PDFNumber.doubleOut(vals[0]) +
- " " + PDFNumber.doubleOut(vals[1]) + " l\n");
- break;
- case PathIterator.SEG_MOVETO:
- currentStream.write(PDFNumber.doubleOut(vals[0]) +
- " " + PDFNumber.doubleOut(vals[1]) + " m\n");
- break;
- case PathIterator.SEG_QUADTO:
- currentStream.write(PDFNumber.doubleOut(vals[0]) +
- " " + PDFNumber.doubleOut(vals[1]) + " " +
- PDFNumber.doubleOut(vals[2]) + " " +
- PDFNumber.doubleOut(vals[3]) + " y\n");
- break;
- case PathIterator.SEG_CLOSE:
- currentStream.write("h\n");
- break;
- default:
- break;
+ case PathIterator.SEG_CUBICTO:
+ currentStream.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " "
+ + PDFNumber.doubleOut(vals[2]) + " "
+ + PDFNumber.doubleOut(vals[3]) + " "
+ + PDFNumber.doubleOut(vals[4]) + " "
+ + PDFNumber.doubleOut(vals[5]) + " c\n");
+ break;
+ case PathIterator.SEG_LINETO:
+ currentStream.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " l\n");
+ break;
+ case PathIterator.SEG_MOVETO:
+ currentStream.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " m\n");
+ break;
+ case PathIterator.SEG_QUADTO:
+ currentStream.write(PDFNumber.doubleOut(vals[0]) + " "
+ + PDFNumber.doubleOut(vals[1]) + " "
+ + PDFNumber.doubleOut(vals[2]) + " "
+ + PDFNumber.doubleOut(vals[3]) + " y\n");
+ break;
+ case PathIterator.SEG_CLOSE:
+ currentStream.write("h\n");
+ break;
+ default:
+ break;
}
iter.next();
}
@@ -912,8 +931,7 @@ public class PDFGraphics2D extends AbstractGraphics2D {
currentStream.write("Q\n");
}
- protected void doDrawing(boolean fill, boolean stroke,
- boolean nonzero) {
+ protected void doDrawing(boolean fill, boolean stroke, boolean nonzero) {
if (fill) {
if (stroke) {
if (nonzero)
@@ -927,7 +945,7 @@ public class PDFGraphics2D extends AbstractGraphics2D {
currentStream.write("f\n");
}
} else {
- //if(stroke)
+ // if(stroke)
currentStream.write("S\n");
}
}
@@ -946,18 +964,18 @@ public class PDFGraphics2D extends AbstractGraphics2D {
*/
static class PDFGraphicsConfiguration extends GraphicsConfiguration {
// We use this to get a good colormodel..
- static BufferedImage BIWithAlpha =
- new BufferedImage (1, 1, BufferedImage.TYPE_INT_ARGB);
+ static BufferedImage BIWithAlpha = new BufferedImage(1, 1,
+ BufferedImage.TYPE_INT_ARGB);
// We use this to get a good colormodel..
- static BufferedImage BIWithOutAlpha =
- new BufferedImage (1, 1, BufferedImage.TYPE_INT_RGB);
+ static BufferedImage BIWithOutAlpha = new BufferedImage(1, 1,
+ BufferedImage.TYPE_INT_RGB);
/**
* Construct a buffered image with an alpha channel, unless
* transparencty is OPAQUE (no alpha at all).
*/
- public BufferedImage createCompatibleImage(int width,
- int height, int transparency) {
+ public BufferedImage createCompatibleImage(int width, int height,
+ int transparency) {
if (transparency == Transparency.OPAQUE)
return new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
@@ -1023,6 +1041,7 @@ public class PDFGraphics2D extends AbstractGraphics2D {
public GraphicsDevice getDevice() {
return new PDFGraphicsDevice(this);
}
+
}
/**
@@ -1032,7 +1051,9 @@ public class PDFGraphics2D extends AbstractGraphics2D {
* I suppose).
*/
static class PDFGraphicsDevice extends GraphicsDevice {
- /** The Graphics Config that created us...
+
+ /**
+ * The Graphics Config that created us...
*/
GraphicsConfiguration gc;
@@ -1046,34 +1067,40 @@ public class PDFGraphics2D extends AbstractGraphics2D {
/**
* Ignore template and return the only config we have
*/
- public GraphicsConfiguration getBestConfiguration (
- GraphicsConfigTemplate gct) {
+ public GraphicsConfiguration getBestConfiguration(GraphicsConfigTemplate gct) {
return gc;
}
+
/**
* Return an array of our one GraphicsConfig
*/
public GraphicsConfiguration[] getConfigurations() {
- return new GraphicsConfiguration[]{ gc };
+ return new GraphicsConfiguration[] {
+ gc
+ };
}
+
/**
* Return out sole GraphicsConfig.
*/
public GraphicsConfiguration getDefaultConfiguration() {
return gc;
}
+
/**
* Generate an IdString..
*/
public String getIDstring() {
return toString();
}
+
/**
* Let the caller know that we are "a printer"
*/
public int getType() {
return GraphicsDevice.TYPE_PRINTER;
}
+
}
/**
@@ -1082,8 +1109,8 @@ public class PDFGraphics2D extends AbstractGraphics2D {
private Graphics2D fmg;
{
- BufferedImage bi =
- new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
+ BufferedImage bi = new BufferedImage(1, 1,
+ BufferedImage.TYPE_INT_ARGB);
fmg = bi.createGraphics();
}
diff --git a/src/org/apache/fop/svg/PDFTextPainter.java b/src/org/apache/fop/svg/PDFTextPainter.java
index a7435cb0f..db9ed1b92 100644
--- a/src/org/apache/fop/svg/PDFTextPainter.java
+++ b/src/org/apache/fop/svg/PDFTextPainter.java
@@ -1,10 +1,9 @@
-/*****************************************************************************
- * Copyright (C) The Apache Software Foundation. All rights reserved. *
- * ------------------------------------------------------------------------- *
- * This software is published under the terms of the Apache Software License *
- * version 1.1, a copy of which has been included with this distribution in *
- * the LICENSE file. *
- *****************************************************************************/
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.svg;
@@ -56,12 +55,12 @@ public class PDFTextPainter implements TextPainter {
*/
public void paint(TextNode node, Graphics2D g2d,
GraphicsNodeRenderContext context) {
- //System.out.println("PDFText paint");
+ // System.out.println("PDFText paint");
String txt = node.getText();
Point2D loc = node.getLocation();
AttributedCharacterIterator aci =
- node.getAttributedCharacterIterator();
+ node.getAttributedCharacterIterator();
// reset position to start of char iterator
if (aci.getBeginIndex() == aci.getEndIndex()) {
return;
@@ -70,46 +69,46 @@ public class PDFTextPainter implements TextPainter {
if (ch == AttributedCharacterIterator.DONE) {
return;
}
- TextNode.Anchor anchor = (TextNode.Anchor) aci.getAttribute(
- GVTAttributedCharacterIterator.TextAttribute.ANCHOR_TYPE);
-
- Vector gvtFonts = (Vector) aci.getAttribute(
- GVTAttributedCharacterIterator.TextAttribute.GVT_FONT_FAMILIES);
- Paint forg = (Paint) aci.getAttribute(TextAttribute.FOREGROUND);
- Float size = (Float) aci.getAttribute(TextAttribute.SIZE);
- Stroke stroke = (Stroke) aci.getAttribute(
- GVTAttributedCharacterIterator.TextAttribute.STROKE);
- Float xpos = (Float) aci.getAttribute(
- GVTAttributedCharacterIterator.TextAttribute.X);
- Float ypos = (Float) aci.getAttribute(
- GVTAttributedCharacterIterator.TextAttribute.Y);
-
- Float posture = (Float) aci.getAttribute(TextAttribute.POSTURE);
- Float taWeight = (Float) aci.getAttribute(TextAttribute.WEIGHT);
+ TextNode.Anchor anchor =
+ (TextNode.Anchor)aci.getAttribute(GVTAttributedCharacterIterator.TextAttribute.ANCHOR_TYPE);
+
+ Vector gvtFonts =
+ (Vector)aci.getAttribute(GVTAttributedCharacterIterator.TextAttribute.GVT_FONT_FAMILIES);
+ Paint forg = (Paint)aci.getAttribute(TextAttribute.FOREGROUND);
+ Float size = (Float)aci.getAttribute(TextAttribute.SIZE);
+ Stroke stroke =
+ (Stroke)aci.getAttribute(GVTAttributedCharacterIterator.TextAttribute.STROKE);
+ Float xpos =
+ (Float)aci.getAttribute(GVTAttributedCharacterIterator.TextAttribute.X);
+ Float ypos =
+ (Float)aci.getAttribute(GVTAttributedCharacterIterator.TextAttribute.Y);
+
+ Float posture = (Float)aci.getAttribute(TextAttribute.POSTURE);
+ Float taWeight = (Float)aci.getAttribute(TextAttribute.WEIGHT);
if (forg instanceof Color) {
- g2d.setColor((Color) forg);
+ g2d.setColor((Color)forg);
}
g2d.setPaint(forg);
g2d.setStroke(stroke);
- String style = ((posture != null) && (posture.floatValue() > 0.0)) ?
- "italic" : "normal";
- String weight = ((taWeight != null) &&
- (taWeight.floatValue() > 1.0)) ? "bold" : "normal";
+ String style = ((posture != null) && (posture.floatValue() > 0.0))
+ ? "italic" : "normal";
+ String weight = ((taWeight != null) && (taWeight.floatValue() > 1.0))
+ ? "bold" : "normal";
FontInfo fi = fontState.getFontInfo();
boolean found = false;
if (gvtFonts != null) {
- for (Enumeration e = gvtFonts.elements();
- e.hasMoreElements();) {
- GVTFontFamily fam = (GVTFontFamily) e.nextElement();
+ for (Enumeration e = gvtFonts.elements(); e.hasMoreElements(); ) {
+ GVTFontFamily fam = (GVTFontFamily)e.nextElement();
String name = fam.getFamilyName();
if (fi.hasFont(name, weight, style)) {
try {
- int fsize = (int) size.floatValue();
+ int fsize = (int)size.floatValue();
fontState = new FontState(fontState.getFontInfo(),
- name, style, weight, fsize * 1000, 0);
+ name, style, weight,
+ fsize * 1000, 0);
} catch (org.apache.fop.apps.FOPException fope) {
fope.printStackTrace();
}
@@ -120,7 +119,7 @@ public class PDFTextPainter implements TextPainter {
}
if (!found) {
try {
- int fsize = (int) size.floatValue();
+ int fsize = (int)size.floatValue();
fontState = new FontState(fontState.getFontInfo(), "any",
style, weight, fsize * 1000, 0);
} catch (org.apache.fop.apps.FOPException fope) {
@@ -151,11 +150,11 @@ public class PDFTextPainter implements TextPainter {
float tx = 0;
if (anchor != null) {
switch (anchor.getType()) {
- case TextNode.Anchor.ANCHOR_MIDDLE:
- tx = -advance / 2;
- break;
- case TextNode.Anchor.ANCHOR_END:
- tx = -advance;
+ case TextNode.Anchor.ANCHOR_MIDDLE:
+ tx = -advance / 2;
+ break;
+ case TextNode.Anchor.ANCHOR_END:
+ tx = -advance;
}
}
g2d.drawString(txt, (float)(loc.getX() + tx), (float)(loc.getY()));
@@ -184,17 +183,16 @@ public class PDFTextPainter implements TextPainter {
* Initiates a text selection on a particular AttributedCharacterIterator,
* using the text/font metrics employed by this TextPainter instance.
* @param x the x coordinate, in the text layout's coordinate system,
- * of the selection event.
+ * of the selection event.
* @param y the y coordinate, in the text layout's coordinate system,
- * of the selection event.
+ * of the selection event.
* @param aci the AttributedCharacterIterator describing the text
* @param context the GraphicsNodeRenderContext to use when doing text layout.
* @return an instance of Mark which encapsulates the state necessary to
* implement hit testing and text selection.
*/
- public Mark selectAt(double x, double y,
- AttributedCharacterIterator aci, TextNode node,
- GraphicsNodeRenderContext context) {
+ public Mark selectAt(double x, double y, AttributedCharacterIterator aci,
+ TextNode node, GraphicsNodeRenderContext context) {
System.out.println("PDFText selectAt");
return null;
}
@@ -203,9 +201,9 @@ public class PDFTextPainter implements TextPainter {
* Continues a text selection on a particular AttributedCharacterIterator,
* using the text/font metrics employed by this TextPainter instance.
* @param x the x coordinate, in the text layout's coordinate system,
- * of the selection event.
+ * of the selection event.
* @param y the y coordinate, in the text layout's coordinate system,
- * of the selection event.
+ * of the selection event.
* @param aci the AttributedCharacterIterator describing the text
* @param context the GraphicsNodeRenderContext to use when doing text layout.
* @return an instance of Mark which encapsulates the state necessary to
@@ -222,9 +220,9 @@ public class PDFTextPainter implements TextPainter {
* Select all of the text represented by an AttributedCharacterIterator,
* using the text/font metrics employed by this TextPainter instance.
* @param x the x coordinate, in the text layout's coordinate system,
- * of the selection event.
+ * of the selection event.
* @param y the y coordinate, in the text layout's coordinate system,
- * of the selection event.
+ * of the selection event.
* @param aci the AttributedCharacterIterator describing the text
* @param context the GraphicsNodeRenderContext to use when doing text layout.
* @return an instance of Mark which encapsulates the state necessary to
@@ -268,8 +266,8 @@ public class PDFTextPainter implements TextPainter {
* selectTo(), since the TextPainter implementation may rely on hidden
* implementation details of its own Mark implementation.
*/
- public int[] getSelected(AttributedCharacterIterator aci,
- Mark start, Mark finish) {
+ public int[] getSelected(AttributedCharacterIterator aci, Mark start,
+ Mark finish) {
System.out.println("PDFText getSelected");
return null;
}
@@ -294,9 +292,9 @@ public class PDFTextPainter implements TextPainter {
* @param node the TextNode to measure
* @param frc the font rendering context.
* @param includeDecoration whether to include text decoration
- * outlines.
+ * outlines.
* @param includeStroke whether to create the "stroke shape outlines"
- * instead of glyph outlines.
+ * instead of glyph outlines.
*/
public Shape getShape(TextNode node, FontRenderContext frc) {
System.out.println("PDFText getShape");
@@ -308,9 +306,9 @@ public class PDFTextPainter implements TextPainter {
* @param node the TextNode to measure
* @param frc the font rendering context.
* @param includeDecoration whether to include text decoration
- * outlines.
+ * outlines.
* @param includeStroke whether to create the "stroke shape outlines"
- * instead of glyph outlines.
+ * instead of glyph outlines.
*/
public Shape getDecoratedShape(TextNode node, FontRenderContext frc) {
System.out.println("PDFText getDecoratedShape");
@@ -353,8 +351,9 @@ public class PDFTextPainter implements TextPainter {
*/
public Rectangle2D getPaintedBounds(TextNode node,
FontRenderContext frc) {
- //System.out.println("PDFText getPaintedBounds");
+ // System.out.println("PDFText getPaintedBounds");
return null;
}
+
}
diff --git a/src/org/apache/fop/svg/PDFTranscoder.java b/src/org/apache/fop/svg/PDFTranscoder.java
index dedd179a9..5ceb4f3b2 100644
--- a/src/org/apache/fop/svg/PDFTranscoder.java
+++ b/src/org/apache/fop/svg/PDFTranscoder.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -130,7 +131,9 @@ public class PDFTranscoder extends XMLAbstractTranscoder {
public static final TranscodingHints.Key KEY_STROKE_TEXT =
new StringKey();
- /** The user agent dedicated to an ImageTranscoder. */
+ /**
+ * The user agent dedicated to an ImageTranscoder.
+ */
protected UserAgent userAgent = new ImageTranscoderUserAgent();
/**
@@ -156,21 +159,20 @@ public class PDFTranscoder extends XMLAbstractTranscoder {
TranscoderOutput output) throws TranscoderException {
if (!(document instanceof SVGOMDocument)) {
- throw new TranscoderException(
- Messages.formatMessage("notsvg", null));
+ throw new TranscoderException(Messages.formatMessage("notsvg",
+ null));
}
- SVGDocument svgDoc = (SVGDocument) document;
+ SVGDocument svgDoc = (SVGDocument)document;
SVGSVGElement root = svgDoc.getRootElement();
// initialize the SVG document with the appropriate context
- String parserClassname =
- (String) hints.get(KEY_XML_PARSER_CLASSNAME);
+ String parserClassname = (String)hints.get(KEY_XML_PARSER_CLASSNAME);
DefaultSVGContext svgCtx = new DefaultSVGContext();
svgCtx.setPixelToMM(userAgent.getPixelToMM());
- ((SVGOMDocument) document).setSVGContext(svgCtx);
+ ((SVGOMDocument)document).setSVGContext(svgCtx);
boolean stroke = true;
if (hints.containsKey(KEY_STROKE_TEXT)) {
- stroke = ((Boolean) hints.get(KEY_STROKE_TEXT)).booleanValue();
+ stroke = ((Boolean)hints.get(KEY_STROKE_TEXT)).booleanValue();
}
// build the GVT tree
@@ -187,21 +189,21 @@ public class PDFTranscoder extends XMLAbstractTranscoder {
throw new TranscoderException(ex);
}
// get the 'width' and 'height' attributes of the SVG document
- float docWidth = (float) ctx.getDocumentSize().getWidth();
- float docHeight = (float) ctx.getDocumentSize().getHeight();
+ float docWidth = (float)ctx.getDocumentSize().getWidth();
+ float docHeight = (float)ctx.getDocumentSize().getHeight();
ctx = null;
builder = null;
// compute the image's width and height according the hints
float imgWidth = -1;
if (hints.containsKey(ImageTranscoder.KEY_WIDTH)) {
- imgWidth = ((Float) hints.get(ImageTranscoder.KEY_WIDTH)).
- floatValue();
+ imgWidth =
+ ((Float)hints.get(ImageTranscoder.KEY_WIDTH)).floatValue();
}
float imgHeight = -1;
if (hints.containsKey(ImageTranscoder.KEY_HEIGHT)) {
- imgHeight = ((Float) hints.get(ImageTranscoder.KEY_HEIGHT)).
- floatValue();
+ imgHeight =
+ ((Float)hints.get(ImageTranscoder.KEY_HEIGHT)).floatValue();
}
float width, height;
if (imgWidth > 0 && imgHeight > 0) {
@@ -242,8 +244,7 @@ public class PDFTranscoder extends XMLAbstractTranscoder {
}
// take the AOI into account if any
if (hints.containsKey(ImageTranscoder.KEY_AOI)) {
- Rectangle2D aoi =
- (Rectangle2D) hints.get(ImageTranscoder.KEY_AOI);
+ Rectangle2D aoi = (Rectangle2D)hints.get(ImageTranscoder.KEY_AOI);
// transform the AOI into the image's coordinate system
aoi = Px.createTransformedShape(aoi).getBounds2D();
AffineTransform Mx = new AffineTransform();
@@ -258,11 +259,11 @@ public class PDFTranscoder extends XMLAbstractTranscoder {
Px.preConcatenate(Mx);
}
// prepare the image to be painted
- int w = (int) width;
- int h = (int) height;
+ int w = (int)width;
+ int h = (int)height;
PDFDocumentGraphics2D graphics = new PDFDocumentGraphics2D(stroke,
- output.getOutputStream(), w, h);
+ output.getOutputStream(), w, h);
graphics.setSVGDimension(docWidth, docHeight);
if (!stroke) {
@@ -273,11 +274,9 @@ public class PDFTranscoder extends XMLAbstractTranscoder {
pdfAElementBridge.setPDFGraphics2D(graphics);
if (hints.containsKey(ImageTranscoder.KEY_BACKGROUND_COLOR)) {
- graphics.setBackgroundColor( (Color) hints.get(
- ImageTranscoder.KEY_BACKGROUND_COLOR));
+ graphics.setBackgroundColor((Color)hints.get(ImageTranscoder.KEY_BACKGROUND_COLOR));
}
- graphics.setGraphicContext(
- new org.apache.batik.ext.awt.g2d.GraphicContext());
+ graphics.setGraphicContext(new org.apache.batik.ext.awt.g2d.GraphicContext());
graphics.setRenderingHints(rc.getRenderingHints());
gvtRoot.paint(graphics, rc);
@@ -301,18 +300,18 @@ public class PDFTranscoder extends XMLAbstractTranscoder {
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
FontRenderContext fontRenderContext =
- new FontRenderContext(new AffineTransform(), true,
- true);
+ new FontRenderContext(new AffineTransform(), true, true);
TextPainter textPainter = null;
textPainter = new StrokingTextPainter();
GraphicsNodeRableFactory gnrFactory =
- new ConcreteGraphicsNodeRableFactory();
+ new ConcreteGraphicsNodeRableFactory();
- nodeRenderContext = new GraphicsNodeRenderContext(
- new AffineTransform(), null, hints,
- fontRenderContext, textPainter, gnrFactory);
+ nodeRenderContext =
+ new GraphicsNodeRenderContext(new AffineTransform(), null,
+ hints, fontRenderContext,
+ textPainter, gnrFactory);
}
return nodeRenderContext;
@@ -326,8 +325,8 @@ public class PDFTranscoder extends XMLAbstractTranscoder {
* @param domImpl the DOM Implementation (not used)
* @param parserClassname the XML parser classname
*/
- protected DocumentFactory createDocumentFactory(
- DOMImplementation domImpl, String parserClassname) {
+ protected DocumentFactory createDocumentFactory(DOMImplementation domImpl,
+ String parserClassname) {
return new SAXSVGDocumentFactory(parserClassname);
}
@@ -374,8 +373,7 @@ public class PDFTranscoder extends XMLAbstractTranscoder {
*/
public void displayMessage(String message) {
try {
- getErrorHandler().warning(
- new TranscoderException(message));
+ getErrorHandler().warning(new TranscoderException(message));
} catch (TranscoderException ex) {
throw new RuntimeException();
}
@@ -386,13 +384,11 @@ public class PDFTranscoder extends XMLAbstractTranscoder {
* TranscodingHints or 0.3528 if any.
*/
public float getPixelToMM() {
- if (getTranscodingHints().containsKey(
- ImageTranscoder.KEY_PIXEL_TO_MM)) {
- return ( (Float) getTranscodingHints().get(
- ImageTranscoder.KEY_PIXEL_TO_MM)).floatValue();
+ if (getTranscodingHints().containsKey(ImageTranscoder.KEY_PIXEL_TO_MM)) {
+ return ((Float)getTranscodingHints().get(ImageTranscoder.KEY_PIXEL_TO_MM)).floatValue();
} else {
// return 0.3528f; // 72 dpi
- return 0.26458333333333333333333333333333f; // 96dpi
+ return 0.26458333333333333333333333333333f; // 96dpi
}
}
@@ -401,10 +397,8 @@ public class PDFTranscoder extends XMLAbstractTranscoder {
* TranscodingHints or "en" (english) if any.
*/
public String getLanguages() {
- if (getTranscodingHints().containsKey(
- ImageTranscoder.KEY_LANGUAGE)) {
- return (String) getTranscodingHints().get(
- ImageTranscoder.KEY_LANGUAGE);
+ if (getTranscodingHints().containsKey(ImageTranscoder.KEY_LANGUAGE)) {
+ return (String)getTranscodingHints().get(ImageTranscoder.KEY_LANGUAGE);
} else {
return "en";
}
@@ -415,18 +409,15 @@ public class PDFTranscoder extends XMLAbstractTranscoder {
* TranscodingHints or null if any.
*/
public String getUserStyleSheetURI() {
- return (String) getTranscodingHints().get(
- ImageTranscoder.KEY_USER_STYLESHEET_URI);
+ return (String)getTranscodingHints().get(ImageTranscoder.KEY_USER_STYLESHEET_URI);
}
/**
* Returns the XML parser to use from the TranscodingHints.
*/
public String getXMLParserClassName() {
- if (getTranscodingHints().containsKey(
- KEY_XML_PARSER_CLASSNAME)) {
- return (String) getTranscodingHints().get(
- KEY_XML_PARSER_CLASSNAME);
+ if (getTranscodingHints().containsKey(KEY_XML_PARSER_CLASSNAME)) {
+ return (String)getTranscodingHints().get(KEY_XML_PARSER_CLASSNAME);
} else {
return XMLResourceDescriptor.getXMLParserClassName();
}
@@ -442,17 +433,17 @@ public class PDFTranscoder extends XMLAbstractTranscoder {
/**
* Unsupported operation.
*/
- public void openLink(SVGAElement elt) { }
+ public void openLink(SVGAElement elt) {}
/**
* Unsupported operation.
*/
- public void setSVGCursor(Cursor cursor) { }
+ public void setSVGCursor(Cursor cursor) {}
/**
* Unsupported operation.
*/
- public void runThread(Thread t) { }
+ public void runThread(Thread t) {}
/**
* Unsupported operation.
@@ -484,8 +475,8 @@ public class PDFTranscoder extends XMLAbstractTranscoder {
return false;
}
- public void registerExtension(BridgeExtension be) {
- }
+ public void registerExtension(BridgeExtension be) {}
+
}
protected final static Set FEATURES = new HashSet();
diff --git a/src/org/apache/fop/svg/SVGArea.java b/src/org/apache/fop/svg/SVGArea.java
index ce1e5424a..d4845be84 100644
--- a/src/org/apache/fop/svg/SVGArea.java
+++ b/src/org/apache/fop/svg/SVGArea.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -30,9 +31,9 @@ public class SVGArea extends Area {
* @param height the height of the area
*/
public SVGArea(FontState fontState, float width, float height) {
- super(fontState, (int) width * 1000, (int) height * 1000);
- currentHeight = (int) height * 1000;
- contentRectangleWidth = (int) width * 1000;
+ super(fontState, (int)width * 1000, (int)height * 1000);
+ currentHeight = (int)height * 1000;
+ contentRectangleWidth = (int)width * 1000;
}
public void setSVGDocument(Document doc) {
@@ -44,7 +45,7 @@ public class SVGArea extends Area {
}
public int getWidth() {
- // return getSVGDocument().getRootElement().getWidth().getBaseVal().getValue();
+ // return getSVGDocument().getRootElement().getWidth().getBaseVal().getValue();
return contentRectangleWidth;
}
@@ -56,4 +57,5 @@ public class SVGArea extends Area {
public void render(Renderer renderer) {
renderer.renderSVGArea(this);
}
+
}
diff --git a/src/org/apache/fop/svg/SVGElement.java b/src/org/apache/fop/svg/SVGElement.java
index ad31bcdc4..91ef47bb0 100644
--- a/src/org/apache/fop/svg/SVGElement.java
+++ b/src/org/apache/fop/svg/SVGElement.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -48,6 +49,7 @@ public class SVGElement extends Svg {
PropertyList propertyList) throws FOPException {
return new SVGElement(parent, propertyList);
}
+
}
/**
@@ -103,27 +105,29 @@ public class SVGElement extends Svg {
try {
String baseDir = Configuration.getStringValue("baseDir");
((SVGOMDocument)doc).setURLObject(new URL(baseDir));
- } catch (Exception e) {
- }
+ } catch (Exception e) {}
DefaultSVGContext dc = new DefaultSVGContext() {
- public float getPixelToMM() {
- return 0.264583333333333333333f;
- // 72 dpi
- }
- public float getViewportWidth() {
- return 100;
- }
- public float getViewportHeight() {
- return 100;
- }
- };
+ public float getPixelToMM() {
+ return 0.264583333333333333333f;
+ // 72 dpi
+ }
+
+ public float getViewportWidth() {
+ return 100;
+ }
+
+ public float getViewportHeight() {
+ return 100;
+ }
+
+ };
((SVGOMDocument)doc).setSVGContext(dc);
buildTopLevel(doc, svgRoot);
- float width = ((SVGSVGElement) svgRoot).getWidth().getBaseVal().
- getValue();
- float height = ((SVGSVGElement) svgRoot).getHeight().getBaseVal().
- getValue();
+ float width =
+ ((SVGSVGElement)svgRoot).getWidth().getBaseVal().getValue();
+ float height =
+ ((SVGSVGElement)svgRoot).getHeight().getBaseVal().getValue();
SVGArea svg = new SVGArea(fs, width, height);
svg.setSVGDocument(doc);
svg.start();
@@ -132,7 +136,7 @@ public class SVGElement extends Svg {
svg.end();
/* add the SVG area to the containing area */
- ForeignObjectArea foa = (ForeignObjectArea) area;
+ ForeignObjectArea foa = (ForeignObjectArea)area;
foa.setObject(svg);
foa.setIntrinsicWidth(svg.getWidth());
foa.setIntrinsicHeight(svg.getHeight());
@@ -140,4 +144,5 @@ public class SVGElement extends Svg {
/* return status */
return new Status(Status.OK);
}
+
}
diff --git a/src/org/apache/fop/svg/SVGElementMapping.java b/src/org/apache/fop/svg/SVGElementMapping.java
index 3ff03ec5c..c6d876f61 100644
--- a/src/org/apache/fop/svg/SVGElementMapping.java
+++ b/src/org/apache/fop/svg/SVGElementMapping.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -60,8 +61,7 @@ public class SVGElementMapping implements ElementMapping {
builder.addMapping(uri, "set", Set.maker());
builder.addMapping(uri, "animateMotion", AnimateMotion.maker());
builder.addMapping(uri, "animateColor", AnimateColor.maker());
- builder.addMapping(uri, "animateTransform",
- AnimateTransform.maker());
+ builder.addMapping(uri, "animateTransform", AnimateTransform.maker());
builder.addMapping(uri, "cursor", Cursor.maker());
builder.addMapping(uri, "filter", Filter.maker());
@@ -72,14 +72,14 @@ public class SVGElementMapping implements ElementMapping {
builder.addMapping(uri, "feMergeNode", FeMergeNode.maker());
- builder.addPropertyList(uri,
- SVGPropertyMapping.getGenericMappings());
+ builder.addPropertyList(uri, SVGPropertyMapping.getGenericMappings());
/* Add any element mappings */
for (Enumeration e = SVGPropertyMapping.getElementMappings();
- e.hasMoreElements();) {
- String elem = (String) e.nextElement();
+ e.hasMoreElements(); ) {
+ String elem = (String)e.nextElement();
builder.addElementPropertyList(uri, elem,
SVGPropertyMapping.getElementMapping(elem));
}
}
+
}
diff --git a/src/org/apache/fop/svg/SVGObj.java b/src/org/apache/fop/svg/SVGObj.java
index 3b4c23814..2a215d730 100644
--- a/src/org/apache/fop/svg/SVGObj.java
+++ b/src/org/apache/fop/svg/SVGObj.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -28,5 +29,6 @@ public abstract class SVGObj extends XMLObj {
public String getNameSpace() {
return "http://www.w3.org/2000/svg";
}
+
}
diff --git a/src/org/apache/fop/svg/SVGStringProperty.java b/src/org/apache/fop/svg/SVGStringProperty.java
index 2937bdbd2..c483773f2 100644
--- a/src/org/apache/fop/svg/SVGStringProperty.java
+++ b/src/org/apache/fop/svg/SVGStringProperty.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * LICENSE file included with these sources.
*/
package org.apache.fop.svg;
@@ -47,10 +48,10 @@ public class SVGStringProperty extends Property {
*
* @param propertyList the property list the property is a member of
*/
- public Property make(PropertyList propertyList)
- throws FOPException {
+ public Property make(PropertyList propertyList) throws FOPException {
return make(propertyList, null, null);
}
+
}
/**
@@ -62,7 +63,9 @@ public class SVGStringProperty extends Property {
return new SVGStringProperty.Maker();
}
- /** the value */
+ /**
+ * the value
+ */
protected String value;
/**
@@ -84,4 +87,5 @@ public class SVGStringProperty extends Property {
public String getString() {
return this.value;
}
+
}
diff --git a/src/org/apache/fop/svg/SVGUtilities.java b/src/org/apache/fop/svg/SVGUtilities.java
index 051a5ebfd..fe854d271 100644
--- a/src/org/apache/fop/svg/SVGUtilities.java
+++ b/src/org/apache/fop/svg/SVGUtilities.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -35,8 +36,7 @@ public class SVGUtilities {
public static final Document createSVGDocument(float width,
float height) {
- DOMImplementation impl =
- SVGDOMImplementation.getDOMImplementation();
+ DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
Document doc = impl.createDocument(svgNS, "svg", null);
Element svgRoot = doc.getDocumentElement();
@@ -48,21 +48,24 @@ public class SVGUtilities {
/**
* Get the string width for a particular string given the font.
*/
- public static final float getStringWidth(String str,
- java.awt.Font font) {
- Rectangle2D rect = font.getStringBounds(str, 0, str.length(),
- new FontRenderContext(new AffineTransform(), true, true));
- return (float) rect.getWidth();
+ public static final float getStringWidth(String str, java.awt.Font font) {
+ Rectangle2D rect =
+ font.getStringBounds(str, 0, str.length(),
+ new FontRenderContext(new AffineTransform(),
+ true, true));
+ return (float)rect.getWidth();
}
/**
* Get the string height for a particular string given the font.
*/
public static final float getStringHeight(String str,
- java.awt.Font font) {
- Rectangle2D rect = font.getStringBounds(str, 0, str.length(),
- new FontRenderContext(new AffineTransform(), true, true));
- return (float) rect.getHeight();
+ java.awt.Font font) {
+ Rectangle2D rect =
+ font.getStringBounds(str, 0, str.length(),
+ new FontRenderContext(new AffineTransform(),
+ true, true));
+ return (float)rect.getHeight();
}
/**
@@ -71,14 +74,15 @@ public class SVGUtilities {
public static final Rectangle2D getStringBounds(String str,
java.awt.Font font) {
return font.getStringBounds(str, 0, str.length(),
- new FontRenderContext(new AffineTransform(), true, true));
+ new FontRenderContext(new AffineTransform(),
+ true, true));
}
/**
* Create an SVG Line
*/
- public static final Element createLine(Document doc, float x,
- float y, float x2, float y2) {
+ public static final Element createLine(Document doc, float x, float y,
+ float x2, float y2) {
Element ellipse = doc.createElementNS(svgNS, "line");
ellipse.setAttributeNS(null, "x1", "" + x);
ellipse.setAttributeNS(null, "x2", "" + x2);
@@ -91,7 +95,7 @@ public class SVGUtilities {
* Create an SVG Ellipse
*/
public static final Element createEllipse(Document doc, float cx,
- float cy, float rx, float ry) {
+ float cy, float rx, float ry) {
Element ellipse = doc.createElementNS(svgNS, "ellipse");
ellipse.setAttributeNS(null, "cx", "" + cx);
ellipse.setAttributeNS(null, "rx", "" + rx);
@@ -112,8 +116,8 @@ public class SVGUtilities {
/**
* Create an SVG Text object.
*/
- public static final Element createText(Document doc, float x,
- float y, String str) {
+ public static final Element createText(Document doc, float x, float y,
+ String str) {
Element textGraph = doc.createElementNS(svgNS, "text");
textGraph.setAttributeNS(null, "x", "" + x);
textGraph.setAttributeNS(null, "y", "" + y);
@@ -125,8 +129,8 @@ public class SVGUtilities {
/**
* Create an SVG Rectangle.
*/
- public static final Element createRect(Document doc, float x,
- float y, float width, float height) {
+ public static final Element createRect(Document doc, float x, float y,
+ float width, float height) {
Element border = doc.createElementNS(svgNS, "rect");
border.setAttributeNS(null, "x", "" + x);
border.setAttributeNS(null, "y", "" + y);
@@ -198,4 +202,5 @@ public class SVGUtilities {
return g;
}
+
}
diff --git a/src/org/apache/fop/svg/XMLObj.java b/src/org/apache/fop/svg/XMLObj.java
index ded424966..e9b41669b 100644
--- a/src/org/apache/fop/svg/XMLObj.java
+++ b/src/org/apache/fop/svg/XMLObj.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -26,6 +27,7 @@ public abstract class XMLObj extends FObj {
protected String tagName = "";
protected String[] props = {};
+
/**
*
* @param parent the parent formatting object
@@ -41,7 +43,7 @@ public abstract class XMLObj extends FObj {
public void addGraphic(Document doc, Element parent) {
Element element = doc.createElementNS(getNameSpace(), tagName);
- // Element element = doc.createElement(tagName);
+ // Element element = doc.createElement(tagName);
for (int count = 0; count < props.length; count++) {
if (this.properties.get(props[count]) != null) {
String rf = this.properties.get(props[count]).getString();
@@ -49,14 +51,15 @@ public abstract class XMLObj extends FObj {
if (props[count].indexOf(":") == -1) {
element.setAttribute(props[count], rf);
} else {
- String pref = props[count].substring(0,
- props[count].indexOf(":"));
+ String pref =
+ props[count].substring(0,
+ props[count].indexOf(":"));
if (pref.equals("xmlns")) {
- ns.put(props[count].substring(
- props[count].indexOf(":") + 1), rf);
+ ns.put(props[count].substring(props[count].indexOf(":")
+ + 1), rf);
}
ns.put("xlink", "http://www.w3.org/1999/xlink");
- element.setAttributeNS((String) ns.get(pref),
+ element.setAttributeNS((String)ns.get(pref),
props[count], rf);
}
}
@@ -67,9 +70,9 @@ public abstract class XMLObj extends FObj {
for (int i = 0; i < numChildren; i++) {
Object child = children.elementAt(i);
if (child instanceof XMLObj) {
- ((XMLObj) child).addGraphic(doc, element);
+ ((XMLObj)child).addGraphic(doc, element);
} else if (child instanceof String) {
- org.w3c.dom.Text text = doc.createTextNode((String) child);
+ org.w3c.dom.Text text = doc.createTextNode((String)child);
element.appendChild(text);
}
}
@@ -84,14 +87,14 @@ public abstract class XMLObj extends FObj {
svgRoot.setAttributeNS(null, props[count], rf);
}
}
- //doc.appendChild(topLevel);
+ // doc.appendChild(topLevel);
int numChildren = this.children.size();
for (int i = 0; i < numChildren; i++) {
Object child = children.elementAt(i);
if (child instanceof XMLObj) {
- ((XMLObj) child).addGraphic(doc, svgRoot);
+ ((XMLObj)child).addGraphic(doc, svgRoot);
} else if (child instanceof String) {
- org.w3c.dom.Text text = doc.createTextNode((String) child);
+ org.w3c.dom.Text text = doc.createTextNode((String)child);
svgRoot.appendChild(text);
}
}
@@ -102,11 +105,11 @@ public abstract class XMLObj extends FObj {
Element svgRoot = null;
try {
- // DOMImplementation impl = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
- // String ns = GraphElementMapping.URI;
- // doc = impl.createDocument(ns, "graph", null);
- doc = javax.xml.parsers.DocumentBuilderFactory.newInstance().
- newDocumentBuilder().newDocument();
+ // DOMImplementation impl = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
+ // String ns = GraphElementMapping.URI;
+ // doc = impl.createDocument(ns, "graph", null);
+ doc =
+ javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element el = doc.createElement("graph");
doc.appendChild(el);
@@ -118,6 +121,7 @@ public abstract class XMLObj extends FObj {
}
return doc;
}
+
/**
* layout this formatting object.
*
@@ -135,26 +139,21 @@ public abstract class XMLObj extends FObj {
/**
* These method overrides prevent problems with the different types.
*/
- public void setIsInTableCell() {
- }
+ public void setIsInTableCell() {}
- public void forceStartOffset(int offset) {
- }
+ public void forceStartOffset(int offset) {}
- public void forceWidth(int width) {
- }
+ public void forceWidth(int width) {}
- public void resetMarker() {
- }
+ public void resetMarker() {}
- public void setLinkSet(LinkSet linkSet) {
- }
+ public void setLinkSet(LinkSet linkSet) {}
public Vector getMarkerSnapshot(Vector snapshot) {
return snapshot;
}
- public void rollback(Vector snapshot) {
- }
+ public void rollback(Vector snapshot) {}
+
}
diff --git a/src/org/apache/fop/system/BufferArray.java b/src/org/apache/fop/system/BufferArray.java
index 628bfe7f3..a5596dc46 100644
--- a/src/org/apache/fop/system/BufferArray.java
+++ b/src/org/apache/fop/system/BufferArray.java
@@ -1,14 +1,15 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
// Seshadri
/* This package is to be used for all Oeprating System related activities. */
/* This buffers data into an array in memory */
- package org.apache.fop.system;
+package org.apache.fop.system;
// FOP
@@ -18,12 +19,10 @@
// Java
-public class BufferArray {
-
-
- public BufferArray() {
-
- }
-
+public class BufferArray {
+
+
+ public BufferArray() {}
+
}
-
+
diff --git a/src/org/apache/fop/system/BufferFile.java b/src/org/apache/fop/system/BufferFile.java
index f92650557..370496f4b 100644
--- a/src/org/apache/fop/system/BufferFile.java
+++ b/src/org/apache/fop/system/BufferFile.java
@@ -1,7 +1,8 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
// Seshadri
@@ -18,9 +19,7 @@ import java.io.*;
public class BufferFile {
-
- public BufferFile () {
-
- }
-
+
+ public BufferFile() {}
+
}
diff --git a/src/org/apache/fop/system/BufferManager.java b/src/org/apache/fop/system/BufferManager.java
index 8269d7edf..75959de49 100644
--- a/src/org/apache/fop/system/BufferManager.java
+++ b/src/org/apache/fop/system/BufferManager.java
@@ -1,12 +1,15 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
// Seshadri
-/* This package is to be used for all Oeprating System related activities.
- This file manages system buffers */
+/*
+ * This package is to be used for all Oeprating System related activities.
+ * This file manages system buffers
+ */
package org.apache.fop.system;
@@ -18,173 +21,170 @@ import org.apache.fop.fo.FONode;
// Java
- import java.io.*;
- import java.util.Hashtable;
+import java.io.*;
+import java.util.Hashtable;
public class BufferManager {
-
-
- protected FileWriter fw;
- protected FileReader fr;
- protected char cache[]; // Cache
- protected long csize; //Cache size
-
-
- protected File buff=null;
-
- protected long fp = 0;
-
- protected long markStart=0; // used to set the current point in the stream while reading
- protected long markEnd=0;
- protected long curMark=0;
-
- // Hash of objects and their offsets within
-
- Hashtable offSetTable = new Hashtable();
-
- private class Offset {
-
- long fp=0; // File Pointer
- int length;
- char[] data; // when no buffer is specified
-
- Offset(long fp,int length,char data[]) {
- this.fp = fp;
- this.length = length;
- this.data = data;
- }
- }
-
-
-
- public void addBufferFile(File buff) {
-
- if (buff != null)
- try {
- fw = new FileWriter(buff);
- fr = new FileReader(buff);
- csize = 100000;
- this.buff = buff;
- }
- catch (Exception e) {
- System.out.println(e);
- }
-
- }
-
- public void writeBuffer(Object obj,char arr[]) {
-
- int length = arr.length;
-
- if (buff != null) {
- offSetTable.put(obj, new Offset(this.fp,length,null));
- try {
- fw.write(arr);
-
- this.fp += length;
- }
-
- catch (Exception e) {
- System.out.println(e);
- }
- }
- else {
- // Store the data in memory
- offSetTable.put(obj, new Offset(this.fp,length,arr));
- }
-
-
- }
-
-
-public void readComplete() {
-
- // An indication that manager can close the writable buffers and prepare
- // for reading..
- if (buff != null)
- try {
-
- fw.close();
-
- cache = new char[(int) csize];
- setupCache(curMark);
-
- }
- catch (Exception e) {
- System.out.println(e);
- }
-}
-
-
-
-
- public char[] readBuffer(Object obj) {
-
- Offset values = (Offset) offSetTable.get(obj);
-
- // Was buffering used?
-
- if (buff != null) {
-
-
- char ca[] = new char[values.length];
-
- // Check if csize is too small
-
- if (csize < values.length) {
- System.out.println("Cache size too small");
- System.exit(0);
- }
-
-
- // Is the data outside the cache?
-
- if (! (values.fp >= markStart && values.fp + values.length <= markEnd)) {
-
- setupCache(values.fp);
- }
-
-
- for (long i = values.fp - markStart,j=0; j < values.length; ++i,++j) {
-
- ca[(int)j] = cache[(int)i];
- }
-
-
- return ca;
- }
- else {
- return values.data;
- }
- }
-
- protected void setupCache(long curMark) {
-
- try {
-
- FileReader fr = new FileReader(buff);
- fr.skip(curMark);
-
- long rem = buff.length() - curMark;
- if (rem > csize) {
-
- rem = csize;
- }
-
- fr.read(cache,0,(int)rem);
-
-
- markStart = curMark;
- markEnd = rem - 1;
-
- }
- catch (Exception e) {
- System.out.println(e);
- }
-
-
- }
-
-
+
+
+ protected FileWriter fw;
+ protected FileReader fr;
+ protected char cache[]; // Cache
+ protected long csize; // Cache size
+
+
+ protected File buff = null;
+
+ protected long fp = 0;
+
+ protected long markStart =
+ 0; // used to set the current point in the stream while reading
+ protected long markEnd = 0;
+ protected long curMark = 0;
+
+ // Hash of objects and their offsets within
+
+ Hashtable offSetTable = new Hashtable();
+
+ private class Offset {
+
+ long fp = 0; // File Pointer
+ int length;
+ char[] data; // when no buffer is specified
+
+ Offset(long fp, int length, char data[]) {
+ this.fp = fp;
+ this.length = length;
+ this.data = data;
+ }
+
+ }
+
+
+
+ public void addBufferFile(File buff) {
+
+ if (buff != null)
+ try {
+ fw = new FileWriter(buff);
+ fr = new FileReader(buff);
+ csize = 100000;
+ this.buff = buff;
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+
+ }
+
+ public void writeBuffer(Object obj, char arr[]) {
+
+ int length = arr.length;
+
+ if (buff != null) {
+ offSetTable.put(obj, new Offset(this.fp, length, null));
+ try {
+ fw.write(arr);
+
+ this.fp += length;
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+ } else {
+ // Store the data in memory
+ offSetTable.put(obj, new Offset(this.fp, length, arr));
+ }
+
+
+ }
+
+
+ public void readComplete() {
+
+ // An indication that manager can close the writable buffers and prepare
+ // for reading..
+ if (buff != null)
+ try {
+
+ fw.close();
+
+ cache = new char[(int)csize];
+ setupCache(curMark);
+
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+ }
+
+
+
+
+ public char[] readBuffer(Object obj) {
+
+ Offset values = (Offset)offSetTable.get(obj);
+
+ // Was buffering used?
+
+ if (buff != null) {
+
+
+ char ca[] = new char[values.length];
+
+ // Check if csize is too small
+
+ if (csize < values.length) {
+ System.out.println("Cache size too small");
+ System.exit(0);
+ }
+
+
+ // Is the data outside the cache?
+
+ if (!(values.fp >= markStart
+ && values.fp + values.length <= markEnd)) {
+
+ setupCache(values.fp);
+ }
+
+
+ for (long i = values.fp - markStart, j = 0; j < values.length;
+ ++i, ++j) {
+
+ ca[(int)j] = cache[(int)i];
+ }
+
+
+ return ca;
+ } else {
+ return values.data;
+ }
+ }
+
+ protected void setupCache(long curMark) {
+
+ try {
+
+ FileReader fr = new FileReader(buff);
+ fr.skip(curMark);
+
+ long rem = buff.length() - curMark;
+ if (rem > csize) {
+
+ rem = csize;
+ }
+
+ fr.read(cache, 0, (int)rem);
+
+
+ markStart = curMark;
+ markEnd = rem - 1;
+
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+
+
+ }
+
+
}
diff --git a/src/org/apache/fop/tools/DocumentInputSource.java b/src/org/apache/fop/tools/DocumentInputSource.java
index 1228ce05a..2a382dbef 100644
--- a/src/org/apache/fop/tools/DocumentInputSource.java
+++ b/src/org/apache/fop/tools/DocumentInputSource.java
@@ -1,10 +1,10 @@
-/*
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
-
package org.apache.fop.tools;
import java.util.*;
@@ -18,31 +18,26 @@ import org.xml.sax.*;
*
*/
-public class DocumentInputSource extends InputSource
-{
+public class DocumentInputSource extends InputSource {
private Document _document;
-
- public DocumentInputSource()
- {
- super();
+
+ public DocumentInputSource() {
+ super();
}
-
- public DocumentInputSource(Document document)
- {
- this();
- _document = document;
+
+ public DocumentInputSource(Document document) {
+ this();
+ _document = document;
}
-
- public Document getDocument()
- {
- return _document;
+
+ public Document getDocument() {
+ return _document;
}
-
- public void setDocument(Document document)
- {
- _document = document;
+
+ public void setDocument(Document document) {
+ _document = document;
}
-
+
}
-
+
diff --git a/src/org/apache/fop/tools/DocumentReader.java b/src/org/apache/fop/tools/DocumentReader.java
index 2abdd537c..27421e490 100644
--- a/src/org/apache/fop/tools/DocumentReader.java
+++ b/src/org/apache/fop/tools/DocumentReader.java
@@ -1,14 +1,14 @@
-/*
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
-
package org.apache.fop.tools;
import java.io.IOException;
-//import java.util.*;
+// import java.util.*;
// DOM
import org.w3c.dom.*;
@@ -25,15 +25,14 @@ import org.xml.sax.helpers.AttributesImpl;
*
*/
-public class DocumentReader implements XMLReader
-{
-
- ////////////////////////////////////////////////////////////////////
+public class DocumentReader implements XMLReader {
+
+ // //////////////////////////////////////////////////////////////////
// Configuration.
- ////////////////////////////////////////////////////////////////////
+ // //////////////////////////////////////////////////////////////////
private boolean _namespaces = true;
private boolean _namespace_prefixes = true;
-
+
/**
* Look up the value of a feature.
@@ -57,24 +56,24 @@ public class DocumentReader implements XMLReader
*
* XMLReader r = new MySAXDriver();
*
- * // try to activate validation
+ * // try to activate validation
* try {
- * r.setFeature("http://xml.org/sax/features/validation", true);
+ * r.setFeature("http://xml.org/sax/features/validation", true);
* } catch (SAXException e) {
- * System.err.println("Cannot activate validation.");
+ * System.err.println("Cannot activate validation.");
* }
*
- * // register event handlers
+ * // register event handlers
* r.setContentHandler(new MyContentHandler());
* r.setErrorHandler(new MyErrorHandler());
*
- * // parse the first document
+ * // parse the first document
* try {
- * r.parse("http://www.foo.com/mydoc.xml");
+ * r.parse("http://www.foo.com/mydoc.xml");
* } catch (IOException e) {
- * System.err.println("I/O exception reading XML document");
+ * System.err.println("I/O exception reading XML document");
* } catch (SAXException e) {
- * System.err.println("XML exception reading document.");
+ * System.err.println("XML exception reading document.");
* }
*
*
@@ -84,27 +83,25 @@ public class DocumentReader implements XMLReader
* @param name The feature name, which is a fully-qualified URI.
* @return The current state of the feature (true or false).
* @exception org.xml.sax.SAXNotRecognizedException When the
- * XMLReader does not recognize the feature name.
+ * XMLReader does not recognize the feature name.
* @exception org.xml.sax.SAXNotSupportedException When the
- * XMLReader recognizes the feature name but
- * cannot determine its value at this time.
+ * XMLReader recognizes the feature name but
+ * cannot determine its value at this time.
* @see #setFeature
*/
- public boolean getFeature (String name)
- throws SAXNotRecognizedException, SAXNotSupportedException
- {
- if ("http://xml.org/sax/features/namespaces".equals(name)) {
- return _namespaces;
- }
- else if ("http://xml.org/sax/features/namespace-prefixes".equals(name)) {
- return _namespace_prefixes;
- }
- else {
- throw new SAXNotRecognizedException("Feature '"+name+"' not recognized or supported by Document2SAXAdapter");
- }
-
+ public boolean getFeature(String name)
+ throws SAXNotRecognizedException, SAXNotSupportedException {
+ if ("http://xml.org/sax/features/namespaces".equals(name)) {
+ return _namespaces;
+ } else if ("http://xml.org/sax/features/namespace-prefixes".equals(name)) {
+ return _namespace_prefixes;
+ } else {
+ throw new SAXNotRecognizedException("Feature '" + name
+ + "' not recognized or supported by Document2SAXAdapter");
+ }
+
}
-
+
/**
@@ -121,34 +118,32 @@ public class DocumentReader implements XMLReader
* http://xml.org/sax/features/namespaces to true and
* http://xml.org/sax/features/namespace-prefixes to false.
*
- * Some feature values may be immutable or mutable only
- * in specific contexts, such as before, during, or after
+ * Some feature values may be immutable or mutable only
+ * in specific contexts, such as before, during, or after
* a parse.
*
* @param name The feature name, which is a fully-qualified URI.
* @param state The requested state of the feature (true or false).
* @exception org.xml.sax.SAXNotRecognizedException When the
- * XMLReader does not recognize the feature name.
+ * XMLReader does not recognize the feature name.
* @exception org.xml.sax.SAXNotSupportedException When the
- * XMLReader recognizes the feature name but
- * cannot set the requested value.
+ * XMLReader recognizes the feature name but
+ * cannot set the requested value.
* @see #getFeature
*/
- public void setFeature (String name, boolean value)
- throws SAXNotRecognizedException, SAXNotSupportedException
- {
- if ("http://xml.org/sax/features/namespaces".equals(name)) {
- _namespaces = value;
- }
- else if ("http://xml.org/sax/features/namespace-prefixes".equals(name)) {
- _namespace_prefixes = value;
- }
- else {
- throw new SAXNotRecognizedException("Feature '"+name+"' not recognized or supported by Document2SAXAdapter");
- }
-
+ public void setFeature(String name, boolean value)
+ throws SAXNotRecognizedException, SAXNotSupportedException {
+ if ("http://xml.org/sax/features/namespaces".equals(name)) {
+ _namespaces = value;
+ } else if ("http://xml.org/sax/features/namespace-prefixes".equals(name)) {
+ _namespace_prefixes = value;
+ } else {
+ throw new SAXNotRecognizedException("Feature '" + name
+ + "' not recognized or supported by Document2SAXAdapter");
+ }
+
}
-
+
/**
@@ -173,18 +168,18 @@ public class DocumentReader implements XMLReader
* @param name The property name, which is a fully-qualified URI.
* @return The current value of the property.
* @exception org.xml.sax.SAXNotRecognizedException When the
- * XMLReader does not recognize the property name.
+ * XMLReader does not recognize the property name.
* @exception org.xml.sax.SAXNotSupportedException When the
- * XMLReader recognizes the property name but
- * cannot determine its value at this time.
+ * XMLReader recognizes the property name but
+ * cannot determine its value at this time.
* @see #setProperty
*/
- public Object getProperty (String name)
- throws SAXNotRecognizedException, SAXNotSupportedException
- {
- throw new SAXNotRecognizedException("Property '"+name+"' not recognized or supported by Document2SAXAdapter");
+ public Object getProperty(String name)
+ throws SAXNotRecognizedException, SAXNotSupportedException {
+ throw new SAXNotRecognizedException("Property '" + name
+ + "' not recognized or supported by Document2SAXAdapter");
}
-
+
/**
@@ -197,11 +192,11 @@ public class DocumentReader implements XMLReader
* Parser}.
*
* XMLReaders are not required to recognize setting
- * any specific property names, though a core set is provided with
+ * any specific property names, though a core set is provided with
* SAX2.
*
- * Some property values may be immutable or mutable only
- * in specific contexts, such as before, during, or after
+ * Some property values may be immutable or mutable only
+ * in specific contexts, such as before, during, or after
* a parse.
*
* This method is also the standard mechanism for setting
@@ -210,27 +205,27 @@ public class DocumentReader implements XMLReader
* @param name The property name, which is a fully-qualified URI.
* @param state The requested value for the property.
* @exception org.xml.sax.SAXNotRecognizedException When the
- * XMLReader does not recognize the property name.
+ * XMLReader does not recognize the property name.
* @exception org.xml.sax.SAXNotSupportedException When the
- * XMLReader recognizes the property name but
- * cannot set the requested value.
+ * XMLReader recognizes the property name but
+ * cannot set the requested value.
*/
- public void setProperty (String name, Object value)
- throws SAXNotRecognizedException, SAXNotSupportedException
- {
- throw new SAXNotRecognizedException("Property '"+name+"' not recognized or supported by Document2SAXAdapter");
+ public void setProperty(String name, Object value)
+ throws SAXNotRecognizedException, SAXNotSupportedException {
+ throw new SAXNotRecognizedException("Property '" + name
+ + "' not recognized or supported by Document2SAXAdapter");
}
- ////////////////////////////////////////////////////////////////////
+ // //////////////////////////////////////////////////////////////////
// Event handlers.
- ////////////////////////////////////////////////////////////////////
+ // //////////////////////////////////////////////////////////////////
private EntityResolver _entityResolver = null;
- private DTDHandler _dtdHandler = null;
+ private DTDHandler _dtdHandler = null;
private ContentHandler _contentHandler = null;
- private ErrorHandler _errorHandler = null;
-
+ private ErrorHandler _errorHandler = null;
+
/**
* Allow an application to register an entity resolver.
@@ -243,29 +238,27 @@ public class DocumentReader implements XMLReader
* resolver immediately.
*
* @param resolver The entity resolver.
- * @exception java.lang.NullPointerException If the resolver
- * argument is null.
+ * @exception java.lang.NullPointerException If the resolver
+ * argument is null.
* @see #getEntityResolver
*/
- public void setEntityResolver (EntityResolver resolver)
- {
- _entityResolver = resolver;
+ public void setEntityResolver(EntityResolver resolver) {
+ _entityResolver = resolver;
}
-
+
/**
* Return the current entity resolver.
*
* @return The current entity resolver, or null if none
- * has been registered.
+ * has been registered.
* @see #setEntityResolver
*/
- public EntityResolver getEntityResolver ()
- {
- return _entityResolver;
+ public EntityResolver getEntityResolver() {
+ return _entityResolver;
}
-
+
/**
@@ -279,29 +272,27 @@ public class DocumentReader implements XMLReader
* handler immediately.
*
* @param handler The DTD handler.
- * @exception java.lang.NullPointerException If the handler
- * argument is null.
+ * @exception java.lang.NullPointerException If the handler
+ * argument is null.
* @see #getDTDHandler
*/
- public void setDTDHandler (DTDHandler handler)
- {
- _dtdHandler = handler;
+ public void setDTDHandler(DTDHandler handler) {
+ _dtdHandler = handler;
}
-
+
/**
* Return the current DTD handler.
*
* @return The current DTD handler, or null if none
- * has been registered.
+ * has been registered.
* @see #setDTDHandler
*/
- public DTDHandler getDTDHandler ()
- {
- return _dtdHandler;
+ public DTDHandler getDTDHandler() {
+ return _dtdHandler;
}
-
+
/**
@@ -316,29 +307,27 @@ public class DocumentReader implements XMLReader
* handler immediately. |
*
* @param handler The content handler.
- * @exception java.lang.NullPointerException If the handler
- * argument is null.
+ * @exception java.lang.NullPointerException If the handler
+ * argument is null.
* @see #getContentHandler
*/
- public void setContentHandler (ContentHandler handler)
- {
- _contentHandler = handler;
+ public void setContentHandler(ContentHandler handler) {
+ _contentHandler = handler;
}
-
+
/**
* Return the current content handler.
*
* @return The current content handler, or null if none
- * has been registered.
+ * has been registered.
* @see #setContentHandler
*/
- public ContentHandler getContentHandler ()
- {
- return _contentHandler;
+ public ContentHandler getContentHandler() {
+ return _contentHandler;
}
-
+
/**
@@ -355,166 +344,163 @@ public class DocumentReader implements XMLReader
* handler immediately.
*
* @param handler The error handler.
- * @exception java.lang.NullPointerException If the handler
- * argument is null.
+ * @exception java.lang.NullPointerException If the handler
+ * argument is null.
* @see #getErrorHandler
*/
- public void setErrorHandler (ErrorHandler handler)
- {
- _errorHandler = handler;
+ public void setErrorHandler(ErrorHandler handler) {
+ _errorHandler = handler;
}
-
+
/**
* Return the current error handler.
*
* @return The current error handler, or null if none
- * has been registered.
+ * has been registered.
* @see #setErrorHandler
*/
- public ErrorHandler getErrorHandler ()
- {
- return _errorHandler;
+ public ErrorHandler getErrorHandler() {
+ return _errorHandler;
}
-
- ////////////////////////////////////////////////////////////////////
+
+ // //////////////////////////////////////////////////////////////////
// Parsing.
- ////////////////////////////////////////////////////////////////////
+ // //////////////////////////////////////////////////////////////////
/**
* Parse an XML DOM document.
*
- *
+ *
*
* @param source The input source for the top-level of the
- * XML document.
+ * XML document.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
- * wrapping another exception.
+ * wrapping another exception.
* @exception java.io.IOException An IO exception from the parser,
- * possibly from a byte stream or character stream
- * supplied by the application.
+ * possibly from a byte stream or character stream
+ * supplied by the application.
* @see org.xml.sax.InputSource
* @see #parse(java.lang.String)
* @see #setEntityResolver
* @see #setDTDHandler
* @see #setContentHandler
- * @see #setErrorHandler
+ * @see #setErrorHandler
*/
- public void parse (InputSource input)
- throws IOException, SAXException
- {
- if (input instanceof DocumentInputSource) {
- Document document = ((DocumentInputSource)input).getDocument();
- if (_contentHandler == null) {
- throw new SAXException("ContentHandler is null. Please use setContentHandler()");
- }
-
- // refactored from org.apache.fop.apps.Driver
- /* most of this code is modified from John Cowan's */
-
- Node currentNode;
- AttributesImpl currentAtts;
-
- /* temporary array for making Strings into character arrays */
- char[] array = null;
-
- currentAtts = new AttributesImpl();
-
- /* start at the document element */
- currentNode = document;
- while (currentNode != null) {
- switch (currentNode.getNodeType()) {
- case Node.DOCUMENT_NODE:
- _contentHandler.startDocument();
- break;
- case Node.CDATA_SECTION_NODE:
- case Node.TEXT_NODE:
- String data = currentNode.getNodeValue();
- int datalen = data.length();
- if (array == null || array.length < datalen) {
- /* if the array isn't big enough, make a new
- one */
- array = new char[datalen];
- }
- data.getChars(0, datalen, array, 0);
- _contentHandler.characters(array, 0, datalen);
- break;
- case Node.PROCESSING_INSTRUCTION_NODE:
- _contentHandler.processingInstruction(currentNode.getNodeName(),
- currentNode.getNodeValue());
- break;
- case Node.ELEMENT_NODE:
- NamedNodeMap map = currentNode.getAttributes();
- currentAtts.clear();
- for (int i = map.getLength() - 1; i >= 0; i--) {
- Attr att = (Attr) map.item(i);
- currentAtts.addAttribute( att.getNamespaceURI(),
- att.getLocalName(), att.getName(),
- "CDATA", att.getValue());
- }
- _contentHandler.startElement(currentNode.getNamespaceURI(),
- currentNode.getLocalName(),
- currentNode.getNodeName(),
- currentAtts);
- break;
+ public void parse(InputSource input) throws IOException, SAXException {
+ if (input instanceof DocumentInputSource) {
+ Document document = ((DocumentInputSource)input).getDocument();
+ if (_contentHandler == null) {
+ throw new SAXException("ContentHandler is null. Please use setContentHandler()");
+ }
+
+ // refactored from org.apache.fop.apps.Driver
+ /* most of this code is modified from John Cowan's */
+
+ Node currentNode;
+ AttributesImpl currentAtts;
+
+ /* temporary array for making Strings into character arrays */
+ char[] array = null;
+
+ currentAtts = new AttributesImpl();
+
+ /* start at the document element */
+ currentNode = document;
+ while (currentNode != null) {
+ switch (currentNode.getNodeType()) {
+ case Node.DOCUMENT_NODE:
+ _contentHandler.startDocument();
+ break;
+ case Node.CDATA_SECTION_NODE:
+ case Node.TEXT_NODE:
+ String data = currentNode.getNodeValue();
+ int datalen = data.length();
+ if (array == null || array.length < datalen) {
+ /*
+ * if the array isn't big enough, make a new
+ * one
+ */
+ array = new char[datalen];
+ }
+ data.getChars(0, datalen, array, 0);
+ _contentHandler.characters(array, 0, datalen);
+ break;
+ case Node.PROCESSING_INSTRUCTION_NODE:
+ _contentHandler.processingInstruction(currentNode.getNodeName(),
+ currentNode.getNodeValue());
+ break;
+ case Node.ELEMENT_NODE:
+ NamedNodeMap map = currentNode.getAttributes();
+ currentAtts.clear();
+ for (int i = map.getLength() - 1; i >= 0; i--) {
+ Attr att = (Attr)map.item(i);
+ currentAtts.addAttribute(att.getNamespaceURI(),
+ att.getLocalName(),
+ att.getName(), "CDATA",
+ att.getValue());
+ }
+ _contentHandler.startElement(currentNode.getNamespaceURI(),
+ currentNode.getLocalName(),
+ currentNode.getNodeName(),
+ currentAtts);
+ break;
}
-
+
Node nextNode = currentNode.getFirstChild();
if (nextNode != null) {
currentNode = nextNode;
continue;
}
-
+
while (currentNode != null) {
switch (currentNode.getNodeType()) {
- case Node.DOCUMENT_NODE:
- _contentHandler.endDocument();
- break;
- case Node.ELEMENT_NODE:
- _contentHandler.endElement(currentNode.getNamespaceURI(),
- currentNode.getLocalName(),
- currentNode.getNodeName());
- break;
+ case Node.DOCUMENT_NODE:
+ _contentHandler.endDocument();
+ break;
+ case Node.ELEMENT_NODE:
+ _contentHandler.endElement(currentNode.getNamespaceURI(),
+ currentNode.getLocalName(),
+ currentNode.getNodeName());
+ break;
}
-
+
nextNode = currentNode.getNextSibling();
if (nextNode != null) {
currentNode = nextNode;
break;
}
-
+
currentNode = currentNode.getParentNode();
}
}
-
- }
- else {
- throw new SAXException("DocumentReader only supports parsing of a DocumentInputSource");
- }
-
+
+ } else {
+ throw new SAXException("DocumentReader only supports parsing of a DocumentInputSource");
+ }
+
}
-
+
/**
* DocumentReader requires a DocumentInputSource, so this is not
- * implements and simply throws a SAXException. Use parse(DocumentInputSource)
+ * implements and simply throws a SAXException. Use parse(DocumentInputSource)
* instead
- *
+ *
* @param systemId The system identifier (URI).
* @exception org.xml.sax.SAXException Any SAX exception, possibly
- * wrapping another exception.
+ * wrapping another exception.
* @exception java.io.IOException An IO exception from the parser,
- * possibly from a byte stream or character stream
- * supplied by the application.
+ * possibly from a byte stream or character stream
+ * supplied by the application.
* @see #parse(org.xml.sax.InputSource)
*/
- public void parse (String systemId)
- throws IOException, SAXException
- {
- throw new SAXException("DocumentReader only supports parsing of a DocumentInputSource");
+ public void parse(String systemId) throws IOException, SAXException {
+ throw new SAXException("DocumentReader only supports parsing of a DocumentInputSource");
}
+
}
-
+
diff --git a/src/org/apache/fop/tools/TestConverter.java b/src/org/apache/fop/tools/TestConverter.java
index c3328377b..3f4538d32 100644
--- a/src/org/apache/fop/tools/TestConverter.java
+++ b/src/org/apache/fop/tools/TestConverter.java
@@ -1,4 +1,5 @@
/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -73,8 +74,7 @@ public class TestConverter {
tc.runTests(testFile, "results", null);
}
- public TestConverter() {
- }
+ public TestConverter() {}
public void setOutputPDF(boolean pdf) {
outputPDF = pdf;
@@ -94,7 +94,7 @@ public class TestConverter {
* The document is read as a dom and each testcase is covered.
*/
public Hashtable runTests(String fname, String dest, String compDir) {
- //System.out.println("running tests in file:" + fname);
+ // System.out.println("running tests in file:" + fname);
try {
if (compDir != null) {
compare = new File(baseDir + "/" + compDir);
@@ -103,7 +103,7 @@ public class TestConverter {
destdir.mkdirs();
File f = new File(baseDir + "/" + fname);
DocumentBuilderFactory factory =
- DocumentBuilderFactory.newInstance();
+ DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
Document doc = db.parse(f);
@@ -116,9 +116,9 @@ public class TestConverter {
testsuite = doc.getDocumentElement();
if (testsuite.hasAttributes()) {
- String profile = testsuite.getAttributes().getNamedItem(
- "profile").getNodeValue();
- //System.out.println("testing test suite:" + profile);
+ String profile =
+ testsuite.getAttributes().getNamedItem("profile").getNodeValue();
+ // System.out.println("testing test suite:" + profile);
}
NodeList testcases = testsuite.getChildNodes();
for (int count = 0; count < testcases.getLength(); count++) {
@@ -141,9 +141,9 @@ public class TestConverter {
*/
protected void runTestCase(Node tcase) {
if (tcase.hasAttributes()) {
- String profile = tcase.getAttributes().getNamedItem(
- "profile").getNodeValue();
- //System.out.println("testing profile:" + profile);
+ String profile =
+ tcase.getAttributes().getNamedItem("profile").getNodeValue();
+ // System.out.println("testing profile:" + profile);
}
NodeList cases = tcase.getChildNodes();
for (int count = 0; count < cases.getLength(); count++) {
@@ -153,8 +153,7 @@ public class TestConverter {
runTestCase(node);
} else if (nodename.equals("test")) {
runTest(tcase, node);
- } else if (nodename.equals("result")) {
- }
+ } else if (nodename.equals("result")) {}
}
}
@@ -171,8 +170,8 @@ public class TestConverter {
Node result = locateResult(testcase, id);
boolean pass = false;
if (result != null) {
- String agreement = result.getAttributes().getNamedItem(
- "agreement").getNodeValue();
+ String agreement =
+ result.getAttributes().getNamedItem("agreement").getNodeValue();
pass = agreement.equals("full");
}
@@ -180,15 +179,14 @@ public class TestConverter {
return;
}
- String xml =
- test.getAttributes().getNamedItem("xml").getNodeValue();
+ String xml = test.getAttributes().getNamedItem("xml").getNodeValue();
Node xslNode = test.getAttributes().getNamedItem("xsl");
String xsl = null;
if (xslNode != null) {
xsl = xslNode.getNodeValue();
}
- //System.out.println("converting xml:" + xml + " and xsl:" +
- // xsl + " to area tree");
+ // System.out.println("converting xml:" + xml + " and xsl:" +
+ // xsl + " to area tree");
try {
File xmlFile = new File(baseDir + "/" + xml);
@@ -205,7 +203,8 @@ public class TestConverter {
inputHandler = new FOInputHandler(xmlFile);
} else {
inputHandler = new XSLTInputHandler(xmlFile,
- new File(baseDir + "/" + xsl));
+ new File(baseDir + "/"
+ + xsl));
}
XMLReader parser = inputHandler.getParser();
@@ -229,9 +228,9 @@ public class TestConverter {
if (outname.endsWith(".xml")) {
outname = outname.substring(0, outname.length() - 4);
}
- driver.setOutputStream( new FileOutputStream(
- new File(destdir, outname + (outputPDF ? ".pdf" : ".at.xml"))));
- //System.out.println("ddir:" + destdir + " on:" + outname + ".pdf");
+ driver.setOutputStream(new FileOutputStream(new File(destdir,
+ outname + (outputPDF ? ".pdf" : ".at.xml"))));
+ // System.out.println("ddir:" + destdir + " on:" + outname + ".pdf");
driver.render();
// check difference
@@ -265,19 +264,17 @@ public class TestConverter {
return false;
}
}
- } catch (Exception e) {
- }
+ } catch (Exception e) {}
return false;
}
- public void setParserFeatures (XMLReader parser) throws FOPException {
+ public void setParserFeatures(XMLReader parser) throws FOPException {
try {
parser.setFeature("http://xml.org/sax/features/namespace-prefixes",
true);
} catch (SAXException e) {
- throw new FOPException(
- "Error in setting up parser feature namespace-prefixes\n" +
- "You need a parser which supports SAX version 2",e);
+ throw new FOPException("Error in setting up parser feature namespace-prefixes\n"
+ + "You need a parser which supports SAX version 2", e);
}
}
@@ -287,8 +284,8 @@ public class TestConverter {
Node node = cases.item(count);
String nodename = node.getNodeName();
if (nodename.equals("result")) {
- String resultid = node.getAttributes().getNamedItem(
- "id").getNodeValue();
+ String resultid =
+ node.getAttributes().getNamedItem("id").getNodeValue();
if (id.equals(resultid)) {
return node;
}
@@ -296,4 +293,5 @@ public class TestConverter {
}
return null;
}
+
}
diff --git a/src/org/apache/fop/tools/anttasks/Compare.java b/src/org/apache/fop/tools/anttasks/Compare.java
index effc7fb88..20e401ea8 100644
--- a/src/org/apache/fop/tools/anttasks/Compare.java
+++ b/src/org/apache/fop/tools/anttasks/Compare.java
@@ -1,56 +1,10 @@
/*
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 1999 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowlegement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowlegement may appear in the software itself,
- * if and wherever such third-party acknowlegements normally appear.
- *
- * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Group.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.tools.anttasks;
@@ -60,141 +14,158 @@ import org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;
import java.text.DateFormat;
- /** This class is an extension of Ant, a script utility from
- * jakarta.apache.org.
- * It provides methods to compare two files
- */
+/**
+ * This class is an extension of Ant, a script utility from
+ * jakarta.apache.org.
+ * It provides methods to compare two files
+ */
public class Compare {
- private String referenceDirectory, testDirectory;
- private String [] filenameList;
- private String filenames;
- private static boolean IDENTICAL_FILES = true;
- private static boolean NOTIDENTICAL_FILES = false;
- private BufferedInputStream oldfileInput;
- private BufferedInputStream newfileInput;
-
- //sets directory for test files
- public void setTestDirectory(String testDirectory) {
- if (!(testDirectory.endsWith("/") | testDirectory.endsWith("\\"))) {
- testDirectory += File.separator;
- }
- this.testDirectory = testDirectory;
- }
-
- //sets directory for reference files
- public void setReferenceDirectory(String referenceDirectory) {
- if (!(referenceDirectory.endsWith("/") | referenceDirectory.endsWith("\\"))) {
- referenceDirectory += File.separator;
+ private String referenceDirectory, testDirectory;
+ private String[] filenameList;
+ private String filenames;
+ private static boolean IDENTICAL_FILES = true;
+ private static boolean NOTIDENTICAL_FILES = false;
+ private BufferedInputStream oldfileInput;
+ private BufferedInputStream newfileInput;
+
+ // sets directory for test files
+ public void setTestDirectory(String testDirectory) {
+ if (!(testDirectory.endsWith("/") | testDirectory.endsWith("\\"))) {
+ testDirectory += File.separator;
+ }
+ this.testDirectory = testDirectory;
}
- this.referenceDirectory = referenceDirectory;
- }
-
- public void setFilenames (String filenames) {
- StringTokenizer tokens = new StringTokenizer(filenames,",");
- Vector filenameListTmp = new Vector(20);
- while (tokens.hasMoreTokens()) {
- filenameListTmp.addElement(tokens.nextToken());
+
+ // sets directory for reference files
+ public void setReferenceDirectory(String referenceDirectory) {
+ if (!(referenceDirectory.endsWith("/")
+ | referenceDirectory.endsWith("\\"))) {
+ referenceDirectory += File.separator;
+ }
+ this.referenceDirectory = referenceDirectory;
}
- filenameList = new String [filenameListTmp.size()] ;
- filenameListTmp.copyInto((String[]) filenameList);
- }
-
- private boolean compareBytes (File oldFile, File newFile) {
- try {
- oldfileInput = new BufferedInputStream(new FileInputStream(oldFile));
- newfileInput = new BufferedInputStream(new FileInputStream(newFile));
- int charactO = 0;
- int charactN = 0;
- boolean identical = true;
-
- while (identical & (charactO != -1)) {
- if (charactO == charactN) {
- charactO = oldfileInput.read();
- charactN = newfileInput.read();
- } else {
- return NOTIDENTICAL_FILES;
+
+ public void setFilenames(String filenames) {
+ StringTokenizer tokens = new StringTokenizer(filenames, ",");
+ Vector filenameListTmp = new Vector(20);
+ while (tokens.hasMoreTokens()) {
+ filenameListTmp.addElement(tokens.nextToken());
}
- }
- return IDENTICAL_FILES;
- } catch (IOException io) {
- System.err.println("Task Compare - Error: \n" + io.toString());
+ filenameList = new String[filenameListTmp.size()];
+ filenameListTmp.copyInto((String[])filenameList);
}
- return NOTIDENTICAL_FILES;
- }
-
- private boolean compareFileSize(File oldFile, File newFile) {
- if (oldFile.length() != newFile.length()) {
- return NOTIDENTICAL_FILES;
- } else {
- return IDENTICAL_FILES;
+
+ private boolean compareBytes(File oldFile, File newFile) {
+ try {
+ oldfileInput =
+ new BufferedInputStream(new FileInputStream(oldFile));
+ newfileInput =
+ new BufferedInputStream(new FileInputStream(newFile));
+ int charactO = 0;
+ int charactN = 0;
+ boolean identical = true;
+
+ while (identical & (charactO != -1)) {
+ if (charactO == charactN) {
+ charactO = oldfileInput.read();
+ charactN = newfileInput.read();
+ } else {
+ return NOTIDENTICAL_FILES;
+ }
+ }
+ return IDENTICAL_FILES;
+ } catch (IOException io) {
+ System.err.println("Task Compare - Error: \n" + io.toString());
+ }
+ return NOTIDENTICAL_FILES;
}
- } //end: compareBytes
-
- private boolean filesExist (File oldFile, File newFile) {
- if (!oldFile.exists()) {
- System.err.println("Task Compare - ERROR: File "
- + referenceDirectory + oldFile.getName()
- + " doesn't exist!");
- return false;
- } else if (!newFile.exists()) {
- System.err.println("Task Compare - ERROR: File "
- + testDirectory + newFile.getName() + " doesn't exist!");
- return false;
- } else {
- return true;
+
+ private boolean compareFileSize(File oldFile, File newFile) {
+ if (oldFile.length() != newFile.length()) {
+ return NOTIDENTICAL_FILES;
+ } else {
+ return IDENTICAL_FILES;
+ }
+ } // end: compareBytes
+
+ private boolean filesExist(File oldFile, File newFile) {
+ if (!oldFile.exists()) {
+ System.err.println("Task Compare - ERROR: File "
+ + referenceDirectory + oldFile.getName()
+ + " doesn't exist!");
+ return false;
+ } else if (!newFile.exists()) {
+ System.err.println("Task Compare - ERROR: File " + testDirectory
+ + newFile.getName() + " doesn't exist!");
+ return false;
+ } else {
+ return true;
+ }
}
- }
-
- public void writeHeader (PrintWriter results) {
- String dateTime = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM).format(new Date());
- results.println("Test Results\n");
- results.println("Compare Results
");
- results.println("created " + dateTime + "
");
- results.println("reference file | test file | "
- + "identical? | ");
-
-
- }
-
- //main method of task compare
- public void execute () throws BuildException {
- boolean identical = false;
- File oldFile;
- File newFile;
- try {
- PrintWriter results = new PrintWriter (new FileWriter("results.html"),true);
- this.writeHeader(results);
- for (int i = 0; i < filenameList.length; i++) {
- oldFile = new File (referenceDirectory + filenameList[i]);
- newFile = new File (testDirectory + filenameList[i]);
- if (filesExist(oldFile, newFile)) {
- identical = compareFileSize(oldFile, newFile);
- if (identical) {
- identical = compareBytes(oldFile,newFile);
- }
- if (!identical) {
- System.out.println("Task Compare: \nFiles " + referenceDirectory
- + oldFile.getName()+ " - " + testDirectory
- + newFile.getName() + " are *not* identical.");
- results.println(""
- + oldFile.getName() + " | "
- + newFile.getName() +""
- + " | No |
");
- } else {
- results.println(""
- + oldFile.getName() + " | "
- + newFile.getName() + ""
- + " | Yes |
");
- }
- }
- }
- results.println("
");
- } catch (IOException ioe) {
- System.err.println("ERROR: " + ioe);
+
+ public void writeHeader(PrintWriter results) {
+ String dateTime = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
+ DateFormat.MEDIUM).format(new Date());
+ results.println("Test Results\n");
+ results.println("Compare Results
");
+ results.println("created " + dateTime
+ + "
");
+ results.println("reference file | test file | "
+ + "identical? | ");
+
+
}
- } //end: execute()
+
+ // main method of task compare
+ public void execute() throws BuildException {
+ boolean identical = false;
+ File oldFile;
+ File newFile;
+ try {
+ PrintWriter results =
+ new PrintWriter(new FileWriter("results.html"), true);
+ this.writeHeader(results);
+ for (int i = 0; i < filenameList.length; i++) {
+ oldFile = new File(referenceDirectory + filenameList[i]);
+ newFile = new File(testDirectory + filenameList[i]);
+ if (filesExist(oldFile, newFile)) {
+ identical = compareFileSize(oldFile, newFile);
+ if (identical) {
+ identical = compareBytes(oldFile, newFile);
+ }
+ if (!identical) {
+ System.out.println("Task Compare: \nFiles "
+ + referenceDirectory
+ + oldFile.getName() + " - "
+ + testDirectory
+ + newFile.getName()
+ + " are *not* identical.");
+ results.println(""
+ + oldFile.getName()
+ + " | " + newFile.getName() + ""
+ + " | No |
");
+ } else {
+ results.println(""
+ + oldFile.getName()
+ + " | " + newFile.getName() + ""
+ + " | Yes |
");
+ }
+ }
+ }
+ results.println("
");
+ } catch (IOException ioe) {
+ System.err.println("ERROR: " + ioe);
+ }
+ } // end: execute()
+
}
diff --git a/src/org/apache/fop/tools/anttasks/CompileXMLFiles.java b/src/org/apache/fop/tools/anttasks/CompileXMLFiles.java
index 0a9ab2af5..15568d03f 100644
--- a/src/org/apache/fop/tools/anttasks/CompileXMLFiles.java
+++ b/src/org/apache/fop/tools/anttasks/CompileXMLFiles.java
@@ -1,68 +1,20 @@
/*
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 1999 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowlegement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowlegement may appear in the software itself,
- * if and wherever such third-party acknowlegements normally appear.
- *
- * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Group.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
- *
- *
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.tools.anttasks;
- /** This class is an extension of Ant, a script utility from
- jakarta.apache.org.
- It takes a couple of xml files conforming to the xml-site dtd and
- writes them all into one xml file, deleting any reference to
- the proprietary protocol sbk. The configFile determines what files
- are read in what sequence.
- */
+/**
+ * This class is an extension of Ant, a script utility from
+ * jakarta.apache.org.
+ * It takes a couple of xml files conforming to the xml-site dtd and
+ * writes them all into one xml file, deleting any reference to
+ * the proprietary protocol sbk. The configFile determines what files
+ * are read in what sequence.
+ */
// Ant
import org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;
@@ -81,216 +33,202 @@ import java.io.*;
import java.util.*;
import java.net.URL;
-public class CompileXMLFiles extends Task
- implements org.xml.sax.EntityResolver,
- org.xml.sax.DTDHandler,
- org.xml.sax.DocumentHandler,
- org.xml.sax.ErrorHandler {
- private String configFile, outFile;
- private String [] filenameList;
- private String filenames;
- private Vector files = new Vector();
-
- //sets name of configuration file, which must
- //be an xml file conforming to the book.dtd used by xml-site
- public void setConfigFile(String configFile) {
- this.configFile = configFile;
- }
-
- public void setOutFile(String outFile) {
- this.outFile = outFile;
- }
-
-
- //main method of this task
- public void execute () throws BuildException {
- boolean errors = false;
-
- if (!(new File(configFile).exists())) {
- errors = true;
- System.err.println("Task CompileXMLFiles - ERROR: config file " + configFile + " is missing.");
+public class CompileXMLFiles extends Task
+ implements org.xml.sax.EntityResolver, org.xml.sax.DTDHandler,
+ org.xml.sax.DocumentHandler, org.xml.sax.ErrorHandler {
+ private String configFile, outFile;
+ private String[] filenameList;
+ private String filenames;
+ private Vector files = new Vector();
+
+ // sets name of configuration file, which must
+ // be an xml file conforming to the book.dtd used by xml-site
+ public void setConfigFile(String configFile) {
+ this.configFile = configFile;
+ }
+
+ public void setOutFile(String outFile) {
+ this.outFile = outFile;
+ }
+
+
+ // main method of this task
+ public void execute() throws BuildException {
+ boolean errors = false;
+
+ if (!(new File(configFile).exists())) {
+ errors = true;
+ System.err.println("Task CompileXMLFiles - ERROR: config file "
+ + configFile + " is missing.");
+ }
+
+ Parser parser = createParser();
+
+ if (parser == null) {
+ System.err.println("Task CompileXMLFiles - ERROR: Unable to create SAX parser");
+ errors = true;
+ }
+ parser.setDocumentHandler(this);
+ try {
+ parser.parse(CompileXMLFiles.fileInputSource(configFile));
+ } catch (SAXException e) {
+ System.out.println(e);
+ } catch (IOException ioe) {
+ System.out.println(ioe);
+ }
+ } // end: execute()
+
+
+ /* the following methods belong to the sax parser and implement the Document Handler */
+ public InputSource resolveEntity(String publicId,
+ String systemId) throws SAXException {
+ return null;
}
-
- Parser parser = createParser();
-
- if (parser == null) {
- System.err.println("Task CompileXMLFiles - ERROR: Unable to create SAX parser");
- errors = true;
+
+ public void notationDecl(String name, String publicId, String systemId) {
+ // no op
}
- parser.setDocumentHandler(this);
- try {
- parser.parse(CompileXMLFiles.fileInputSource(configFile));
- } catch (SAXException e) {
- System.out.println(e);
- } catch (IOException ioe) {
- System.out.println(ioe);
+
+ public void unparsedEntityDecl(String name, String publicId,
+ String systemId, String notationName) {
+ // no op
}
- } //end: execute()
-
-
- /*the following methods belong to the sax parser and implement the Document Handler*/
- public InputSource resolveEntity (String publicId, String systemId)
- throws SAXException
- {
- return null;
- }
-
- public void notationDecl (String name, String publicId, String systemId)
- {
- // no op
- }
-
- public void unparsedEntityDecl (String name, String publicId,
- String systemId, String notationName)
- {
- // no op
- }
-
- public void setDocumentLocator (Locator locator)
- {
- // no op
- }
-
- public void startDocument ()
- throws SAXException
- {
- // no op
- }
-
- /* After the cnfiguration file has been parsed all files which
- have been collected in the ArrayList files are concatinated
- and written to a new (temporary) file */
- public void endDocument ()
- throws SAXException
- {
- String line, filename;
- BufferedReader in;
- Enumeration iterator = files.elements();
- try {
- BufferedWriter out =
- new BufferedWriter (new FileWriter("compileXMLFiles-tmp.xml"));
- out.write("\n" +
- "\n" +
- "]>\n");
- while (iterator.hasMoreElements()) {
- filename = (String) iterator.nextElement();
- in = new BufferedReader(new FileReader(filename));
- while ((line = in.readLine()) != null) {
- //kill the lines pointing to the sbk protocol and the xml declaration
- if (line.indexOf("\n"
+ + "\n" + "]>\n");
+ while (iterator.hasMoreElements()) {
+ filename = (String)iterator.nextElement();
+ in = new BufferedReader(new FileReader(filename));
+ while ((line = in.readLine()) != null) {
+ // kill the lines pointing to the sbk protocol and the xml declaration
+ if (line.indexOf("");
+ out.close();
+ } catch (Exception e) {
+ System.out.println(e);
}
- out.flush();
- }
- out.write("\n");
- out.close();
- } catch (Exception e) {
- System.out.println(e);
+
}
-
- }
-
- public void startElement (String name, AttributeList atts)
- throws SAXException {
- String id, label, source;
- if (name.equals("document") || name.equals("entry")) {
- source = atts.getValue("source");
- files.addElement(source);
+
+ public void startElement(String name,
+ AttributeList atts) throws SAXException {
+ String id, label, source;
+ if (name.equals("document") || name.equals("entry")) {
+ source = atts.getValue("source");
+ files.addElement(source);
+ }
+ }
+
+ public void endElement(String name) throws SAXException {
+ // no op
}
- }
- public void endElement (String name)
- throws SAXException
- {
- // no op
- }
-
- public void characters (char ch[], int start, int length)
- throws SAXException
- {
- // no op
- }
-
- public void ignorableWhitespace (char ch[], int start, int length)
- throws SAXException
- {
- // no op
- }
- public void processingInstruction (String target, String data)
- throws SAXException
- {
- // no op
- }
-
- public void warning (SAXParseException e)
- throws SAXException
- {
- // no op
- }
- public void error (SAXParseException e)
- throws SAXException
- {
- // no op
- }
-
- public void fatalError (SAXParseException e)
- throws SAXException
- {
- throw e;
- }
-
- /* ------------------------*/
- /**
- * creates a SAX parser, using the value of org.xml.sax.parser
- * defaulting to org.apache.xerces.parsers.SAXParser
- *
- * @return the created SAX parser
- */
- static Parser createParser() {
- String parserClassName = System.getProperty("org.xml.sax.parser");
- if (parserClassName == null) {
- parserClassName = "org.apache.xerces.parsers.SAXParser";
+
+ public void characters(char ch[], int start,
+ int length) throws SAXException {
+ // no op
}
- System.err.println("using SAX parser " + parserClassName);
-
- try {
- return (Parser) Class.forName(parserClassName).newInstance();
- } catch (ClassNotFoundException e) {
- System.err.println("Could not find " + parserClassName);
- } catch (InstantiationException e) {
- System.err.println("Could not instantiate " + parserClassName);
- } catch (IllegalAccessException e) {
- System.err.println("Could not access " + parserClassName);
- } catch (ClassCastException e) {
- System.err.println(parserClassName + " is not a SAX driver");
+
+ public void ignorableWhitespace(char ch[], int start,
+ int length) throws SAXException {
+ // no op
}
- return null;
- }
-
- /**
- * create an InputSource from a file name
- *
- * @param filename the name of the file
- * @return the InputSource created
- */
- protected static InputSource fileInputSource(String filename) {
-
- /* this code adapted from James Clark's in XT */
- File file = new File(filename);
- String path = file.getAbsolutePath();
- String fSep = System.getProperty("file.separator");
- if (fSep != null && fSep.length() == 1)
- path = path.replace(fSep.charAt(0), '/');
- if (path.length() > 0 && path.charAt(0) != '/')
- path = '/' + path;
- try {
- return new InputSource(new URL("file", null, path).toString());
- } catch (java.net.MalformedURLException e) {
- throw new Error("unexpected MalformedURLException");
+
+ public void processingInstruction(String target,
+ String data) throws SAXException {
+ // no op
+ }
+
+ public void warning(SAXParseException e) throws SAXException {
+ // no op
+ }
+
+ public void error(SAXParseException e) throws SAXException {
+ // no op
}
- }
-
+
+ public void fatalError(SAXParseException e) throws SAXException {
+ throw e;
+ }
+
+ /* ------------------------ */
+
+ /**
+ * creates a SAX parser, using the value of org.xml.sax.parser
+ * defaulting to org.apache.xerces.parsers.SAXParser
+ *
+ * @return the created SAX parser
+ */
+ static Parser createParser() {
+ String parserClassName = System.getProperty("org.xml.sax.parser");
+ if (parserClassName == null) {
+ parserClassName = "org.apache.xerces.parsers.SAXParser";
+ }
+ System.err.println("using SAX parser " + parserClassName);
+
+ try {
+ return (Parser)Class.forName(parserClassName).newInstance();
+ } catch (ClassNotFoundException e) {
+ System.err.println("Could not find " + parserClassName);
+ } catch (InstantiationException e) {
+ System.err.println("Could not instantiate " + parserClassName);
+ } catch (IllegalAccessException e) {
+ System.err.println("Could not access " + parserClassName);
+ } catch (ClassCastException e) {
+ System.err.println(parserClassName + " is not a SAX driver");
+ }
+ return null;
+ }
+
+ /**
+ * create an InputSource from a file name
+ *
+ * @param filename the name of the file
+ * @return the InputSource created
+ */
+ protected static InputSource fileInputSource(String filename) {
+
+ /* this code adapted from James Clark's in XT */
+ File file = new File(filename);
+ String path = file.getAbsolutePath();
+ String fSep = System.getProperty("file.separator");
+ if (fSep != null && fSep.length() == 1)
+ path = path.replace(fSep.charAt(0), '/');
+ if (path.length() > 0 && path.charAt(0) != '/')
+ path = '/' + path;
+ try {
+ return new InputSource(new URL("file", null, path).toString());
+ } catch (java.net.MalformedURLException e) {
+ throw new Error("unexpected MalformedURLException");
+ }
+ }
+
}
diff --git a/src/org/apache/fop/tools/anttasks/Fop.java b/src/org/apache/fop/tools/anttasks/Fop.java
index a04810903..4369c7119 100644
--- a/src/org/apache/fop/tools/anttasks/Fop.java
+++ b/src/org/apache/fop/tools/anttasks/Fop.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -34,10 +35,10 @@ import org.apache.fop.configuration.Configuration;
* Wrapper for Fop which allows it to be accessed from within an Ant task.
* Accepts the inputs:
*
- * - fofile -> formatting objects file to be transformed
- * - pdffile -> output filename
- * - baseDir -> directory to work from
- * - messagelevel -> (info | verbose | debug) level to output non-error messages
+ * - fofile -> formatting objects file to be transformed
+ * - pdffile -> output filename
+ * - baseDir -> directory to work from
+ * - messagelevel -> (info | verbose | debug) level to output non-error messages
*
*/
public class Fop extends Task {
@@ -96,8 +97,8 @@ public class Fop extends Task {
} else if (messageLevel.equalsIgnoreCase("debug")) {
messageType = Project.MSG_DEBUG;
} else {
- log("messagelevel set to unknown value \"" + messageLevel +
- "\"", Project.MSG_ERR);
+ log("messagelevel set to unknown value \"" + messageLevel + "\"",
+ Project.MSG_ERR);
throw new BuildException("unknown messagelevel");
}
}
@@ -128,7 +129,7 @@ public class Fop extends Task {
/**
* Starts execution of this task
*/
- public void execute () throws BuildException {
+ public void execute() throws BuildException {
try {
Starter starter = new FOPTaskStarter(this);
starter.run();
@@ -137,6 +138,7 @@ public class Fop extends Task {
}
}
+
}
class FOPTaskStarter extends Starter {
@@ -150,10 +152,11 @@ class FOPTaskStarter extends Starter {
logger.setMessageLevel(task.getMessageType());
}
- public void run () throws FOPException {
+ public void run() throws FOPException {
try {
- //Configuration.put("baseDir", task.getBasedir().toURL().toExternalForm());
- Configuration.put("baseDir", task.getFofile().getParentFile().toURL().toExternalForm());
+ // Configuration.put("baseDir", task.getBasedir().toURL().toExternalForm());
+ Configuration.put("baseDir",
+ task.getFofile().getParentFile().toURL().toExternalForm());
} catch (Exception e) {
task.log("Error setting base directory", Project.MSG_DEBUG);
}
@@ -170,14 +173,13 @@ class FOPTaskStarter extends Starter {
throw new BuildException(ex);
}
- task.log("Using base directory: " +
- Configuration.getValue("baseDir"), Project.MSG_DEBUG);
- task.log(task.getFofile().getName() + " -> " +
- task.getPdffile().getName(), Project.MSG_INFO);
+ task.log("Using base directory: "
+ + Configuration.getValue("baseDir"), Project.MSG_DEBUG);
+ task.log(task.getFofile().getName() + " -> "
+ + task.getPdffile().getName(), Project.MSG_INFO);
try {
- Driver driver =
- new Driver(inputHandler.getInputSource(), pdfOut);
+ Driver driver = new Driver(inputHandler.getInputSource(), pdfOut);
driver.setRenderer(Driver.RENDER_PDF);
driver.setXMLReader(parser);
driver.run();
@@ -187,6 +189,7 @@ class FOPTaskStarter extends Starter {
}
logger.die();
}
+
}
class MessageLogger implements MessageListener {
@@ -245,8 +248,7 @@ class MessageLogger implements MessageListener {
}
for (int i = 0; !flushed && i < breakChars.length(); i++) {
- if (event.getMessage().lastIndexOf(breakChars.charAt(i)) !=
- -1) {
+ if (event.getMessage().lastIndexOf(breakChars.charAt(i)) != -1) {
flush();
flushed = true;
}
@@ -254,8 +256,8 @@ class MessageLogger implements MessageListener {
}
public void flush() {
- StringTokenizer output =
- new StringTokenizer(cache.toString(), "\n", false);
+ StringTokenizer output = new StringTokenizer(cache.toString(), "\n",
+ false);
while (output.hasMoreElements()) {
task.log(output.nextElement().toString(), lastMessageLevel);
}
@@ -269,4 +271,5 @@ class MessageLogger implements MessageListener {
// multiple tags in a buildfile
handler.removeListener(this);
}
+
}
diff --git a/src/org/apache/fop/tools/anttasks/Manifest.java b/src/org/apache/fop/tools/anttasks/Manifest.java
index f0e7c68a0..3c7820348 100644
--- a/src/org/apache/fop/tools/anttasks/Manifest.java
+++ b/src/org/apache/fop/tools/anttasks/Manifest.java
@@ -1,7 +1,8 @@
-/*
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
- * For details on use and redistribution please refer to the
- * LICENSE file included with these sources."
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.tools.anttasks;
@@ -22,42 +23,43 @@ import java.util.Properties;
*
* Attributes are as follows:
*
- * - file
- the manifest file to write out to (required)
- * - overwrite
- if set to yes or true, overwrite the given
- * manifest file. Default is no
- * - version
- manifest version. Defaults to "1.0"
- * - spectitle
- the specification title
- * - specversion
- the specification version
- * - specvendor
- the specification vendor
- * - impltitle
- the implementation title
- * - implversion
- the implementation version.
- * - implvendor
- the implementation vendor
- * - mainclass
- the class to run when java -jar is invoked
- * - classpath
- the classpath to use when java -jar is invoked
- * - createdby
- the string to set the Created-By field to
- * - buildid
- A build identifier. Defaults to a build identifier
- * containing date + " ("+username+"@"+hostname+" ["+os+" "+version+" "+arch+"]
+ * - file
- the manifest file to write out to (required)
+ * - overwrite
- if set to yes or true, overwrite the given
+ * manifest file. Default is no
+ * - version
- manifest version. Defaults to "1.0"
+ * - spectitle
- the specification title
+ * - specversion
- the specification version
+ * - specvendor
- the specification vendor
+ * - impltitle
- the implementation title
+ * - implversion
- the implementation version.
+ * - implvendor
- the implementation vendor
+ * - mainclass
- the class to run when java -jar is invoked
+ * - classpath
- the classpath to use when java -jar is invoked
+ * - createdby
- the string to set the Created-By field to
+ * - buildid
- A build identifier. Defaults to a build identifier
+ * containing date + " ("+username+"@"+hostname+" ["+os+" "+version+" "+arch+"]
*
*
* @author Kelly A. Campbell
*/
-public class Manifest extends Task
-{
+public class Manifest extends Task {
public static final String MANIFEST_VERSION = "Manifest-Version: ";
public static final String CREATED_BY = "Created-By: ";
public static final String REQUIRED_VERSION = "Required-Version: ";
-
+
public static final String SPECIFICATION_TITLE = "Specification-Title: ";
- public static final String SPECIFICATION_VERSION = "Specification-Version: ";
- public static final String SPECIFICATION_VENDOR = "Specification-Vendor: ";
- public static final String IMPL_TITLE = "Implementation-Title: ";
+ public static final String SPECIFICATION_VERSION =
+ "Specification-Version: ";
+ public static final String SPECIFICATION_VENDOR =
+ "Specification-Vendor: ";
+ public static final String IMPL_TITLE = "Implementation-Title: ";
public static final String IMPL_VERSION = "Implementation-Version: ";
- public static final String IMPL_VENDOR = "Implementation-Vendor: ";
- public static final String BUILD_ID = "Build-ID: ";
- public static final String MAIN_CLASS = "Main-Class: ";
- public static final String CLASS_PATH = "Class-Path: ";
-
+ public static final String IMPL_VENDOR = "Implementation-Vendor: ";
+ public static final String BUILD_ID = "Build-ID: ";
+ public static final String MAIN_CLASS = "Main-Class: ";
+ public static final String CLASS_PATH = "Class-Path: ";
+
private String _manifestVersion = "1.0";
private String _spectitle;
@@ -70,170 +72,160 @@ public class Manifest extends Task
private String _classpath;
private String _createdby;
private String _buildid;
-
+
private String _manifestFilename;
private Boolean _overwrite = Boolean.FALSE;
-
- public void setFile(String s)
- {
- _manifestFilename = s;
- }
-
- public void setOverwrite(Boolean b)
- {
- _overwrite = b;
- }
-
- public void setSpectitle(String s)
- {
- _spectitle = s;
- }
- public void setSpecversion(String s)
- {
- _specvers = s;
- }
- public void setSpecvendor(String s)
- {
- _specvend = s;
- }
- public void setImpltitle(String s)
- {
- _impltitle = s;
- }
- public void setImplversion(String s)
- {
- _implvers = s;
- }
- public void setImplvendor(String s)
- {
- _implvend = s;
- }
- public void setMainclass(String s)
- {
- _mainclass = s;
- }
- public void setClasspath(String s)
- {
- _classpath = s;
- }
- public void setCreatedby(String s)
- {
- _createdby = s;
- }
- public void setBuildid(String s)
- {
- _buildid = s;
- }
-
+
+ public void setFile(String s) {
+ _manifestFilename = s;
+ }
+
+ public void setOverwrite(Boolean b) {
+ _overwrite = b;
+ }
+
+ public void setSpectitle(String s) {
+ _spectitle = s;
+ }
+
+ public void setSpecversion(String s) {
+ _specvers = s;
+ }
+
+ public void setSpecvendor(String s) {
+ _specvend = s;
+ }
+
+ public void setImpltitle(String s) {
+ _impltitle = s;
+ }
+
+ public void setImplversion(String s) {
+ _implvers = s;
+ }
+
+ public void setImplvendor(String s) {
+ _implvend = s;
+ }
+
+ public void setMainclass(String s) {
+ _mainclass = s;
+ }
+
+ public void setClasspath(String s) {
+ _classpath = s;
+ }
+
+ public void setCreatedby(String s) {
+ _createdby = s;
+ }
+
+ public void setBuildid(String s) {
+ _buildid = s;
+ }
+
/**
* Main task method which runs this task and creates the manifest file.
* @exception BuildException if one of the required attributes isn't set
*/
- public void execute ()
- throws BuildException
- {
- // System.out.println("Executing manifest task");
-
- PrintWriter out;
- try {
- if (_manifestFilename != null) {
- // open the file for writing
- File f = new File(_manifestFilename);
- if (f.exists()) {
- if (_overwrite.booleanValue()) {
- f.delete();
- }
- else {
- throw new BuildException("Will not overwrite existing file: "+_manifestFilename+". Use overwrite='yes' if you wish to overwrite the file.");
- }
- }
- System.out.println("creating "+f);
-
- //jdk1.2 -- f.createNewFile();
- out = new PrintWriter(new FileOutputStream(f));
-
- }
- else {
- throw new BuildException("Manifest task requires a 'file' attribute");
- }
- }
- catch (IOException ex) {
- throw new BuildException(ex);
- }
-
- // setup the implementation versionn (buildID)
- if (_buildid == null || _buildid.trim().equals("")) {
- _buildid = createBuildID();
- }
- if (_createdby == null || _createdby.trim().equals("")) {
- _createdby = getCreator();
- }
-
- print(out, MANIFEST_VERSION, _manifestVersion);
- print(out, CREATED_BY, _createdby);
-
- print(out, SPECIFICATION_TITLE, _spectitle);
- print(out, SPECIFICATION_VERSION, _specvers);
- print(out, SPECIFICATION_VENDOR, _specvend);
- print(out, IMPL_TITLE, _impltitle);
- print(out, IMPL_VERSION, _implvers);
- print(out, IMPL_VENDOR, _implvend);
- print(out, BUILD_ID, _buildid);
- print(out, MAIN_CLASS, _mainclass);
- print(out, CLASS_PATH, _classpath);
-
- out.flush();
- out.close();
-
- }
-
- protected void print(PrintWriter out, String header, String value)
- {
- if (value != null && !value.trim().equals("")) {
- out.println(header+value);
- // System.out.println("manifest: "+header+value);
- }
- }
-
- private static String createBuildID()
- {
- Date d = new Date();
- SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd-HHmmss-z");
- String date = f.format(d);
- String hostname, username, os, version, arch;
- try {
- hostname = InetAddress.getLocalHost().getHostName();
- }
- catch (Exception ex) {
- hostname = "unknown";
- }
- username = System.getProperty("user.name");
- os = System.getProperty("os.name");
- version = System.getProperty("os.version");
- arch = System.getProperty("os.arch");
- String buildid = date + " ("+username+"@"+hostname+" ["+os+" "+version+" "+arch+"])";
- return buildid;
-
- }
-
- private static String getCreator()
- {
- try {
- Properties props = new Properties();
- InputStream in = org.apache.tools.ant.Main.class.getResourceAsStream("/org/apache/tools/ant/version.txt");
- if (in != null) {
- props.load(in);
- in.close();
-
- return "Ant "+props.getProperty("VERSION");
- }
- else {
- return null;
- }
- }
- catch (IOException ex) {
- return null;
- }
- }
-
+ public void execute() throws BuildException {
+ // System.out.println("Executing manifest task");
+
+ PrintWriter out;
+ try {
+ if (_manifestFilename != null) {
+ // open the file for writing
+ File f = new File(_manifestFilename);
+ if (f.exists()) {
+ if (_overwrite.booleanValue()) {
+ f.delete();
+ } else {
+ throw new BuildException("Will not overwrite existing file: "
+ + _manifestFilename
+ + ". Use overwrite='yes' if you wish to overwrite the file.");
+ }
+ }
+ System.out.println("creating " + f);
+
+ // jdk1.2 -- f.createNewFile();
+ out = new PrintWriter(new FileOutputStream(f));
+
+ } else {
+ throw new BuildException("Manifest task requires a 'file' attribute");
+ }
+ } catch (IOException ex) {
+ throw new BuildException(ex);
+ }
+
+ // setup the implementation versionn (buildID)
+ if (_buildid == null || _buildid.trim().equals("")) {
+ _buildid = createBuildID();
+ }
+ if (_createdby == null || _createdby.trim().equals("")) {
+ _createdby = getCreator();
+ }
+
+ print(out, MANIFEST_VERSION, _manifestVersion);
+ print(out, CREATED_BY, _createdby);
+
+ print(out, SPECIFICATION_TITLE, _spectitle);
+ print(out, SPECIFICATION_VERSION, _specvers);
+ print(out, SPECIFICATION_VENDOR, _specvend);
+ print(out, IMPL_TITLE, _impltitle);
+ print(out, IMPL_VERSION, _implvers);
+ print(out, IMPL_VENDOR, _implvend);
+ print(out, BUILD_ID, _buildid);
+ print(out, MAIN_CLASS, _mainclass);
+ print(out, CLASS_PATH, _classpath);
+
+ out.flush();
+ out.close();
+
+ }
+
+ protected void print(PrintWriter out, String header, String value) {
+ if (value != null &&!value.trim().equals("")) {
+ out.println(header + value);
+ // System.out.println("manifest: "+header+value);
+ }
+ }
+
+ private static String createBuildID() {
+ Date d = new Date();
+ SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd-HHmmss-z");
+ String date = f.format(d);
+ String hostname, username, os, version, arch;
+ try {
+ hostname = InetAddress.getLocalHost().getHostName();
+ } catch (Exception ex) {
+ hostname = "unknown";
+ }
+ username = System.getProperty("user.name");
+ os = System.getProperty("os.name");
+ version = System.getProperty("os.version");
+ arch = System.getProperty("os.arch");
+ String buildid = date + " (" + username + "@" + hostname + " [" + os
+ + " " + version + " " + arch + "])";
+ return buildid;
+
+ }
+
+ private static String getCreator() {
+ try {
+ Properties props = new Properties();
+ InputStream in =
+ org.apache.tools.ant.Main.class.getResourceAsStream("/org/apache/tools/ant/version.txt");
+ if (in != null) {
+ props.load(in);
+ in.close();
+
+ return "Ant " + props.getProperty("VERSION");
+ } else {
+ return null;
+ }
+ } catch (IOException ex) {
+ return null;
+ }
+ }
+
}
diff --git a/src/org/apache/fop/tools/anttasks/RunTest.java b/src/org/apache/fop/tools/anttasks/RunTest.java
index 0cb25f627..53e58f89b 100644
--- a/src/org/apache/fop/tools/anttasks/RunTest.java
+++ b/src/org/apache/fop/tools/anttasks/RunTest.java
@@ -1,4 +1,5 @@
/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -36,8 +37,7 @@ public class RunTest extends Task {
String referenceJar = "";
String refVersion = "";
- public RunTest() {
- }
+ public RunTest() {}
public void setTestSuite(String str) {
testsuite = str;
@@ -73,18 +73,21 @@ public class RunTest extends Task {
*/
protected void testNewBuild() {
try {
- ClassLoader loader = new URLClassLoader(new URL[]{new URL("file:build/fop.jar")});
- Hashtable diff = runConverter(loader, "areatree", "reference/output/");
- if (diff != null && !diff.isEmpty()) {
+ ClassLoader loader = new URLClassLoader(new URL[] {
+ new URL("file:build/fop.jar")
+ });
+ Hashtable diff = runConverter(loader, "areatree",
+ "reference/output/");
+ if (diff != null &&!diff.isEmpty()) {
System.out.println("====================================");
System.out.println("The following files differ:");
boolean broke = false;
for (Enumeration keys = diff.keys();
- keys.hasMoreElements();) {
+ keys.hasMoreElements(); ) {
Object fname = keys.nextElement();
- Boolean pass = (Boolean) diff.get(fname);
- System.out.println("file: " + fname +
- " - reference success: " + pass);
+ Boolean pass = (Boolean)diff.get(fname);
+ System.out.println("file: " + fname
+ + " - reference success: " + pass);
if (pass.booleanValue()) {
broke = true;
}
@@ -108,13 +111,14 @@ public class RunTest extends Task {
protected void runReference() throws BuildException {
// check not already done
File f = new File(basedir + "/reference/output/");
- //if(f.exists()) {
+ // if(f.exists()) {
// need to check that files have actually been created.
- //return;
- //} else {
+ // return;
+ // } else {
try {
- ClassLoader loader = new URLClassLoader(
- new URL[]{new URL("file:" + referenceJar)});
+ ClassLoader loader = new URLClassLoader(new URL[] {
+ new URL("file:" + referenceJar)
+ });
boolean failed = false;
try {
@@ -125,39 +129,32 @@ public class RunTest extends Task {
loader);
Method get = cla.getMethod("getVersion", new Class[]{});
if (!get.invoke(null, new Object[]{}).equals(refVersion)) {
- throw new BuildException(
- "Reference jar is not correct version it must be: " +
- refVersion);
+ throw new BuildException("Reference jar is not correct version it must be: "
+ + refVersion);
}
} catch (IllegalAccessException iae) {
failed = true;
- }
- catch (IllegalArgumentException are) {
+ } catch (IllegalArgumentException are) {
failed = true;
- }
- catch (InvocationTargetException are) {
+ } catch (InvocationTargetException are) {
failed = true;
- }
- catch (ClassNotFoundException are) {
+ } catch (ClassNotFoundException are) {
failed = true;
- }
- catch (InstantiationException are) {
+ } catch (InstantiationException are) {
failed = true;
- }
- catch (NoSuchMethodException are) {
+ } catch (NoSuchMethodException are) {
failed = true;
}
if (failed) {
- throw new BuildException(
- "Reference jar could not be found in: " +
- basedir + "/reference/");
+ throw new BuildException("Reference jar could not be found in: "
+ + basedir + "/reference/");
}
f.mkdirs();
runConverter(loader, "reference/output/", null);
} catch (MalformedURLException mue) {
mue.printStackTrace();
}
- //}
+ // }
}
/**
@@ -178,16 +175,23 @@ public class RunTest extends Task {
Object tc = cla.newInstance();
Method meth;
- meth = cla.getMethod("setBaseDir", new Class[]{String.class});
- meth.invoke(tc, new Object[]{basedir});
-
- meth = cla.getMethod("runTests", new Class[]{String.class,
- String.class, String.class});
- diff = (Hashtable) meth.invoke(tc, new Object[]{testsuite,
- dest, compDir});
+ meth = cla.getMethod("setBaseDir", new Class[] {
+ String.class
+ });
+ meth.invoke(tc, new Object[] {
+ basedir
+ });
+
+ meth = cla.getMethod("runTests", new Class[] {
+ String.class, String.class, String.class
+ });
+ diff = (Hashtable)meth.invoke(tc, new Object[] {
+ testsuite, dest, compDir
+ });
} catch (Exception e) {
e.printStackTrace();
}
return diff;
}
+
}
diff --git a/src/org/apache/fop/tools/anttasks/SerializeHyphPattern.java b/src/org/apache/fop/tools/anttasks/SerializeHyphPattern.java
index e3477d325..db205d9b0 100644
--- a/src/org/apache/fop/tools/anttasks/SerializeHyphPattern.java
+++ b/src/org/apache/fop/tools/anttasks/SerializeHyphPattern.java
@@ -1,59 +1,13 @@
/*
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 1999 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowlegement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowlegement may appear in the software itself,
- * if and wherever such third-party acknowlegements normally appear.
- *
- * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Group.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
+
package org.apache.fop.tools.anttasks;
-//package org.apache.tools.ant.taskdefs;
+// package org.apache.tools.ant.taskdefs;
import org.apache.tools.ant.taskdefs.MatchingTask;
import org.apache.tools.ant.DirectoryScanner;
@@ -62,12 +16,12 @@ import java.io.*;
import java.util.*;
import org.xml.sax.SAXException;
-//fop
+// fop
import org.apache.fop.layout.hyphenation.HyphenationTree;
import org.apache.fop.layout.hyphenation.HyphenationException;
/**
- * SerializeHyphPattern
+ * SerializeHyphPattern
*/
@@ -76,56 +30,56 @@ public class SerializeHyphPattern extends MatchingTask {
private boolean errorDump = false;
/**
- * Main method, which is called by ant.
- */
- public void execute () throws org.apache.tools.ant.BuildException {
+ * Main method, which is called by ant.
+ */
+ public void execute() throws org.apache.tools.ant.BuildException {
DirectoryScanner ds = this.getDirectoryScanner(sourceDir);
String[] files = ds.getIncludedFiles();
- for (int i = 0; i < files.length ; i++) {
+ for (int i = 0; i < files.length; i++) {
processFile(files[i].substring(0, files[i].length() - 4));
}
- } //end execute
+ } // end execute
/**
- * Sets the source directory
- *
- */
- public void setSourceDir (String sourceDir) {
+ * Sets the source directory
+ *
+ */
+ public void setSourceDir(String sourceDir) {
File dir = new File(sourceDir);
if (!dir.exists()) {
- System.err.println("Fatal Error: source directory " +
- sourceDir + " for hyphenation files doesn't exist.");
+ System.err.println("Fatal Error: source directory " + sourceDir
+ + " for hyphenation files doesn't exist.");
System.exit(1);
}
this.sourceDir = dir;
}
/**
- * Sets the target directory
- *
- */
- public void setTargetDir (String targetDir) {
+ * Sets the target directory
+ *
+ */
+ public void setTargetDir(String targetDir) {
File dir = new File(targetDir);
this.targetDir = dir;
}
/**
- * more error information
- *
- */
- public void setErrorDump (boolean errorDump) {
+ * more error information
+ *
+ */
+ public void setErrorDump(boolean errorDump) {
this.errorDump = errorDump;
}
/*
- * checks whether input or output files exists or the latter is older than input file
- * and start build if necessary
- */
- private void processFile (String filename) {
- File infile = new File (sourceDir , filename + ".xml");
- File outfile = new File(targetDir , filename + ".hyp");
+ * checks whether input or output files exists or the latter is older than input file
+ * and start build if necessary
+ */
+ private void processFile(String filename) {
+ File infile = new File(sourceDir, filename + ".xml");
+ File outfile = new File(targetDir, filename + ".hyp");
long outfileLastModified = outfile.lastModified();
boolean startProcess = true;
@@ -136,9 +90,9 @@ public class SerializeHyphPattern extends MatchingTask {
}
/*
- * serializes pattern files
- */
- private void buildPatternFile (File infile, File outfile) {
+ * serializes pattern files
+ */
+ private void buildPatternFile(File infile, File outfile) {
System.out.println("Processing " + infile);
HyphenationTree hTree = new HyphenationTree();
try {
@@ -148,52 +102,52 @@ public class SerializeHyphPattern extends MatchingTask {
hTree.printStats();
}
} catch (HyphenationException ex) {
- System.err.println("Can't load patterns from xml file " +
- infile + " - Maybe hyphenation.dtd is missing?");
+ System.err.println("Can't load patterns from xml file " + infile
+ + " - Maybe hyphenation.dtd is missing?");
if (errorDump) {
System.err.println(ex.toString());
}
}
- //serialize class
+ // serialize class
try {
- ObjectOutputStream out = new ObjectOutputStream (
- new FileOutputStream(outfile));
+ ObjectOutputStream out =
+ new ObjectOutputStream(new FileOutputStream(outfile));
out.writeObject(hTree);
out.close();
} catch (IOException ioe) {
- System.err.println("Can't write compiled pattern file: " +
- outfile);
+ System.err.println("Can't write compiled pattern file: "
+ + outfile);
System.err.println(ioe);
}
}
/**
- * Checks for existence of output file and compares
- * dates with input and stylesheet file
- */
- private boolean rebuild (File infile, File outfile) {
+ * Checks for existence of output file and compares
+ * dates with input and stylesheet file
+ */
+ private boolean rebuild(File infile, File outfile) {
if (outfile.exists()) {
- //checks whether output file is older than input file
+ // checks whether output file is older than input file
if (outfile.lastModified() < infile.lastModified()) {
return true;
}
} else {
- //if output file does not exist, start process
+ // if output file does not exist, start process
return true;
}
return false;
- } //end rebuild
+ } // end rebuild
-/*
- //quick access for debugging
- public static void main (String args[]) {
- SerializeHyphPattern ser = new SerializeHyphPattern();
- ser.setIncludes("*.xml");
- ser.setSourceDir("\\xml-fop\\hyph\\");
- ser.setTargetDir("\\xml-fop\\hyph\\");
- ser.execute();
- }
-*/
+ /*
+ * //quick access for debugging
+ * public static void main (String args[]) {
+ * SerializeHyphPattern ser = new SerializeHyphPattern();
+ * ser.setIncludes("*.xml");
+ * ser.setSourceDir("\\xml-fop\\hyph\\");
+ * ser.setTargetDir("\\xml-fop\\hyph\\");
+ * ser.execute();
+ * }
+ */
}
diff --git a/src/org/apache/fop/tools/anttasks/Xslt.java b/src/org/apache/fop/tools/anttasks/Xslt.java
index c38fd6961..1bc56492a 100644
--- a/src/org/apache/fop/tools/anttasks/Xslt.java
+++ b/src/org/apache/fop/tools/anttasks/Xslt.java
@@ -1,55 +1,8 @@
/*
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 1999 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowlegement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowlegement may appear in the software itself,
- * if and wherever such third-party acknowlegements normally appear.
- *
- * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Group.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.tools.anttasks;
@@ -97,68 +50,70 @@ import org.xml.sax.SAXException;
public class Xslt extends Task {
private String infile, outfile, xsltfile, mergefile;
- private String smart = "no"; //defaults to do conversion everytime task is called
- private String dependent = "none"; //defaults to no dependencies
+ private String smart =
+ "no"; // defaults to do conversion everytime task is called
+ private String dependent = "none"; // defaults to no dependencies
private boolean startXslt = false;
- /** When true, we use the trax api's from xalan2, otherwise
+ /**
+ * When true, we use the trax api's from xalan2, otherwise
* just the xalan1 native interfaces
*/
private boolean useTrax = false;
-
+
/**
* Sets the input file
*
*/
- public void setInfile (String infile) {
+ public void setInfile(String infile) {
this.infile = infile;
}
- public void setMergefile (String mergefile) {
+ public void setMergefile(String mergefile) {
this.mergefile = mergefile;
}
/**
- * Sets the stylesheet file
- *
- */
- public void setXsltfile (String xsltfile) {
+ * Sets the stylesheet file
+ *
+ */
+ public void setXsltfile(String xsltfile) {
this.xsltfile = xsltfile;
}
/**
- * Sets the output file
- *
- */
- public void setOutfile (String outfile) {
+ * Sets the output file
+ *
+ */
+ public void setOutfile(String outfile) {
this.outfile = outfile;
}
/**
- * Sets the value for smart
- *
- * @param option valid values:
- *
- * - yes: check whether output file is older than input or stylesheet
- *
- no: (default) do conversion everytime task is called
- *
- */
- public void setSmart (String smart) {
+ * Sets the value for smart
+ *
+ * @param option valid values:
+ *
+ * - yes: check whether output file is older than input or stylesheet
+ *
- no: (default) do conversion everytime task is called
+ *
+ */
+ public void setSmart(String smart) {
this.smart = smart;
}
/**
- * Sets the value for dependent
- *
- * @param option valid values:
- *
- * - none: (default)
- *
- comma delimited list of files whose existence and date is checked
- * against the output file
- *
- */
- public void setDependent (String dependent) {
+ * Sets the value for dependent
+ *
+ * @param option valid values:
+ *
+ * - none: (default)
+ *
- comma delimited list of files whose existence and date is checked
+ * against the output file
+ *
+ */
+ public void setDependent(String dependent) {
this.dependent = dependent;
}
@@ -167,90 +122,86 @@ public class Xslt extends Task {
* Builds a document from the given file, merging the mergefile onto the end of the root node
*/
private org.w3c.dom.Document buildDocument(String xmlFile)
- throws IOException, SAXException {
+ throws IOException, SAXException {
try {
javax.xml.parsers.DocumentBuilder docBuilder =
- javax.xml.parsers.DocumentBuilderFactory.newInstance().
- newDocumentBuilder();
+ javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = docBuilder.parse(new FileInputStream(xmlFile));
- if (mergefile != null && !mergefile.equals("")) {
+ if (mergefile != null &&!mergefile.equals("")) {
File mergefileF = new File(mergefile);
Document mergedoc =
- docBuilder.parse(new FileInputStream(mergefileF));
- Node mergenode =
- doc.importNode(mergedoc.getDocumentElement(), true);
+ docBuilder.parse(new FileInputStream(mergefileF));
+ Node mergenode = doc.importNode(mergedoc.getDocumentElement(),
+ true);
doc.getDocumentElement().appendChild(mergenode);
}
return doc;
} catch (javax.xml.parsers.ParserConfigurationException e) {
- System.out.println("Task xslt - SAX ERROR:\n " +
- e.getMessage());
+ System.out.println("Task xslt - SAX ERROR:\n "
+ + e.getMessage());
}
return null;
}
/**
- * Calls Xalan and does the transformation
- *
- */
- private void transform() {
- try {
- org.w3c.dom.Document source = buildDocument(infile);
- // Perform the transformation.
- System.out.println("============================");
- System.out.println("xslt \nin: " + infile + "\nstyle: " +
- xsltfile + "\nout: " + outfile);
- System.out.println("============================");
- org.apache.fop.tools.xslt.XSLTransform.transform(source,xsltfile,outfile);
-
-
- } catch (org.xml.sax.SAXException saxerror) {
+ * Calls Xalan and does the transformation
+ *
+ */
+ private void transform() {
+ try {
+ org.w3c.dom.Document source = buildDocument(infile);
+ // Perform the transformation.
+ System.out.println("============================");
+ System.out.println("xslt \nin: " + infile + "\nstyle: "
+ + xsltfile + "\nout: " + outfile);
+ System.out.println("============================");
+ org.apache.fop.tools.xslt.XSLTransform.transform(source,
+ xsltfile, outfile);
+
+
+ } catch (org.xml.sax.SAXException saxerror) {
System.out.println("Task xslt - SAX ERROR:\n " + saxerror);
- }
- catch (MalformedURLException urlerror) {
+ } catch (MalformedURLException urlerror) {
System.out.println("Task xslt - URL ERROR:\n " + urlerror);
- }
- catch (IOException ioerror) {
+ } catch (IOException ioerror) {
System.out.println("Task xslt - IO ERROR:\n " + ioerror);
+ } catch (Exception ex) {
+ ex.printStackTrace();
}
-
- catch (Exception ex) {
- ex.printStackTrace();
- }
-
- } //end transform
-
-
+
+ } // end transform
+
+
/**
- * Checks for existence of output file and compares
- * dates with input and stylesheet file
+ * Checks for existence of output file and compares
+ * dates with input and stylesheet file
*/
- private boolean smartCheck (File outfileF,
- long outfileLastModified, File infileF, File xsltfileF) {
+ private boolean smartCheck(File outfileF, long outfileLastModified,
+ File infileF, File xsltfileF) {
if (outfileF.exists()) {
- //checks whether output file is older than input file or xslt stylesheet file
- if ((outfileLastModified < infileF.lastModified()) |
- (outfileLastModified < xsltfileF.lastModified())) {
+ // checks whether output file is older than input file or xslt stylesheet file
+ if ((outfileLastModified < infileF.lastModified())
+ | (outfileLastModified < xsltfileF.lastModified())) {
return true;
}
} else {
- //if output file does not exist, start xslt process
+ // if output file does not exist, start xslt process
return true;
}
return false;
- } //end smartCheck
+ } // end smartCheck
/**
- * Checks for existence and date of dependent files
- * This could be folded together with smartCheck by using
- * a general routine but it wouldn't be as fast as now
+ * Checks for existence and date of dependent files
+ * This could be folded together with smartCheck by using
+ * a general routine but it wouldn't be as fast as now
*/
private boolean dependenciesCheck(File outfileF,
long outfileLastModified) {
@@ -258,82 +209,79 @@ public class Xslt extends Task {
File dependentFile;
StringTokenizer tokens = new StringTokenizer(dependent, ",");
while (tokens.hasMoreTokens()) {
- dependentFileName = (String) tokens.nextToken();
- dependentFile = new File (dependentFileName);
- //check: does dependent file exist
+ dependentFileName = (String)tokens.nextToken();
+ dependentFile = new File(dependentFileName);
+ // check: does dependent file exist
if (dependentFile.exists()) {
- //check dates
+ // check dates
if ((outfileLastModified < dependentFile.lastModified())) {
return true;
}
} else {
- System.err.println(
- "Task xslt - ERROR in attribute 'dependent':\n file " +
- dependentFileName + " does not exist.");
+ System.err.println("Task xslt - ERROR in attribute 'dependent':\n file "
+ + dependentFileName + " does not exist.");
}
}
return false;
- } //end dependenciesCheck
+ } // end dependenciesCheck
/**
- * Main method, which is called by ant.
- * Checks for the value of smart and calls startTransform accordingly
+ * Main method, which is called by ant.
+ * Checks for the value of smart and calls startTransform accordingly
*/
- public void execute () throws org.apache.tools.ant.BuildException {
+ public void execute() throws org.apache.tools.ant.BuildException {
- File outfileF = new File (outfile);
+ File outfileF = new File(outfile);
File infileF = new File(infile);
- File xsltfileF = new File (xsltfile);
+ File xsltfileF = new File(xsltfile);
long outfileLastModified = outfileF.lastModified();
boolean startFileExist = true;
- //checks whether input and stylesheet exist.
- //this could be left to the parser, but this solution does make problems if smart is set to yes
+ // checks whether input and stylesheet exist.
+ // this could be left to the parser, but this solution does make problems if smart is set to yes
if (!infileF.exists()) {
- System.err.println(
- "Task xslt - ERROR:\n Input file " + infile +
- " does not exist!");
+ System.err.println("Task xslt - ERROR:\n Input file "
+ + infile + " does not exist!");
startFileExist = false;
} else if (!xsltfileF.exists()) {
- System.err.println(
- "Task xslt - ERROR:\n Stylesheet file " +
- xsltfile + " does not exist!");
+ System.err.println("Task xslt - ERROR:\n Stylesheet file "
+ + xsltfile + " does not exist!");
startFileExist = false;
}
- //checks attribute 'smart'
+ // checks attribute 'smart'
if (smart.equals("no")) {
startXslt = true;
- //if attribute smart = 'yes'
+ // if attribute smart = 'yes'
} else if (smart.equals("yes")) {
- startXslt = smartCheck (outfileF, outfileLastModified,
- infileF, xsltfileF);
- //checks dependent files against output file, makes only sense if smartCheck returns false
+ startXslt = smartCheck(outfileF, outfileLastModified, infileF,
+ xsltfileF);
+ // checks dependent files against output file, makes only sense if smartCheck returns false
if (!dependent.equals("none") & (startXslt == false)) {
- startXslt =
- dependenciesCheck(outfileF, outfileLastModified);
+ startXslt = dependenciesCheck(outfileF, outfileLastModified);
}
- //returns error message, if smart has another value as 'yes' or 'no'
+ // returns error message, if smart has another value as 'yes' or 'no'
} else {
System.err.println("Task xslt - ERROR: Allowed values for the attribute smart are 'yes' or 'no'");
}
if (startFileExist & startXslt) {
transform();
}
- } //end execute
+ } // end execute
- //quick access for debugging
- //usage XSLT infile xsltfile outfile (smart is 'yes')
+ // quick access for debugging
+ // usage XSLT infile xsltfile outfile (smart is 'yes')
/*
- public static void main (String args[]) {
- Xslt xslt = new Xslt();
- xslt.setInfile(args[0]);
- xslt.setXsltfile(args[1]);
- xslt.setOutfile(args[2]);
- xslt.setSmart("yes");
- xslt.setDependent("test1,test2");
- xslt.execute();
-} */
+ * public static void main (String args[]) {
+ * Xslt xslt = new Xslt();
+ * xslt.setInfile(args[0]);
+ * xslt.setXsltfile(args[1]);
+ * xslt.setOutfile(args[2]);
+ * xslt.setSmart("yes");
+ * xslt.setDependent("test1,test2");
+ * xslt.execute();
+ * }
+ */
diff --git a/src/org/apache/fop/tools/xslt/TraxTransform.java b/src/org/apache/fop/tools/xslt/TraxTransform.java
index 82808ae5d..d997c1a27 100644
--- a/src/org/apache/fop/tools/xslt/TraxTransform.java
+++ b/src/org/apache/fop/tools/xslt/TraxTransform.java
@@ -1,55 +1,8 @@
/*
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 1999 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowlegement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowlegement may appear in the software itself,
- * if and wherever such third-party acknowlegements normally appear.
- *
- * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Group.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.tools.xslt;
@@ -67,104 +20,92 @@ import org.w3c.dom.Document;
* Handles xslt tranformations via Trax (xalan2)
*/
-public class TraxTransform
-{
- /** Cache of compiled stylesheets (filename, StylesheetRoot) */
+public class TraxTransform {
+
+ /**
+ * Cache of compiled stylesheets (filename, StylesheetRoot)
+ */
private static Hashtable _stylesheetCache = new Hashtable();
- public static Transformer getTransformer(String xsltFilename,
- boolean cache)
- {
- try {
- if (cache && _stylesheetCache.containsKey(xsltFilename)) {
- Templates cachedStylesheet = (Templates)_stylesheetCache.get(xsltFilename);
- return cachedStylesheet.newTransformer();
- }
-
- Source xslSheet =
- new javax.xml.transform.stream.StreamSource (xsltFilename);
-
-
- /* System.out.println("****************************");
- System.out.println("trax compile \nin: " + xsltFilename);
- System.out.println("****************************");
- */
- TransformerFactory factory = TransformerFactory.newInstance();
-
- Templates compiledSheet =
- factory.newTemplates(xslSheet);
- if (cache) {
- _stylesheetCache.put(xsltFilename, compiledSheet);
- }
- return compiledSheet.newTransformer();
- }
- catch (TransformerConfigurationException ex) {
- ex.printStackTrace();
- }
- return null;
-
+ public static Transformer getTransformer(String xsltFilename,
+ boolean cache) {
+ try {
+ if (cache && _stylesheetCache.containsKey(xsltFilename)) {
+ Templates cachedStylesheet =
+ (Templates)_stylesheetCache.get(xsltFilename);
+ return cachedStylesheet.newTransformer();
+ }
+
+ Source xslSheet =
+ new javax.xml.transform.stream.StreamSource(xsltFilename);
+
+
+ /*
+ * System.out.println("****************************");
+ * System.out.println("trax compile \nin: " + xsltFilename);
+ * System.out.println("****************************");
+ */
+ TransformerFactory factory = TransformerFactory.newInstance();
+
+ Templates compiledSheet = factory.newTemplates(xslSheet);
+ if (cache) {
+ _stylesheetCache.put(xsltFilename, compiledSheet);
+ }
+ return compiledSheet.newTransformer();
+ } catch (TransformerConfigurationException ex) {
+ ex.printStackTrace();
+ }
+ return null;
+
}
- public static void transform(String xmlSource,
- String xslURL,
- String outputFile)
- {
- transform(new javax.xml.transform.stream.StreamSource(xmlSource),
- new javax.xml.transform.stream.StreamSource(xslURL),
- new javax.xml.transform.stream.StreamResult(outputFile));
+ public static void transform(String xmlSource, String xslURL,
+ String outputFile) {
+ transform(new javax.xml.transform.stream.StreamSource(xmlSource),
+ new javax.xml.transform.stream.StreamSource(xslURL),
+ new javax.xml.transform.stream.StreamResult(outputFile));
}
-
- public static void transform(Document xmlSource,
- String xslURL,
- String outputFile)
- {
- transform(new javax.xml.transform.dom.DOMSource(xmlSource),
- new javax.xml.transform.stream.StreamSource(xslURL),
- new javax.xml.transform.stream.StreamResult(outputFile));
+ public static void transform(Document xmlSource, String xslURL,
+ String outputFile) {
+
+ transform(new javax.xml.transform.dom.DOMSource(xmlSource),
+ new javax.xml.transform.stream.StreamSource(xslURL),
+ new javax.xml.transform.stream.StreamResult(outputFile));
}
-
- public static void transform(String xmlSource,
- String xslURL,
- Writer output)
- {
- transform(new javax.xml.transform.stream.StreamSource(xmlSource),
- new javax.xml.transform.stream.StreamSource(xslURL),
- new javax.xml.transform.stream.StreamResult(output));
+
+ public static void transform(String xmlSource, String xslURL,
+ Writer output) {
+ transform(new javax.xml.transform.stream.StreamSource(xmlSource),
+ new javax.xml.transform.stream.StreamSource(xslURL),
+ new javax.xml.transform.stream.StreamResult(output));
}
-
- public static void transform(Document xmlSource,
- InputStream xsl,
- Document outputDoc)
- {
- transform(new javax.xml.transform.dom.DOMSource(xmlSource),
- new javax.xml.transform.stream.StreamSource(xsl),
- new javax.xml.transform.dom.DOMResult(outputDoc));
+
+ public static void transform(Document xmlSource, InputStream xsl,
+ Document outputDoc) {
+ transform(new javax.xml.transform.dom.DOMSource(xmlSource),
+ new javax.xml.transform.stream.StreamSource(xsl),
+ new javax.xml.transform.dom.DOMResult(outputDoc));
}
- public static void transform(Source xmlSource,
- Source xslSource,
- Result result)
- {
- try {
- Transformer transformer;
- if (xslSource.getSystemId() == null) {
- TransformerFactory factory = TransformerFactory.newInstance();
- transformer = factory.newTransformer(xslSource);
- }
- else {
- transformer = getTransformer(xslSource.getSystemId(),true);
- }
- transformer.transform(xmlSource, result);
- }
- catch (TransformerConfigurationException ex) {
- ex.printStackTrace();
- }
- catch (TransformerException ex) {
- ex.printStackTrace();
- }
-
+ public static void transform(Source xmlSource, Source xslSource,
+ Result result) {
+ try {
+ Transformer transformer;
+ if (xslSource.getSystemId() == null) {
+ TransformerFactory factory = TransformerFactory.newInstance();
+ transformer = factory.newTransformer(xslSource);
+ } else {
+ transformer = getTransformer(xslSource.getSystemId(), true);
+ }
+ transformer.transform(xmlSource, result);
+ } catch (TransformerConfigurationException ex) {
+ ex.printStackTrace();
+ } catch (TransformerException ex) {
+ ex.printStackTrace();
+ }
+
}
-
+
}
diff --git a/src/org/apache/fop/tools/xslt/XSLTransform.java b/src/org/apache/fop/tools/xslt/XSLTransform.java
index c30d7eef5..c764af22e 100644
--- a/src/org/apache/fop/tools/xslt/XSLTransform.java
+++ b/src/org/apache/fop/tools/xslt/XSLTransform.java
@@ -1,55 +1,8 @@
/*
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 1999 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowlegement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowlegement may appear in the software itself,
- * if and wherever such third-party acknowlegements normally appear.
- *
- * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Group.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.tools.xslt;
@@ -58,128 +11,126 @@ import java.io.*;
import java.lang.reflect.*;
-public class XSLTransform
-{
-
- public static void transform(String xmlSource,
- String xslURL,
- String outputFile)
- throws Exception
- {
- Class[] argTypes = {String.class, String.class, String.class};
- Object[] params = {xmlSource, xslURL, outputFile};
- transform(params, argTypes);
+public class XSLTransform {
+
+ public static void transform(String xmlSource, String xslURL,
+ String outputFile) throws Exception {
+ Class[] argTypes = {
+ String.class, String.class, String.class
+ };
+ Object[] params = {
+ xmlSource, xslURL, outputFile
+ };
+ transform(params, argTypes);
}
public static void transform(org.w3c.dom.Document xmlSource,
- String xslURL,
- String outputFile)
- throws Exception
- {
- Class[] argTypes = {org.w3c.dom.Document.class,
- String.class, String.class};
-
- Object[] params = {xmlSource, xslURL, outputFile};
- transform(params, argTypes);
-
+ String xslURL,
+ String outputFile) throws Exception {
+ Class[] argTypes = {
+ org.w3c.dom.Document.class, String.class, String.class
+ };
+
+ Object[] params = {
+ xmlSource, xslURL, outputFile
+ };
+ transform(params, argTypes);
+
}
-
- public static void transform(String xmlSource,
- String xslURL,
- Writer outputWriter)
- throws Exception
- {
- Class[] argTypes = {String.class, String.class, Writer.class};
- Object[] params = {xmlSource, xslURL, outputWriter};
- transform(params, argTypes);
-
+
+ public static void transform(String xmlSource, String xslURL,
+ Writer outputWriter) throws Exception {
+ Class[] argTypes = {
+ String.class, String.class, Writer.class
+ };
+ Object[] params = {
+ xmlSource, xslURL, outputWriter
+ };
+ transform(params, argTypes);
+
}
-
+
public static void transform(org.w3c.dom.Document xmlSource,
- InputStream xsl,
- org.w3c.dom.Document outputDoc)
- throws Exception
- {
- Class[] argTypes = {org.w3c.dom.Document.class, InputStream.class,
- org.w3c.dom.Document.class};
- Object[] params = {xmlSource, xsl, outputDoc};
- transform(params, argTypes);
-
+ InputStream xsl,
+ org.w3c.dom.Document outputDoc) throws Exception {
+ Class[] argTypes = {
+ org.w3c.dom.Document.class, InputStream.class,
+ org.w3c.dom.Document.class
+ };
+ Object[] params = {
+ xmlSource, xsl, outputDoc
+ };
+ transform(params, argTypes);
+
}
-
-
- private static void transform(Object[] args, Class[] argTypes)
- throws Exception
- {
- Class transformer = getTransformClass();
- if (transformer != null) {
- Method transformMethod = getTransformMethod(transformer,argTypes);
- if (transformMethod != null) {
- try {
- transformMethod.invoke(null, args);
- }
- catch (InvocationTargetException ex) {
- ex.printStackTrace();
- }
- }
- else {
- throw new Exception("transform method not found");
- }
- }
- else {
- throw new Exception("no transformer class found");
- }
-
+
+
+ private static void transform(Object[] args,
+ Class[] argTypes) throws Exception {
+ Class transformer = getTransformClass();
+ if (transformer != null) {
+ Method transformMethod = getTransformMethod(transformer,
+ argTypes);
+ if (transformMethod != null) {
+ try {
+ transformMethod.invoke(null, args);
+ } catch (InvocationTargetException ex) {
+ ex.printStackTrace();
+ }
+ } else {
+ throw new Exception("transform method not found");
+ }
+ } else {
+ throw new Exception("no transformer class found");
+ }
+
}
-
-
- private static Class getTransformClass()
- {
- try {
- // try trax first
- Class transformer = Class.forName("javax.xml.transform.Transformer");
- // ok, make sure we have a liaison to trax
- transformer = Class.forName("org.apache.fop.tools.xslt.TraxTransform");
- return transformer;
-
- }
- catch (ClassNotFoundException ex){
- }
- // otherwise, try regular xalan1
- try {
- Class transformer = Class.forName("org.apache.xalan.xslt.XSLTProcessor");
- // get the liaison
- transformer = Class.forName("org.apache.fop.tools.xslt.Xalan1Transform");
- return transformer;
- }
- catch (ClassNotFoundException ex){
- }
- return null;
-
+
+
+ private static Class getTransformClass() {
+ try {
+ // try trax first
+ Class transformer =
+ Class.forName("javax.xml.transform.Transformer");
+ // ok, make sure we have a liaison to trax
+ transformer =
+ Class.forName("org.apache.fop.tools.xslt.TraxTransform");
+ return transformer;
+
+ } catch (ClassNotFoundException ex) {}
+ // otherwise, try regular xalan1
+ try {
+ Class transformer =
+ Class.forName("org.apache.xalan.xslt.XSLTProcessor");
+ // get the liaison
+ transformer =
+ Class.forName("org.apache.fop.tools.xslt.Xalan1Transform");
+ return transformer;
+ } catch (ClassNotFoundException ex) {}
+ return null;
+
}
-
-
- private static Method getTransformMethod(Class c, Class[] argTypes)
- {
- // System.out.println("transformer class = "+c);
-
- try {
- // Class[] argTypes = new Class[args.length];
- for (int i=0; i.
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
*/
package org.apache.fop.tools.xslt;
@@ -65,103 +18,90 @@ import org.w3c.dom.Document;
* Handles xslt tranformations via Xalan1 (non-trax)
*/
-public class Xalan1Transform
-{
- /** Cache of compiled stylesheets (filename, StylesheetRoot) */
+public class Xalan1Transform {
+
+ /**
+ * Cache of compiled stylesheets (filename, StylesheetRoot)
+ */
private static Hashtable _stylesheetCache = new Hashtable();
- public static StylesheetRoot getStylesheet(String xsltFilename,
- boolean cache)
- throws org.xml.sax.SAXException
- {
- if (cache && _stylesheetCache.containsKey(xsltFilename)) {
- return (StylesheetRoot)_stylesheetCache.get(xsltFilename);
- }
-
- // Use XSLTProcessor to instantiate an XSLTProcessor.
- XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
-
- XSLTInputSource xslSheet = new XSLTInputSource (xsltFilename);
-
- // Perform the transformation.
- StylesheetRoot compiledSheet =
- processor.processStylesheet(xslSheet);
- if (cache) {
- _stylesheetCache.put(xsltFilename, compiledSheet);
- }
- return compiledSheet;
+ public static StylesheetRoot getStylesheet(String xsltFilename, boolean cache)
+ throws org.xml.sax.SAXException {
+ if (cache && _stylesheetCache.containsKey(xsltFilename)) {
+ return (StylesheetRoot)_stylesheetCache.get(xsltFilename);
+ }
+
+ // Use XSLTProcessor to instantiate an XSLTProcessor.
+ XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
+
+ XSLTInputSource xslSheet = new XSLTInputSource(xsltFilename);
+
+ // Perform the transformation.
+ StylesheetRoot compiledSheet = processor.processStylesheet(xslSheet);
+ if (cache) {
+ _stylesheetCache.put(xsltFilename, compiledSheet);
+ }
+ return compiledSheet;
}
public static void transform(String xmlSource, String xslURL,
- String outputFile)
- throws java.io.IOException,
- java.net.MalformedURLException,
- org.xml.sax.SAXException
- {
- try {
- javax.xml.parsers.DocumentBuilder docBuilder =
- javax.xml.parsers.DocumentBuilderFactory.newInstance().
- newDocumentBuilder();
- Document doc = docBuilder.parse(new FileInputStream(xmlSource));
- transform(doc,xslURL,outputFile);
- }
- catch (javax.xml.parsers.ParserConfigurationException ex){
- throw new org.xml.sax.SAXException(ex);
- }
+ String outputFile) throws java.io.IOException,
+ java.net.MalformedURLException,
+ org.xml.sax.SAXException {
+ try {
+ javax.xml.parsers.DocumentBuilder docBuilder =
+ javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
+ Document doc = docBuilder.parse(new FileInputStream(xmlSource));
+ transform(doc, xslURL, outputFile);
+ } catch (javax.xml.parsers.ParserConfigurationException ex) {
+ throw new org.xml.sax.SAXException(ex);
+ }
}
-
- public static void transform(Document xmlSource,
- String xslURL,
- String outputFile)
- throws java.io.IOException,
- java.net.MalformedURLException,
- org.xml.sax.SAXException
- {
-
- XSLTResultTarget xmlResult = new XSLTResultTarget (outputFile);
-
- StylesheetRoot stylesheet = getStylesheet(xslURL,true);
-
+
+ public static void transform(Document xmlSource, String xslURL,
+ String outputFile) throws java.io.IOException,
+ java.net.MalformedURLException,
+ org.xml.sax.SAXException {
+
+ XSLTResultTarget xmlResult = new XSLTResultTarget(outputFile);
+
+ StylesheetRoot stylesheet = getStylesheet(xslURL, true);
+
// Perform the transformation.
- stylesheet.process(XSLTProcessorFactory.getProcessor(),
- xmlSource, xmlResult);
+ stylesheet.process(XSLTProcessorFactory.getProcessor(), xmlSource,
+ xmlResult);
}
-
- public static void transform(String xmlSource,
- String xslURL,
- java.io.Writer outputFile)
- throws java.io.IOException,
- java.net.MalformedURLException,
- org.xml.sax.SAXException
- {
-
- XSLTInputSource source = new XSLTInputSource (xmlSource);
- XSLTResultTarget xmlResult = new XSLTResultTarget (outputFile);
-
- StylesheetRoot stylesheet = getStylesheet(xslURL,true);
-
+
+ public static void transform(String xmlSource, String xslURL,
+ java.io.Writer outputFile) throws java.io.IOException,
+ java.net.MalformedURLException,
+ org.xml.sax.SAXException {
+
+ XSLTInputSource source = new XSLTInputSource(xmlSource);
+ XSLTResultTarget xmlResult = new XSLTResultTarget(outputFile);
+
+ StylesheetRoot stylesheet = getStylesheet(xslURL, true);
+
// Perform the transformation.
- stylesheet.process(XSLTProcessorFactory.getProcessor(),
- source, xmlResult);
+ stylesheet.process(XSLTProcessorFactory.getProcessor(), source,
+ xmlResult);
}
- public static void transform(Document xmlSource,
- InputStream xsl,
- Document outputDoc)
- throws java.io.IOException,
- java.net.MalformedURLException,
- org.xml.sax.SAXException
- {
-
- XSLTInputSource source = new XSLTInputSource (xmlSource);
- XSLTInputSource xslSheet = new XSLTInputSource(xsl);
- XSLTResultTarget xmlResult = new XSLTResultTarget (outputDoc);
-
-
+ public static void transform(Document xmlSource, InputStream xsl,
+ Document outputDoc) throws java.io.IOException,
+ java.net.MalformedURLException,
+ org.xml.sax.SAXException {
+
+ XSLTInputSource source = new XSLTInputSource(xmlSource);
+ XSLTInputSource xslSheet = new XSLTInputSource(xsl);
+ XSLTResultTarget xmlResult = new XSLTResultTarget(outputDoc);
+
+
// Perform the transformation.
- XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
-
+ XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
+
processor.process(source, xslSheet, xmlResult);
}
+
}
diff --git a/src/org/apache/fop/viewer/Command.java b/src/org/apache/fop/viewer/Command.java
index 4fd793692..d25377a81 100644
--- a/src/org/apache/fop/viewer/Command.java
+++ b/src/org/apache/fop/viewer/Command.java
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
@@ -6,9 +7,9 @@
package org.apache.fop.viewer;
/*
- Juergen Verwohlt: Juergen.Verwohlt@jcatalog.com,
- Rainer Steinkuhle: Rainer.Steinkuhle@jcatalog.com,
- Stanislav Gorkhover: Stanislav.Gorkhover@jcatalog.com
+ * Juergen Verwohlt: Juergen.Verwohlt@jcatalog.com,
+ * Rainer Steinkuhle: Rainer.Steinkuhle@jcatalog.com,
+ * Stanislav Gorkhover: Stanislav.Gorkhover@jcatalog.com
*/
import java.awt.event.ActionEvent;
@@ -33,7 +34,7 @@ public class Command extends AbstractAction {
public static String IMAGE_DIR = "/org/apache/fop/viewer/Images/";
public Command(String name) {
- this(name, (ImageIcon) null);
+ this(name, (ImageIcon)null);
}
public Command(String name, ImageIcon anIcon) {
@@ -61,4 +62,5 @@ public class Command extends AbstractAction {
public void undoit() {
MessageHandler.errorln("Not implemented.");
}
+
}
diff --git a/src/org/apache/fop/viewer/GoToPageDialog.java b/src/org/apache/fop/viewer/GoToPageDialog.java
index c5b1f4198..f5bce3f66 100644
--- a/src/org/apache/fop/viewer/GoToPageDialog.java
+++ b/src/org/apache/fop/viewer/GoToPageDialog.java
@@ -1,8 +1,15 @@
/*
- originally contributed by
- Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
- Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
- Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
+/*
+ * originally contributed by
+ * Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
+ * Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
+ * Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
*/
package org.apache.fop.viewer;
@@ -14,75 +21,90 @@ import java.awt.event.*;
import org.apache.fop.messaging.MessageHandler;
public class GoToPageDialog extends JDialog {
- JPanel panel1 = new JPanel();
- GridBagLayout gridBagLayout1 = new GridBagLayout();
- JLabel pgNbLabel = new JLabel();
- JTextField pgNbField = new JTextField();
- JButton okButton = new JButton();
- JButton cancelButton = new JButton();
-
- int pageNumber = -1;
-
- public GoToPageDialog(Frame frame, String title, boolean modal) {
- super(frame, title, modal);
- try {
- jbInit();
- pack();
+ JPanel panel1 = new JPanel();
+ GridBagLayout gridBagLayout1 = new GridBagLayout();
+ JLabel pgNbLabel = new JLabel();
+ JTextField pgNbField = new JTextField();
+ JButton okButton = new JButton();
+ JButton cancelButton = new JButton();
+
+ int pageNumber = -1;
+
+ public GoToPageDialog(Frame frame, String title, boolean modal) {
+ super(frame, title, modal);
+ try {
+ jbInit();
+ pack();
+ } catch (Exception ex) {
+ MessageHandler.errorln("GoToPageDialog: Konstruktor: "
+ + ex.getMessage());
+ }
+ }
+
+ public GoToPageDialog() {
+ this(null, "", false);
}
- catch(Exception ex) {
- MessageHandler.errorln("GoToPageDialog: Konstruktor: " + ex.getMessage());
+
+ void jbInit() throws Exception {
+ panel1.setLayout(gridBagLayout1);
+ pgNbLabel.setText("Page number");
+ okButton.setText("Ok");
+ okButton.addActionListener(new java.awt.event.ActionListener() {
+
+ public void actionPerformed(ActionEvent e) {
+ okButton_actionPerformed(e);
+ }
+
+ });
+ cancelButton.setText("Cancel");
+ cancelButton.addActionListener(new java.awt.event.ActionListener() {
+
+ public void actionPerformed(ActionEvent e) {
+ cancelButton_actionPerformed(e);
+ }
+
+ });
+ panel1.setMinimumSize(new Dimension(250, 78));
+ getContentPane().add(panel1);
+ panel1.add(pgNbLabel,
+ new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
+ GridBagConstraints.WEST,
+ GridBagConstraints.NONE,
+ new Insets(10, 10, 10, 5), 0, 0));
+ panel1.add(pgNbField,
+ new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0,
+ GridBagConstraints.WEST,
+ GridBagConstraints.BOTH,
+ new Insets(10, 5, 10, 10), 0, 0));
+ panel1.add(okButton,
+ new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
+ GridBagConstraints.EAST,
+ GridBagConstraints.NONE,
+ new Insets(0, 0, 10, 5), 0, 0));
+ panel1.add(cancelButton,
+ new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,
+ GridBagConstraints.WEST,
+ GridBagConstraints.NONE,
+ new Insets(0, 10, 10, 10), 0, 0));
}
- }
-
- public GoToPageDialog() {
- this(null, "", false);
- }
-
- void jbInit() throws Exception {
- panel1.setLayout(gridBagLayout1);
- pgNbLabel.setText("Page number");
- okButton.setText("Ok");
- okButton.addActionListener(new java.awt.event.ActionListener() {
-
- public void actionPerformed(ActionEvent e) {
- okButton_actionPerformed(e);
- }
- });
- cancelButton.setText("Cancel");
- cancelButton.addActionListener(new java.awt.event.ActionListener() {
-
- public void actionPerformed(ActionEvent e) {
- cancelButton_actionPerformed(e);
- }
- });
- panel1.setMinimumSize(new Dimension(250, 78));
- getContentPane().add(panel1);
- panel1.add(pgNbLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
- ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 5), 0, 0));
- panel1.add(pgNbField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0
- ,GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(10, 5, 10, 10), 0, 0));
- panel1.add(okButton, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
- ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 10, 5), 0, 0));
- panel1.add(cancelButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
- ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 10, 10, 10), 0, 0));
- }
-
- void okButton_actionPerformed(ActionEvent e) {
- try {
- pageNumber = Integer.parseInt(pgNbField.getText());
- dispose();
- } catch (Exception ex) {
- pgNbField.setText("???");
+
+ void okButton_actionPerformed(ActionEvent e) {
+ try {
+ pageNumber = Integer.parseInt(pgNbField.getText());
+ dispose();
+ } catch (Exception ex) {
+ pgNbField.setText("???");
+ }
+
}
- }
+ void cancelButton_actionPerformed(ActionEvent e) {
+ pageNumber = -1;
+ dispose();
+ }
- void cancelButton_actionPerformed(ActionEvent e) {
- pageNumber = -1;
- dispose();
- }
+ public int getPageNumber() {
+ return pageNumber;
+ }
- public int getPageNumber() {
- return pageNumber;
- }
-}
\ No newline at end of file
+}
diff --git a/src/org/apache/fop/viewer/IconToolBar.java b/src/org/apache/fop/viewer/IconToolBar.java
index 8704aec91..c67d13eb4 100644
--- a/src/org/apache/fop/viewer/IconToolBar.java
+++ b/src/org/apache/fop/viewer/IconToolBar.java
@@ -1,10 +1,17 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.viewer;
/*
- originally contributed by
- Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
- Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
- Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
+ * originally contributed by
+ * Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
+ * Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
+ * Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
*/
@@ -13,23 +20,24 @@ import java.beans.PropertyChangeListener;
public class IconToolBar extends JToolBar {
- public JButton add(Action a) {
- String name = (String) a.getValue(Action.NAME);
- Icon icon = (Icon) a.getValue(Action.SMALL_ICON);
- return add(a, name, icon);
- }
-
- public JButton add(Action a, String name, Icon icon) {
- JButton b = new JButton(icon);
- b.setToolTipText(name);
- b.setEnabled(a.isEnabled());
- b.addActionListener(a);
- add(b);
- PropertyChangeListener actionPropertyChangeListener =
- createActionChangeListener(b);
- a.addPropertyChangeListener(actionPropertyChangeListener);
- return b;
- }
+ public JButton add(Action a) {
+ String name = (String)a.getValue(Action.NAME);
+ Icon icon = (Icon)a.getValue(Action.SMALL_ICON);
+ return add(a, name, icon);
+ }
+
+ public JButton add(Action a, String name, Icon icon) {
+ JButton b = new JButton(icon);
+ b.setToolTipText(name);
+ b.setEnabled(a.isEnabled());
+ b.addActionListener(a);
+ add(b);
+ PropertyChangeListener actionPropertyChangeListener =
+ createActionChangeListener(b);
+ a.addPropertyChangeListener(actionPropertyChangeListener);
+ return b;
+ }
+
}
diff --git a/src/org/apache/fop/viewer/LoadableProperties.java b/src/org/apache/fop/viewer/LoadableProperties.java
index 95010f25b..6e00e00bf 100644
--- a/src/org/apache/fop/viewer/LoadableProperties.java
+++ b/src/org/apache/fop/viewer/LoadableProperties.java
@@ -1,3 +1,10 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.viewer;
import java.io.*;
@@ -18,63 +25,63 @@ import java.util.*;
*/
public class LoadableProperties extends Hashtable {
- public LoadableProperties() {
- super();
- }
+ public LoadableProperties() {
+ super();
+ }
- public void load(InputStream inStream) throws IOException {
+ public void load(InputStream inStream) throws IOException {
- BufferedReader in = new BufferedReader(new InputStreamReader(inStream, "8859_1"));
+ BufferedReader in = new BufferedReader(new InputStreamReader(inStream,
+ "8859_1"));
- String aKey;
- String aValue;
- int index;
- String line = getNextLine(in);
- while (line != null) {
- line = line.trim();
- if (isValid(line)) {
- index = line.indexOf("=");
- aKey = line.substring(0, index);
- aValue = line.substring(index + 1);
- put(aKey, aValue);
- }
- line = getNextLine(in);
+ String aKey;
+ String aValue;
+ int index;
+ String line = getNextLine(in);
+ while (line != null) {
+ line = line.trim();
+ if (isValid(line)) {
+ index = line.indexOf("=");
+ aKey = line.substring(0, index);
+ aValue = line.substring(index + 1);
+ put(aKey, aValue);
+ }
+ line = getNextLine(in);
+ }
}
- }
- private boolean isValid(String str) {
- if (str == null)
- return false;
- if (str.length() > 0) {
- if (str.startsWith("#") || str.startsWith("!")) {
- return false;
- }
- }
- else {
- return false;
- }
+ private boolean isValid(String str) {
+ if (str == null)
+ return false;
+ if (str.length() > 0) {
+ if (str.startsWith("#") || str.startsWith("!")) {
+ return false;
+ }
+ } else {
+ return false;
+ }
- int index = str.indexOf("=");
- if (index > 0 && str.length() > index) {
- return true;
- }
- else {
- MessageHandler.logln(getClass().getName() + ": load(): invalid line " +
- str + "." + " Character '=' missed.");
- return false;
+ int index = str.indexOf("=");
+ if (index > 0 && str.length() > index) {
+ return true;
+ } else {
+ MessageHandler.logln(getClass().getName()
+ + ": load(): invalid line " + str + "."
+ + " Character '=' missed.");
+ return false;
+ }
}
- }
- private String getNextLine(BufferedReader br) {
- try {
- return br.readLine();
- } catch (Exception e) {
- return null;
- }
+ private String getNextLine(BufferedReader br) {
+ try {
+ return br.readLine();
+ } catch (Exception e) {
+ return null;
+ }
- }
+ }
}
diff --git a/src/org/apache/fop/viewer/MessageException.java b/src/org/apache/fop/viewer/MessageException.java
index 53da10fc3..eb9b25c15 100644
--- a/src/org/apache/fop/viewer/MessageException.java
+++ b/src/org/apache/fop/viewer/MessageException.java
@@ -1,3 +1,10 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.viewer;
import java.lang.Exception;
@@ -15,54 +22,57 @@ import java.lang.Exception;
*/
public class MessageException extends Exception {
- /** Angabe der auslösenden Exception, wie z.B. NullPointerException.
- * Dieses Feld ist optional.
- */
- protected Exception exception;
+ /**
+ * Angabe der auslösenden Exception, wie z.B. NullPointerException.
+ * Dieses Feld ist optional.
+ */
+ protected Exception exception;
+
+ /**
+ * ID der Meldung, die für diese Exception ausgegeben werden soll
+ */
+ protected String messageId;
- /**
- * ID der Meldung, die für diese Exception ausgegeben werden soll
- */
- protected String messageId;
+ /**
+ * Parameterliste zur Meldung
+ */
+ protected String[] parameterList;
- /**
- * Parameterliste zur Meldung
- */
- protected String[] parameterList;
+ // Konstruktoren
- // Konstruktoren
+ public MessageException() {
+ this("UNKNOWN_EXCEPTION");
+ }
- public MessageException() {
- this("UNKNOWN_EXCEPTION");
- }
+ public MessageException(String aMessageId) {
+ this(aMessageId, null);
+ }
- public MessageException(String aMessageId) {
- this(aMessageId, null);
- }
+ public MessageException(String aMessageId, String[] aParameterList) {
+ this(aMessageId, aParameterList, null);
+ }
- public MessageException(String aMessageId, String[] aParameterList) {
- this(aMessageId, aParameterList, null);
- }
+ public MessageException(String aMessageId, String[] aParameterList,
+ Exception anException) {
+ super(aMessageId);
+ messageId = aMessageId;
+ parameterList = aParameterList;
+ exception = anException;
+ }
- public MessageException(String aMessageId, String[] aParameterList, Exception anException) {
- super(aMessageId);
- messageId = aMessageId;
- parameterList = aParameterList;
- exception = anException;
- }
+ // Zugriffsmethoden
- // Zugriffsmethoden
+ public String getMessageId() {
+ return messageId;
+ }
- public String getMessageId() {
- return messageId;
- }
+ public String[] getParameterList() {
+ return parameterList;
+ }
- public String[] getParameterList() {
- return parameterList;
- }
+ public Exception getException() {
+ return exception;
+ }
- public Exception getException() {
- return exception;
- }
}
diff --git a/src/org/apache/fop/viewer/MessagesDialog.java b/src/org/apache/fop/viewer/MessagesDialog.java
index 33b763b0c..dafcefbff 100644
--- a/src/org/apache/fop/viewer/MessagesDialog.java
+++ b/src/org/apache/fop/viewer/MessagesDialog.java
@@ -1,3 +1,10 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.viewer;
import javax.swing.*;
@@ -23,208 +30,236 @@ import org.apache.fop.apps.*;
*/
public class MessagesDialog extends JOptionPane {
- static Translator res;
-
- public static void setTranslator(Translator aRes) {
- res = aRes;
- iniConstants();
- }
-
-
- static String DETAIL_OPTION;
- static String YES_OPTION;
- static String NO_OPTION;
- static String CANCEL_OPTION;
- static String OK_OPTION;
-
- static String[] defaultDetailOption;
- static String[] yesNoDetailOption;
- static String[] yesNoCancelDetailOption;
- static String[] okCancelDetailOption;
-
- static String[] defaultOption;
- static String[] yesNoOption;
- static String[] yesNoCancelOption;
- static String[] okCancelOption;
-
-
-
- private static void iniConstants() {
- DETAIL_OPTION = res.getString("Details");
- YES_OPTION = res.getString("Yes");
- NO_OPTION = res.getString("No");
- CANCEL_OPTION = res.getString("Cancel");
- OK_OPTION = res.getString("Ok");
-
- defaultDetailOption = new String[] { OK_OPTION, DETAIL_OPTION };
- yesNoDetailOption = new String[] { YES_OPTION, NO_OPTION, DETAIL_OPTION };
- yesNoCancelDetailOption = new String[] { YES_OPTION, NO_OPTION, CANCEL_OPTION, DETAIL_OPTION };
- okCancelDetailOption = new String[] { OK_OPTION, CANCEL_OPTION, DETAIL_OPTION };
-
- defaultOption = new String[] { OK_OPTION };
- yesNoOption = new String[] { YES_OPTION, NO_OPTION };
- yesNoCancelOption = new String[] { YES_OPTION, NO_OPTION, CANCEL_OPTION };
- okCancelOption = new String[] { OK_OPTION, CANCEL_OPTION };
- }
-
-
- protected String detailInformation = null;
- protected JDialog dialog = null;
- protected boolean showsDetails = false;
-
-// MessagesDialog.showConfirmDialog(null,preparedMes,title,
-// optionTypeIndex,messageTypeIndex);
-
- public MessagesDialog(Object message, int messageType, int optionType,
- Icon icon, Object[] options, Object initialValue) {
- super(message, messageType, optionType, icon, options, initialValue);
- setMinimumSize(new Dimension(240, 96));
- }
-
- public static int showConfirmDialog(Component parentComponent, Object message,
- String title, int optionType, int messageType) {
- Object[] options;
-
- switch (optionType) {
- case JOptionPane.YES_NO_OPTION:
- options = yesNoOption; break;
- case JOptionPane.YES_NO_CANCEL_OPTION:
- options = yesNoCancelOption; break;
- case JOptionPane.OK_CANCEL_OPTION:
- options = okCancelOption; break;
- default:
- options = defaultOption;
- }
+ static Translator res;
- MessagesDialog pane = new MessagesDialog(message, messageType,
- JOptionPane.DEFAULT_OPTION, null,
- options, options[0]);
-
- pane.setInitialValue(options[0]);
-
- JDialog dialog = pane.createDialog(parentComponent, title);
-
- pane.setDialog(dialog);
- pane.selectInitialValue();
-
- dialog.show();
-
- Object selectedValue = pane.getValue();
-
- if(selectedValue == null)
- return CLOSED_OPTION;
-
- if (selectedValue.equals(OK_OPTION))
- return JOptionPane.OK_OPTION;
- if (selectedValue.equals(CANCEL_OPTION))
- return JOptionPane.CANCEL_OPTION;
- if (selectedValue.equals(YES_OPTION))
- return JOptionPane.YES_OPTION;
- if (selectedValue.equals(NO_OPTION))
- return JOptionPane.NO_OPTION;
-
- return CLOSED_OPTION;
- }
-
- /**
- * Öffnet ein Dialogfenster, bei dem zusätzlich zu den spez. Buttons noch ein
- * 'Detail'-Button erscheint. Wird dieser Knopf vom Benutzer betätigt, erscheint
- * die übergebene Detailinformation in einem scrollbaren Bereich des Dialogs.
- */
- public static int showDetailDialog(Component parentComponent, Object message, String title, int optionType,
- int messageType, Icon icon, String newDetailInformation) {
- Object[] options;
-
- switch (optionType) {
- case JOptionPane.YES_NO_OPTION:
- options = yesNoDetailOption; break;
- case JOptionPane.YES_NO_CANCEL_OPTION:
- options = yesNoCancelDetailOption; break;
- case JOptionPane.OK_CANCEL_OPTION:
- options = okCancelDetailOption; break;
- default:
- options = defaultDetailOption;
+ public static void setTranslator(Translator aRes) {
+ res = aRes;
+ iniConstants();
}
- MessagesDialog pane = new MessagesDialog(message, messageType,
- JOptionPane.DEFAULT_OPTION, icon,
- options, options[0]);
-
- pane.setDetailInformation(newDetailInformation);
- pane.setInitialValue(options[0]);
- JDialog dialog = pane.createDialog(parentComponent, title);
-
- pane.setDialog(dialog);
- pane.selectInitialValue();
+ static String DETAIL_OPTION;
+ static String YES_OPTION;
+ static String NO_OPTION;
+ static String CANCEL_OPTION;
+ static String OK_OPTION;
+
+ static String[] defaultDetailOption;
+ static String[] yesNoDetailOption;
+ static String[] yesNoCancelDetailOption;
+ static String[] okCancelDetailOption;
+
+ static String[] defaultOption;
+ static String[] yesNoOption;
+ static String[] yesNoCancelOption;
+ static String[] okCancelOption;
+
+
+
+ private static void iniConstants() {
+ DETAIL_OPTION = res.getString("Details");
+ YES_OPTION = res.getString("Yes");
+ NO_OPTION = res.getString("No");
+ CANCEL_OPTION = res.getString("Cancel");
+ OK_OPTION = res.getString("Ok");
+
+ defaultDetailOption = new String[] {
+ OK_OPTION, DETAIL_OPTION
+ };
+ yesNoDetailOption = new String[] {
+ YES_OPTION, NO_OPTION, DETAIL_OPTION
+ };
+ yesNoCancelDetailOption = new String[] {
+ YES_OPTION, NO_OPTION, CANCEL_OPTION, DETAIL_OPTION
+ };
+ okCancelDetailOption = new String[] {
+ OK_OPTION, CANCEL_OPTION, DETAIL_OPTION
+ };
+
+ defaultOption = new String[] {
+ OK_OPTION
+ };
+ yesNoOption = new String[] {
+ YES_OPTION, NO_OPTION
+ };
+ yesNoCancelOption = new String[] {
+ YES_OPTION, NO_OPTION, CANCEL_OPTION
+ };
+ okCancelOption = new String[] {
+ OK_OPTION, CANCEL_OPTION
+ };
+ }
- dialog.show();
- Object selectedValue = pane.getValue();
+ protected String detailInformation = null;
+ protected JDialog dialog = null;
+ protected boolean showsDetails = false;
- if(selectedValue == null)
- return CLOSED_OPTION;
+ // MessagesDialog.showConfirmDialog(null,preparedMes,title,
+ // optionTypeIndex,messageTypeIndex);
- if (((String)selectedValue).equals(DETAIL_OPTION))
- return CLOSED_OPTION;
+ public MessagesDialog(Object message, int messageType, int optionType,
+ Icon icon, Object[] options, Object initialValue) {
+ super(message, messageType, optionType, icon, options, initialValue);
+ setMinimumSize(new Dimension(240, 96));
+ }
- if (selectedValue.equals(OK_OPTION))
- return JOptionPane.OK_OPTION;
- if (selectedValue.equals(CANCEL_OPTION))
- return JOptionPane.CANCEL_OPTION;
- if (selectedValue.equals(YES_OPTION))
- return JOptionPane.YES_OPTION;
- if (selectedValue.equals(NO_OPTION))
- return JOptionPane.NO_OPTION;
+ public static int showConfirmDialog(Component parentComponent,
+ Object message, String title,
+ int optionType, int messageType) {
+ Object[] options;
+
+ switch (optionType) {
+ case JOptionPane.YES_NO_OPTION:
+ options = yesNoOption;
+ break;
+ case JOptionPane.YES_NO_CANCEL_OPTION:
+ options = yesNoCancelOption;
+ break;
+ case JOptionPane.OK_CANCEL_OPTION:
+ options = okCancelOption;
+ break;
+ default:
+ options = defaultOption;
+ }
+
+ MessagesDialog pane = new MessagesDialog(message, messageType,
+ JOptionPane.DEFAULT_OPTION,
+ null, options, options[0]);
+
+ pane.setInitialValue(options[0]);
+
+ JDialog dialog = pane.createDialog(parentComponent, title);
+
+ pane.setDialog(dialog);
+ pane.selectInitialValue();
+
+ dialog.show();
+
+ Object selectedValue = pane.getValue();
+
+ if (selectedValue == null)
+ return CLOSED_OPTION;
+
+ if (selectedValue.equals(OK_OPTION))
+ return JOptionPane.OK_OPTION;
+ if (selectedValue.equals(CANCEL_OPTION))
+ return JOptionPane.CANCEL_OPTION;
+ if (selectedValue.equals(YES_OPTION))
+ return JOptionPane.YES_OPTION;
+ if (selectedValue.equals(NO_OPTION))
+ return JOptionPane.NO_OPTION;
+
+ return CLOSED_OPTION;
+ }
- return CLOSED_OPTION;
- }
+ /**
+ * Öffnet ein Dialogfenster, bei dem zusätzlich zu den spez. Buttons noch ein
+ * 'Detail'-Button erscheint. Wird dieser Knopf vom Benutzer betätigt, erscheint
+ * die übergebene Detailinformation in einem scrollbaren Bereich des Dialogs.
+ */
+ public static int showDetailDialog(Component parentComponent,
+ Object message, String title,
+ int optionType, int messageType,
+ Icon icon,
+ String newDetailInformation) {
+ Object[] options;
+
+ switch (optionType) {
+ case JOptionPane.YES_NO_OPTION:
+ options = yesNoDetailOption;
+ break;
+ case JOptionPane.YES_NO_CANCEL_OPTION:
+ options = yesNoCancelDetailOption;
+ break;
+ case JOptionPane.OK_CANCEL_OPTION:
+ options = okCancelDetailOption;
+ break;
+ default:
+ options = defaultDetailOption;
+ }
+
+ MessagesDialog pane = new MessagesDialog(message, messageType,
+ JOptionPane.DEFAULT_OPTION,
+ icon, options, options[0]);
+
+ pane.setDetailInformation(newDetailInformation);
+ pane.setInitialValue(options[0]);
+
+ JDialog dialog = pane.createDialog(parentComponent, title);
+
+ pane.setDialog(dialog);
+ pane.selectInitialValue();
+
+ dialog.show();
+
+ Object selectedValue = pane.getValue();
+
+ if (selectedValue == null)
+ return CLOSED_OPTION;
+
+ if (((String)selectedValue).equals(DETAIL_OPTION))
+ return CLOSED_OPTION;
+
+ if (selectedValue.equals(OK_OPTION))
+ return JOptionPane.OK_OPTION;
+ if (selectedValue.equals(CANCEL_OPTION))
+ return JOptionPane.CANCEL_OPTION;
+ if (selectedValue.equals(YES_OPTION))
+ return JOptionPane.YES_OPTION;
+ if (selectedValue.equals(NO_OPTION))
+ return JOptionPane.NO_OPTION;
+
+ return CLOSED_OPTION;
+ }
- /**
- * Die Methode fügt in den übergebenen Dialog eine scrollbare Textkomponente ein,
- * in der die Detailinformation angezeigt wird.
- *
- * @param JDialog dialog Der Dialog, in den die Textkomponente eingefügt werden soll
- */
- protected void displayDetails(JDialog dialog) {
- if (getDetailInformation() != null && dialog != null && showsDetails == false) {
- showsDetails = true;
- JScrollPane aScrollPane = new JScrollPane();
- JTextArea aTextArea = new JTextArea();
- StringWriter aStringWriter = new StringWriter();
+ /**
+ * Die Methode fügt in den übergebenen Dialog eine scrollbare Textkomponente ein,
+ * in der die Detailinformation angezeigt wird.
+ *
+ * @param JDialog dialog Der Dialog, in den die Textkomponente eingefügt werden soll
+ */
+ protected void displayDetails(JDialog dialog) {
+ if (getDetailInformation() != null && dialog != null
+ && showsDetails == false) {
+ showsDetails = true;
+ JScrollPane aScrollPane = new JScrollPane();
+ JTextArea aTextArea = new JTextArea();
+ StringWriter aStringWriter = new StringWriter();
+
+ aTextArea.setText(getDetailInformation());
+ aTextArea.setEditable(false);
+
+ aScrollPane.getViewport().add(aTextArea, null);
+ dialog.getContentPane().add(aScrollPane, BorderLayout.SOUTH);
+ aScrollPane.setPreferredSize(new Dimension(320, 240));
+ dialog.pack();
+ }
+ }
- aTextArea.setText(getDetailInformation());
- aTextArea.setEditable(false);
+ // Zugriff
- aScrollPane.getViewport().add(aTextArea, null);
- dialog.getContentPane().add(aScrollPane, BorderLayout.SOUTH);
- aScrollPane.setPreferredSize(new Dimension(320, 240));
- dialog.pack();
+ public void setValue(Object aValue) {
+ if (aValue != null && DETAIL_OPTION.equals(aValue))
+ displayDetails(getDialog());
+ else
+ super.setValue(aValue);
}
- }
- // Zugriff
-
- public void setValue(Object aValue) {
- if (aValue != null && DETAIL_OPTION.equals(aValue))
- displayDetails(getDialog());
- else
- super.setValue(aValue);
- }
+ public String getDetailInformation() {
+ return detailInformation;
+ }
- public String getDetailInformation() {
- return detailInformation;
- }
+ public void setDetailInformation(String aValue) {
+ detailInformation = aValue;
+ }
- public void setDetailInformation(String aValue) {
- detailInformation = aValue;
- }
+ public JDialog getDialog() {
+ return dialog;
+ }
- public JDialog getDialog() {
- return dialog;
- }
+ public void setDialog(JDialog aValue) {
+ dialog = aValue;
+ }
- public void setDialog(JDialog aValue) {
- dialog = aValue;
- }
}
diff --git a/src/org/apache/fop/viewer/PreviewDialog.java b/src/org/apache/fop/viewer/PreviewDialog.java
index 15ca7390a..29ba72a8f 100644
--- a/src/org/apache/fop/viewer/PreviewDialog.java
+++ b/src/org/apache/fop/viewer/PreviewDialog.java
@@ -1,18 +1,24 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.viewer;
/*
- originally contributed by
- Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
- Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
- Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
-
- Doro Wiarda (wiarda@dwiarda.com:
- added MessageListener support and made
- the showing of the progress and error
- messages Swing thread safe.
- This is needed as xml parse errors do not
- necessarily occur in the
- EventDispatchThread.
+ * originally contributed by
+ * Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
+ * Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
+ * Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
+ * Doro Wiarda (wiarda@dwiarda.com:
+ * added MessageListener support and made
+ * the showing of the progress and error
+ * messages Swing thread safe.
+ * This is needed as xml parse errors do not
+ * necessarily occur in the
+ * EventDispatchThread.
*/
import java.awt.*;
@@ -32,7 +38,7 @@ import org.apache.fop.messaging.*;
* Frame and User Interface for Preview
*/
public class PreviewDialog extends JFrame implements ProgressListener,
- MessageListener {
+ MessageListener {
protected Translator res;
@@ -49,9 +55,14 @@ public class PreviewDialog extends JFrame implements ProgressListener,
protected Command nextPageAction;
protected Command lastPageAction;
- protected JLabel zoomLabel = new JLabel(); //{public float getAlignmentY() { return 0.0f; }};
+ protected JLabel zoomLabel =
+ new JLabel(); // {public float getAlignmentY() { return 0.0f; }};
protected JComboBox scale = new JComboBox() {
- public float getAlignmentY() { return 0.5f; }};
+ public float getAlignmentY() {
+ return 0.5f;
+ }
+
+ };
protected JScrollPane previewArea = new JScrollPane();
// protected JLabel statusBar = new JLabel();
@@ -70,97 +81,118 @@ public class PreviewDialog extends JFrame implements ProgressListener,
* @param aRes the to use translator
*/
public PreviewDialog(AWTRenderer aRenderer, Translator aRes) {
- res = aRes;
- renderer = aRenderer;
-
- printAction = new Command(res.getString("Print"), "Print") {
- public void doit() {print();}};
- firstPageAction =
- new Command(res.getString("First page"), "firstpg") {
- public void doit() {goToFirstPage(null);}};
- previousPageAction =
- new Command(res.getString("Previous page"), "prevpg") {
- public void doit() {goToPreviousPage(null);}};
- nextPageAction = new Command(res.getString("Next page"),"nextpg") {
- public void doit() {goToNextPage(null);}};
- lastPageAction = new Command(res.getString("Last page"), "lastpg") {
- public void doit() {goToLastPage(null);}};
-
- setDefaultCloseOperation(DISPOSE_ON_CLOSE);
- this.setSize(new Dimension(379, 476));
- previewArea.setMinimumSize(new Dimension(50, 50));
-
- this.setTitle("FOP: AWT-" + res.getString("Preview"));
-
- scale.addItem("25");
- scale.addItem("50");
- scale.addItem("75");
- scale.addItem("100");
- scale.addItem("150");
- scale.addItem("200");
-
- scale.setMaximumSize(new Dimension(80, 24));
- scale.setPreferredSize(new Dimension(80, 24));
-
- scale.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(ActionEvent e) {
- scale_actionPerformed(e);
- }
- });
-
- scale.setSelectedItem("100");
- renderer.setScaleFactor(100.0);
-
- zoomLabel.setText(res.getString("Zoom"));
-
- this.setJMenuBar(setupMenue());
-
- this.getContentPane().add(toolBar, BorderLayout.NORTH);
-
- toolBar.add(printAction);
- toolBar.addSeparator();
- toolBar.add(firstPageAction);
- toolBar.add(previousPageAction);
- toolBar.add(nextPageAction);
- toolBar.add(lastPageAction);
- toolBar.addSeparator();
- toolBar.add(zoomLabel, null);
- toolBar.addSeparator();
- toolBar.add(scale, null);
-
- this.getContentPane().add(previewArea, BorderLayout.CENTER);
- this.getContentPane().add(statusBar, BorderLayout.SOUTH);
-
- statisticsStatus.setBorder(BorderFactory.createEtchedBorder());
- processStatus.setBorder(BorderFactory.createEtchedBorder());
- infoStatus.setBorder(BorderFactory.createEtchedBorder());
-
- statusBar.setLayout(statusBarLayout);
-
- processStatus.setPreferredSize(new Dimension(200, 21));
- statisticsStatus.setPreferredSize(new Dimension(100, 21));
- infoStatus.setPreferredSize(new Dimension(100, 21));
- processStatus.setMinimumSize(new Dimension(200, 21));
- statisticsStatus.setMinimumSize(new Dimension(100, 21));
- infoStatus.setMinimumSize(new Dimension(100, 21));
- statusBar.add(processStatus,
- new GridBagConstraints(0, 0, 2, 1, 2.0, 0.0,
- GridBagConstraints.CENTER,
- GridBagConstraints.HORIZONTAL,
- new Insets(0, 0, 0, 5), 0, 0));
- statusBar.add(statisticsStatus,
- new GridBagConstraints(2, 0, 1, 2, 1.0, 0.0,
- GridBagConstraints.CENTER,
- GridBagConstraints.HORIZONTAL,
- new Insets(0, 0, 0, 5), 0, 0));
- statusBar.add(infoStatus,
- new GridBagConstraints(3, 0, 1, 1, 1.0, 0.0,
- GridBagConstraints.CENTER,
- GridBagConstraints.HORIZONTAL,
- new Insets(0, 0, 0, 0), 0, 0));
-
- previewArea.getViewport().add(previewImageLabel);
- showPage();
+ res = aRes;
+ renderer = aRenderer;
+
+ printAction = new Command(res.getString("Print"), "Print") {
+ public void doit() {
+ print();
+ }
+
+ };
+ firstPageAction = new Command(res.getString("First page"),
+ "firstpg") {
+ public void doit() {
+ goToFirstPage(null);
+ }
+
+ };
+ previousPageAction = new Command(res.getString("Previous page"),
+ "prevpg") {
+ public void doit() {
+ goToPreviousPage(null);
+ }
+
+ };
+ nextPageAction = new Command(res.getString("Next page"), "nextpg") {
+ public void doit() {
+ goToNextPage(null);
+ }
+
+ };
+ lastPageAction = new Command(res.getString("Last page"), "lastpg") {
+ public void doit() {
+ goToLastPage(null);
+ }
+
+ };
+
+ setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+ this.setSize(new Dimension(379, 476));
+ previewArea.setMinimumSize(new Dimension(50, 50));
+
+ this.setTitle("FOP: AWT-" + res.getString("Preview"));
+
+ scale.addItem("25");
+ scale.addItem("50");
+ scale.addItem("75");
+ scale.addItem("100");
+ scale.addItem("150");
+ scale.addItem("200");
+
+ scale.setMaximumSize(new Dimension(80, 24));
+ scale.setPreferredSize(new Dimension(80, 24));
+
+ scale.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ scale_actionPerformed(e);
+ }
+
+ });
+
+ scale.setSelectedItem("100");
+ renderer.setScaleFactor(100.0);
+
+ zoomLabel.setText(res.getString("Zoom"));
+
+ this.setJMenuBar(setupMenue());
+
+ this.getContentPane().add(toolBar, BorderLayout.NORTH);
+
+ toolBar.add(printAction);
+ toolBar.addSeparator();
+ toolBar.add(firstPageAction);
+ toolBar.add(previousPageAction);
+ toolBar.add(nextPageAction);
+ toolBar.add(lastPageAction);
+ toolBar.addSeparator();
+ toolBar.add(zoomLabel, null);
+ toolBar.addSeparator();
+ toolBar.add(scale, null);
+
+ this.getContentPane().add(previewArea, BorderLayout.CENTER);
+ this.getContentPane().add(statusBar, BorderLayout.SOUTH);
+
+ statisticsStatus.setBorder(BorderFactory.createEtchedBorder());
+ processStatus.setBorder(BorderFactory.createEtchedBorder());
+ infoStatus.setBorder(BorderFactory.createEtchedBorder());
+
+ statusBar.setLayout(statusBarLayout);
+
+ processStatus.setPreferredSize(new Dimension(200, 21));
+ statisticsStatus.setPreferredSize(new Dimension(100, 21));
+ infoStatus.setPreferredSize(new Dimension(100, 21));
+ processStatus.setMinimumSize(new Dimension(200, 21));
+ statisticsStatus.setMinimumSize(new Dimension(100, 21));
+ infoStatus.setMinimumSize(new Dimension(100, 21));
+ statusBar.add(processStatus,
+ new GridBagConstraints(0, 0, 2, 1, 2.0, 0.0,
+ GridBagConstraints.CENTER,
+ GridBagConstraints.HORIZONTAL,
+ new Insets(0, 0, 0, 5), 0, 0));
+ statusBar.add(statisticsStatus,
+ new GridBagConstraints(2, 0, 1, 2, 1.0, 0.0,
+ GridBagConstraints.CENTER,
+ GridBagConstraints.HORIZONTAL,
+ new Insets(0, 0, 0, 5), 0, 0));
+ statusBar.add(infoStatus,
+ new GridBagConstraints(3, 0, 1, 1, 1.0, 0.0,
+ GridBagConstraints.CENTER,
+ GridBagConstraints.HORIZONTAL,
+ new Insets(0, 0, 0, 0), 0, 0));
+
+ previewArea.getViewport().add(previewImageLabel);
+ showPage();
}
/**
@@ -169,68 +201,128 @@ public class PreviewDialog extends JFrame implements ProgressListener,
* @return the newly created menubar
*/
private JMenuBar setupMenue() {
- JMenuBar menuBar;
- JMenuItem menuItem;
- JMenu menu;
- JMenu subMenu;
+ JMenuBar menuBar;
+ JMenuItem menuItem;
+ JMenu menu;
+ JMenu subMenu;
- menuBar = new JMenuBar();
- menu = new JMenu(res.getString("File"));
+ menuBar = new JMenuBar();
+ menu = new JMenu(res.getString("File"));
subMenu = new JMenu("OutputFormat");
- subMenu.add(new Command("mHTML"));
- subMenu.add(new Command("mPDF"));
- subMenu.add(new Command("mRTF"));
- subMenu.add(new Command("mTEXT"));
+ subMenu.add(new Command("mHTML"));
+ subMenu.add(new Command("mPDF"));
+ subMenu.add(new Command("mRTF"));
+ subMenu.add(new Command("mTEXT"));
// menu.add(subMenu);
// menu.addSeparator();
menu.add(new Command(res.getString("Print")) {
- public void doit(){print();}});
+ public void doit() {
+ print();
+ }
+
+ });
menu.addSeparator();
menu.add(new Command(res.getString("Exit")) {
- public void doit() {dispose();}} );
- menuBar.add(menu);
- menu = new JMenu(res.getString("View"));
+ public void doit() {
+ dispose();
+ }
+
+ });
+ menuBar.add(menu);
+ menu = new JMenu(res.getString("View"));
menu.add(new Command(res.getString("First page")) {
- public void doit() {goToFirstPage(null);}} );
+ public void doit() {
+ goToFirstPage(null);
+ }
+
+ });
menu.add(new Command(res.getString("Previous page")) {
- public void doit() {goToPreviousPage(null);}} );
+ public void doit() {
+ goToPreviousPage(null);
+ }
+
+ });
menu.add(new Command(res.getString("Next page")) {
- public void doit() {goToNextPage(null);}} );
+ public void doit() {
+ goToNextPage(null);
+ }
+
+ });
menu.add(new Command(res.getString("Last page")) {
- public void doit() {goToLastPage(null);}} );
+ public void doit() {
+ goToLastPage(null);
+ }
+
+ });
menu.add(new Command(res.getString("Go to Page") + " ...") {
- public void doit() {goToPage(null);}} );
+ public void doit() {
+ goToPage(null);
+ }
+
+ });
menu.addSeparator();
subMenu = new JMenu(res.getString("Zoom"));
- subMenu.add(new Command("25%") {
- public void doit() {setScale(25.0);}} );
- subMenu.add(new Command("50%") {
- public void doit() {setScale(50.0);}} );
- subMenu.add(new Command("75%") {
- public void doit() {setScale(75.0);}} );
- subMenu.add(new Command("100%") {
- public void doit() {setScale(100.0);}} );
- subMenu.add(new Command("150%") {
- public void doit() {setScale(150.0);}} );
- subMenu.add(new Command("200%") {
- public void doit() {setScale(200.0);}} );
+ subMenu.add(new Command("25%") {
+ public void doit() {
+ setScale(25.0);
+ }
+
+ });
+ subMenu.add(new Command("50%") {
+ public void doit() {
+ setScale(50.0);
+ }
+
+ });
+ subMenu.add(new Command("75%") {
+ public void doit() {
+ setScale(75.0);
+ }
+
+ });
+ subMenu.add(new Command("100%") {
+ public void doit() {
+ setScale(100.0);
+ }
+
+ });
+ subMenu.add(new Command("150%") {
+ public void doit() {
+ setScale(150.0);
+ }
+
+ });
+ subMenu.add(new Command("200%") {
+ public void doit() {
+ setScale(200.0);
+ }
+
+ });
menu.add(subMenu);
menu.addSeparator();
menu.add(new Command(res.getString("Default zoom")) {
- public void doit() {setScale(100.0);}} );
- menuBar.add(menu);
- menu = new JMenu(res.getString("Help"));
+ public void doit() {
+ setScale(100.0);
+ }
+
+ });
+ menuBar.add(menu);
+ menu = new JMenu(res.getString("Help"));
menu.add(new Command(res.getString("Index")));
menu.addSeparator();
menu.add(new Command(res.getString("Introduction")));
menu.addSeparator();
- menu.add(new Command(res.getString("About")){
- public void doit() {startHelpAbout(null);}} );
- menuBar.add(menu);
- return menuBar;
+ menu.add(new Command(res.getString("About")) {
+ public void doit() {
+ startHelpAbout(null);
+ }
+
+ });
+ menuBar.add(menu);
+ return menuBar;
}
- //Aktion Hilfe | Info durchgeführt
+ // Aktion Hilfe | Info durchgeführt
/**
* Show the About box
@@ -238,14 +330,14 @@ public class PreviewDialog extends JFrame implements ProgressListener,
* @param e a value of type 'ActionEvent'
*/
public void startHelpAbout(ActionEvent e) {
- PreviewDialogAboutBox dlg = new PreviewDialogAboutBox(this);
- Dimension dlgSize = dlg.getPreferredSize();
- Dimension frmSize = getSize();
- Point loc = getLocation();
- dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,
- (frmSize.height - dlgSize.height) / 2 + loc.y);
- dlg.setModal(true);
- dlg.show();
+ PreviewDialogAboutBox dlg = new PreviewDialogAboutBox(this);
+ Dimension dlgSize = dlg.getPreferredSize();
+ Dimension frmSize = getSize();
+ Point loc = getLocation();
+ dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,
+ (frmSize.height - dlgSize.height) / 2 + loc.y);
+ dlg.setModal(true);
+ dlg.show();
}
/**
@@ -254,19 +346,19 @@ public class PreviewDialog extends JFrame implements ProgressListener,
* @param number the page number to go to
*/
private void goToPage(int number) {
- currentPage = number;
- renderer.setPageNumber(number);
- showPage();
+ currentPage = number;
+ renderer.setPageNumber(number);
+ showPage();
}
/**
* Shows the previous page.
*/
private void goToPreviousPage(ActionEvent e) {
- if (currentPage <= 0)
- return;
- currentPage--;
- goToPage(currentPage);
+ if (currentPage <= 0)
+ return;
+ currentPage--;
+ goToPage(currentPage);
}
@@ -274,10 +366,10 @@ public class PreviewDialog extends JFrame implements ProgressListener,
* Shows the next page.
*/
private void goToNextPage(ActionEvent e) {
- if (currentPage >= pageCount - 1)
- return;
- currentPage++;
- goToPage(currentPage);
+ if (currentPage >= pageCount - 1)
+ return;
+ currentPage++;
+ goToPage(currentPage);
}
/**
@@ -285,10 +377,11 @@ public class PreviewDialog extends JFrame implements ProgressListener,
*/
private void goToLastPage(ActionEvent e) {
- if (currentPage == pageCount - 1) return;
- currentPage = pageCount - 1;
+ if (currentPage == pageCount - 1)
+ return;
+ currentPage = pageCount - 1;
- goToPage(currentPage);
+ goToPage(currentPage);
}
/**
@@ -296,69 +389,72 @@ public class PreviewDialog extends JFrame implements ProgressListener,
*/
private void goToPage(ActionEvent e) {
- GoToPageDialog d = new GoToPageDialog(this, res.getString("Go to Page"), true);
- d.setLocation((int) getLocation().getX() + 50, (int) getLocation().getY() + 50);
- d.show();
- currentPage = d.getPageNumber();
+ GoToPageDialog d = new GoToPageDialog(this,
+ res.getString("Go to Page"),
+ true);
+ d.setLocation((int)getLocation().getX() + 50,
+ (int)getLocation().getY() + 50);
+ d.show();
+ currentPage = d.getPageNumber();
- if (currentPage < 1 || currentPage > pageCount)
- return;
+ if (currentPage < 1 || currentPage > pageCount)
+ return;
- currentPage--;
+ currentPage--;
- goToPage(currentPage);
+ goToPage(currentPage);
}
/**
* Shows the first page.
*/
private void goToFirstPage(ActionEvent e) {
- if (currentPage == 0)
- return;
- currentPage = 0;
- goToPage(currentPage);
+ if (currentPage == 0)
+ return;
+ currentPage = 0;
+ goToPage(currentPage);
}
private void print() {
- PrinterJob pj = PrinterJob.getPrinterJob();
- // Nicht nötig, Pageable get a Printable.
- // pj.setPrintable(renderer);
- pj.setPageable(renderer);
-
- if (pj.printDialog()) {
- try {
- pj.print();
- } catch(PrinterException pe) {
- pe.printStackTrace();
- }
- }
+ PrinterJob pj = PrinterJob.getPrinterJob();
+ // Nicht nötig, Pageable get a Printable.
+ // pj.setPrintable(renderer);
+ pj.setPageable(renderer);
+
+ if (pj.printDialog()) {
+ try {
+ pj.print();
+ } catch (PrinterException pe) {
+ pe.printStackTrace();
+ }
+ }
}
public void setScale(double scaleFactor) {
- if (scaleFactor == 25.0)
- scale.setSelectedIndex(0);
- else if (scaleFactor == 50.0)
- scale.setSelectedIndex(1);
- else if (scaleFactor == 75.0)
- scale.setSelectedIndex(2);
- else if (scaleFactor == 100.0)
- scale.setSelectedIndex(3);
- else if (scaleFactor == 150.0)
- scale.setSelectedIndex(4);
- else if (scaleFactor == 200.0)
- scale.setSelectedIndex(5);
-
- renderer.setScaleFactor(scaleFactor);
- showPage();
+ if (scaleFactor == 25.0)
+ scale.setSelectedIndex(0);
+ else if (scaleFactor == 50.0)
+ scale.setSelectedIndex(1);
+ else if (scaleFactor == 75.0)
+ scale.setSelectedIndex(2);
+ else if (scaleFactor == 100.0)
+ scale.setSelectedIndex(3);
+ else if (scaleFactor == 150.0)
+ scale.setSelectedIndex(4);
+ else if (scaleFactor == 200.0)
+ scale.setSelectedIndex(5);
+
+ renderer.setScaleFactor(scaleFactor);
+ showPage();
}
void scale_actionPerformed(ActionEvent e) {
- setScale(new Double((String)scale.getSelectedItem()).doubleValue());
+ setScale(new Double((String)scale.getSelectedItem()).doubleValue());
}
public void progress(int percentage) {
- progress(new String(percentage + "%"));
+ progress(new String(percentage + "%"));
}
public void progress(int percentage, String message) {
@@ -367,176 +463,175 @@ public class PreviewDialog extends JFrame implements ProgressListener,
/**
- * Setting the text of a JLabel is not thread save, it
+ * Setting the text of a JLabel is not thread save, it
* needs to be done in the EventThread. Here we make sure
* it is done.
*/
public void progress(String message) {
- SwingUtilities.invokeLater( new showProgress( message, false ) );
+ SwingUtilities.invokeLater(new showProgress(message, false));
}
- /**
- * This class is used to show status and error messages in
+ /**
+ * This class is used to show status and error messages in
* a thread safe way.
*/
- class showProgress implements Runnable{
+ class showProgress implements Runnable {
+
/**
- * The message to display
- */
- Object message;
-
+ * The message to display
+ */
+ Object message;
+
/**
- * Is this an errorMessage, i.e. should it be shown in
- * an JOptionPane or in the status bar.
- */
- boolean isErrorMessage = false;
-
+ * Is this an errorMessage, i.e. should it be shown in
+ * an JOptionPane or in the status bar.
+ */
+ boolean isErrorMessage = false;
+
/**
- * Constructs showProgress thread
- * @param message message to display
- * @param isErrorMessage show in status bar or in JOptionPane
- */
- public showProgress(Object message, boolean isErrorMessage){
- this.message = message;
- this.isErrorMessage = isErrorMessage;
- }
-
- public void run(){
- if( isErrorMessage ){
- JOptionPane.showMessageDialog(null, message, "Error",
- JOptionPane.ERROR_MESSAGE);
- }
- else processStatus.setText(message.toString());
- }
- }
-
- public void showPage(){
- showPageImage viewer = new showPageImage();
-
- if( SwingUtilities.isEventDispatchThread() ){
- viewer.run();
- }
- else SwingUtilities.invokeLater(viewer);
- }
+ * Constructs showProgress thread
+ * @param message message to display
+ * @param isErrorMessage show in status bar or in JOptionPane
+ */
+ public showProgress(Object message, boolean isErrorMessage) {
+ this.message = message;
+ this.isErrorMessage = isErrorMessage;
+ }
+
+ public void run() {
+ if (isErrorMessage) {
+ JOptionPane.showMessageDialog(null, message, "Error",
+ JOptionPane.ERROR_MESSAGE);
+ } else
+ processStatus.setText(message.toString());
+ }
+
+ }
+
+ public void showPage() {
+ showPageImage viewer = new showPageImage();
+
+ if (SwingUtilities.isEventDispatchThread()) {
+ viewer.run();
+ } else
+ SwingUtilities.invokeLater(viewer);
+ }
/**
- * This class is used to update the page image
- * in a thread safe way.
+ * This class is used to update the page image
+ * in a thread safe way.
*/
- class showPageImage implements Runnable{
-
- /**
- * The run method that does the actuall updating
+ class showPageImage implements Runnable {
+
+ /**
+ * The run method that does the actuall updating
*/
- public void run() {
- BufferedImage pageImage = null;
- Graphics graphics = null;
-
- renderer.render(currentPage);
- pageImage = renderer.getLastRenderedPage();
+ public void run() {
+ BufferedImage pageImage = null;
+ Graphics graphics = null;
+
+ renderer.render(currentPage);
+ pageImage = renderer.getLastRenderedPage();
if (pageImage == null)
return;
- graphics = pageImage.getGraphics();
- graphics.setColor(Color.black);
- graphics.drawRect(0, 0, pageImage.getWidth() - 1,
- pageImage.getHeight() -1 );
-
- previewImageLabel.setIcon(new ImageIcon(pageImage));
-
- pageCount = renderer.getPageCount();
-
- statisticsStatus.setText(res.getString("Page") + " " +
- (currentPage + 1) + " " +
- res.getString("of") + " " +
- pageCount);
- }
- }
-
-
- /**
+ graphics = pageImage.getGraphics();
+ graphics.setColor(Color.black);
+ graphics.drawRect(0, 0, pageImage.getWidth() - 1,
+ pageImage.getHeight() - 1);
+
+ previewImageLabel.setIcon(new ImageIcon(pageImage));
+
+ pageCount = renderer.getPageCount();
+
+ statisticsStatus.setText(res.getString("Page") + " "
+ + (currentPage + 1) + " "
+ + res.getString("of") + " " + pageCount);
+ }
+
+ }
+
+
+ /**
* Called by MessageHandler if an error message or a
* log message is received.
- */
- public void processMessage ( MessageEvent event ){
- String error = event.getMessage();
- String text = processStatus.getText();
- FontMetrics fmt = processStatus.getFontMetrics(
- processStatus.getFont());
- int width = processStatus.getWidth()-fmt.stringWidth("...");
- showProgress showIt;
-
- if( event.getMessageType() == event.LOG){
- if( !text.endsWith("\n") ) {
- text = text + error;
- while ( fmt.stringWidth(text) > width){
- text = text.substring(1);
- width = processStatus.getWidth()-fmt.stringWidth("...");
- }
- }
- else text = error;
- progress( text );
- }
- else{
- error = error.trim();
- if( error.equals(">") ){
- text = text + error;
- while ( fmt.stringWidth(text) > width){
- text = text.substring(1);
- width = processStatus.getWidth()-fmt.stringWidth("...");
- }
- progress( processStatus.getText() + error );
- return;
- }
- if( error.equals("") ) return;
- if( error.length() < 60) {
- showIt = new showProgress( error, true );
- }
- else{
- StringTokenizer tok = new StringTokenizer(error," ");
+ */
+ public void processMessage(MessageEvent event) {
+ String error = event.getMessage();
+ String text = processStatus.getText();
+ FontMetrics fmt =
+ processStatus.getFontMetrics(processStatus.getFont());
+ int width = processStatus.getWidth() - fmt.stringWidth("...");
+ showProgress showIt;
+
+ if (event.getMessageType() == event.LOG) {
+ if (!text.endsWith("\n")) {
+ text = text + error;
+ while (fmt.stringWidth(text) > width) {
+ text = text.substring(1);
+ width = processStatus.getWidth() - fmt.stringWidth("...");
+ }
+ } else
+ text = error;
+ progress(text);
+ } else {
+ error = error.trim();
+ if (error.equals(">")) {
+ text = text + error;
+ while (fmt.stringWidth(text) > width) {
+ text = text.substring(1);
+ width = processStatus.getWidth() - fmt.stringWidth("...");
+ }
+ progress(processStatus.getText() + error);
+ return;
+ }
+ if (error.equals(""))
+ return;
+ if (error.length() < 60) {
+ showIt = new showProgress(error, true);
+ } else {
+ StringTokenizer tok = new StringTokenizer(error, " ");
Vector labels = new Vector();
- StringBuffer buffer = new StringBuffer();
- String tmp,list[];
-
- while(tok.hasMoreTokens()){
- tmp = tok.nextToken();
- if( (buffer.length()+tmp.length() +1) < 60 ){
+ StringBuffer buffer = new StringBuffer();
+ String tmp, list[];
+
+ while (tok.hasMoreTokens()) {
+ tmp = tok.nextToken();
+ if ((buffer.length() + tmp.length() + 1) < 60) {
buffer.append(" ").append(tmp);
- }
- else{
+ } else {
labels.add(buffer.toString());
buffer = new StringBuffer();
buffer.append(tmp);
- }
- }
+ }
+ }
labels.add(buffer.toString());
- list = new String[ labels.size() ];
- for( int i = 0 ; i < labels.size() ; i++) {
- list[i] = labels.elementAt(i).toString();
- }
- showIt = new showProgress( list, true );
- }
- if( SwingUtilities.isEventDispatchThread() ){
- showIt.run();
- }
- else {
- try{
- SwingUtilities.invokeAndWait( showIt );
- }
- catch( Exception e){
- e.printStackTrace();
- progress( event.getMessage() );
- }
- }
- }
- }
+ list = new String[labels.size()];
+ for (int i = 0; i < labels.size(); i++) {
+ list[i] = labels.elementAt(i).toString();
+ }
+ showIt = new showProgress(list, true);
+ }
+ if (SwingUtilities.isEventDispatchThread()) {
+ showIt.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(showIt);
+ } catch (Exception e) {
+ e.printStackTrace();
+ progress(event.getMessage());
+ }
+ }
+ }
+ }
public void dispose() {
- System.exit(0);
+ System.exit(0);
}
-} // class PreviewDialog
+
+} // class PreviewDialog
diff --git a/src/org/apache/fop/viewer/PreviewDialogAboutBox.java b/src/org/apache/fop/viewer/PreviewDialogAboutBox.java
index 9aea565d6..decee0666 100644
--- a/src/org/apache/fop/viewer/PreviewDialogAboutBox.java
+++ b/src/org/apache/fop/viewer/PreviewDialogAboutBox.java
@@ -1,11 +1,17 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
package org.apache.fop.viewer;
/*
- originally contributed by
- Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
- Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
- Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
+ * originally contributed by
+ * Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
+ * Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
+ * Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
*/
@@ -20,79 +26,80 @@ import org.apache.fop.apps.Version;
public class PreviewDialogAboutBox extends Dialog implements ActionListener {
- JPanel panel1 = new JPanel();
- JPanel panel2 = new JPanel();
- JPanel insetsPanel1 = new JPanel();
- JPanel insetsPanel2 = new JPanel();
- JPanel insetsPanel3 = new JPanel();
- JButton button1 = new JButton();
- JLabel imageControl1 = new JLabel();
- ImageIcon imageIcon;
- JLabel label1 = new JLabel();
- JLabel label2 = new JLabel();
- JLabel label3 = new JLabel();
- JLabel label4 = new JLabel();
- BorderLayout borderLayout1 = new BorderLayout();
- BorderLayout borderLayout2 = new BorderLayout();
- FlowLayout flowLayout1 = new FlowLayout();
- FlowLayout flowLayout2 = new FlowLayout();
- GridLayout gridLayout1 = new GridLayout();
- String product = "FOP AWT-Preview";
- String version = "Version: " + Version.getVersion();
- String copyright = "See xml.apache.org";
- String comments = "";//"Print Preview";
-
- public PreviewDialogAboutBox(Frame parent) {
- super(parent);
- enableEvents(AWTEvent.WINDOW_EVENT_MASK);
-
- //imageIcon = new ImageIcon(getClass().getResource("Hier der Grafikname"));
- this.setTitle("Info");
- setResizable(false);
- panel1.setLayout(borderLayout1);
- panel2.setLayout(borderLayout2);
- insetsPanel1.setLayout(flowLayout1);
- insetsPanel2.setLayout(flowLayout1);
- insetsPanel2.setBorder(new EmptyBorder(10, 10, 10, 10));
- gridLayout1.setRows(4);
- gridLayout1.setColumns(1);
- label1.setText(product);
- label2.setText(version);
- label3.setText(copyright);
- label4.setText(comments);
- insetsPanel3.setLayout(gridLayout1);
- insetsPanel3.setBorder(new EmptyBorder(10, 60, 10, 10));
- button1.setText("OK");
- button1.addActionListener(this);
- insetsPanel2.add(imageControl1, null);
- panel2.add(insetsPanel2, BorderLayout.WEST);
- this.add(panel1, null);
- insetsPanel3.add(label1, null);
- insetsPanel3.add(label2, null);
- insetsPanel3.add(label3, null);
- insetsPanel3.add(label4, null);
- panel2.add(insetsPanel3, BorderLayout.CENTER);
- insetsPanel1.add(button1, null);
- panel1.add(insetsPanel1, BorderLayout.SOUTH);
- panel1.add(panel2, BorderLayout.NORTH);
- pack();
- }
-
- protected void processWindowEvent(WindowEvent e) {
- if (e.getID() == WindowEvent.WINDOW_CLOSING) {
- cancel();
+ JPanel panel1 = new JPanel();
+ JPanel panel2 = new JPanel();
+ JPanel insetsPanel1 = new JPanel();
+ JPanel insetsPanel2 = new JPanel();
+ JPanel insetsPanel3 = new JPanel();
+ JButton button1 = new JButton();
+ JLabel imageControl1 = new JLabel();
+ ImageIcon imageIcon;
+ JLabel label1 = new JLabel();
+ JLabel label2 = new JLabel();
+ JLabel label3 = new JLabel();
+ JLabel label4 = new JLabel();
+ BorderLayout borderLayout1 = new BorderLayout();
+ BorderLayout borderLayout2 = new BorderLayout();
+ FlowLayout flowLayout1 = new FlowLayout();
+ FlowLayout flowLayout2 = new FlowLayout();
+ GridLayout gridLayout1 = new GridLayout();
+ String product = "FOP AWT-Preview";
+ String version = "Version: " + Version.getVersion();
+ String copyright = "See xml.apache.org";
+ String comments = ""; // "Print Preview";
+
+ public PreviewDialogAboutBox(Frame parent) {
+ super(parent);
+ enableEvents(AWTEvent.WINDOW_EVENT_MASK);
+
+ // imageIcon = new ImageIcon(getClass().getResource("Hier der Grafikname"));
+ this.setTitle("Info");
+ setResizable(false);
+ panel1.setLayout(borderLayout1);
+ panel2.setLayout(borderLayout2);
+ insetsPanel1.setLayout(flowLayout1);
+ insetsPanel2.setLayout(flowLayout1);
+ insetsPanel2.setBorder(new EmptyBorder(10, 10, 10, 10));
+ gridLayout1.setRows(4);
+ gridLayout1.setColumns(1);
+ label1.setText(product);
+ label2.setText(version);
+ label3.setText(copyright);
+ label4.setText(comments);
+ insetsPanel3.setLayout(gridLayout1);
+ insetsPanel3.setBorder(new EmptyBorder(10, 60, 10, 10));
+ button1.setText("OK");
+ button1.addActionListener(this);
+ insetsPanel2.add(imageControl1, null);
+ panel2.add(insetsPanel2, BorderLayout.WEST);
+ this.add(panel1, null);
+ insetsPanel3.add(label1, null);
+ insetsPanel3.add(label2, null);
+ insetsPanel3.add(label3, null);
+ insetsPanel3.add(label4, null);
+ panel2.add(insetsPanel3, BorderLayout.CENTER);
+ insetsPanel1.add(button1, null);
+ panel1.add(insetsPanel1, BorderLayout.SOUTH);
+ panel1.add(panel2, BorderLayout.NORTH);
+ pack();
}
- super.processWindowEvent(e);
- }
- void cancel() {
- dispose();
- }
+ protected void processWindowEvent(WindowEvent e) {
+ if (e.getID() == WindowEvent.WINDOW_CLOSING) {
+ cancel();
+ }
+ super.processWindowEvent(e);
+ }
+
+ void cancel() {
+ dispose();
+ }
- public void actionPerformed(ActionEvent e) {
- if (e.getSource() == button1) {
- cancel();
+ public void actionPerformed(ActionEvent e) {
+ if (e.getSource() == button1) {
+ cancel();
+ }
}
- }
+
}
diff --git a/src/org/apache/fop/viewer/ProgressListener.java b/src/org/apache/fop/viewer/ProgressListener.java
index 751838917..b72fb7437 100644
--- a/src/org/apache/fop/viewer/ProgressListener.java
+++ b/src/org/apache/fop/viewer/ProgressListener.java
@@ -1,16 +1,23 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.viewer;
/*
- originally contributed by
- Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
- Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
- Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
+ * originally contributed by
+ * Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
+ * Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
+ * Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
*/
public interface ProgressListener {
- public void progress(int percentage);
- public void progress(String message);
- public void progress(int percentage, String message);
+ public void progress(int percentage);
+ public void progress(String message);
+ public void progress(int percentage, String message);
}
diff --git a/src/org/apache/fop/viewer/SecureResourceBundle.java b/src/org/apache/fop/viewer/SecureResourceBundle.java
index 3f68d6c16..6ed849ea9 100644
--- a/src/org/apache/fop/viewer/SecureResourceBundle.java
+++ b/src/org/apache/fop/viewer/SecureResourceBundle.java
@@ -1,3 +1,10 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.viewer;
import java.util.*;
@@ -14,85 +21,86 @@ import java.io.*;
* @author Stanislav.Gorkhover@jCatalog.com
* @version 1.0 18.03.1999
*/
-public class SecureResourceBundle extends ResourceBundle implements Translator {
+public class SecureResourceBundle extends ResourceBundle
+ implements Translator {
+
+ // Fehlende keys mit einer Meldung zurückgeben.
+ private boolean isMissingEmphasized = false;
- // Fehlende keys mit einer Meldung zurückgeben.
- private boolean isMissingEmphasized = false;
+ // private Properties lookup = new Properties();
+ private LoadableProperties lookup = new LoadableProperties();
- //private Properties lookup = new Properties();
- private LoadableProperties lookup = new LoadableProperties();
+ private boolean isSourceFound = true;
- private boolean isSourceFound = true;
+ public void setMissingEmphasized(boolean flag) {
+ isMissingEmphasized = flag;
+ }
+
+ /**
+ * Kreiert ein ResourceBundle mit der Quelle in in.
+ */
+
+ public SecureResourceBundle(InputStream in) {
+ try {
+ lookup.load(in);
+ } catch (Exception ex) {
+ MessageHandler.logln("Abgefangene Exception: " + ex.getMessage());
+ isSourceFound = false;
+ }
+ }
- public void setMissingEmphasized(boolean flag) {
- isMissingEmphasized = flag;
- }
- /**
- * Kreiert ein ResourceBundle mit der Quelle in in.
- */
- public SecureResourceBundle(InputStream in) {
- try {
- lookup.load(in);
- } catch(Exception ex) {
- MessageHandler.logln("Abgefangene Exception: " + ex.getMessage());
- isSourceFound = false;
+ public Enumeration getKeys() {
+ return lookup.keys();
}
- }
-
-
-
- public Enumeration getKeys() {
- return lookup.keys();
- }
-
-
-
- /**
- * Händelt den abgefragten Key, liefert entweder den zugehörigen Wert oder eine Meldung.
- * Die null wird nie zurückgegeben.
- * Schreibt die fehlenden Suchschlüssel in die Protokoll-Datei.
- * @return Object
- * - den zu dem Suchschlüssel key gefundenen Wert, falls vorhanden,
- * - Meldung Key key not found, falls der Suchschlüssel fehlt
- * und die Eigenschaft "jCatalog.DevelopmentStartModus" in der ini-Datei aus true gesetzt ist.
- *
- Meldung Key is null, falls der Suchschlüssel
null
ist.
- *
- *
- */
- public Object handleGetObject(String key) {
-
- if (key == null)
- return "Key is null";
-
- Object obj = lookup.get(key);
- if (obj != null)
- return obj;
- else {
- if (isMissingEmphasized) {
- MessageHandler.logln(getClass().getName() + ": missing key: " + key);
- return getMissedRepresentation(key.toString());
- }
- else
- return key.toString();
+
+
+
+ /**
+ * Händelt den abgefragten Key, liefert entweder den zugehörigen Wert oder eine Meldung.
+ * Die null wird nie zurückgegeben.
+ * Schreibt die fehlenden Suchschlüssel in die Protokoll-Datei.
+ * @return Object
+ * - den zu dem Suchschlüssel key gefundenen Wert, falls vorhanden,
+ * - Meldung Key key not found, falls der Suchschlüssel fehlt
+ * und die Eigenschaft "jCatalog.DevelopmentStartModus" in der ini-Datei aus true gesetzt ist.
+ *
- Meldung Key is null, falls der Suchschlüssel
null
ist.
+ *
+ *
+ */
+ public Object handleGetObject(String key) {
+
+ if (key == null)
+ return "Key is null";
+
+ Object obj = lookup.get(key);
+ if (obj != null)
+ return obj;
+ else {
+ if (isMissingEmphasized) {
+ MessageHandler.logln(getClass().getName() + ": missing key: "
+ + key);
+ return getMissedRepresentation(key.toString());
+ } else
+ return key.toString();
+ }
}
- }
- /**
- * Stellt fest, ob es den Key gibt.
- */
- public boolean contains(String key) {
- return (key == null || lookup.get(key) == null) ? false : true;
- }
+ /**
+ * Stellt fest, ob es den Key gibt.
+ */
+ public boolean contains(String key) {
+ return (key == null || lookup.get(key) == null) ? false : true;
+ }
- private String getMissedRepresentation(String str) {
- return "";
- }
+ private String getMissedRepresentation(String str) {
+ return "";
+ }
- public boolean isSourceFound() {
- return isSourceFound;
- }
+ public boolean isSourceFound() {
+ return isSourceFound;
+ }
-}
\ No newline at end of file
+}
diff --git a/src/org/apache/fop/viewer/Translator.java b/src/org/apache/fop/viewer/Translator.java
index 6c4da08f8..26e2cbaf7 100644
--- a/src/org/apache/fop/viewer/Translator.java
+++ b/src/org/apache/fop/viewer/Translator.java
@@ -1,3 +1,10 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.viewer;
@@ -10,20 +17,23 @@ package org.apache.fop.viewer;
*/
public interface Translator {
- /**
- * Übersetzt ein Wort.
- */
- public String getString(String key);
- /**
- * Ein Translator soll die fehlenden keys hervorheben können.
- */
- public void setMissingEmphasized(boolean b);
- /**
- * Gibt an ob die Übersetzungsquelle gefunden ist.
- */
- public boolean isSourceFound();
- /**
- * Gibt an ob ein Key in der Übersetzungsquelle vorhanden ist.
- */
- public boolean contains(String key);
-}
\ No newline at end of file
+ /**
+ * Übersetzt ein Wort.
+ */
+ public String getString(String key);
+
+ /**
+ * Ein Translator soll die fehlenden keys hervorheben können.
+ */
+ public void setMissingEmphasized(boolean b);
+
+ /**
+ * Gibt an ob die Übersetzungsquelle gefunden ist.
+ */
+ public boolean isSourceFound();
+
+ /**
+ * Gibt an ob ein Key in der Übersetzungsquelle vorhanden ist.
+ */
+ public boolean contains(String key);
+}
diff --git a/src/org/apache/fop/viewer/UserMessage.java b/src/org/apache/fop/viewer/UserMessage.java
index 512a6c728..ceb1ce0f9 100644
--- a/src/org/apache/fop/viewer/UserMessage.java
+++ b/src/org/apache/fop/viewer/UserMessage.java
@@ -1,3 +1,10 @@
+/*
+ * $Id$
+ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
+ * For details on use and redistribution please refer to the
+ * LICENSE file included with these sources.
+ */
+
package org.apache.fop.viewer;
import java.awt.*;
@@ -32,318 +39,391 @@ import javax.swing.JComponent.*;
*/
public class UserMessage {
- private static Translator res = null;
+ private static Translator res = null;
+
+ public static void setTranslator(Translator aRes) {
+ res = aRes;
+ if (res == null) {
+ MessageHandler.logln("UserMessage: setTranslator(null) !");
+ res = new SecureResourceBundle(null);
+ }
- public static void setTranslator(Translator aRes) {
- res = aRes;
- if (res == null) {
- MessageHandler.logln("UserMessage: setTranslator(null) !");
- res = new SecureResourceBundle(null);
+ MessagesDialog.setTranslator(res);
}
- MessagesDialog.setTranslator(res);
- }
-
-
- // Zulässige Werte für Dialogart:
- /**
- * Möglicher Wert des Meldungstypes. Fenster-Title "Info" (de).
- */
- private static final int INFO = JOptionPane.PLAIN_MESSAGE;
- /**
- * Möglicher Wert des Meldungstypes. Fenster-Title "Warnung" (de).
- */
- private static final int WARNING = JOptionPane.WARNING_MESSAGE;
- /**
- * Möglicher Wert des Meldungstypes. Fenster-Title "Frage" (de).
- */
- private static final int QUESTION = JOptionPane.QUESTION_MESSAGE;
- /**
- * Möglicher Wert des Meldungstypes. Fenster-Title "Fehler" (de).
- */
- private static final int ERROR = JOptionPane.ERROR_MESSAGE;
- /**
- * Möglicher Wert des Meldungstypes. Fenster-Title "Systemfehler" (de).
- */
- private static final int SYS_ERROR = JOptionPane.ERROR_MESSAGE;
-
-
-
- /* Style Constanten orientieren sich auf die
- * Constanten der ButtonDialog-Klasse und legen das Dialog-ButtonSet fest.
- */
- /** Wert für Setzten keines Buttons */
- public static final int STYLE_NOBUTTON = -2;
- /** Wert für Setzten von nur Ja-Button.*/
- public static final int STYLE_Y = JOptionPane.DEFAULT_OPTION;
- //ButtonDialog.YES; // = 1
- /** Wert für Setzten von Ja- und Nein-Buttons.*/
- public static final int STYLE_Y_N = JOptionPane.YES_NO_OPTION;
- //ButtonDialog.YES_NO; // = 2;
- /** Wert für Setzten von Ja-, Nein-und Abbruch Buttons.*/
- public static final int STYLE_Y_N_C = JOptionPane.YES_NO_CANCEL_OPTION;
- //ButtonDialog.YES_NO_CANCEL; // = 3;
-
-
- // Platzhalter für Parameter in der Properties-Datei
- private static final String PARAMETER_TAG = "&&&";
-
-
- /**
- * Benutzer-Antwort-Constanten orientieren sich auf die
- * Constanten der ButtonDialog-Klasse
- */
- /**Möglicher Rückgabewert @see ButtonDialog*/
- public static final int YES = JOptionPane.YES_OPTION;
- //ButtonDialog.YES; // = 2
- /**Möglicher Rückgabewert @see ButtonDialog*/
- public static final int NO = JOptionPane.NO_OPTION;
- //ButtonDialog.NO; // = 4;
- /**Möglicher Rückgabewert @see ButtonDialog*/
- public static final int CANCEL = JOptionPane.CANCEL_OPTION;
- //ButtonDialog.CANCEL; // = 8;
-
-
- // Default-Values
- private static int buttonType = STYLE_Y;
- private static int iconType = WARNING;
- private static String currentIconName = "";
- private static String actMessId = null;
- // private static MessagesDialog nobuttonDialog = null;
-
-
- /**
- * Ersetzt die eventuellen Platzhalter durch die übergebenen Parameter
- */
- static String prepareMessage(String rawText, String[] par) {
- MessageHandler.logln("prepareMessage(): " + rawText + ", parameter: " + par);
- int index = rawText.indexOf(PARAMETER_TAG);
- String composedMess = "";
- if ((index == -1) && (par == null)) return rawText;
- if ((index != -1) && (par == null)) {
- MessageHandler.logln("Message " + actMessId+ " erwartet Parameter. Aufgerufen ohne Parameter");
- return rawText;
+
+ // Zulässige Werte für Dialogart:
+
+ /**
+ * Möglicher Wert des Meldungstypes. Fenster-Title "Info" (de).
+ */
+ private static final int INFO = JOptionPane.PLAIN_MESSAGE;
+
+ /**
+ * Möglicher Wert des Meldungstypes. Fenster-Title "Warnung" (de).
+ */
+ private static final int WARNING = JOptionPane.WARNING_MESSAGE;
+
+ /**
+ * Möglicher Wert des Meldungstypes. Fenster-Title "Frage" (de).
+ */
+ private static final int QUESTION = JOptionPane.QUESTION_MESSAGE;
+
+ /**
+ * Möglicher Wert des Meldungstypes. Fenster-Title "Fehler" (de).
+ */
+ private static final int ERROR = JOptionPane.ERROR_MESSAGE;
+
+ /**
+ * Möglicher Wert des Meldungstypes. Fenster-Title "Systemfehler" (de).
+ */
+ private static final int SYS_ERROR = JOptionPane.ERROR_MESSAGE;
+
+
+
+ /*
+ * Style Constanten orientieren sich auf die
+ * Constanten der ButtonDialog-Klasse und legen das Dialog-ButtonSet fest.
+ */
+
+ /**
+ * Wert für Setzten keines Buttons
+ */
+ public static final int STYLE_NOBUTTON = -2;
+
+ /**
+ * Wert für Setzten von nur Ja-Button.
+ */
+ public static final int STYLE_Y = JOptionPane.DEFAULT_OPTION;
+ // ButtonDialog.YES; // = 1
+
+ /**
+ * Wert für Setzten von Ja- und Nein-Buttons.
+ */
+ public static final int STYLE_Y_N = JOptionPane.YES_NO_OPTION;
+ // ButtonDialog.YES_NO; // = 2;
+
+ /**
+ * Wert für Setzten von Ja-, Nein-und Abbruch Buttons.
+ */
+ public static final int STYLE_Y_N_C = JOptionPane.YES_NO_CANCEL_OPTION;
+ // ButtonDialog.YES_NO_CANCEL; // = 3;
+
+
+ // Platzhalter für Parameter in der Properties-Datei
+ private static final String PARAMETER_TAG = "&&&";
+
+
+ /**
+ * Benutzer-Antwort-Constanten orientieren sich auf die
+ * Constanten der ButtonDialog-Klasse
+ */
+
+ /**
+ * Möglicher Rückgabewert @see ButtonDialog
+ */
+ public static final int YES = JOptionPane.YES_OPTION;
+ // ButtonDialog.YES; // = 2
+
+ /**
+ * Möglicher Rückgabewert @see ButtonDialog
+ */
+ public static final int NO = JOptionPane.NO_OPTION;
+ // ButtonDialog.NO; // = 4;
+
+ /**
+ * Möglicher Rückgabewert @see ButtonDialog
+ */
+ public static final int CANCEL = JOptionPane.CANCEL_OPTION;
+ // ButtonDialog.CANCEL; // = 8;
+
+
+ // Default-Values
+ private static int buttonType = STYLE_Y;
+ private static int iconType = WARNING;
+ private static String currentIconName = "";
+ private static String actMessId = null;
+ // private static MessagesDialog nobuttonDialog = null;
+
+
+ /**
+ * Ersetzt die eventuellen Platzhalter durch die übergebenen Parameter
+ */
+ static String prepareMessage(String rawText, String[] par) {
+ MessageHandler.logln("prepareMessage(): " + rawText + ", parameter: "
+ + par);
+ int index = rawText.indexOf(PARAMETER_TAG);
+ String composedMess = "";
+ if ((index == -1) && (par == null))
+ return rawText;
+ if ((index != -1) && (par == null)) {
+ MessageHandler.logln("Message " + actMessId
+ + " erwartet Parameter. Aufgerufen ohne Parameter");
+ return rawText;
+ }
+ if ((index == -1) && (par != null)) {
+ MessageHandler.logln("Message " + actMessId
+ + " erwartet keine Parameter. Aufgerufen mit folgenden Parametern:");
+ for (int i = 0; i < par.length; ++i)
+ MessageHandler.logln(par[i].toString());
+ return rawText;
+ }
+ int tagCount = 0;
+ while (rawText.indexOf(PARAMETER_TAG) != -1) {
+ index = rawText.indexOf(PARAMETER_TAG);
+ try {
+ composedMess += rawText.substring(0, index) + par[tagCount];
+ } catch (ArrayIndexOutOfBoundsException ex) {
+ MessageHandler.logln("Anzahl der übergebenen Parameter zu der Meldung "
+ + actMessId
+ + " ist weniger als erwartet.");
+ ex.printStackTrace();
+ return composedMess + rawText;
+ }
+ rawText = rawText.substring(index + PARAMETER_TAG.length());
+ tagCount++;
+ }
+ composedMess += rawText;
+ if (tagCount != par.length)
+ MessageHandler.logln("Die zu der Meldung " + actMessId
+ + " übergebenen Parameter sind mehr als die Meldung vorsieht.");
+ return composedMess;
}
- if ((index == -1) && (par != null)) {
- MessageHandler.logln("Message " + actMessId + " erwartet keine Parameter. Aufgerufen mit folgenden Parametern:");
- for(int i = 0; i < par.length; ++i)
- MessageHandler.logln(par[i].toString());
- return rawText;
+
+ /**
+ * Gibt den Title fürs Dialogfenster.
+ * Dieser wird durch die Dialogart festgelegt
+ * (erster Teil in der MeldungsDefinition in der Properties-Datei).
+ */
+ static String getTitle(String strVal) {
+ String title = null;
+ int choice = getValue(strVal);
+ switch (choice) {
+ case INFO:
+ title = "Info";
+ currentIconName = "info.gif";
+ break;
+ case WARNING:
+ title = "Warning";
+ currentIconName = "warn.gif";
+ break;
+ case QUESTION:
+ title = "Question";
+ currentIconName = "quest.gif";
+ break;
+ case ERROR:
+ title = "Error";
+ currentIconName = "error.gif";
+ break;
+ default:
+ title =
+ "Ungültiger IonType für diese Meldung. Prüfen in Übersetzungsdatei.";
+ }
+ return title;
}
- int tagCount = 0;
- while (rawText.indexOf(PARAMETER_TAG) != -1) {
- index = rawText.indexOf(PARAMETER_TAG);
- try {
- composedMess += rawText.substring(0, index) + par[tagCount];
- } catch(ArrayIndexOutOfBoundsException ex) {
- MessageHandler.logln("Anzahl der \u00FCbergebenen Parameter zu der Meldung " + actMessId + " ist weniger als erwartet.");
- ex.printStackTrace();
- return composedMess + rawText;
- }
- rawText = rawText.substring(index+PARAMETER_TAG.length());
- tagCount++;
+
+ /**
+ * Liefert den Wert der über den Nemen übergebenen Klassenvariablen.
+ */
+ static int getValue(String fieldName) {
+
+ int val = -1;
+ if (fieldName.equals("INFO"))
+ return INFO;
+ else if (fieldName.equals("WARNING"))
+ return WARNING;
+ else if (fieldName.equals("ERROR"))
+ return ERROR;
+ else if (fieldName.equals("SYS_ERROR"))
+ return SYS_ERROR;
+ else if (fieldName.equals("QUESTION"))
+ return QUESTION;
+ else if (fieldName.equals("STYLE_NOBUTTON"))
+ return STYLE_NOBUTTON;
+ else if (fieldName.equals("STYLE_Y"))
+ return STYLE_Y;
+ else if (fieldName.equals("STYLE_Y_N"))
+ return STYLE_Y_N;
+ else if (fieldName.equals("STYLE_Y_N_C"))
+ return STYLE_Y_N_C;
+ return val;
}
- composedMess += rawText;
- if (tagCount != par.length)
- MessageHandler.logln("Die zu der Meldung " + actMessId + " \u00FCbergebenen Parameter sind mehr als die Meldung vorsieht.");
- return composedMess;
- }
-
- /**
- * Gibt den Title fürs Dialogfenster.
- * Dieser wird durch die Dialogart festgelegt
- * (erster Teil in der MeldungsDefinition in der Properties-Datei).
- */
- static String getTitle(String strVal) {
- String title = null;
- int choice = getValue(strVal);
- switch (choice) {
- case INFO : title = "Info"; currentIconName = "info.gif"; break;
- case WARNING : title = "Warning"; currentIconName = "warn.gif"; break;
- case QUESTION : title = "Question"; currentIconName = "quest.gif"; break;
- case ERROR : title = "Error"; currentIconName = "error.gif"; break;
- default : title = "Ung\u00FCltiger IonType f\u00FCr diese Meldung. Pr\u00FCfen in \u00DCbersetzungsdatei.";
+
+ private static String getStackTrace(Exception exception) {
+
+ if (exception == null)
+ return "null";
+
+ String stack = "";
+
+ StringWriter strWriter = new StringWriter();
+ exception.printStackTrace(new PrintWriter(strWriter));
+ stack = strWriter.toString();
+ stack = stack.replace('\r', ' ');
+ stack = stack.replace('\t', ' ');
+ return stack;
}
- return title;
- }
-
- /**
- * Liefert den Wert der über den Nemen übergebenen Klassenvariablen.
- */
- static int getValue(String fieldName) {
-
- int val = -1;
- if (fieldName.equals("INFO")) return INFO;
- else if (fieldName.equals("WARNING")) return WARNING;
- else if (fieldName.equals("ERROR")) return ERROR;
- else if (fieldName.equals("SYS_ERROR")) return SYS_ERROR;
- else if (fieldName.equals("QUESTION")) return QUESTION;
- else if (fieldName.equals("STYLE_NOBUTTON")) return STYLE_NOBUTTON;
- else if (fieldName.equals("STYLE_Y")) return STYLE_Y;
- else if (fieldName.equals("STYLE_Y_N")) return STYLE_Y_N;
- else if (fieldName.equals("STYLE_Y_N_C")) return STYLE_Y_N_C;
- return val;
- }
-
- private static String getStackTrace(Exception exception) {
-
- if (exception == null)
- return "null";
-
- String stack = "";
-
- StringWriter strWriter = new StringWriter();
- exception.printStackTrace(new PrintWriter(strWriter));
- stack = strWriter.toString();
- stack = stack.replace('\r', ' ');
- stack = stack.replace('\t', ' ');
- return stack;
- }
-
- private static int display(String textID, String[] param, Exception exception, Frame frame) {
-
- String translatedMes = "";
- String preparedMes = "";
- String messageType = "";
- String optionType = "";
- String title = "";
- MessagesDialog dialog = null;
- actMessId = textID;
-
- boolean messageFound = res.contains(textID);
- translatedMes = res.getString(textID);
-
- if (messageFound) {
- try {
- messageType = translatedMes.substring(0, translatedMes.indexOf(':'));
- translatedMes = translatedMes.substring(translatedMes.indexOf(':')+1);
-
- optionType = translatedMes.substring(0, translatedMes.indexOf(':'));
- translatedMes = translatedMes.substring(translatedMes.indexOf(':')+1);
-
- } catch(Exception ex) {
- MessageHandler.logln("FALSCHES FORMAT: MESSAGE: " + textID);
- }
+
+ private static int display(String textID, String[] param,
+ Exception exception, Frame frame) {
+
+ String translatedMes = "";
+ String preparedMes = "";
+ String messageType = "";
+ String optionType = "";
+ String title = "";
+ MessagesDialog dialog = null;
+ actMessId = textID;
+
+ boolean messageFound = res.contains(textID);
+ translatedMes = res.getString(textID);
+
+ if (messageFound) {
+ try {
+ messageType =
+ translatedMes.substring(0, translatedMes.indexOf(':'));
+ translatedMes =
+ translatedMes.substring(translatedMes.indexOf(':') + 1);
+
+ optionType =
+ translatedMes.substring(0, translatedMes.indexOf(':'));
+ translatedMes =
+ translatedMes.substring(translatedMes.indexOf(':') + 1);
+
+ } catch (Exception ex) {
+ MessageHandler.logln("FALSCHES FORMAT: MESSAGE: " + textID);
+ }
+ } else { // Message not found
+ MessageHandler.logln("UserMessage: textID '" + textID
+ + "' not found. Return "
+ + "value 'CANCEL' = " + CANCEL);
+
+ // return CANCEL;
+
+ messageType = "ERROR";
+ optionType = "STYLE_Y";
+ translatedMes = "textID '" + textID + "' not found."
+ + "\nIt is possible the message file not found.";
+ }
+
+ preparedMes = prepareMessage(translatedMes, param);
+ // Exception exception = getException(param);
+
+ // WARNING -> nach Warnung übersetzen
+ title = res.getString(getTitle(messageType));
+
+ // WARNING -> JOptionPane.WARNING_MESSAGE
+ int messageTypeIndex = getValue(messageType);
+
+ // Button Set idetifizieren
+ int optionTypeIndex = getValue(optionType);
+
+ int result = CANCEL;
+
+ if (exception != null) {
+ String str = getStackTrace(exception);
+ if (exception instanceof MessageException) {
+ MessageException ex = (MessageException)exception;
+ if (ex.getException() != null)
+ str += "\n" + getStackTrace(ex.getException());
+ }
+ result = MessagesDialog.showDetailDialog(null, preparedMes,
+ title, optionTypeIndex,
+ messageTypeIndex, null,
+ str);
+ } else {
+ if (optionTypeIndex == STYLE_NOBUTTON) {
+ // Wird nicht mehr unterstützt
+ MessageHandler.logln("UserMessage: STYLE_NOBUTTON wird nicht unterstützt");
+ return result;
+ } else {
+ result = MessagesDialog.showConfirmDialog(null, preparedMes,
+ title,
+ optionTypeIndex,
+ messageTypeIndex);
+ }
+ }
+ return result;
}
- else { // Message not found
- MessageHandler.logln("UserMessage: textID '" + textID + "' not found. Return " +
- "value 'CANCEL' = " + CANCEL);
- //return CANCEL;
+ /**
+ * Öffnet das Dialogfenster mit der Übersetzung der per Suchschlüssel übergebenen Meldung
+ * mit eingesetzten Parametern. Für die Übersetzung der Parameter trägt die aufrufende Stelle die Sorge.
+ * Der Dialog ist modal zum Frame frame
.
+ * @param
+ * - textID - Suchschlüssel der Meldung im Meldungspool,
+ *
- param - Array der in die Meldung einzusetztenden Parameter,
+ *
- frame - das Fenster, zu dem der Dialog modal ist.
+ *
+ * @return
+ * - -1 wenn keine Rückgabe möglich ist oder Dialog NICHT MODAL ist.
+ *
- ButtonDialog.YES = 2
+ *
- ButtonDialog.NO = 4
+ *
- ButtonDialog.CANCEL = 8
+ *
- Wird das Dialog-Fenster ohne Buttonklick geschlossen (Kreuzchen oben rechts), so ist die Rückgabe gleich ButtonDialog.CANCEL.
+ *
+ */
+ public static int show(String messageId, String[] parameterList,
+ Exception anException, Frame parentFrame) {
+ return display(messageId, parameterList, anException, parentFrame);
+ }
- messageType = "ERROR";
- optionType = "STYLE_Y";
- translatedMes = "textID '"+textID +"' not found." +
- "\nIt is possible the message file not found.";
+ public static int show(String messageId, String[] parameterList,
+ Exception anException) {
+ return display(messageId, parameterList, anException, (Frame)null);
}
- preparedMes = prepareMessage(translatedMes, param);
- // Exception exception = getException(param);
+ public static int show(String messageId, String[] parameterList,
+ Frame parentFrame) {
+ return display(messageId, parameterList, (Exception)null,
+ parentFrame);
+ }
- // WARNING -> nach Warnung übersetzen
- title = res.getString(getTitle(messageType));
+ public static int show(String messageId, String[] parameterList) {
+ return display(messageId, parameterList, (Exception)null,
+ (Frame)null);
+ }
- // WARNING -> JOptionPane.WARNING_MESSAGE
- int messageTypeIndex = getValue(messageType);
+ public static int show(String messageId, String parameter,
+ Frame parentFrame) {
+ return display(messageId, new String[] {
+ parameter
+ }, (Exception)null, parentFrame);
+ }
- // Button Set idetifizieren
- int optionTypeIndex = getValue(optionType);
+ public static int show(String messageId, String parameter) {
+ return display(messageId, new String[] {
+ parameter
+ }, (Exception)null, (Frame)null);
+ }
- int result = CANCEL;
+ public static int show(String messageId, Frame parentFrame) {
+ return display(messageId, (String[])null, (Exception)null,
+ parentFrame);
+ }
- if (exception != null) {
- String str = getStackTrace(exception);
- if (exception instanceof MessageException ) {
- MessageException ex = (MessageException)exception;
- if (ex.getException() != null)
- str += "\n" + getStackTrace(ex.getException());
- }
- result = MessagesDialog.showDetailDialog(null, preparedMes, title,
- optionTypeIndex, messageTypeIndex, null, str);
+ public static int show(String messageId) {
+ return display(messageId, (String[])null, (Exception)null,
+ (Frame)null);
}
- else {
- if (optionTypeIndex == STYLE_NOBUTTON) {
- // Wird nicht mehr unterstützt
- MessageHandler.logln("UserMessage: STYLE_NOBUTTON wird nicht unterst\u00FCtzt");
- return result;
- }
- else {
- result = MessagesDialog.showConfirmDialog(null,preparedMes,title,
- optionTypeIndex,messageTypeIndex);
- }
+
+ public static int show(String messageId, Exception anException,
+ Frame aFrame) {
+ return display(messageId, (String[])null, anException, aFrame);
}
- return result;
- }
-
- /**
- * Öffnet das Dialogfenster mit der Übersetzung der per Suchschlüssel übergebenen Meldung
- * mit eingesetzten Parametern. Für die Übersetzung der Parameter trägt die aufrufende Stelle die Sorge.
- * Der Dialog ist modal zum Frame frame
.
- * @param
- * - textID - Suchschlüssel der Meldung im Meldungspool,
- *
- param - Array der in die Meldung einzusetztenden Parameter,
- *
- frame - das Fenster, zu dem der Dialog modal ist.
- *
- * @return
- * - -1 wenn keine Rückgabe möglich ist oder Dialog NICHT MODAL ist.
- *
- ButtonDialog.YES = 2
- *
- ButtonDialog.NO = 4
- *
- ButtonDialog.CANCEL = 8
- *
- Wird das Dialog-Fenster ohne Buttonklick geschlossen (Kreuzchen oben rechts), so ist die Rückgabe gleich ButtonDialog.CANCEL.
- *
- */
- public static int show(String messageId, String[] parameterList,
- Exception anException, Frame parentFrame) {
- return display(messageId, parameterList, anException, parentFrame);
- }
-
- public static int show(String messageId, String[] parameterList,
- Exception anException) {
- return display(messageId, parameterList, anException, (Frame)null);
- }
-
- public static int show(String messageId, String[] parameterList,
- Frame parentFrame) {
- return display(messageId, parameterList, (Exception)null, parentFrame);
- }
-
- public static int show(String messageId, String[] parameterList) {
- return display(messageId, parameterList, (Exception)null, (Frame)null);
- }
-
- public static int show(String messageId, String parameter,
- Frame parentFrame) {
- return display(messageId, new String[] { parameter }, (Exception)null, parentFrame);
- }
-
- public static int show(String messageId, String parameter) {
- return display(messageId, new String[] { parameter }, (Exception)null, (Frame)null);
- }
-
- public static int show(String messageId, Frame parentFrame) {
- return display(messageId, (String[])null, (Exception)null, parentFrame);
- }
-
- public static int show(String messageId) {
- return display(messageId, (String[])null, (Exception)null, (Frame)null);
- }
-
- public static int show(String messageId, Exception anException, Frame aFrame) {
- return display(messageId, (String[])null, anException, aFrame);
- }
-
- public static int show(String messageId, Exception anException) {
- return display(messageId, (String[])null, anException, (Frame)null);
- }
-
- public static int show(Exception anException, Frame aFrame) {
- if (anException instanceof MessageException) {
- MessageException ex = (MessageException)anException;
- return show(ex.getMessageId(), ex.getParameterList(), ex, aFrame);
+
+ public static int show(String messageId, Exception anException) {
+ return display(messageId, (String[])null, anException, (Frame)null);
+ }
+
+ public static int show(Exception anException, Frame aFrame) {
+ if (anException instanceof MessageException) {
+ MessageException ex = (MessageException)anException;
+ return show(ex.getMessageId(), ex.getParameterList(), ex, aFrame);
+ } else
+ return show("UNHANDLED_EXCEPTION", (String[])null, anException,
+ aFrame);
}
- else
- return show("UNHANDLED_EXCEPTION", (String[])null, anException, aFrame);
- }
}
--
2.39.5