summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndrew John Hughes <gnu_andrew@member.fsf.org>2006-06-11 18:23:15 +0000
committerAndrew John Hughes <gnu_andrew@member.fsf.org>2006-06-11 18:23:15 +0000
commit35d18ccf396a6cfdcbe5bbdf38df7d01852250bc (patch)
tree562e6d161a8957db8a46900b46f661c5e52e1a34
parentc5877847749d21bdf84e33929ffa52a56e5c6ca0 (diff)
downloadclasspath-35d18ccf396a6cfdcbe5bbdf38df7d01852250bc.tar.gz
2006-06-11 Andrew John Hughes <gnu_andrew@member.fsf.org>
* Merge of HEAD-->generics between 2006/05/29 and 2006/06/11.
-rw-r--r--ChangeLog1903
-rw-r--r--NEWS10
-rw-r--r--configure.ac31
-rw-r--r--doc/tools.texinfo437
-rw-r--r--examples/gnu/classpath/examples/swing/Demo.java2
-rw-r--r--examples/gnu/classpath/examples/swing/FillRect.java118
-rw-r--r--examples/gnu/classpath/examples/swing/HtmlDemo.java165
-rw-r--r--gnu/classpath/debug/TeeInputStream.java98
-rw-r--r--gnu/classpath/debug/TeeOutputStream.java93
-rw-r--r--gnu/classpath/debug/TeeReader.java98
-rw-r--r--gnu/classpath/debug/TeeWriter.java93
-rw-r--r--gnu/classpath/jdwp/processor/ClassTypeCommandSet.java8
-rw-r--r--gnu/classpath/jdwp/processor/EventRequestCommandSet.java2
-rw-r--r--gnu/classpath/jdwp/processor/ThreadGroupReferenceCommandSet.java8
-rw-r--r--gnu/java/awt/Buffers.java88
-rw-r--r--gnu/java/awt/font/opentype/truetype/VirtualMachine.java6
-rw-r--r--gnu/java/awt/java2d/AbstractGraphics2D.java28
-rw-r--r--gnu/java/awt/java2d/PolyEdge.java3
-rw-r--r--gnu/java/awt/java2d/TexturePaintContext.java205
-rw-r--r--gnu/java/awt/peer/gtk/BufferedImageGraphics.java258
-rw-r--r--gnu/java/awt/peer/gtk/CairoGraphics2D.java (renamed from gnu/java/awt/peer/gtk/GdkGraphics2D.java)1858
-rw-r--r--gnu/java/awt/peer/gtk/CairoSurface.java315
-rw-r--r--gnu/java/awt/peer/gtk/CairoSurfaceGraphics.java101
-rw-r--r--gnu/java/awt/peer/gtk/ComponentGraphics.java275
-rw-r--r--gnu/java/awt/peer/gtk/ComponentGraphicsCopy.java129
-rw-r--r--gnu/java/awt/peer/gtk/FreetypeGlyphVector.java468
-rw-r--r--gnu/java/awt/peer/gtk/GdkFontPeer.java84
-rw-r--r--gnu/java/awt/peer/gtk/GdkGlyphVector.java359
-rw-r--r--gnu/java/awt/peer/gtk/GdkGraphicsConfiguration.java40
-rw-r--r--gnu/java/awt/peer/gtk/GdkGraphicsEnvironment.java71
-rw-r--r--gnu/java/awt/peer/gtk/GdkPixbufDecoder.java64
-rw-r--r--gnu/java/awt/peer/gtk/GdkScreenGraphicsDevice.java282
-rw-r--r--gnu/java/awt/peer/gtk/GdkTextLayout.java29
-rw-r--r--gnu/java/awt/peer/gtk/GtkComponentPeer.java14
-rw-r--r--gnu/java/awt/peer/gtk/GtkImage.java273
-rw-r--r--gnu/java/awt/peer/gtk/GtkToolkit.java22
-rw-r--r--gnu/java/awt/peer/gtk/GtkVolatileImage.java91
-rw-r--r--gnu/java/awt/peer/gtk/VolatileImageGraphics.java127
-rw-r--r--gnu/java/awt/peer/qt/QtToolkit.java3
-rw-r--r--gnu/java/awt/print/JavaPrinterGraphics.java4
-rw-r--r--gnu/java/io/PlatformHelper.java94
-rw-r--r--gnu/java/nio/charset/Provider.java30
-rw-r--r--gnu/java/security/PolicyFile.java4
-rw-r--r--gnu/java/security/Properties.java51
-rw-r--r--gnu/java/security/Registry.java3
-rw-r--r--gnu/java/security/hash/Whirlpool.java98
-rw-r--r--gnu/java/security/jce/sig/EncodedKeyFactory.java39
-rw-r--r--gnu/java/security/jce/sig/SignatureAdapter.java8
-rw-r--r--gnu/java/security/key/dss/DSSKeyPairGenerator.java38
-rw-r--r--gnu/java/security/key/dss/DSSKeyPairPKCS8Codec.java14
-rw-r--r--gnu/java/security/key/dss/DSSPrivateKey.java9
-rw-r--r--gnu/java/security/key/rsa/GnuRSAPrivateKey.java24
-rw-r--r--gnu/java/security/key/rsa/RSAKeyPairGenerator.java15
-rw-r--r--gnu/java/security/key/rsa/RSAKeyPairPKCS8Codec.java32
-rw-r--r--gnu/java/security/key/rsa/RSAKeyPairX509Codec.java14
-rw-r--r--gnu/java/security/pkcs/PKCS7SignedData.java66
-rw-r--r--gnu/java/security/pkcs/SignerInfo.java79
-rw-r--r--gnu/java/security/provider/PKIXCertPathValidatorImpl.java49
-rw-r--r--gnu/java/security/sig/ISignature.java4
-rw-r--r--gnu/java/security/sig/rsa/EMSA_PSS.java84
-rw-r--r--gnu/java/security/sig/rsa/RSAPSSSignature.java36
-rw-r--r--gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java2
-rw-r--r--gnu/java/security/util/Base64.java35
-rw-r--r--gnu/java/security/util/ExpirableObject.java4
-rw-r--r--gnu/java/security/util/Prime2.java63
-rw-r--r--gnu/java/security/util/SimpleList.java2
-rw-r--r--gnu/java/security/x509/Util.java4
-rw-r--r--gnu/java/security/x509/X509CRL.java73
-rw-r--r--gnu/java/security/x509/X509CRLEntry.java41
-rw-r--r--gnu/java/security/x509/ext/Extension.java26
-rw-r--r--gnu/java/security/x509/ext/GeneralNames.java3
-rw-r--r--gnu/java/util/regex/BacktrackStack.java (renamed from gnu/regexp/BacktrackStack.java)2
-rw-r--r--gnu/java/util/regex/CharIndexed.java (renamed from gnu/regexp/CharIndexed.java)2
-rw-r--r--gnu/java/util/regex/CharIndexedCharArray.java (renamed from gnu/regexp/CharIndexedCharArray.java)2
-rw-r--r--gnu/java/util/regex/CharIndexedCharSequence.java (renamed from gnu/regexp/CharIndexedCharSequence.java)2
-rw-r--r--gnu/java/util/regex/CharIndexedInputStream.java (renamed from gnu/regexp/CharIndexedInputStream.java)2
-rw-r--r--gnu/java/util/regex/CharIndexedString.java (renamed from gnu/regexp/CharIndexedString.java)2
-rw-r--r--gnu/java/util/regex/CharIndexedStringBuffer.java (renamed from gnu/regexp/CharIndexedStringBuffer.java)2
-rw-r--r--gnu/java/util/regex/RE.java (renamed from gnu/regexp/RE.java)2
-rw-r--r--gnu/java/util/regex/REException.java (renamed from gnu/regexp/REException.java)2
-rw-r--r--gnu/java/util/regex/REFilterInputStream.java (renamed from gnu/regexp/REFilterInputStream.java)2
-rw-r--r--gnu/java/util/regex/REMatch.java (renamed from gnu/regexp/REMatch.java)2
-rw-r--r--gnu/java/util/regex/REMatchEnumeration.java (renamed from gnu/regexp/REMatchEnumeration.java)2
-rw-r--r--gnu/java/util/regex/RESyntax.java (renamed from gnu/regexp/RESyntax.java)2
-rw-r--r--gnu/java/util/regex/REToken.java (renamed from gnu/regexp/REToken.java)2
-rw-r--r--gnu/java/util/regex/RETokenAny.java (renamed from gnu/regexp/RETokenAny.java)2
-rw-r--r--gnu/java/util/regex/RETokenBackRef.java (renamed from gnu/regexp/RETokenBackRef.java)2
-rw-r--r--gnu/java/util/regex/RETokenChar.java (renamed from gnu/regexp/RETokenChar.java)2
-rw-r--r--gnu/java/util/regex/RETokenEnd.java (renamed from gnu/regexp/RETokenEnd.java)2
-rw-r--r--gnu/java/util/regex/RETokenEndOfPreviousMatch.java (renamed from gnu/regexp/RETokenEndOfPreviousMatch.java)2
-rw-r--r--gnu/java/util/regex/RETokenEndSub.java (renamed from gnu/regexp/RETokenEndSub.java)2
-rw-r--r--gnu/java/util/regex/RETokenIndependent.java (renamed from gnu/regexp/RETokenIndependent.java)2
-rw-r--r--gnu/java/util/regex/RETokenLookAhead.java (renamed from gnu/regexp/RETokenLookAhead.java)2
-rw-r--r--gnu/java/util/regex/RETokenLookBehind.java (renamed from gnu/regexp/RETokenLookBehind.java)2
-rw-r--r--gnu/java/util/regex/RETokenNamedProperty.java (renamed from gnu/regexp/RETokenNamedProperty.java)2
-rw-r--r--gnu/java/util/regex/RETokenOneOf.java (renamed from gnu/regexp/RETokenOneOf.java)2
-rw-r--r--gnu/java/util/regex/RETokenPOSIX.java (renamed from gnu/regexp/RETokenPOSIX.java)2
-rw-r--r--gnu/java/util/regex/RETokenRange.java (renamed from gnu/regexp/RETokenRange.java)2
-rw-r--r--gnu/java/util/regex/RETokenRepeated.java (renamed from gnu/regexp/RETokenRepeated.java)2
-rw-r--r--gnu/java/util/regex/RETokenStart.java (renamed from gnu/regexp/RETokenStart.java)2
-rw-r--r--gnu/java/util/regex/RETokenWordBoundary.java (renamed from gnu/regexp/RETokenWordBoundary.java)2
-rw-r--r--gnu/java/util/regex/UncheckedRE.java (renamed from gnu/regexp/UncheckedRE.java)4
-rw-r--r--gnu/javax/crypto/RSACipherImpl.java7
-rw-r--r--gnu/javax/crypto/assembly/Cascade.java2
-rw-r--r--gnu/javax/crypto/assembly/Direction.java4
-rw-r--r--gnu/javax/crypto/assembly/Transformer.java2
-rw-r--r--gnu/javax/crypto/cipher/Anubis.java144
-rw-r--r--gnu/javax/crypto/cipher/BaseCipher.java15
-rw-r--r--gnu/javax/crypto/cipher/IBlockCipherSpi.java2
-rw-r--r--gnu/javax/crypto/cipher/Khazad.java146
-rw-r--r--gnu/javax/crypto/cipher/Rijndael.java252
-rw-r--r--gnu/javax/crypto/cipher/Twofish.java249
-rw-r--r--gnu/javax/crypto/jce/cipher/CipherAdapter.java4
-rw-r--r--gnu/javax/crypto/jce/key/AnubisSecretKeyFactoryImpl.java7
-rw-r--r--gnu/javax/crypto/jce/key/BlowfishSecretKeyFactoryImpl.java7
-rw-r--r--gnu/javax/crypto/jce/key/Cast5SecretKeyFactoryImpl.java7
-rw-r--r--gnu/javax/crypto/jce/key/KhazadSecretKeyFactoryImpl.java7
-rw-r--r--gnu/javax/crypto/jce/key/RijndaelSecretKeyFactoryImpl.java7
-rw-r--r--gnu/javax/crypto/jce/key/SerpentSecretKeyFactoryImpl.java7
-rw-r--r--gnu/javax/crypto/jce/key/SquareSecretKeyFactoryImpl.java7
-rw-r--r--gnu/javax/crypto/jce/key/TwofishSecretKeyFactoryImpl.java7
-rw-r--r--gnu/javax/crypto/jce/keyring/GnuKeyring.java183
-rw-r--r--gnu/javax/crypto/jce/mac/OMacImpl.java1
-rw-r--r--gnu/javax/crypto/jce/prng/CSPRNGSpi.java3
-rw-r--r--gnu/javax/crypto/jce/prng/ICMRandomSpi.java75
-rw-r--r--gnu/javax/crypto/jce/prng/UMacRandomSpi.java30
-rw-r--r--gnu/javax/crypto/jce/spec/TMMHParameterSpec.java2
-rw-r--r--gnu/javax/crypto/key/dh/GnuDHKeyPairGenerator.java38
-rw-r--r--gnu/javax/crypto/key/dh/GnuDHPrivateKey.java2
-rw-r--r--gnu/javax/crypto/key/srp6/SRPKeyPairGenerator.java32
-rw-r--r--gnu/javax/crypto/keyring/AuthenticatedEntry.java17
-rw-r--r--gnu/javax/crypto/keyring/CertPathEntry.java3
-rw-r--r--gnu/javax/crypto/keyring/CertificateEntry.java2
-rw-r--r--gnu/javax/crypto/keyring/EncryptedEntry.java24
-rw-r--r--gnu/javax/crypto/keyring/Entry.java5
-rw-r--r--gnu/javax/crypto/keyring/EnvelopeEntry.java71
-rw-r--r--gnu/javax/crypto/keyring/GnuPrivateKeyring.java123
-rw-r--r--gnu/javax/crypto/keyring/GnuPublicKeyring.java39
-rw-r--r--gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java46
-rw-r--r--gnu/javax/crypto/keyring/PasswordEncryptedEntry.java36
-rw-r--r--gnu/javax/crypto/keyring/PublicKeyEntry.java17
-rw-r--r--gnu/javax/crypto/mac/OMAC.java39
-rw-r--r--gnu/javax/crypto/mode/BaseMode.java2
-rw-r--r--gnu/javax/crypto/mode/CTR.java2
-rw-r--r--gnu/javax/crypto/pad/BasePad.java94
-rw-r--r--gnu/javax/crypto/pad/IPad.java2
-rw-r--r--gnu/javax/crypto/pad/ISO10126.java109
-rw-r--r--gnu/javax/crypto/pad/PKCS1_V1_5.java52
-rw-r--r--gnu/javax/crypto/pad/PKCS7.java42
-rw-r--r--gnu/javax/crypto/pad/PadFactory.java41
-rw-r--r--gnu/javax/crypto/pad/TBC.java41
-rw-r--r--gnu/javax/crypto/pad/TLS1.java2
-rw-r--r--gnu/javax/crypto/prng/CSPRNG.java252
-rw-r--r--gnu/javax/crypto/sasl/SaslInputStream.java178
-rw-r--r--gnu/javax/crypto/sasl/SaslOutputStream.java96
-rw-r--r--gnu/javax/crypto/sasl/SaslUtil.java1
-rw-r--r--gnu/javax/crypto/sasl/srp/PasswordFile.java3
-rw-r--r--gnu/javax/crypto/sasl/srp/SRPClient.java701
-rw-r--r--gnu/javax/crypto/sasl/srp/SRPRegistry.java2
-rw-r--r--gnu/javax/crypto/sasl/srp/SRPServer.java799
-rw-r--r--gnu/javax/security/auth/login/ConfigFileParser.java72
-rw-r--r--gnu/javax/security/auth/login/GnuConfiguration.java100
-rw-r--r--gnu/javax/swing/text/html/CharacterAttributeTranslator.java86
-rw-r--r--gnu/javax/swing/text/html/CombinedAttributes.java213
-rw-r--r--gnu/javax/swing/text/html/ImageViewIconFactory.java282
-rw-r--r--gnu/javax/swing/text/html/parser/SmallHtmlAttributeSet.java261
-rw-r--r--gnu/javax/swing/text/html/parser/htmlAttributeSet.java98
-rw-r--r--gnu/xml/dom/DomIterator.java6
-rw-r--r--gnu/xml/stream/SAXParser.java54
-rw-r--r--gnu/xml/stream/XMLParser.java261
-rw-r--r--gnu/xml/transform/TransformerImpl.java19
-rw-r--r--include/Makefile.am11
-rw-r--r--include/gnu_java_awt_peer_gtk_CairoGraphics2D.h45
-rw-r--r--include/gnu_java_awt_peer_gtk_CairoSurface.h28
-rw-r--r--include/gnu_java_awt_peer_gtk_ComponentGraphics.h26
-rw-r--r--include/gnu_java_awt_peer_gtk_ComponentGraphicsCopy.h20
-rw-r--r--include/gnu_java_awt_peer_gtk_FreetypeGlyphVector.h22
-rw-r--r--include/gnu_java_awt_peer_gtk_GdkFontPeer.h2
-rw-r--r--include/gnu_java_awt_peer_gtk_GdkGraphics2D.h55
-rw-r--r--include/gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.h4
-rw-r--r--include/gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.h26
-rw-r--r--include/gnu_java_awt_peer_gtk_GdkTextLayout.h2
-rw-r--r--include/gnu_java_awt_peer_gtk_GtkImage.h9
-rw-r--r--include/gnu_java_awt_peer_gtk_GtkVolatileImage.h23
-rw-r--r--include/java_io_VMFile.h1
-rw-r--r--include/jni.h41
-rw-r--r--java/awt/Component.java48
-rw-r--r--java/awt/Container.java40
-rw-r--r--java/awt/DefaultKeyboardFocusManager.java10
-rw-r--r--java/awt/LightweightDispatcher.java61
-rw-r--r--java/awt/TexturePaint.java8
-rw-r--r--java/awt/Window.java3
-rw-r--r--java/awt/datatransfer/DataFlavor.java7
-rw-r--r--java/awt/dnd/DropTargetContext.java45
-rw-r--r--java/awt/dnd/DropTargetDropEvent.java55
-rw-r--r--java/awt/font/TextLayout.java519
-rw-r--r--java/awt/geom/AffineTransform.java4
-rw-r--r--java/awt/image/BufferedImage.java43
-rw-r--r--java/io/File.java10
-rw-r--r--java/lang/String.java2
-rw-r--r--java/lang/management/RuntimeMXBean.java274
-rw-r--r--java/net/InetSocketAddress.java9
-rw-r--r--java/security/UnresolvedPermission.java41
-rw-r--r--java/text/Bidi.java3
-rw-r--r--java/util/Arrays.java16
-rw-r--r--java/util/Collections.java4
-rw-r--r--java/util/logging/LogManager.java6
-rw-r--r--java/util/regex/Matcher.java6
-rw-r--r--java/util/regex/Pattern.java6
-rw-r--r--javax/swing/JComboBox.java8
-rw-r--r--javax/swing/JComponent.java51
-rw-r--r--javax/swing/JEditorPane.java8
-rw-r--r--javax/swing/JFormattedTextField.java74
-rw-r--r--javax/swing/JFrame.java3
-rw-r--r--javax/swing/JLayeredPane.java14
-rw-r--r--javax/swing/JMenuBar.java27
-rw-r--r--javax/swing/JMenuItem.java107
-rw-r--r--javax/swing/JScrollPane.java8
-rw-r--r--javax/swing/JSlider.java6
-rw-r--r--javax/swing/JSpinner.java2
-rw-r--r--javax/swing/JSplitPane.java9
-rw-r--r--javax/swing/JTabbedPane.java48
-rw-r--r--javax/swing/JTable.java1198
-rw-r--r--javax/swing/JTree.java40
-rw-r--r--javax/swing/JViewport.java2
-rw-r--r--javax/swing/ListSelectionModel.java264
-rw-r--r--javax/swing/MenuSelectionManager.java3
-rw-r--r--javax/swing/RepaintManager.java20
-rw-r--r--javax/swing/UIDefaults.java26
-rw-r--r--javax/swing/UIManager.java27
-rw-r--r--javax/swing/border/MatteBorder.java9
-rw-r--r--javax/swing/event/EventListenerList.java10
-rw-r--r--javax/swing/plaf/basic/BasicButtonUI.java9
-rw-r--r--javax/swing/plaf/basic/BasicComboBoxRenderer.java16
-rw-r--r--javax/swing/plaf/basic/BasicDirectoryModel.java14
-rw-r--r--javax/swing/plaf/basic/BasicFileChooserUI.java4
-rw-r--r--javax/swing/plaf/basic/BasicIconFactory.java10
-rw-r--r--javax/swing/plaf/basic/BasicInternalFrameUI.java40
-rw-r--r--javax/swing/plaf/basic/BasicListUI.java55
-rw-r--r--javax/swing/plaf/basic/BasicLookAndFeel.java16
-rw-r--r--javax/swing/plaf/basic/BasicOptionPaneUI.java2
-rw-r--r--javax/swing/plaf/basic/BasicProgressBarUI.java31
-rw-r--r--javax/swing/plaf/basic/BasicRootPaneUI.java5
-rw-r--r--javax/swing/plaf/basic/BasicScrollBarUI.java179
-rw-r--r--javax/swing/plaf/basic/BasicScrollPaneUI.java256
-rw-r--r--javax/swing/plaf/basic/BasicSpinnerUI.java4
-rw-r--r--javax/swing/plaf/basic/BasicSplitPaneUI.java150
-rw-r--r--javax/swing/plaf/basic/BasicTabbedPaneUI.java56
-rw-r--r--javax/swing/plaf/basic/BasicTableUI.java50
-rw-r--r--javax/swing/plaf/basic/BasicTextAreaUI.java4
-rw-r--r--javax/swing/plaf/basic/BasicTextUI.java94
-rw-r--r--javax/swing/plaf/basic/BasicTreeUI.java668
-rw-r--r--javax/swing/plaf/basic/SharedUIDefaults.java78
-rw-r--r--javax/swing/plaf/metal/MetalButtonUI.java101
-rw-r--r--javax/swing/plaf/metal/MetalInternalFrameUI.java18
-rw-r--r--javax/swing/plaf/metal/MetalSplitPaneDivider.java14
-rw-r--r--javax/swing/table/JTableHeader.java34
-rw-r--r--javax/swing/text/DefaultStyledDocument.java8
-rw-r--r--javax/swing/text/GapContent.java10
-rw-r--r--javax/swing/text/PlainView.java233
-rw-r--r--javax/swing/text/StyleContext.java24
-rw-r--r--javax/swing/text/html/HTMLDocument.java87
-rw-r--r--javax/swing/text/html/HTMLEditorKit.java5
-rw-r--r--javax/swing/text/html/ImageView.java441
-rw-r--r--javax/swing/tree/DefaultTreeCellEditor.java1
-rw-r--r--javax/swing/tree/TreePath.java16
-rw-r--r--javax/swing/tree/VariableHeightLayoutCache.java16
-rw-r--r--lib/.cvsignore1
-rw-r--r--lib/Makefile.am15
-rwxr-xr-xlib/gen-classlist.sh.in4
-rw-r--r--native/fdlibm/dtoa.c17
-rw-r--r--native/fdlibm/mprec.c275
-rw-r--r--native/fdlibm/mprec.h8
-rw-r--r--native/jawt/Makefile.am2
-rw-r--r--native/jni/classpath/jcl.h6
-rw-r--r--native/jni/gtk-peer/Makefile.am14
-rw-r--r--native/jni/gtk-peer/cairographics2d.h116
-rw-r--r--native/jni/gtk-peer/gdkdisplay.h67
-rw-r--r--native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoGraphics2D.c706
-rw-r--r--native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c302
-rw-r--r--native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c311
-rw-r--r--native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphicsCopy.c132
-rw-r--r--native/jni/gtk-peer/gnu_java_awt_peer_gtk_FreetypeGlyphVector.c348
-rw-r--r--native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkFontPeer.c132
-rw-r--r--native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkGraphics2D.c1898
-rw-r--r--native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.c142
-rw-r--r--native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.c354
-rw-r--r--native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkTextLayout.c153
-rw-r--r--native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkClipboard.c9
-rw-r--r--native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkFramePeer.c5
-rw-r--r--native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkImage.c332
-rw-r--r--native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkVolatileImage.c195
-rw-r--r--native/jni/gtk-peer/gtkpeer.h55
-rw-r--r--native/jni/java-io/java_io_VMFile.c236
-rw-r--r--native/jni/midi-dssi/dssi_data.h7
-rw-r--r--native/jni/qt-peer/qtmenupeer.cpp47
-rw-r--r--native/plugin/Makefile.am14
-rw-r--r--native/plugin/gcjwebplugin.cc575
-rw-r--r--resource/gnu/classpath/tools/keytool/messages.properties28
-rw-r--r--tools/.cvsignore1
-rwxr-xr-xtools/Makefile.am8
-rw-r--r--tools/gnu/classpath/tools/appletviewer/AppletTag.java2
-rw-r--r--tools/gnu/classpath/tools/keytool/CACertCmd.java302
-rw-r--r--tools/gnu/classpath/tools/keytool/CertReqCmd.java2
-rw-r--r--tools/gnu/classpath/tools/keytool/Command.java22
-rw-r--r--tools/gnu/classpath/tools/keytool/DeleteCmd.java2
-rw-r--r--tools/gnu/classpath/tools/keytool/ExportCmd.java2
-rw-r--r--tools/gnu/classpath/tools/keytool/GenKeyCmd.java2
-rw-r--r--tools/gnu/classpath/tools/keytool/IdentityDBCmd.java2
-rw-r--r--tools/gnu/classpath/tools/keytool/ImportCmd.java2
-rw-r--r--tools/gnu/classpath/tools/keytool/KeyCloneCmd.java2
-rw-r--r--tools/gnu/classpath/tools/keytool/KeyPasswdCmd.java2
-rw-r--r--tools/gnu/classpath/tools/keytool/ListCmd.java2
-rw-r--r--tools/gnu/classpath/tools/keytool/Main.java23
-rw-r--r--tools/gnu/classpath/tools/keytool/SelfCertCmd.java2
-rw-r--r--tools/gnu/classpath/tools/keytool/StorePasswdCmd.java2
-rw-r--r--tools/jarsigner.in18
-rw-r--r--tools/keytool.in18
-rw-r--r--vm/reference/java/io/VMFile.java16
319 files changed, 18902 insertions, 9197 deletions
diff --git a/ChangeLog b/ChangeLog
index d5161a79f..b8789c7f2 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,8 +1,1137 @@
+2006-06-11 Raif S. Naffah <raif@swiftdsl.com.au>
+
+ PR Classpath/26065
+ * gnu/javax/security/auth/login/GnuConfiguration.java: Condition all trace/
+ debug code based on Configuration.DEBUG.
+ Use logger instead of STDOUT and ot STDERR.
+ * gnu/javax/security/auth/login/ConfigFileParser.java: Likewise.
+ * gnu/javax/crypto/sasl/SaslOutputStream.java: Likewise.
+ * gnu/javax/crypto/sasl/SaslInputStream.java: Likewise.
+ * gnu/javax/crypto/sasl/srp/SRPServer.java: Likewise.
+ * gnu/javax/crypto/sasl/srp/SRPClient.java: Likewise.
+ * gnu/javax/crypto/prng/CSPRNG.java: Likewise.
+ * gnu/javax/crypto/pad/TBC.java: Likewise.
+ * gnu/javax/crypto/pad/PKCS7.java: Likewise.
+ * gnu/javax/crypto/pad/PKCS1_V1_5.java: Likewise.
+ * gnu/javax/crypto/pad/BasePad.java: Likewise.
+ * gnu/javax/crypto/mac/OMAC.java: Likewise.
+ * gnu/javax/crypto/keyring/PasswordEncryptedEntry.java: Likewise.
+ * gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java: Likewise.
+ * gnu/javax/crypto/keyring/GnuPublicKeyring.java: Likewise.
+ * gnu/javax/crypto/keyring/GnuPrivateKeyring.java: Likewise.
+ * gnu/javax/crypto/keyring/EnvelopeEntry.java: Likewise.
+ * gnu/javax/crypto/keyring/Entry.java: Likewise.
+ * gnu/javax/crypto/key/srp6/SRPKeyPairGenerator.java: Likewise.
+ * gnu/javax/crypto/key/dh/GnuDHKeyPairGenerator.java: Likewise.
+ * gnu/javax/crypto/jce/prng/UMacRandomSpi.java: Likewise.
+ * gnu/javax/crypto/jce/prng/ICMRandomSpi.java: Likewise.
+ * gnu/javax/crypto/jce/keyring/GnuKeyring.java: Likewise.
+ * gnu/javax/crypto/cipher/Twofish.java: Likewise.
+ * gnu/javax/crypto/cipher/Khazad.java: Likewise.
+ * gnu/javax/crypto/cipher/Rijndael.java: Likewise.
+ * gnu/javax/crypto/cipher/BaseCipher.java: Likewise.
+ * gnu/javax/crypto/cipher/Anubis.java: Likewise.
+ * gnu/java/security/Properties.java: Likewise.
+ * gnu/java/security/x509/X509CRLEntry.java: Likewise.
+ * gnu/java/security/x509/X509CRL.java: Likewise.
+ * gnu/java/security/x509/ext/Extension.java: Likewise.
+ * gnu/java/security/util/Prime2.java: Likewise.
+ * gnu/java/security/util/Base64.java: Likewise.
+ * gnu/java/security/sig/rsa/RSAPSSSignature.java: Likewise.
+ * gnu/java/security/sig/rsa/EMSA_PSS.java: Likewise.
+ * gnu/java/security/provider/PKIXCertPathValidatorImpl.java: Likewise.
+ * gnu/java/security/pkcs/SignerInfo.java: Likewise.
+ * gnu/java/security/pkcs/PKCS7SignedData.java: Likewise.
+ * gnu/java/security/key/rsa/RSAKeyPairX509Codec.java: Likewise.
+ * gnu/java/security/key/rsa/RSAKeyPairPKCS8Codec.java: Likewise.
+ * gnu/java/security/key/rsa/RSAKeyPairGenerator.java: Likewise.
+ * gnu/java/security/key/rsa/GnuRSAPrivateKey.java: Likewise.
+ * gnu/java/security/key/dss/DSSPrivateKey.java: Likewise.
+ * gnu/java/security/key/dss/DSSKeyPairPKCS8Codec.java: Likewise.
+ * gnu/java/security/key/dss/DSSKeyPairGenerator.java: Likewise.
+ * gnu/java/security/jce/sig/SignatureAdapter.java: Likewise.
+ * gnu/java/security/jce/sig/EncodedKeyFactory.java: Likewise.
+ * gnu/java/security/hash/Whirlpool.java: Likewise.
+
+2006-06-11 Mark Wielaard <mark@klomp.org>
+
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_FreetypeGlyphVector.c
+ (Java_gnu_java_awt_peer_gtk_FreetypeGlyphVector_getGlyphs):
+ Remove unused variable glyph_index.
+
+2006-06-11 Mark Wielaard <mark@klomp.org>
+
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java (drawImage):
+ Don't recurse, return false if not an BufferedImage and no image
+ source available.
+ * gnu/java/awt/peer/gtk/ComponentGraphics.java (draw): Add
+ end_gdk_drawing() to finally block.
+ (fill): Likewise.
+ (drawRenderedImage): Likewise.
+ (drawImage): Likewise.
+ (drawGlyphVector): Likewise.
+
+2006-06-11 Raif S. Naffah <raif@swiftdsl.com.au>
+
+ * doc/tools.texinfo: Added text for new -cacert command.
+ Re-structured sections.
+ * resource/gnu/classpath/tools/keytool/messages.properties: Added messages
+ for -cacert command.
+ * tools/gnu/classpath/tools/keytool/Main.java (CACERT_CMD): New constant.
+ (_CACERT): Likewise.
+ (shutdownThread): New field.
+ (Main): Install shutdown thread.
+ (main): Uninstall shutdown thread.
+ (start): Handle new -cacert command.
+ (getParser): Likewise.
+ (teardown): Increased visibility.
+ (ShutdownHook): New inner class.
+ * tools/gnu/classpath/tools/keytool/CACertCmd.java: New file.
+
+2006-06-11 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/FreetypeGlyphVector.java
+ (setupGlyphMetrics): New method. Add glyphmetrics caching.
+ (getOutline): Operate on the shape directly.
+ * gnu/java/awt/peer/gtk/GdkFontPeer.java
+ (getGlyphMetrics,putGlyphMetrics): Add GlyphMetrics caching.
+ * include/gnu_java_awt_peer_gtk_FreetypeGlyphVector.h
+ (getGlyph renamed getGlyphs)
+ * java/awt/geom/AffineTransform.java
+ (getTranslateInstance): Set fields directly.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_FreetypeGlyphVector.c
+ (getGlyphs): Get all glyph codes at once.
+
+2006-06-11 Raif S. Naffah <raif@swiftdsl.com.au>
+
+ PR Classpath/27853
+ * gnu/javax/crypto/RSACipherImpl.java (engineDoFinal): Was short by 1 byte.
+
+2006-06-11 Sven de Marothy <sven@physto.se>
+
+ * java/awt/font/TextLayout.java
+ (getLogicalHighlightShape): Add check.
+ * gnu/java/awt/peer/gtk/FreetypeGlyphVector.java
+ (getLogicalBounds, getGlyphPositions): Cache bounds, positions.
+
+2006-06-11 Raif S. Naffah <raif@swiftdsl.com.au>
+
+ * gnu/javax/security/auth/login/ConfigFileParser.java (validateClassName):
+ Check that every component of 'cn' starts with a valid Java identifier char.
+
+2006-06-10 Tom Tromey <tromey@redhat.com>
+
+ * java/io/File.java (pathSeparator): Typo fix.
+
+2006-06-10 Mark Wielaard <mark@klomp.org>
+
+ * native/jni/gtk-peer/cairographics2d.h (cp_gtk_get_cairo_t):
+ Removed.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoGraphics2D.c
+ Mark all unused parameters.
+ (cp_gtk_get_cairo_t): Removed.
+ (Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSetMatrix):
+ Don't mix declerations and statements.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c:
+ Mark all unused parameters.
+ (Java_gnu_java_awt_peer_gtk_CairoSurface_nativeDrawSurface):
+ Get cairographics2d pointer directly.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkTextLayout.c
+ (Java_gnu_java_awt_peer_gtk_GdkTextLayout_cairoDrawGdkTextLayout):
+ Use jlong to pass pointer.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkVolatileImage.c:
+ Mark all unused parameters.
+ * include/gnu_java_awt_peer_gtk_CairoGraphics2D.h: Regenerated.
+ * include/gnu_java_awt_peer_gtk_CairoSurface.h: Regenerated.
+ * include/gnu_java_awt_peer_gtk_ComponentGraphics.h: Regenerated.
+ * include/gnu_java_awt_peer_gtk_GdkTextLayout.h: Regenerated.
+ * include/gnu_java_awt_peer_gtk_GtkVolatileImage.h: Regenerated.
+ * include/java_io_VMFile.h: Regenerated.
+
+2006-06-10 Roman Kennke <kennke@aicas.com>
+
+ * gnu/java/awt/peer/gtk/VolatileImageGraphics.java
+ (VolatileImageGraphics(VolatileImageGraphics)): Use clipRect()
+ instead of setClip(), so that an already present clip is intersected
+ and not resetted.
+
+2006-06-10 Mark Wielaard <mark@klomp.org>
+
+ * gnu/java/awt/peer/gtk/GdkFontPeer.java (GdkFontLineMetrics):
+ Call getSize() to avoid accessor method.
+
+2006-06-10 Mark Wielaard <mark@klomp.org>
+
+ * javax/swing/text/html/HTMLDocument.java (addSpecialElement):
+ Qualify ElementSpec.
+
+2006-06-10 Mark Wielaard <mark@klomp.org>
+
+ * lib/.cvsignore: Add sun.
+ * lib/Makefile.am (dist-hook): Likewise.
+
+2006-06-10 Roman Kennke <kennke@aicas.com>
+
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java
+ * gnu/java/awt/peer/gtk/CairoSurface.java
+ * gnu/java/awt/peer/gtk/CairoSurfaceGraphics.java
+ * gnu/java/awt/peer/gtk/ComponentGraphics.java
+ * gnu/java/awt/peer/gtk/GtkVolatileImage.java
+ * native/jni/gtk-peer/cairographics2d.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoGraphics2D.c
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkVolatileImage.c:
+ Changed method signatures and calls to pass native pointers directly
+ into the JNI code, in order to avoid costly lookups on each
+ JNI call.
+ * include/gnu_java_awt_peer_gtk_CairoGraphics2D.h,
+ * include/gnu_java_awt_peer_gtk_CairoSurface.h,
+ * include/gnu_java_awt_peer_gtk_ComponentGraphics.h,
+ * include/gnu_java_awt_peer_gtk_GtkVolatileImage.h:
+ Regenerated
+
+2006-06-10 Audrius Meskauskas <AudriusA@Bioinformatics.org>
+
+ PR 27973
+ * javax/swing/text/DefaultStyledDocument.java
+ (ElementBuffer.insertContentTag):
+ Do not recreate leaves and do not remove elements here.
+
+2006-06-10 Audrius Meskauskas <AudriusA@Bioinformatics.org>
+
+ * javax/swing/text/html/HTMLDocument.java
+ (HTMLReader.HiddenAction): Implemented.
+
+2006-06-10 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/RepaintManager.java
+ (getVolatileOffscreenBuffer): Store the created buffer.
+ * javax/swing/JComponent.java
+ (paintDoubleBuffered): Try to use a volatile offscreen buffer
+ for better performance.
+
+2006-06-10 Roman Kennke <kennke@aicas.com>
+
+ * gnu/java/awt/peer/gtk/VolatileImageGraphics.java
+ (VolatileImageGraphics(VolatileImageGraphics)): Initialize native
+ context correctly.
+ (getRealBounds): Overridden to return the correct bounds.
+
+2006-06-10 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/plaf/metal/MetalButtonUI.java
+ (update): Fixed to paint the gradient under the correct conditions.
+ (updateWidthGradient): Removed.
+ (isToolbarButton): New helper method.
+ (isDrawingGradient): New helper method.
+
+2006-06-09 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/JTabbedPane.java
+ (setSelectedIndex): Don't change the visibility of the components,
+ this is done by the UI class.
+ * javax/swing/plaf/basic/BasicTabbedPaneUI.java
+ (TabbedPaneLayout.layoutContainer): Change visibility of component
+ here, depending on the selected index. Only do this if the new
+ selected component is not null. Some programs seem to expect
+ this.
+ (visibleComponent): New field.
+ (getVisibleComponent): Changed to return visibleComponent field.
+ (setVisibleComponent): Changed to set the visibility of
+ the old and new visible component.
+
+2006-06-09 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/JComponent.java
+ (paintChildrenOptimized): Paint component with a new Graphics
+ object to protect the other painting code from modifications
+ done in that object, and avoid cleanup ops on possibly dispose()ed
+ Graphics object.
+
+2006-06-09 Sven de Marothy <sven@physto.se>
+
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphics_disposeSurface):
+ Use GTK locks while disposing (Xlib) surface.
+
+2006-06-09 Tom Tromey <tromey@redhat.com>
+
+ * lib/Makefile.am (install-data-local): Copy 'sun' files.
+ (uninstall-local): Delete 'sun' directory.
+ (glibj.zip): Include 'sun' classes.
+ (clean-local): Delete 'sun' directory.
+ * lib/gen-classlist.sh.in: Search 'sun' subdirectories.
+
+2006-06-09 Roman Kennke <kennke@aicas.com>
+
+ * gnu/java/awt/java2d/AbstractGraphics2D.java
+ (drawImage): Fixed scaling.
+ (fillShape): Removed offset handling.
+ (fillShapeImpl): Limit scanlining to device bounds.
+ (getSegments): Removed offset handling.
+ * gnu/java/awt/java2d/PolyEdge.java
+ (toString): Include isClip flag in output.
+
+2006-06-08 Sven de Marothy <sven@physto.se>
+
+ * java/awt/font/TextLayout.java
+ (getOutline): Allow null transform.
+
+2006-06-08 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java
+ (drawString): Use TextLayout instead of GlyphVector.
+
+2006-06-08 Sven de Marothy <sven@physto.se>
+
+ * java/text/Bidi.java: Treat WS as neutral for rules N1 & N2.
+ * gnu/java/awt/peer/gtk/FreetypeGlyphVector.java
+ New constructor for bidirectionality.
+ (getGlyphMetrics): Return whitespace glyphs.
+ (getLogicalBounds): Offset rectangles to correct positions.
+ * gnu/java/awt/peer/gtk/GdkFontPeer.java
+ (getBaselineFor): Default to ROMAN_BASELINE.
+ (GdkFontLineMetrics): Guess some values for underline and
+ strikethrough.
+ (layoutGlyphVector): Use bidirectionality.
+ * java/awt/font/TextLayout.java: Implement, mostly.
+
+2006-06-09 Anthony Green <green@redhat.com>
+
+ PR classpath/27888:
+ * javax/swing/text/GapContent.java (binarySearch): Use unsigned shift.
+ * java/util/Collections.java (binarySearch): Use unsigned shift.
+ * java/util/Arrays.java (binarySearch): Use unsigned shift.
+
+2006-06-09 Tom Tromey <tromey@redhat.com>
+
+ * tools/.cvsignore: Added .deps.
+
+2006-06-09 Kazuya Ujihara <ujihara@aurora.dti.ne.jp>
+
+ PR classpath/27966:
+ * gnu/javax/security/auth/login/ConfigFileParser.java
+ (validateClassName): Quote '.' in regexp.
+
+2006-06-09 Tom Tromey <tromey@redhat.com>
+
+ PR classpath/23863:
+ * native/fdlibm/dtoa.c (_dtoa): Free contents of _Jv_reent when
+ finished.
+ * native/fdlibm/mprec.c: New version from newlib. Commented out
+ some includes. Added <assert.h>.
+ (_reent, _Bigint): New defines.
+ (_REENT_CHECK_MP, _REENT_MP_FREELIST, _REENT_MP_P5S): Likewise.
+ (__ULong, __Long): New types.
+ (_calloc_r): New function.
+ (Balloc): Dynamically add new _freelist entries as needed.
+ * native/fdlibm/mprec.h (struct _Jv_Bigint): Don't use
+ MAX_BIGNUMS to size _x[].
+ (struct _Jv_reent): _freelist now a _Jv_Bigint**. Removed
+ _allocation_map, num. Added _max_k.
+
+2006-06-09 Roman Kennke <kennke@aicas.com>
+
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java
+ (drawGlyphVector): Added fallback for non-FreetypeGlyphVector
+ implementations.
+
+2006-06-09 David Gilbert <david.gilbert@object-refinery.com>
+
+ * java/awt/image/BufferedImage.java
+ (BufferedImage(int, int, int)): Added API docs,
+ (getProperty(String)): Return correct value for undefined properties,
+ (getPropertyNames()): Added comments and removed FIXME.
+
+2006-06-09 Thomas Fitzsimmons <fitzsim@redhat.com>
+
+ * native/plugin/gcjwebplugin.cc (PLUGIN_ERROR_THREE): New macro.
+ (NP_Initialize): Use PLUGIN_ERROR_THREE in place of g_strconcat.
+
+2006-06-09 Francis Kung <fkung@redhat.com>
+
+ * javax/swing/plaf/basic/BasicComboBoxRenderer.java:
+ (getPreferredSize): Return correct height for null or empty
+ items.
+
+2006-06-09 David Gilbert <david.gilbert@object-refinery.com>
+
+ * java/awt/datatransfer/DataFlavor.java
+ (readExternal): Mark as stub,
+ (writeExternal): Likewise,
+ * java/awt/dnd/DropTargetContext.java
+ (dropComplete): Mark as stub,
+ (acceptDrag): Likewise,
+ (rejectDrag): Likewise,
+ (acceptDrop): Likewise,
+ (rejectDrop): Likewise,
+ (getCurrentDataFlavors): Likewise,
+ (getTransferable): Likewise,
+ * java/awt/dnd/DropTargetDropEvent.java
+ (dropComplete): Mark as stub.
+
+2006-06-09 Audrius Meskauskas <AudriusA@Bioinformatics.org>
+
+ * gnu/javax/swing/text/html/parser/SmallHtmlAttributeSet.java
+ (constructor): Do not lowercase the values.
+ * javax/swing/text/html/HTMLDocument.java
+ (HTMLReader.addSpecialElement): Implemented.
+ * examples/gnu/classpath/examples/swing/HtmlDemo.java: New file.
+
+2006-06-09 Raif S. Naffah <raif@swiftdsl.com.au>
+
+ On behalf of Matthew Wringe <mwringe@redhat.com>
+ * gnu/java/security/Registry.java (ISO10126_PAD): New constant.
+ * gnu/javax/crypto/pad/ISO10126.java: New class.
+ * gnu/javax/crypto/pad/PadFactory.java (names): New field.
+ (getInstance): Added support for ISO-10126 scheme.
+ (getNames): Likewise.
+ Cache result for speed.
+
+2006-06-09 Raif S. Naffah <raif@swiftdsl.com.au>
+
+ * gnu/javax/crypto/pad/BasePad.java (selfTest): Re-factored to allow more
+ flexible self-test by sub-classes.
+ (test1BlockSize): New method.
+
+2006-06-09 David Gilbert <david.gilbert@object-refinery.com>
+
+ * javax/swing/plaf/basic/BasicLookAndFeel.java
+ (initComponentDefaults): Corrected 'ScrollBar.focusInputMap' entry,
+ * javax/swing/plaf/basic/BasicScrollBarUI.java
+ (installKeyboardActions): Implemented,
+ (uninstallKeyboardActions): Implemented,
+ (getInputMap): New method,
+ (getActionMap): New method,
+ (createActionMap): New method,
+ (installUI): Call installKeyboardActions(),
+ (uninstallUI): Call uninstallKeyboardActions().
+
+2006-06-09 David Gilbert <david.gilbert@object-refinery.com>
+
+ * javax/swing/plaf/basic/BasicScrollPaneUI.java
+ (getActionMap): Use correct key to store action map.
+
+2006-06-09 Jeroen Frijters <jeroen@frijters.net>
+
+ * gnu/java/awt/font/opentype/truetype/VirtualMachine.java
+ (executeInstruction): Added NOT support.
+
+2006-06-09 Jeroen Frijters <jeroen@frijters.net>
+
+ * sun/reflect/annotation/AnnotationInvocationHandler.java:
+ New file.
+
+2006-06-08 Tom Tromey <tromey@redhat.com>
+
+ * java/text/Bidi.java (resolveNeutralTypes): Set j'th slot
+ of 'types'.
+
+2006-06-09 Andrew John Hughes <gnu_andrew@member.fsf.org>
+
+ * java/lang/management/RuntimeMXBean.java:
+ New file.
+
+2006-06-08 Lillian Angel <langel@redhat.com>
+
+ * native/plugin/gcjwebplugin.cc:
+ (NP_Shutdown): Freed whitelist_filename.
+
+2006-06-08 Lillian Angel <langel@redhat.com>
+
+ * native/plugin/Makefile.am:
+ Removed DATA_DIRECTORY.
+ * native/plugin/gcjwebplugin.cc:
+ Added new global fields for whitelist_file
+ and data_directory. Removed WHITELIST_FILE.
+ (NP_Initialize): Initialized new fields. Also,
+ Changed to use new fields.
+ (NP_Shutdown): Freed data_directory.
+ (GCJ_New): Changed to use new fields.
+ (plugin_ask_user_about_documentbase): Likewise.
+
+2006-06-08 Lillian Angel <langel@redhat.com>
+
+ * native/plugin/Makefile.am:
+ Changed DATA_DIRECTORY to be ~/.gcjwebplugin.
+ * native/plugin/gcjwebplugin.cc:
+ Changed all instances of PLUGIN_DATA_DIRECTORY
+ to DATA_DIRECTORY.
+
+2006-06-08 Roman Kennke <kennke@aicas.com>
+
+ * java/awt/LightweightDispatcher.java
+ (handleMouseEvent): Replaced calls to AWTUtilities.convertPoint()
+ with convertPointToChild(). This is more efficient and avoids
+ problems with getLocationOnScreen().
+ (findTarget): Check for component beeing showing() early.
+ Simplified AWTUtilities.convertPoint() to a simple substraction
+ operation.
+ (convertPointToChild): New helper method.
+
+2006-06-08 Thomas Fitzsimmons <fitzsim@redhat.com>
+
+ * native/plugin/gcjwebplugin.cc (SECURITY_DESCRIPTION): Update
+ message.
+
+2006-06-08 Tom Fitzsimmons <fitzsim@redhat.com>
+ Lillian Angel <langel@redhat.com>
+
+ * native/plugin/gcjwebplugin.cc
+ (NP_Shutdown): Added code to free plugin mutex and whitelist file.
+ Also, reset initialized field.
+
+2006-06-08 Lillian Angel <langel@redhat.com>
+
+ * javax/swing/plaf/basic/BasicProgressBarUI.java
+ (paintString): Fixed to paint string at the correct location.
+
+2006-06-08 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/plaf/basic/BasicTreeUI.java
+ (createDefaultActions): Added new actions.
+ (TreePageAction.TreePageAction): Set action name.
+ (TreePageAction.actionPerformed): Implemented.
+ (TreePageAction.isEnabled): Implemented.
+ (TreeToggleAction.TreePageAction): Set action name.
+ (TreeToggleAction.actionPerformed): Implemented.
+ (TreeToggleAction.isEnabled): Implemented.
+ (TreeTraverseAction.TreeTraverseAction): Set action name.
+ (TreeTraverseAction.actionPerformed): Use action name as command.
+ (TreeTraverseAction.isEnabled): Implemented.
+
+2006-06-08 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/plaf/basic/BasicTreeUI.java
+ (installKeyboardActions): Rewritten to correctly install the UI
+ input and action maps.
+ (getActionMap): New helper method.
+ (createDefaultActionMap): New helper method.
+ (TreeHomeAction.TreeHomeAction()): Implemented.
+ (TreeHomeAction.actionPerformed): Implemented.
+ (TreeHomeAction.isEnabled): Implemented.
+ (TreeIncrementAction.TreeIncrementAction()): Implemented.
+ (TreeIncrementAction.actionPerformed): Use action name as command.
+ (TreeIncrementAction.isEnabled): Implemented.
+
+2006-06-08 Mark Wielaard <mark@klomp.org>
+
+ PR 27917
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkImage.c
+ (Java_gnu_java_awt_peer_gtk_GtkImage_loadImageFromData): Ref pixbuf
+ and unref loader.
+
+2006-06-08 Mark Wielaard <mark@klomp.org>
+
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkFontPeer.c
+ (attrs): Removed unused static.
+
+2006-06-08 David Gilbert <david.gilbert@object-refinery.com>
+
+ * javax/swing/plaf/basic/BasicScrollPaneUI.java
+ (getInputMap): New method,
+ (getActionMap): New method,
+ (createActionMap): New method,
+ (installKeyboardActions): Implemented,
+ (uninstallKeyboardActions): Implemented.
+
+2006-06-08 Robert Schuster <robertschuster@fsfe.org>
+
+ * javax/swing/border/MatteBorder.java:
+ (MatteBorder(int,int,int,int,Icon)): Removed if-statement and exception
+ throwing.
+ (paintBorder): Added if-statement to abort painting early.
+
+2006-06-08 Robert Schuster <robertschuster@fsfe.org>
+
+ Fixes PR27864.
+ * gnu/xml/dom/DomIterator.java:
+ (successor): Changed expression.
+
+2006-06-08 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/FreetypeGlyphVector.java
+ (defaultLayout): Do kerning.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_FreetypeGlyphVector.c
+ (getKerning): Correct class name, removed unused variable.
+
+2006-06-07 Thomas Fitzsimmons <fitzsim@redhat.com>
+
+ * gnu/java/awt/peer/qt/QtToolkit.java (initToolkit): Load
+ libqtpeer.so unconditionally.
+
2006-06-07 Andrew John Hughes <gnu_andrew@member.fsf.org>
* java/util/InputMismatchException.java:
Documented.
+2006-06-07 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * native/jawt/Makefile.am (AM_LDFLAGS): Add XTEST_LIBS.
+
+2006-06-07 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/plaf/basic/BasicTreeUI.java
+ (completeUIUninstall): Implemented.
+ (uninstallUI): Moved some bits to completeUIUninstall(). Complete
+ editing before uninstalling anything.
+ (isToggleEvent): Implemented.
+ (selectPathForEvent): Make use of isToggleEvent().
+ (ComponentHandler.componentMoved): Implemented.
+ (ComponentHandler.startTimer): Implemented.
+ (ComponentHandler.getScrollPane): Implemented.
+ (ComponentHandler.actionPerformed): Implemented.
+
+2006-06-07 Francis Kung <fkung@redhat.com>
+
+ * javax/swing/JMenuBar.java:
+ (getSubElements): Do not return null values.
+
+2006-06-07 Roman Kennke <kennke@aicas.com>
+
+ PR 27902
+ * gnu/regexp/BacktrackStack.java
+ * gnu/regexp/CharIndexed.java
+ * gnu/regexp/CharIndexedCharArray.java
+ * gnu/regexp/CharIndexedCharSequence.java
+ * gnu/regexp/CharIndexedInputStream.java
+ * gnu/regexp/CharIndexedString.java
+ * gnu/regexp/CharIndexedStringBuffer.java
+ * gnu/regexp/RE.java
+ * gnu/regexp/REException.java
+ * gnu/regexp/REFilterInputStream.java
+ * gnu/regexp/REMatch.java
+ * gnu/regexp/REMatchEnumeration.java
+ * gnu/regexp/RESyntax.java
+ * gnu/regexp/REToken.java
+ * gnu/regexp/RETokenAny.java
+ * gnu/regexp/RETokenBackRef.java
+ * gnu/regexp/RETokenChar.java
+ * gnu/regexp/RETokenEnd.java
+ * gnu/regexp/RETokenEndOfPreviousMatch.java
+ * gnu/regexp/RETokenEndSub.java
+ * gnu/regexp/RETokenIndependent.java
+ * gnu/regexp/RETokenLookAhead.java
+ * gnu/regexp/RETokenLookBehind.java
+ * gnu/regexp/RETokenNamedProperty.java
+ * gnu/regexp/RETokenOneOf.java
+ * gnu/regexp/RETokenPOSIX.java
+ * gnu/regexp/RETokenRange.java
+ * gnu/regexp/RETokenRepeated.java
+ * gnu/regexp/RETokenStart.java
+ * gnu/regexp/RETokenWordBoundary.java
+ * gnu/regexp/UncheckedRE.java
+ * gnu/java/util/regex/BacktrackStack.java
+ * gnu/java/util/regex/CharIndexed.java
+ * gnu/java/util/regex/CharIndexedCharArray.java
+ * gnu/java/util/regex/CharIndexedCharSequence.java
+ * gnu/java/util/regex/CharIndexedInputStream.java
+ * gnu/java/util/regex/CharIndexedString.java
+ * gnu/java/util/regex/CharIndexedStringBuffer.java
+ * gnu/java/util/regex/RE.java
+ * gnu/java/util/regex/REException.java
+ * gnu/java/util/regex/REFilterInputStream.java
+ * gnu/java/util/regex/REMatch.java
+ * gnu/java/util/regex/REMatchEnumeration.java
+ * gnu/java/util/regex/RESyntax.java
+ * gnu/java/util/regex/REToken.java
+ * gnu/java/util/regex/RETokenAny.java
+ * gnu/java/util/regex/RETokenBackRef.java
+ * gnu/java/util/regex/RETokenChar.java
+ * gnu/java/util/regex/RETokenEnd.java
+ * gnu/java/util/regex/RETokenEndOfPreviousMatch.java
+ * gnu/java/util/regex/RETokenEndSub.java
+ * gnu/java/util/regex/RETokenIndependent.java
+ * gnu/java/util/regex/RETokenLookAhead.java
+ * gnu/java/util/regex/RETokenLookBehind.java
+ * gnu/java/util/regex/RETokenNamedProperty.java
+ * gnu/java/util/regex/RETokenOneOf.java
+ * gnu/java/util/regex/RETokenPOSIX.java
+ * gnu/java/util/regex/RETokenRange.java
+ * gnu/java/util/regex/RETokenRepeated.java
+ * gnu/java/util/regex/RETokenStart.java
+ * gnu/java/util/regex/RETokenWordBoundary.java
+ * gnu/java/util/regex/UncheckedRE.java
+ Moved gnu.regexp classes to gnu.java.util.regex package.
+ * java/util/regex/Matcher.java
+ * java/util/regex/Pattern.java
+ Adjusted import statements for new package name for gnu regexp.
+
+2006-06-07 Tom Tromey <tromey@redhat.com>
+
+ PR classpath/27905:
+ * gnu/java/nio/charset/Provider.java (loadExtended): Now synchronized.
+ Added missing charsets.
+ (charsetForName): Don't check 'extendedLoaded'.
+
+2006-06-07 Roman Kennke <kennke@aicas.com>
+
+ PR 27833
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java
+ (clip(Shape)): Implemented correctly, so that the current shape
+ gets intersected by the parameter shape.
+
+2006-06-07 Lillian Angel <langel@redhat.com>
+
+ * javax/swing/plaf/basic/BasicTabbedPaneUI.java
+ (getTabBounds): If this method is called with a tab index
+ that is not in the rects array, we need to re-layout the container
+ so it is created.
+
+2006-06-07 Lillian Angel <langel@redhat.com>
+
+ * gnu/java/awt/peer/gtk/FreetypeGlyphVector.java
+ (FreetypeGlyphVector): Removed assignment. Caused compilation error.
+ * java/lang/String.java
+ (codePointCount): Fixed check to match API. Shouldn't throw exception
+ if end == count. end is 1 more than the endIndex, so end == count is
+ possible.
+
+2006-06-07 Gary Benson <gbenson@redhat.com>
+
+ PR 24895
+ * native/jni/java-io/java_io_VMFile.c
+ (Java_java_io_VMFile_toCanonicalForm): New method.
+ * configure.ac: Added checks for lstat and readlink.
+ * include/java_io_VMFile.h: Added new method.
+ * vm/reference/java/io/VMFile.java: Use new method.
+ * gnu/java/io/PlatformHelper.java (toCanonicalForm): Removed.
+ * NEWS: Documented the above.
+ * java/io/File.java: Javadoc fix.
+
+2006-06-07 Roman Kennke <kennke@aicas.com>
+
+ PR 27920
+ * javax/swing/JTree.java
+ (JTree()): Initialize with default model.
+ (JTree(TreeModel)): Clear expanded state hashtable. Added comment
+ on the updateUI() / setModel() order.
+ (setModel): Correctly (un-)setup the listeners. Clear the expanded
+ paths.
+ * javax/swing/plaf/basic/BasicTreeUI.java
+ (BasicTreeUI()): Initialize listeners in installListeners().
+ (setModel): Complete editing on model change. Correctly resetup
+ the listeners. Update the layout cache accordingly.
+ (setShowRootHandles): Complete editing and update layout. Do not
+ call back into the JTree, this could cause cycles.
+ (prepareForUIInstall): Implemented. Moved some init code from
+ installUI() to this method.
+ (completeUIInstall): Implemented. Moved some init code from
+ installUI() to this method.
+ (createDefaultCellEditor): Check for type of renderer, and install
+ with null renderer when not DefaultTreeCellRenderer.
+ (updateLayoutCacheExpandedNodes): Added null check for tree root
+ to avoid NPE.
+ (updateRenderer): Call updateEditor().
+ (installListeners): Initialize the listeners here. Added some null
+ checks to avoid NPEs.
+ (installUI): Moved some init code to prepareForUIInstall() and
+ completeUIInstall().
+ (completeEditing): Return immediately if editing component is null
+ or if the setting is to not stop editing on complete editing.
+ (checkForClickInExpandControl): Call handleExpandControlClick()
+ instead of toggleExpandState() directly.
+ (isLocationInExpandControl): Rewritten to correctly determine the
+ expand click location.
+ (MouseHandler.mousePressed): Rewritten to make better use of the
+ instance methods of BasicTreeUI to handle the click.
+ (PropertyHandler.propertyChange): Handle model and cell renderer
+ updates.
+ * javax/swing/tree/DefaultTreeCellEditor.java
+ (DefaultTreeCellEditor): Removed initialization of the icon. This
+ is done so that the constructor can deal with null renderer as the
+ RI does. Maybe this needs more fixing.
+ * javax/swing/tree/TreePath.java
+ (isDescendant): Fixed this method. The previous version did too
+ much and compared the wrong things, which lead to a ClassCastException
+ in equals().
+ * javax/swing/tree/VariableHeightLayoutCache.java
+ (update): Do nothing when model is null.
+ (setModel): Clear the tables and update the layout. Added null
+ check to prevent NPE.
+
+2006-06-07 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/GdkGlyphVector: Removed file.
+
+2006-06-07 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/FreetypeGlyphVector.java
+ * include/gnu_java_awt_peer_gtk_FreetypeGlyphVector.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_FreetypeGlyphVector.c
+ New files.
+
+ * gnu/java/awt/peer/gtk/GdkFontPeer.java
+ (getGlyphVector): Removed native method.
+ (createGlyphVector, getStringBounds): Use new GV class.
+
+ * include/Makefile.am
+ * native/jni/gtk-peer/Makefile.am
+ Add new files.
+
+ * include/gnu_java_awt_peer_gtk_GdkFontPeer.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkFontPeer.c
+ (getGlyphVector): Removed native method.
+
+2006-06-07 Chris Burdess <dog@gnu.org>
+
+ * gnu/classpath/debug/TeeInputStream.java,
+ gnu/classpath/debug/TeeOutputStream.java,
+ gnu/classpath/debug/TeeReader.java,
+ gnu/classpath/debug/TeeWriter.java: New classes for debugging streams.
+ * gnu/xml/stream/XMLParser.java: Use tee streams for debugging. Don't
+ read more characters than absolutely necessary in tryRead method.
+
+2006-06-07 Robert Schuster <robertschuster@fsfe.org>
+
+ * examples/gnu/classpath/examples/swing/Demo.java:
+ (mkMenuBar): Put look and feel radio buttons into
+ appropriate button group.
+
+2006-06-07 Chris Burdess <dog@gnu.org>
+
+ * gnu/xml/stream/SAXParser.java,
+ gnu/xml/stream/XMLParser.java: Add command line options for setting
+ parsing parameters (for simpler debugging).
+ * gnu/xml/transform/TransformerImpl.java: Try to ensure that I/O error
+ closing output stream is propagated to application.
+
+2006-06-06 Mark Wielaard <mark@klomp.org>
+
+ PR 27917
+ * gnu/java/awt/peer/gtk/CairoSurface.java (finalize): Call dispose.
+ * gnu/java/awt/peer/gtk/ComponentGraphics.java: Override dispose to
+ call disposeSurface.
+ (disposeSurface): New native method.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoGraphics2D.c
+ (Java_gnu_java_awt_peer_gtk_CairoGraphics2D_disposeNative): Free
+ pattern_pixels.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
+ (Java_gnu_java_awt_peer_gtk_CairoSurface_drawSurface): Call
+ cairo_pattern_destroy.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphics_disposeSurface):
+ New function to destroy the surface.
+ * include/gnu_java_awt_peer_gtk_CairoGraphics2D.h: Regenerated.
+ * include/gnu_java_awt_peer_gtk_CairoSurface.h: Likewise.
+ * include/gnu_java_awt_peer_gtk_ComponentGraphics.h: Likewise.
+
+2006-06-06 Mark Wielaard <mark@klomp.org>
+
+ * include/jni.h (JDK1_1InitArgs): Mark pointer-to-function types
+ with JNICALL.
+
+2006-06-06 David Gilbert <david.gilbert@object-refinery.com>
+
+ * javax/swing/plaf/metal/MetalSplitPaneDivider.java
+ (paint): If has focus, paint special background color,
+ * javax/swing/plaf/basic/BasicSplitPaneUI.java
+ (FocusHandler.focusGained): Implemented,
+ (FocusHandler.focusLost): Implemented.
+
+2006-06-06 Tom Tromey <tromey@redhat.com>
+
+ * javax/swing/text/StyleContext.java (registerStaticAttributeKey):
+ Javadoc fix.
+ (writeAttributeSet): Implemented.
+
+2006-06-06 Tom Tromey <tromey@redhat.com>
+
+ * javax/swing/text/html/HTMLDocument.java (SpecialAction.start):
+ Implement.
+ (SpecialAction.end): Removed.
+ (IsindexAction.end): Likewise.
+
+2006-06-06 Tom Tromey <tromey@redhat.com>
+
+ * include/jni.h (JDK1_1InitArgs): New struct.
+ (JDK1_1AttachArgs): Likewise.
+
+2006-06-06 Tom Tromey <tromey@redhat.com>
+
+ * java/security/UnresolvedPermission.java (getUnresolvedType): New
+ method.
+ (getUnresolvedName): New method.
+ (getUnresolvedActions): New method.
+ (getUnresolvedCerts): New method.
+
+2006-06-06 Audrius Meskauskas <AudriusA@Bioinformatics.org>
+
+ * gnu/javax/swing/text/html/CharacterAttributeTranslator.java
+ (getColor): Removed debugging code.
+
+2006-06-06 Audrius Meskauskas <AudriusA@Bioinformatics.org>
+
+ * gnu/javax/swing/text/html/CharacterAttributeTranslator.java
+ (getColor): Added support for "rgb(red, green, blue)" notation.
+ (translateTag): Use Boolean.TRUE, not new Boolean().
+
+2006-06-06 Roman Kennke <kennke@aicas.com>
+
+ PR 27651
+ * javax/swing/JTree.java
+ (JTree(TreeModel)): Call updateUI() before setModel().
+ (setModel): Don't call updateUI here.
+
+2006-06-06 Lillian Angel <langel@redhat.com>
+
+ * native/plugin/gcjwebplugin.cc:
+ Fixed failure message and commenting.
+ (NP_Initialize): Added more comments.
+
+2006-06-06 David Gilbert <david.gilbert@object-refinery.com>
+
+ * javax/swing/JSplitPane.java
+ (AccessibleJSplitPane): API doc fixes,
+ (setDividerLocation): Likewise,
+ * javax/swing/plaf/basic/BasicLookAndFeel.java
+ (initComponentDefaults): Additions to SplitPane.ancestorInputMap,
+ * javax/swing/plaf/basic/BasicSplitPaneUI.java
+ (getInputMap): New method,
+ (getActionMap): New method,
+ (createActionMap): New method,
+ (installKeyboardActions): Implemented,
+ (uninstallKeyboardActions): Implemented.
+
+2006-06-06 Roman Kennke <kennke@aicas.com>
+
+ PR 27523
+ * javax/swing/MenuSelectionManager.java
+ (processKeyEvent): Added check to avoid
+ ArrayIndexOutOfBoundsException.
+
+2006-06-06 Audrius Meskauskas <AudriusA@Bioinformatics.org>
+
+ * gnu/javax/swing/text/html/htmlAttributeSet.java
+ (getAttributeNames): Rewritten
+
+2006-06-06 Chris Burdess <dog@gnu.org>
+
+ * gnu/xml/transform/TransformerImpl.java: Check type of created
+ document (more cases).
+
+2006-06-06 Audrius Meskauskas <AudriusA@Bioinformatics.org>
+
+ * gnu/javax/swing/text/html/htmlAttributeSet.java
+ (clone): New method. (copyAttributes): New method.
+ (getResolveParent): Comment fix. (getAttribute):
+ Rewritten. (addAttribute): Rewritten.
+ * gnu/javax/swing/text/html/SmallHtmlAttributeSet.java:
+ New file.
+
+2006-06-06 Roman Kennke <kennke@aicas.com>
+
+ PR 27522
+ * javax/swing/JMenuBar.java
+ (processKeyBindingHelper): Added null check to prevent NPE.
+
+2006-06-06 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/plaf/basic/BasicInternalFrameUI.java
+ (ShowSystemMenuAction): New class.
+ (installKeyboardActions): Implemented.
+ (uninstallKeyboardActions): Implemented.
+ * javax/swing/plaf/metal/MetalInternalFrameUI.java
+ (installKeyboardActions): Overridden to remove showSystemMenu action.
+
+2006-06-06 Chris Burdess <dog@gnu.org>
+
+ * gnu/xml/transform/TransformerImpl.java: Check type of created
+ document.
+
+2006-06-06 Robert Schuster <robertschuster@fsfe.org>
+
+ * gnu/java/awt/peer/gtk/GdkGraphicsEnvironment.java:
+ (getScreenDevices): Added explicit cast.
+
+2006-06-06 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/plaf/basic/BasicTextUI.java
+ (installKeyboardActions): Use shared input map. Correctly
+ install the input/action maps in the component's input/action
+ map hierarchies.
+ (getActionMap): New helper method for fetching an ActionMap from
+ the UIManager or creating a default one if there is none supplied
+ by the UIManager.
+ (createActionMap): Add the TransferHandler's actions here. Made
+ method private.
+ (getInputMap): Leave out unnecessary method parameter. Load
+ shared input map.
+ * javax/swing/plaf/basic/SharedUIDefaults.java: New file.
+
+2006-06-06 Robert Schuster <robertschuster@fsfe.org>
+
+ * configure.ac: Added missing [ to expression.
+
+2006-06-06 Robert Schuster <robertschuster@fsfe.org>
+
+ * configure.ac: Added missing { to expression.
+
+2006-06-06 Robert Schuster <robertschuster@fsfe.org>
+
+ * include/gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.h: Regenerated.
+ * include/gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.h: New file.
+ * include/Makefile.am: Added
+ gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.
+ * gnu/java/awt/peer/gtk/GdkGraphicsConfiguration.java:
+ (GdkGraphicsConfiguration): Rewritten.
+ (getColorModel): Rewritten.
+ (getColorModel(int)): Rewritten.
+ (getBounds): Rewritten.
+ (createCompatibleVolatileImage): Implemented.
+ * gnu/java/awt/peer/gtk/GdkGraphicsEnvironment.java: Added static
+ initializer.
+ (getDefaultScreenDevice): Rewritten.
+ (nativeGetDefaultScreenDevice): New method.
+ (getScreenDevices): Rewritten.
+ (nativeGetScreenDevices): New method.
+ (nativeInitState): New method.
+ * gnu/java/awt/peer/gtk/GdkScreenGraphicsDevice.java: Entirely
+ rewritten.
+ (X11DisplayMode): New inner class.
+ * native/jni/gtk-peer/Makefile.am: Added gdkdisplay.h and
+ gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.c
+ * native/jni/gtk-peer/gdkdisplay.h: New file.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.c:
+ (Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment_initStaticState):
+ New function.
+ (Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment_nativeInitState):
+ New function.
+ (Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment
+ _nativeGetScreenDevices):
+ New function.
+ (Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment
+ _nativeGetDefaultScreenDevice):
+ New function.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.c:
+ New file.
+ * configure.ac: Added check for Xrandr library.
+
+2006-06-06 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/plaf/basic/BasicTableUI.java
+ (getMaximumSize): Don't return null. Fixed calculation of
+ table height.
+ (getMinimumSize): Don't return null. Fixed calculation of
+ table height.
+ (getPreferredSize): Fixed calculation of with and height. Added
+ API docs.
+ (getHeight): New helper method.
+
+2006-06-06 David Gilbert <david.gilbert@object-refinery.com>
+
+ * javax/swing/JComponent.java
+ (getInputMap(int)): Throw IllegalArgumentException for unknown
+ condition argument, and added API docs,
+ (getInputMap()): Added API docs.
+
+2006-06-06 Robert Schuster <robertschuster@fsfe.org>
+
+ * java/awt/BufferedImage.java: Added fourth 8 to bits4 field.
+
+2006-06-06 David Gilbert <david.gilbert@object-refinery.com>
+
+ * javax/swing/JTable.java
+ (AccessibleJTableHeaderCell.header): New field,
+ (AccessibleJTableHeaderCell.columnIndex): Likewise,
+ (AccessibleJTableHeaderCell.AccessibleJTableHeaderCell()): Initialise,
+ (AccessibleJTableHeaderCell.getColumnHeaderRenderer): New method,
+ (AccessibleJTableHeaderCell.getAccessibleContext): Implemented,
+ (AccessibleJTableHeaderCell.getAccessibleRole): Implemented,
+ (AccessibleJTable.getAccessibleChild(int)): Overridden,
+ (AccessibleJTable.getAccessibleAt): Reimplemented.
+
+2006-06-05 Sven de Marothy <sven@physto.se>
+
+ * include/gnu_java_awt_peer_gtk_ComponentGraphics.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
+ * gnu/java/awt/peer/gtk/ComponentGraphics.java
+ (initFromVolatile): New method.
+ * gnu/java/awt/peer/gtk/GtkVolatileImage.java
+ * gnu/java/awt/peer/gtk/VolatileImageGraphics.java
+ Reimplement.
+ * include/gnu_java_awt_peer_gtk_GtkVolatileImage.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkVolatileImage.c
+ (copyArea, drawVolatileImage): New methods.
+
+2006-06-05 Tania Bento <tbento@redhat.com>
+
+ * javax/swing/JFrame.java
+ (frameInit): Set background color and fixed layout parameters.
+
+2006-06-05 Tom Tromey <tromey@redhat.com>
+
+ * NEWS: Mention VMURLConnection.
+
+2006-06-05 Lillian Angel <langel@redhat.com>
+
+ * native/plugin/gcjwebplugin.cc:
+ Added new field to keep track of initialization.
+ (plugin_start_appletviewer): Fixed to return an error value, if
+ an error was encountered when loading the appletviewer.
+ (GCJ_NEW): Added call to plugin_failed if the loading of the appletviewer
+ has failed.
+ (plugin_failed): New helper function. Shows a warning if the appletviewer
+ has not been installed.
+ (NP_Initialize): Added code to make sure this function is only called
+ once.
+
+2006-06-05 Lillian Angel <langel@redhat.com>
+
+ * native/plugin/Makefile.am:
+ Fixed to use a set plugin directory in the .mozilla directory.
+ All applet logs are now stored here, instead of /tmp.
+ * native/plugin/gcjwebplugin.cc:
+ Added new fields for security warning.
+ (GCJ_NEW): Added code to generate a security warning for all pages
+ that spawn an appletviewer. This warning asks the user if they trust
+ the applet and if they would like to add it to a 'whitelist'. This
+ whitelist keeps track of all the addresses the user would like
+ to trust indefinitely.
+ (plugin_user_trusts_documentbase): New helper function.
+ (plugin_add_documentbase_to_whitelist): New helper function.
+ (plugin_ask_user_about_documentbase): New helper function.
+ (plugin_in_pipe_callback): Fixed check to determine if channel_error
+ has been set.
+ (plugin_start_appletviewer): Likewise.
+ (plugin_create_applet_tag): Reset all fields to null after they have been
+ freed.
+ (plugin_send_message_to_appletviewer): Fixed all error checks to determine
+ if channel_error has been set.
+ (plugin_stop_appletviewer): Likewise.
+ (NP_Initialize): Likewise. Also, added code to determine if directory and file
+ should be created.
+
+2006-06-05 Francis Kung <fkung@redhat.com>
+
+ PR 27507
+ * gnu/java/awt/peer/gtk/GtkImage.java
+ (getSource): Added check to determine if in
+ errorLoading state.
+ * gnu/java/awt/peer/gtk/GtkToolkit.java
+ (createImage): Added check to prevent NPE.
+
+2006-06-05 Audrius Meskauskas <AudriusA@Bioinformatics.org>
+
+ * javax/swing/text/html/HTMLEditorKit.java (HTMLFactory.create):
+ Create the ImageView, when applicable.
+ * gnu/javax/swing/text/html/CombinedAttributes.java,
+ javax/swing/text/html/ImageView.java: New files.
+
+2006-06-05 Roman Kennke <kennke@aicas.com>
+
+ PR 27834
+ * javax/swing/text/GapContent.java
+ (setPositionsInRange): Compare with startIndex and endIndex
+ rather than start and end.
+ (dumpMarks): Only dump real marks.
+
+2006-06-05 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/ComponentGraphics.java
+ (ComponentGraphics): Use 0,0 as clip origin.
+
2006-06-04 Andrew John Hughes <gnu_andrew@member.fsf.org>
* java/util/Formattable.java,
@@ -41,6 +1170,93 @@
(getenv()): Handle cases where split only
returns an array of size 1.
+2006-06-04 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/GtkComponentPeer.java
+ (createVolatileImage): Pass peer to VolatileImage constructor.
+ * java/awt/Component.java
+ (createVolatileImage): Call peer method directly.
+
+2006-06-04 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/CairoSurface.java
+ (getFlippedBuffer): New method.
+ (getGtkImage): Renamed method.
+ * gnu/java/awt/peer/gtk/ComponentGraphicsCopy.java
+ * gnu/java/awt/peer/gtk/GtkVolatileImage.java
+ Renamed getSharedImage to getGtkImage.
+ * include/gnu_java_awt_peer_gtk_CairoSurface.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
+ (getFlippedBuffer): New method
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
+ Avoid window casts.
+2006-06-04 Andrew John Hughes <gnu_andrew@member.fsf.org>
+
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c:
+ (drawVolatile): Add casts.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkTextLayout.c:
+ (getOutline): Add casts.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkVolatileImage.c:
+ Comment out unused prototype.
+ (getPixels): Add appropriate cast and comment out unused variable.
+
+2006-06-04 Raif S. Naffah <raif@swiftdsl.com.au>
+
+ * gnu/javax/crypto/sasl/SaslUtil.java: Remove unused import.
+ * gnu/javax/crypto/sasl/srp/SRPRegistry.java (PASSWORD_DB): Fix javadoc @link.
+ * gnu/javax/crypto/sasl/srp/PasswordFile.java: Removed unused import.
+ * gnu/javax/crypto/prng/CSPRNG.java (FILE_SOURCES): Fix javadoc @see.
+ (getSystemInstance): Fix javadoc @link.
+ (counter): Increased visibility.
+ * gnu/javax/crypto/pad/TLS1.java: Remove unused import.
+ * gnu/javax/crypto/pad/IPad.java: Fix javadoc @link.
+ * gnu/javax/crypto/pad/PKCS1_V1_5.java (PKCS1_V1_5): Likewise.
+ * gnu/javax/crypto/pad/PKCS7.java (PKCS7): Likewise.
+ * gnu/javax/crypto/pad/TBC.java (TBC): Likewise.
+ * gnu/javax/crypto/mode/CTR.java: Remove unused import.
+ * gnu/javax/crypto/mode/BaseMode.java (defaultBlockSize): Fix javadoc @see.
+ * gnu/javax/crypto/key/dh/GnuDHPrivateKey.java (getEncoded): Fix javadoc @see.
+ * gnu/javax/crypto/jce/spec/TMMHParameterSpec.java: Fix javadoc @link.
+ * gnu/javax/crypto/keyring/AuthenticatedEntry.java: Remove unused imports.
+ * gnu/javax/crypto/keyring/CertificateEntry.java: Likewise.
+ * gnu/javax/crypto/keyring/CertPathEntry.java: Likewise.
+ * gnu/javax/crypto/keyring/EncryptedEntry.java: Likewise.
+ * gnu/javax/crypto/keyring/PublicKeyEntry.java: Likewise.
+ * gnu/javax/crypto/mac/OMAC.java: Likewise.
+ * gnu/javax/crypto/jce/key/AnubisSecretKeyFactoryImpl.java: Likewise.
+ * gnu/javax/crypto/jce/key/BlowfishSecretKeyFactoryImpl.java: Likewise.
+ * gnu/javax/crypto/jce/key/Cast5SecretKeyFactoryImpl.java: Likewise.
+ * gnu/javax/crypto/jce/key/KhazadSecretKeyFactoryImpl.java: Likewise.
+ * gnu/javax/crypto/jce/key/RijndaelSecretKeyFactoryImpl.java: Likewise.
+ * gnu/javax/crypto/jce/key/SerpentSecretKeyFactoryImpl.java: Likewise.
+ * gnu/javax/crypto/jce/key/SquareSecretKeyFactoryImpl.java: Likewise.
+ * gnu/javax/crypto/jce/key/TwofishSecretKeyFactoryImpl.java: Likewise.
+ * gnu/javax/crypto/jce/mac/OMacImpl.java: Likewise.
+ * gnu/javax/crypto/jce/prng/CSPRNGSpi.java: Likewise.
+ * gnu/javax/crypto/cipher/IBlockCipherSpi.java: Fix javadoc @link.
+ * gnu/javax/crypto/jce/cipher/CipherAdapter.java (CipherAdapter): Likewise.
+ * gnu/javax/crypto/cipher/BaseCipher.java: Remove unused import.
+ * gnu/javax/crypto/assembly/Cascade.java: Fix javadoc @link.
+ * gnu/javax/crypto/assembly/Direction.java: Likewise.
+ * gnu/javax/crypto/assembly/Transformer.java: Likewise.
+
+2006-06-04 Raif S. Naffah <raif@swiftdsl.com.au>
+
+ * gnu/java/security/PolicyFile.java: Updated copyright year.
+ (logger): Increased visibility.
+ * gnu/java/security/x509/Util.java: Updated copyright year.
+ (hexDump): Fix javadoc @link.
+ * gnu/java/security/x509/ext/GeneralNames.java: Updated copyright year.
+ Removed unused import.
+ * gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java: Fix javadoc @link.
+ * gnu/java/security/sig/ISignature.java (SOURCE_OF_RANDOMNESS): Likewise.
+ * gnu/java/security/util/ExpirableObject.java: Likewise.
+ (destroy): Likewise.
+ * gnu/java/security/util/SimpleList.java (SimpleList): Likewise.
+ * gnu/java/security/provider/PKIXCertPathValidatorImpl.java:
+ Updated copyright year.
+ (checkCRL): Fix javadoc @param.
+
2006-06-03 Andrew John Hughes <gnu_andrew@member.fsf.org>
* java/lang/annotation/IncompleteAnnotationException.java:
@@ -57,6 +1273,693 @@
(EnvironmentMap.put(String,String)): Override superclass
method with checks for nulls and non-Strings.
+2006-06-02 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java
+ (cairoPreserveClip, cairoResetClip): New methods.
+ (setClip, clip): Reimplement.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoGraphics2D.c
+ * include/gnu_java_awt_peer_gtk_CairoGraphics2D.h
+ (cairoPreserveClip, cairoResetClip): New methods.
+
+2006-06-02 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/VolatileImageGraphics.java
+ * include/gnu_java_awt_peer_gtk_GtkVolatileImage.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkVolatileImage.c
+ New files.
+ * gnu/java/awt/peer/gtk/ComponentGraphics.java
+ (drawImage): Overloads for VolatileImage drawing.
+ (drawVolatile): New method.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
+ * include/gnu_java_awt_peer_gtk_ComponentGraphics.h
+ (drawVolatile): New method.
+ * gnu/java/awt/peer/gtk/GtkVolatileImage.java
+ Unstub implementation.
+ * include/Makefile.am
+ * native/jni/gtk-peer/Makefile.am
+ Add new files.
+ * native/jni/gtk-peer/gtkpeer.h
+ New prototype.
+
+2006-06-03 Roman Kennke <kennke@aicas.com>
+
+ PR 27418
+ * javax/swing/plaf/basic/BasicTextUI.java
+ (damageRange): Added null check to avoid NPE.
+
+2006-06-03 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/text/PlainView.java
+ (updateDamage): Check for valid longestLine and initialize if
+ necessary.
+
+2006-06-03 Mark Wielaard <mark@klomp.org>
+
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c: Use C
+ comments, not C++.
+
+2006-06-02 Sven de Marothy <sven@physto.se>
+
+ PR 27879
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java
+ (copyArea): Implement.
+ (copyAreaImpl, getRealBounds): New methods.
+ * gnu/java/awt/peer/gtk/CairoSurfaceGraphics.java
+ * gnu/java/awt/peer/gtk/ComponentGraphics.java
+ * gnu/java/awt/peer/gtk/BufferedImageGraphics.java
+ (copyAreaImpl, getRealBounds): Implement.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
+ (nativeCopyArea): Reimplement.
+
+2006-06-02 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * configure.ac: Add -lX11 and -lXtst to XTEST_LIBS.
+ (XTEST_LIBS): New, substitute.
+ * native/jni/gtk-peer/Makefile.am (AM_LDFLAGS): Add XTEST_LIBS.
+
+2006-06-02 Roman Kennke <kennke@aicas.com>
+
+ PR 26738
+ * javax/swing/text/PlainView.java
+ (updateDamage): Rewritten for correct repainting and revalidating.
+ (findLongestLine): New helper method.
+ (getLineLength): New helper method.
+
+2006-06-02 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/BufferedImageGraphics.java
+ * gnu/java/awt/peer/gtk/CairoSurfaceGraphics.java
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
+ (nativeCopyArea): Change stride parameter to use # of ints.
+ (setPixels): Add checks.
+ * gnu/java/awt/peer/gtk/ComponentGraphics.java
+ (ComponentGraphics): Set background, clip.
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java
+ (Cairographics2D): Don't set clip.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
+ Add flush.
+
+2006-06-02 Lillian Angel <langel@redhat.com>
+
+ PR 24458
+ * java/awt/DefaultKeyboardFocusManager.java
+ (dispatchEvent): Fixed to getFocusOwner, if that fails it tries
+ to get the focused window.
+
+2006-06-01 Miriam Schuster <schmir11@web.de>
+
+ * Makefile.am: Add fallback if "mozilla-plugin" is not available.
+ Fallbacks used: "firefox-plugin" and "xulrunner-plugin".
+
+2006-06-02 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/JTable.java
+ (columnSelectionChanged): Don't return when there's only one
+ column (might still need repainting). Correctly calculate
+ repaint rectangle.
+ (valueChanged): Use return value of SwingUtilities.computeUnion
+ as dirty region.
+
+2006-06-01 Keith Seitz <keiths@redhat.com>
+
+ From Martin Platter <motse@complang.tuwien.ac.at>:
+ * gnu/classpath/jdwp/processor/EventRequestCommandSet.java
+ (executeSet): Fix buffer underflow reading reference ID.
+ * gnu/classpath/jdwp/processor/ThreadGroupReferenceCommandSet.java
+ (executeParent): Fix NPE if ThreadGroup is top-level ThreadGroup.
+ * gnu/classpath/jdwp/processor/ClassTypeCommandSet.java
+ (executeSuperclass): Handle case of Object with ID zero.
+
+2006-06-02 Raif S. Naffah <raif@swiftdsl.com.au>
+
+ * tools/gnu/classpath/tools/keytool/StorePasswdCmd.java: Fixed typo.
+ * tools/gnu/classpath/tools/keytool/CertReqCmd.java: Likewise.
+ * tools/gnu/classpath/tools/keytool/DeleteCmd.java: Likewise.
+ * tools/gnu/classpath/tools/keytool/ExportCmd.java: Likewise.
+ * tools/gnu/classpath/tools/keytool/GenKeyCmd.java: Likewise.
+ * tools/gnu/classpath/tools/keytool/IdentityDBCmd.java: Likewise.
+ * tools/gnu/classpath/tools/keytool/ImportCmd.java: Likewise.
+ * tools/gnu/classpath/tools/keytool/KeyCloneCmd.java: Likewise.
+ * tools/gnu/classpath/tools/keytool/KeyPasswdCmd.java: Likewise.
+ * tools/gnu/classpath/tools/keytool/ListCmd.java: Likewise.
+ * tools/gnu/classpath/tools/keytool/SelfCertCmd.java: Likewise.
+
+2006-06-02 Raif S. Naffah <raif@swiftdsl.com.au>
+
+ * tools/gnu/classpath/tools/keytool/Command.java (shutdownThread): New field.
+ (Command): Add the shutdown hook.
+ (doCommand): Remove the shutdown hook.
+ (ShutdownHook): New class.
+
+2006-06-02 Raif S. Naffah <raif@swiftdsl.com.au>
+
+ * tools/jarsigner.in: Use @VM_BINARY@.
+ * tools/keytool.in: Likewise.
+
+2006-06-01 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java:
+ (setColor): Update the cairo paint.
+
+2006-06-01 Mark Wielaard <mark@klomp.org>
+
+ * java/util/logging/LogManager.java (createInstance): Always add
+ original exception on warning.
+
+2006-06-01 Lillian Angel <langel@redhat.com>
+
+ * tools/gnu/classpath/tools/appletviewer/AppletTag.java
+ (prependCodebase): Fixed check. No dirname was ever considered to
+ be a file, so every applet fell into the if-statement causing a lot
+ of classloading problems with the applets.
+
+2006-06-01 Sven de Marothy <sven@physto.se>
+
+ Patch submitted by Boris Dusek.
+ * native/jni/qt-peer/qtmenupeer.cpp
+ Fix segfault
+
+2006-06-01 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/JTable.java
+ (AccessibleJTableCell.getAccessibleRow): Added comment explaining
+ why the behaviour is like it is.
+ (AccessibleJTableCell.getAccessibleStateSet): Implemented.
+ (AccessibleJTableHeader): New inner class.
+ (AccessibleJTableHeaderCell): New inner class.
+ (AccessibleJTable.lastSelectedRow): New field.
+ (AccessibleJTable.lastSelectedColumn): New field.
+ (AccessibleJTable.caption): New field.
+ (AccessibleJTable.summary): New field.
+ (AccessibleJTable.rowDescriptions): New field.
+ (AccessibleJTable.columnDescriptions): New field.
+ (AccessibleJTable): Initialize lastSelectedRow and lastSelectedColumn.
+ (AccessibleJTable.getAccessibleSelection(int)): Implemented.
+ (AccessibleJTable.isAccessibleChildSelected): Implemented.
+ (AccessibleJTable.addAccessibleSelection): Implemented.
+ (AccessibleJTable.removeAccessibleSelection): Implemented.
+ (AccessibleJTable.clearAccessibleSelection): Implemented.
+ (AccessibleJTable.selectAllAccessibleSelection): Implemented.
+ (AccessibleJTable.valueChange): Implemented.
+ (AccessibleJTable.tableRowsInserted): Implemented.
+ (AccessibleJTable.tableRowsDeleted): Implemented.
+ (AccessibleJTable.handleRowChange): New helper method.
+ (AccessibleJTable.columnAdded): Implemented.
+ (AccessibleJTable.columnMarginChanged): Implemented.
+ (AccessibleJTable.columnMoved): Implemented.
+ (AccessibleJTable.columnRemoved): Implemented.
+ (AccessibleJTable.columnSelectionChanged): Implemented.
+ (AccessibleJTable.handleColumnChange): New helper method.
+ (AccessibleJTable.editingCanceled): Implemented.
+ (AccessibleJTable.editingStopped): Implemented.
+ (AccessibleJTable.getAccessibleRow): Implemented.
+ (AccessibleJTable.getAccessibleColumn): Implemented.
+ (AccessibleJTable.getAccessibleIndex): Implemented.
+ (AccessibleJTable.getAccessibleCaption): Implemented.
+ (AccessibleJTable.setAccessibleCaption): Implemented.
+ (AccessibleJTable.getAccessibleSummary): Implemented.
+ (AccessibleJTable.setAccessibleSummary): Implemented.
+ (AccessibleJTable.getAccessibleRowCount): Implemented.
+ (AccessibleJTable.getAccessibleColumnCount): Implemented.
+ (AccessibleJTable.getAccessibleAt): Implemented.
+ (AccessibleJTable.getAccessibleRowExtentAt): Implemented.
+ (AccessibleJTable.getAccessibleColumnExtentAt): Implemented.
+ (AccessibleJTable.getAccessibleRowHeader): Implemented.
+ (AccessibleJTable.setAccessibleRowHeader): Implemented.
+ (AccessibleJTable.getAccessibleColumnHeader): Implemented.
+ (AccessibleJTable.setAccessibleColumnHeader): Implemented.
+ (AccessibleJTable.getAccessibleRowDescription): Implemented.
+ (AccessibleJTable.setAccessibleRowDescription): Implemented.
+ (AccessibleJTable.getAccessibleColumnDescription): Implemented.
+ (AccessibleJTable.setAccessibleColumnDescription): Implemented.
+ (AccessibleJTable.isAccessibleSelected): Implemented.
+ (AccessibleJTable.isAccessibleRowSelected): Implemented.
+ (AccessibleJTable.isAccessibleColumnSelected): Implemented.
+ (AccessibleJTable.getSelectedAccessibleRows): Implemented.
+ (AccessibleJTable.getSelectedAccessibleColumns): Implemented.
+ (getAccessibleContext): Register listeners for the accessibility
+ class on the JTable.
+
+2006-06-01 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java:
+ (setPaint): Scale +1 pixel larger.
+
+2006-06-01 Sven de Marothy <sven@physto.se>
+
+ PR 27854
+ * gnu/java/awt/Buffers.java (getData): Reimplement.
+ * gnu/java/awt/peer/gtk/CairoSurface.java
+ (getElem, setElem): Call native methods.
+
+2006-06-01 Audrius Meskauskas <AudriusA@Bioinformatics.org>
+
+ * gnu/javax/swing/text/html/ImageViewIconFactory.java: New file.
+
+2006-06-01 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java
+ (drawImage): Check for zero size.
+ * gnu/java/awt/peer/gtk/GdkTextLayout.java:
+ (setFont): Declare new native method.
+ (GdkTextLayout): Read some attributes.
+ * include/gnu_java_awt_peer_gtk_GdkTextLayout.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkTextLayout.c
+ (setFont): New native method.
+
+2006-06-01 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/BufferedImageGraphics.java
+ (updateBufferedImage): Fix some errors.
+
+2006-06-01 David Gilbert <david.gilbert@object-refinery.com>
+
+ * javax/swing/plaf/basic/BasicButtonUI.java: Minor source code style
+ fixes,
+ * javax/swing/plaf/basic/BasicDirectoryModel.java: Likewise,
+ * javax/swing/plaf/basic/BasicFileChooserUI.java: Likewise,
+ * javax/swing/plaf/basic/BasicIconFactory.java: Likewise,
+ * javax/swing/plaf/basic/BasicListUI.java: Likewise,
+ * javax/swing/plaf/basic/BasicOptionPaneUI.java: Likewise,
+ * javax/swing/plaf/basic/BasicRootPaneUI.java: Likewise,
+ * javax/swing/plaf/basic/BasicScrollPaneUI.java: Likewise,
+ * javax/swing/plaf/basic/BasicSpinnerUI.java: Likewise,
+ * javax/swing/plaf/basic/BasicTabbedPaneUI.java: Likewise,
+ * javax/swing/plaf/basic/BasicTextAreaUI.java: Likewise.
+
+2006-06-01 David Gilbert <david.gilbert@object-refinery.com>
+
+ * javax/swing/JComboBox.java: Minor source code formatting fixes,
+ * javax/swing/JEditorPane.java: Likewise,
+ * javax/swing/JFormattedTextField.java: Likewise,
+ * javax/swing/JLayeredPane.java: Likewise,
+ * javax/swing/JScrollPane.java: Likewise,
+ * javax/swing/JSlider.java: Likewise,
+ * javax/swing/JSpinner.java: Likewise,
+ * javax/swing/JTree.java: Likewise,
+ * javax/swing/JViewport.java: Likewise,
+ * javax/swing/UIDefaults.java: Likewise,
+ * javax/swing/UIManager.java: Likewise.
+
+2006-06-01 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/BufferedImageGraphics.java
+ (BufferedImageGraphics): Cache surfaces.
+ (updateBufferedImage): Copy directly for certain color models.
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java
+ (drawImage): Reimplement.
+
+2006-06-01 Sven de Marothy <sven@physto.se>
+
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
+ (setPixels): Don't swap, correct size.
+
+2006-05-31 Anthony Green <green@redhat.com>
+
+ PR 27828
+ * java/net/InetSocketAddress.java: Defer getting the host
+ name until somebody calls InetSocketAddress.getHostName().
+ Fix "represenation" typo.
+
+2006-06-01 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/BufferedImageGraphics.java
+ (updateBufferedImage): Simplify.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
+ (getPixels): Don't swap.
+
+2006-06-01 Sven de Marothy <sven@physto.se>
+
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoGraphics2D.c
+ (setGradient): Reimplement.
+
+2006-06-01 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * native/jni/gtk-peer/cairographics2d.h: Rename/prefix function
+ CairoGraphics2D_getCairoT to cp_gtk_get_cairo_t correctly.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
+ (Java_gnu_java_awt_peer_gtk_CairoSurface_drawSurface): Rename function
+ CairoGraphics2D_getCairoT to cp_gtk_get_cairo_t.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkTextLayout.c
+ (Java_gnu_java_awt_peer_gtk_GdkTextLayout_cairoDrawGdkTextLayout):
+ Likewise.
+
+2006-05-31 David Gilbert <david.gilbert@object-refinery.com>
+
+ * javax/swing/table/JTableHeader.java
+ (getColumnHeaderRenderer): New method,
+ (getAccessibleColumnHeaderRenderer): Delegate part to new
+ getColumnHeaderRenderer() method,
+ (getLocale): Implemented.
+
+2006-05-31 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
+ (cp_gtk_grab_current_drawable): Rename
+ cp_java_awt_peer_gtk_ComponentGraphics_grab_current_drawable to
+ cp_gtk_grab_current_drawable, remove static declaration.
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphics_initState): Renamed above
+ function.
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphics_copyAreaNative): Likewise.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphicsCopy.c:
+ Remove prototype of
+ cp_java_awt_peer_gtk_ComponentGraphics_grab_current_drawable.
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphicsCopy_getPixbuf): Rename
+ function.
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphicsCopy_copyPixbuf): Likewise.
+ * native/jni/gtk-peer/gtkpeer.h: Add prototype for
+ cp_gtk_grab_current_drawable here.
+
+2006-05-31 Sven de Marothy <sven@physto.se>
+
+ Should fix PR 27835
+ * gnu/java/awt/peer/gtk/BufferedImageGraphics.java
+ (updateBufferedImage): Keep within image bounds.
+
+2006-05-31 Thomas Fitzsimmons <fitzsim@redhat.com>
+ Andreas Tobler <a.tobler@schweiz.ch>
+
+ * configure.ac: Check for libXrender when the GTK peers are
+ enabled, and set HAVE_XRENDER accordingly. Add -lXrender to
+ X_EXTRA_LIBS.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphics_hasXRender)
+ [HAVE_XRENDER]: Call XRenderQueryExtension conditionally.
+
+2006-05-31 Lillian Angel <langel@redhat.com>
+
+ * javax/swing/plaf/basic/BasicProgressBarUI.java
+ (paintString): Implemented to paint the string vertically.
+
+2006-05-31 David Gilbert <david.gilbert@object-refinery.com>
+
+ * javax/swing/JTable.java
+ (AccessibleJTable.AccessibleJTable()): Check for null editor,
+ (AccessibleJTable.getAccessibleRole()): Overridden to return correct
+ value,
+ (AccessibleJTable.getAccessibleTable()): Likewise,
+ (getAccessibleContext): Create new context if required.
+
+2006-05-31 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/JTabbedPane.java
+ (AccessibleJTabbedPane.stateChanged): Implemented.
+ (Page.getAccessibleStateSet): Implemented.
+ (Page.getAccessibleIndexInParent): Implemented.
+ (getAccessibleContext): Add AccessibleJTabbedPane object
+ as ChangeListener to the JTabbedPane.
+
+2006-05-31 Roman Kennke <kennke@aicas.com>
+
+ * javax/swing/JMenuItem.java
+ (getAccessibleContext): Register accessible object as ChangeListener
+ to the JMenuItem.
+ (AccessibleJMenuItem.armed): New field.
+ (AccessibleJMenuItem.focusOwner): New field.
+ (AccessibleJMenuItem.pressed): New field.
+ (AccessibleJMenuItem.selected): New field.
+ (stateChanged): Implemented.
+
+2006-05-31 David Gilbert <david.gilbert@object-refinery.com>
+
+ * javax/swing/ListSelectionModel.java: Added API docs all over.
+
+2006-05-31 Audrius Meskauskas <AudriusA@Bioinformatics.org>
+
+ * examples/gnu/classpath/examples/swing/FillRect.java
+ (paintComponent): Optionally paint lines rather than rectangles.
+ (createContent): Added option to test line painting.
+
+2006-05-31 David Gilbert <david.gilbert@object-refinery.com>
+
+ * javax/swing/event/EventListenerList.java
+ (getListenerList): Updated API docs.
+
+2006-05-30 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java
+ (drawImage): Clip scaled image to dest rectangle.
+
+2006-05-30 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/CairoSurface.java:
+ (CairoSurface): Convert pixels properly.
+ * gnu/java/awt/peer/gtk/ComponentGraphics.java
+ Remove commented-out lines.
+
+2006-05-30 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java
+ (drawImage): Use Toolkit to convert to BufferedImage.
+ * gnu/java/awt/peer/gtk/CairoSurface.java
+ (CairoSurface(GtkImage)): New Constructor.
+ (getBufferedImage): New method.
+ * gnu/java/awt/peer/gtk/ComponentGraphics.java
+ Don't fill background - FIXME.
+ * gnu/java/awt/peer/gtk/GdkPixbufDecoder.java:
+ Remove unused methods.
+ * gnu/java/awt/peer/gtk/GtkImage.java:
+ (pixbuflock): New field. Methods change to use this lock.
+ * gnu/java/awt/peer/gtk/GtkToolkit.java
+ (createImage): Use Cairo-backed surfaces via GtkImage instead of
+ GtkPixbufDecoder.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
+ (setPixels): Correct length in bytes.
+
+2006-05-30 Thomas Fitzsimmons <fitzsim@redhat.com>
+
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java (static): Call
+ System.loadLibrary unconditionally.
+ * gnu/java/awt/peer/gtk/GdkFontPeer.java: Likewise.
+ * gnu/java/awt/peer/gtk/GdkPixbufDecoder.java: Likewise.
+ * gnu/java/awt/peer/gtk/GdkTextLayout.java: Likewise.
+ * gnu/java/awt/peer/gtk/GtkToolkit.java: Likewise.
+
+2006-05-30 Mark Wielaard <mark@klomp.org>
+
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphics_copyAreaNative):
+ Mark unused parameters, remove unused variables.
+
+2006-05-30 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/ComponentGraphics.java
+ (copyArea): Implemented.
+ * include/gnu_java_awt_peer_gtk_ComponentGraphics.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c:
+ (copyAreaNative): New method.
+
+2006-05-30 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
+ (Java_gnu_java_awt_peer_gtk_CairoSurface_getPixels): Define i only
+ for non big endian systems.
+ (Java_gnu_java_awt_peer_gtk_CairoSurface_setPixels): Likewise.
+
+2006-05-30 Roman Kennke <kennke@aicas.com>
+
+ * gnu/java/awt/java2d/TexturePaintContext.java: New file.
+ * java/awt/TexturePaint.java
+ (createContext): Implemented.
+
+2006-05-30 Robert Schuster <robertschuster@fsfe.org>
+
+ * javax/swing/table/DefaultTableMode.java: Initialize dataVector
+ field early.
+
+2006-05-30 Robert Schuster <robertschuster@fsfe.org>
+
+ * java/awt/Container.java:
+ (removeAll): Reimplemented, added note.
+
+2006-05-30 Robert Schuster <robertschuster@fsfe.org>
+
+ * java/awt/Container.java:
+ (removeAll): Implemented different removal mechanism, added note.
+
+2006-05-30 Lillian Angel <langel@redhat.com>
+
+ PR 27785
+ * java/awt/Component.java:
+ (translateEvent): Added handling to translate WindowEvents
+ * java/awt/Window.java:
+ Removed unneeded imports.
+
+2006-05-30 Mark Wielaard <mark@klomp.org>
+
+ * native/jni/gtk-peer/Makefile.am (libgtkpeer_la_SOURCES): Add
+ cairographics2d.h.
+
+2006-05-30 Thomas Fitzsimmons <fitzsim@redhat.com>
+
+ * gnu/java/awt/peer/gtk/GtkImage.java: Fix constructor javadoc.
+
+2006-05-29 Audrius Meskauskas <AudriusA@Bioinformatics.org>
+
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java
+ (clearRect): Do not reuse the fg field, call updateColor.
+ (drawRaster): Likewise.
+ (setColor): Call updateColor.
+ (updateColor): New method.
+
+2006-05-30 Mark Wielaard <mark@klomp.org>
+
+ * native/jni/classpath/jcl.h (JLONG_TO_PTR): New macro.
+ (PTR_TO_JLONG): Likewise.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoGraphics2D.c
+ (getPointer): Use new conversion macros.
+ (Java_gnu_java_awt_peer_gtk_CairoGraphics2D_init): Likewise.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
+ (Java_gnu_java_awt_peer_gtk_CairoSurface_newCairoContext):
+ Likewise.
+ (setNativeObject): Likewise.
+ (getNativeObject): Likewise.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
+ (cp_java_awt_peer_gtk_ComponentGraphics_grab_current_drawable):
+ Mark static.
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphics_initState):
+ Correctly cast XID and pointer values.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphicsCopy.c
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphicsCopy_getPixbuf):
+ Mark unused variables.
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphicsCopy_copyPixbuf):
+ Likewise.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkTextLayout.c
+ (Java_gnu_java_awt_peer_gtk_GdkTextLayout_cairoDrawGdkTextLayout):
+ Remove unused cairographics2d struct.
+ (_moveTo, _lineTo, _quadTo, _curveTo): Mark arguments const.
+ (Java_gnu_java_awt_peer_gtk_GtkImage_initFromBuffer):
+ Use new conversion macros.
+ * native/jni/midi-dssi/dssi_data.h: Move conversion macros to jcl.h.
+
+2006-05-30 Mark Wielaard <mark@klomp.org>
+
+ * include/Makefile.am (gnu_java_nio_VMChannel.h): Added.
+
+2006-05-29 Audrius Meskauskas <AudriusA@Bioinformatics.org>
+
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java
+ (copy): Do not reuse the fd field.
+ (setColor): Do not set the color if the parameter
+ matches fd field.
+ (translate(double, double): Rewritten to use
+ AffineTransform.translate.
+
+2006-05-30 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/ComponentGraphicsCopy.java
+ * include/gnu_java_awt_peer_gtk_ComponentGraphicsCopy.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphicsCopy.c
+ New files.
+ * include/Makefile.am
+ * native/jni/gtk-peer/Makefile.am
+ Add new files.
+ * gnu/java/awt/peer/gtk/CairoSurface.java
+ (getSharedGtkImage): New method.
+ * gnu/java/awt/peer/gtk/CairoSurfaceGraphics.java
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
+ Fix copyArea.
+ * gnu/java/awt/peer/gtk/ComponentGraphics.java
+ Support a non-xrender context.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
+ Plug memory leak.
+ * gnu/java/awt/peer/gtk/GtkImage.java
+ * include/gnu_java_awt_peer_gtk_GtkImage.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkImage.c
+ (initFromBuffer): New method.
+ * native/jni/gtk-peer/gtkpeer.h:
+ Remove declarations of previouslyremoved methods.
+
+2006-05-29 Thomas Fitzsimmons <fitzsim@redhat.com>
+
+ * tools/Makefile.am [FOUND_CACAO] (LIBJVM): Define to -ljvm.
+
+2006-05-29 Mark Wielaard <mark@klomp.org>
+
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoGraphics2D.c
+ (Java_gnu_java_awt_peer_gtk_CairoGraphics2D_init): Mark unused
+ arguments.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
+ (Java_gnu_java_awt_peer_gtk_CairoSurface_setPixels): Declare size
+ early. Remove unused return statement in void function.
+ (Java_gnu_java_awt_peer_gtk_CairoSurface_newCairoContext): Declare
+ ptr early.
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphics_hasXRender): Mark
+ unused arguments.
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphics_initState): Likewise.
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphics_start_1gdk_1drawing):
+ Likewise.
+ (Java_gnu_java_awt_peer_gtk_ComponentGraphics_end_1gdk_1drawing):
+ Likewise.
+
+2006-05-29 Sven de Marothy <sven@physto.se>
+
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
+ (setPixels): Remove superfluous return statement.
+
+2006-05-29 Sven de Marothy <sven@physto.se>
+
+ * gnu/java/awt/peer/gtk/BufferedImageGraphics.java
+ * gnu/java/awt/peer/gtk/CairoGraphics2D.java
+ * gnu/java/awt/peer/gtk/CairoSurface.java
+ * gnu/java/awt/peer/gtk/CairoSurfaceGraphics.java
+ * gnu/java/awt/peer/gtk/ComponentGraphics.java
+ * include/gnu_java_awt_peer_gtk_CairoGraphics2D.h
+ * include/gnu_java_awt_peer_gtk_CairoSurface.h
+ * include/gnu_java_awt_peer_gtk_ComponentGraphics.h
+ * native/jni/gtk-peer/cairographics2d.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoGraphics2D.c
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
+ New files.
+
+ * gnu/java/awt/peer/gtk/GdkGraphics2D.java
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkGraphics2D.c
+ * include/gnu_java_awt_peer_gtk_GdkGraphics2D.h
+ Removed
+
+ * include/gnu_java_awt_peer_gtk_GdkFontPeer.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkFontPeer.c
+ * gnu/java/awt/peer/gtk/GdkFontPeer.java
+ (releasePeerGraphicsResource): Moved to Font peer class.
+
+ * gnu/java/awt/peer/gtk/GdkGraphicsEnvironment.java
+ (createGraphics): Use new context classes.
+
+ * gnu/java/awt/peer/gtk/GdkPixbufDecoder.java:
+ Use native BufferedImages where possible.
+
+ * gnu/java/awt/peer/gtk/GdkTextLayout.java
+ * include/gnu_java_awt_peer_gtk_GdkTextLayout.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkTextLayout.c
+ Move GdkGraphics2D.drawGdkTextLayout to the GdkTextLayout class,
+ renamed to cairoDrawGdkTextLayout.
+
+ * gnu/java/awt/peer/gtk/GtkComponentPeer.java
+ (getGraphics): Use ComponentGraphics context.
+ (createImage): Use native BufferedImage.
+
+ * gnu/java/awt/peer/gtk/GtkImage.java:
+ * include/gnu_java_awt_peer_gtk_GtkImage.h
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkImage.c
+ Remove pixmap support. (GtkImage(int, int) constructor, getGraphics)
+ Remove drawing methods.
+
+ * gnu/java/awt/print/JavaPrinterGraphics.java:
+ Use CairoSurface instead of GtkImage.
+
+ * include/Makefile.am
+ * native/jni/gtk-peer/Makefile.am
+ Update for new files.
+
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkClipboard.c
+ * native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkFramePeer.c
+ Remove superfluous GtkImage code for GdkPixmaps.
+
+ * native/jni/gtk-peer/gtkpeer.h
+ Remove graphics2d structure.
+
2006-05-29 Audrius Meskauskas <AudriusA@Bioinformatics.org>
* gnu/java/awt/peer/gtk/GdkGraphics2D.java (copying constructor):
diff --git a/NEWS b/NEWS
index c27e24433..2b9f4384b 100644
--- a/NEWS
+++ b/NEWS
@@ -21,6 +21,16 @@ New in release 0.92 (UNRELEASED)
A new configure option --enable-tool-wrappers causes wrapper
binaries to be built for VMs that support the JNI Invocation API.
+Runtime interface changes:
+
+* A new class, VMURLConnection, is used to implement
+ URLConnection.guessContentTypeFromStream. The reference
+ implementation uses libmagic (and falls back to doing nothing if
+ libmagic is not available).
+* The method gnu.java.io.PlatformHelper.toCanonicalForm() has been
+ replaced with a JNI implementation of VMFile.toCanonicalForm() for
+ GNU/Posix systems.
+
New in release 0.91 (May 15, 2006)
* Experimental activation (java.rmi.activation) support, including RMI
diff --git a/configure.ac b/configure.ac
index bdfb727f7..c9b9d6585 100644
--- a/configure.ac
+++ b/configure.ac
@@ -321,6 +321,7 @@ if test "x${COMPILE_JNI}" = xyes; then
strerror_r \
fcntl \
mmap munmap mincore msync madvise getpagesize sysconf \
+ lstat readlink \
])
LIBMAGIC=
@@ -400,12 +401,27 @@ if test "x${COMPILE_JNI}" = xyes; then
AC_MSG_ERROR([GTK+ peers requested but no X library available])
fi
dnl We explicitly want the XTest Extension for Robot support.
- AC_CHECK_LIB([Xtst], [XTestQueryExtension], [true],
- [AC_MSG_ERROR([libXtst NOT found, required for GdkRobot])],
- [${X_LIBS}])
+ AC_CHECK_LIB([Xtst], [XTestQueryExtension],
+ [XTEST_LIBS="$XTEST_LIBS -lX11 -lXtst"],
+ [AC_MSG_ERROR([libXtst NOT found, required for GdkRobot])],
+ [${X_LIBS}])
+
PKG_CHECK_MODULES(GTK, gtk+-2.0 >= 2.8 gthread-2.0 >= 2.2 gdk-pixbuf-2.0)
PKG_CHECK_MODULES(FREETYPE2, freetype2)
PKG_CHECK_MODULES(PANGOFT2, pangoft2)
+ dnl Check if we can link against the XRender library and set
+ dnl HAVE_XRENDER accordingly.
+ AC_CHECK_LIB([Xrender], [XRenderQueryExtension],
+ [AC_DEFINE(HAVE_XRENDER, 1, [Define to 1 if you have libXrender.])[X_EXTRA_LIBS="$X_EXTRA_LIBS -lXrender"]],
+ [true],
+ [${X_LIBS}])
+
+ dnl Check if we can link against the XRandR library and set
+ dnl HAVE_XRANDR accordingly.
+ AC_CHECK_LIB([Xrandr], [XRRQueryExtension],
+ [AC_DEFINE(HAVE_XRANDR, 1, [Define to 1 if you have libXrandr.])[X_EXTRA_LIBS="$X_EXTRA_LIBS -lXrandr"]],
+ [true],
+ [${X_LIBS}])
AC_SUBST(GTK_CFLAGS)
AC_SUBST(GTK_LIBS)
@@ -413,6 +429,7 @@ if test "x${COMPILE_JNI}" = xyes; then
AC_SUBST(FREETYPE2_CFLAGS)
AC_SUBST(PANGOFT2_LIBS)
AC_SUBST(PANGOFT2_CFLAGS)
+ AC_SUBST(XTEST_LIBS)
fi
dnl Check for AWT related Qt4
@@ -466,7 +483,13 @@ if test "x${COMPILE_JNI}" = xyes; then
dnl Check for plugin support headers and libraries.
if test "x${COMPILE_PLUGIN}" = xyes; then
- PKG_CHECK_MODULES(MOZILLA, mozilla-plugin)
+ PKG_CHECK_MODULES(MOZILLA, mozilla-plugin, [MOZILLA_FOUND=yes], [MOZILLA_FOUND=no])
+ if test "x${MOZILLA_FOUND}" = xno; then
+ PKG_CHECK_MODULES(MOZILLA, firefox-plugin, [MOZILLA_FOUND=yes], [MOZILLA_FOUND=no])
+ fi
+ if test "x${MOZILLA_FOUND}" = xno; then
+ PKG_CHECK_MODULES(MOZILLA, xulrunner-plugin, [MOZILLA_FOUND=yes], [MOZILLA_FOUND=no])
+ fi
PKG_CHECK_MODULES(GLIB, glib-2.0)
AC_SUBST(MOZILLA_CFLAGS)
diff --git a/doc/tools.texinfo b/doc/tools.texinfo
index ad61f6f74..9550d0b2b 100644
--- a/doc/tools.texinfo
+++ b/doc/tools.texinfo
@@ -5,7 +5,7 @@
@settitle GNU Classpath Tools Guide
@c %**end of header
-@setchapternewpage off
+@setchapternewpage on
@ifinfo
This file documents the Tools included in a standard distribution of the GNU
@@ -37,6 +37,8 @@ Permission is granted to copy and distribute translations of this manual into an
@end titlepage
+@contents
+
@ifinfo
@node Top, Security Tools, (dir), (dir)
@top GNU Classpath Tools Guide
@@ -62,6 +64,47 @@ Security Tools
* jarsigner Tool:: Sign and verify .JAR files
* keytool Tool:: Manage private keys and public certificates
+jarsigner Tool
+
+* Common jarsigner Options:: Options used when signing or verifying a file
+* Signing Options:: Options only used when signing a .JAR file
+* Verification Options:: Options only used when verifying a .JAR file
+
+keytool Tool
+
+* Getting Help:: How to get help with keytool commands
+* Common keytool Options:: Options used in more than one command
+* Distinguished Names:: X.500 Distinguished Names used in certificates
+* Add/Update Commands:: Commands for adding data to a Key Store
+* Export Commands:: Commands for exporting data from a Key Store
+* Display Commands:: Commands for displaying data in a Key Store
+* Management Commands:: Commands for managing a Key Store
+
+Add/Update Commands
+
+* Command -genkey:: Generate private key and self-signed certificate
+* Command -import:: Import certificates and certificate replies
+* Command -selfcert:: Generate self-signed certificate
+* Command -cacert:: Import a CA Trusted Certificate
+* Command -identitydb:: Import JDK-1 style identities
+
+Export Commands
+
+* Command -certreq:: Generate Certificate Signing Requests (CSR)
+* Command -export:: Export a certificate in a Key Store
+
+Display Commands
+
+* Command -list:: Display information about one or all Aliases
+* Command -printcert:: Print a certificate or a certificate fingerprint
+
+Management Commands
+
+* Command -keyclone:: Clone a Key Entry in a Key Store
+* Command -storepasswd:: Change the password protecting a Key Store
+* Command -keypasswd:: Change the password protecting a Key Entry
+* Command -delete:: Remove an entry in a Key Store
+
I18N Issues
* Language Resources:: Where resources are located
@@ -76,7 +119,7 @@ I18N Issues
@comment node-name, next, previous, up
@chapter Security Tools
-Two Security Tools are available with GNU Classpath: @b{jarsugner} and @b{keytool}.
+Two Security Tools are available with GNU Classpath: @b{jarsigner} and @b{keytool}.
@menu
* jarsigner Tool:: Sign and verify .JAR files
@@ -91,22 +134,59 @@ If while using these tools you think you found a bug, then please report it at @
@comment node-name, next, previous, up
@section The @code{jarsigner} Tool
-@table @b
+The @b{jarsigner} tool is invoked from the command line, in one of two forms, as follows:
-@item SYNOPSIS
-@code{jarsigner [OPTION]... FILE ALIAS}@*
+@example
+@code{jarsigner [OPTION]... FILE ALIAS}
@code{jarsigner -verify [OPTION]... FILE}
+@end example
-@item DESCRIPTION
-When the first form is used, the tool signs the designated JAR file.
-
-The second form, on the other hand, is used to verify a previously signed JAR file.
+When the first form is used, the tool signs the designated JAR file. The second form, on the other hand, is used to verify a previously signed JAR file.
@code{FILE} is the .JAR file to process; i.e. to sign if the first syntax form is used, or to verify if the second syntax form is used instead.
-@code{ALIAS} must be a known @i{Alias} of a @i{Key Entry} in the designated key store. The private key material associated with this @i{Alias} is then used for signing the designated .JAR file.
+@code{ALIAS} must be a known @i{Alias} of a @i{Key Entry} in the designated @i{Key Store}. The private key material associated with this @i{Alias} is then used for signing the designated .JAR file.
+
+@menu
+* Common jarsigner Options:: Options used when signing or verifying a file
+* Signing Options:: Options only used when signing a .JAR file
+* Verification Options:: Options only used when verifying a .JAR file
+@end menu
+
+@comment ----------------------------------------------------------------------
+
+@node Common jarsigner Options, Signing Options, jarsigner Tool, jarsigner Tool
+@comment node-name, next, previous, up
+@subsection Common options
+
+The following options may be used when the tool is used for either signing, or verifying, a .JAR file.
+
+@table @b
+@item -verbose
+Use this option to force the tool to generate more verbose messages, during its processing.
+
+@item -internalsf
+When present, the tool will include --which otherwise it does not-- the @code{.SF} file in the @code{.DSA} generated file.
+
+@item -sectionsonly
+When present, the tool will include in the @code{.SF} generated file --which otherwise it does not-- a header containing a hash of the whole manifest file. When that header is included, the tool can quickly check, during verification, if the hash (in the header) matches or not the manifest file.
+
+@item -provider PROVIDER_CLASS_NAME
+A fully qualified class name of a @i{Security Provider} to add to the current list of @i{Security Providers} already installed in the JVM in-use. If a provider class is specified with this option, and was successfully added to the runtime --i.e. it was not already installed-- then the tool will attempt to remove this @i{Security Provider} before exiting.
+
+@item -help
+Prints a help text similar to this one.
+
+@end table
+
+@comment ----------------------------------------------------------------------
+
+@node Signing Options, Verification Options, Common jarsigner Options, jarsigner Tool
+@comment node-name, next, previous, up
+@subsection Signing options
+
+The following options may be specified when using the tool for signing purposes.
-@item SIGNING OPTIONS
@table @b
@item -keystore URL
Use this option to specify the location of the key store to use. The default value is a file URL referencing the file named @file{.keystore} located in the path returned by the call to @code{java.lang.System#getProperty(String)} using @code{user.home} as argument.
@@ -129,12 +209,19 @@ Use this option to designate a literal that will be used to construct file names
If this option is missing, the first eight characters of the @code{ALIAS} argument will be used. When this is the case, any character in @code{ALIAS} that is outside the permissible range of characters will be replaced by an underscore.
-@item -signedjar FILE_NAME
+@item -signedjar FILE
Use this option to specify the file name of the signed JAR. If this option is omitted, then the signed JAR will be named the same as @code{FILE}; i.e. the input JAR file will be replaced with the signed copy.
@end table
-@item VERIFICATION OPTIONS
+@comment ----------------------------------------------------------------------
+
+@node Verification Options, , Signing Options, jarsigner Tool
+@comment node-name, next, previous, up
+@subsection Verification options
+
+The following options may be specified when using the tool for verification purposes.
+
@table @b
@item -verify
Use this option to indicate that the tool is to be used for verification purposes.
@@ -144,44 +231,37 @@ This option is used in conjunction with the @code{-verbose} option. When present
@end table
-@item COMMON OPTIONS
-@table @b
-@item -verbose
-Use this option to force the tool to generate more verbose messages, during its processing.
-
-@item -internalsf
-When present, the tool will include --which otherwise it does not-- the @code{.SF} file in the @code{.DSA} generated file.
+@comment ----------------------------------------------------------------------
-@item -sectionsonly
-When present, the tool will include in the @code{.SF} generated file --which otherwise it does not-- a header containing a hash of the whole manifest file. When that header is included, the tool can quickly check, during verification, if the hash (in the header) matches or not the manifest file.
+@node keytool Tool, , jarsigner Tool, Security Tools
+@comment node-name, next, previous, up
+@section The @code{keytool} Tool
-@item -provider PROVIDER_CLASS_NAME
-A fully qualified class name of a @i{Security Provider} to add to the current list of @i{Security Providers} already installed in the JVM in-use. If a provider class is specified with this option, and was successfully added to the runtime --i.e. it was not already installed-- then the tool will attempt to remove this @i{Security Provider} before exiting.
+Cryptographic credentials, in a Java environment, are usually stored in a @i{Key Store}. The Java SDK specifies a @i{Key Store} as a persistent container of two types of objects: @i{Key Entries} and @i{Trusted Certificates}. The security tool @b{keytool} is a Java-based application for managing those types of objects.
-@item -help
-Prints a help text similar to this one.
+A @i{Key Entry} represents the private key part of a key-pair used in Public-Key Cryptography, and a signed X.509 certificate which authenticates the public key part for a known entity; i.e. the owner of the key-pair. The X.509 certificate itself contains the public key part of the key-pair.
-@end table
-@end table
+A @i{Trusted Certificate} is a signed X.509 certificate issued by a trusted entity. The @i{Trust} in this context is relative to the User of the @b{keytool}. In other words, the existence of a @i{Trusted Certificate} in the @i{Key Store} processed by a @b{keytool} command implies that the User trusts the @i{Issuer} of that @i{Trusted Certificate} to also sign, and hence authenticates, other @i{Subjects} the tool may process.
-@comment ----------------------------------------------------------------------
+@i{Trusted Certificates} are important because they allow the tool to mechanically construct @i{Chains of Trust} starting from one of the @i{Trusted Certificates} in a @i{Key Store} and ending with a certificate whose @i{Issuer} is potentially unknown. A valid chain is an ordered list, starting with a @i{Trusted Certificate} (also called the @i{anchor}), ending with the target certificate, and satisfying the condition that the @i{Subject} of certificate @code{#i} is the @i{Issuer} of certificate @code{#i + 1}.
-@node keytool Tool, , jarsigner Tool, Security Tools
-@comment node-name, next, previous, up
-@section The @code{keytool} Tool
+The @b{keytool} is invoked from the command line as follows:
-@table @b
-@item SYNOPSIS
+@example
@code{keytool [COMMAND]...}
+@end example
-@item DESCRIPTION
-A Java-based tool for managing both @i{Key Entries} as well as @i{Trusted Certificates}.
+Multiple @code{COMMAND}s may be specified at once, each complete with its own options. @b{keytool} will parse all the arguments, before processing, and executing, each @code{COMMAND}. If an exception occurs while executing one @code{COMMAND} @b{keytool} will abort. Note however that because the implementation of the tool uses code to parse command line options that also supports GNU-style options, you have to separate each command group with a double-hyphen; e.g
-Multiple @code{COMMAND}s may be specified at once, each complete with its own options. @b{keytool} will parse all the arguments, before processing, and executing, each @code{COMMAND}. If an exception occurs while executing one @code{COMMAND} @b{keytool} will abort.
+@example
+@code{keytool -list -- -printcert -alias mykey}
+@end example
-A @code{COMMAND} can be one of the followings:
+Here is a summary of the commands supported by the tool:
-@table @b
+@enumerate
+@item Add/Update commands
+@itemize @bullet
@item -genkey [OPTION]@dots{}
Generate a new @i{Key Entry}, eventually creating a new key store.
@@ -191,22 +271,34 @@ Add, to a key store, @i{Key Entries} (private keys and certificate chains authen
@item -selfcert [OPTION]@dots{}
Generate a new self-signed @i{Trusted Certificate}.
+@item -cacert [OPTION]@dots{}
+Import a CA @i{Trusted Certificate}.
+
@item -identitydb [OPTION]@dots{}
@b{NOT IMPLEMENTED YET}.@*
Import a JDK 1.1 style Identity Database.
+@end itemize
+@item Export commands
+@itemize @bullet
@item -certreq [OPTION]@dots{}
Issue a @i{Certificate Signing Request} (CSR) which can be then sent to a @i{Certification Authority} (CA) to issue a certificate signed (by the CA) and authenticating the @i{Subject} of the request.
@item -export [OPTION]@dots{}
Export a certificate from a key store.
+@end itemize
+@item Display commands
+@itemize @bullet
@item -list [OPTION]@dots{}
Print one or all certificates in a key store to @code{STDOUT}.
@item -printcert [OPTION]@dots{}
Print a human-readable form of a certificate, in a designated file, to @code{STDOUT}.
+@end itemize
+@item Management commands
+@itemize @bullet
@item -keyclone [OPTION]@dots{}
Clone a @i{Key Entry} in a key store.
@@ -218,13 +310,48 @@ Change the password protecting a @i{Key Entry} in a key store.
@item -delete [OPTION]@dots{}
Delete a @i{Key Entry} or a @i{Trusted Certificate} from a key store.
+@end itemize
-@item -help
-Prints a help text similar to this one.
+@end enumerate
-@end table
+@menu
+* Getting Help:: How to get help with keytool commands
+* Common keytool Options:: Options used in more than one command
+* Distinguished Names:: X.500 Distinguished Names used in certificates
+* Add/Update Commands:: Commands for adding data to a Key Store
+* Export Commands:: Commands for exporting data from a Key Store
+* Display Commands:: Commands for displaying data in a Key Store
+* Management Commands:: Commands for managing a Key Store
+@end menu
+
+@comment ----------------------------------------------------------------------
+
+@node Getting Help, Common keytool Options, keytool Tool, keytool Tool
+@comment node-name, next, previous, up
+@subsection Getting help
+
+To get a general help text about the tool, use the @code{-help} option; e.g.
+
+@example
+@code{keytool -help}
+@end example
+
+To get more specific help text about one of the tool's command use the @code{-help} option for that command; e.g.
+
+@example
+@code{keytool -genkey -help}
+@end example
+
+In both instances, the tool will print a help text and then will exit the running JVM.
+
+It is worth noting here that the help messages printed by the tool are I18N-ready. This means that if/when the contents of the tool's @i{Message Bundle} properties file are available in languages other than English, you may see those messages in that language.
+
+@comment ----------------------------------------------------------------------
+
+@node Common keytool Options, Distinguished Names, Getting Help, keytool Tool
+@comment node-name, next, previous, up
+@subsection Common options
-@item OPTIONS COMMON TO MORE THAN ONE COMMAND
The following @code{OPTION}s are used in more than one @code{COMMAND}. They are described here to reduce redundancy.
@table @b
@@ -263,7 +390,7 @@ If a URL was specified, but was found to be malformed --e.g. missing protocol el
A fully qualified class name of a @i{Security Provider} to add to the current list of @i{Security Providers} already installed in the JVM in-use. If a provider class is specified with this option, and was successfully added to the runtime --i.e. it was not already installed-- then the tool will attempt to removed this @i{Security Provider} before exiting.
@anchor{file}
-@item -file FILE_NAME
+@item -file FILE
Use this option to designate a file to use with a command. When specified with this option, the value is expected to be the fully qualified path of a file accessible by the File System. Depending on the command, the file may be used as input or as output. When this option is omitted from the command line, @code{STDIN} will be used instead, as the source of input, and @code{STDOUT} will be used instead as the output destination.
@anchor{verbose}
@@ -272,8 +399,13 @@ Unless specified otherwise, use this option to enable more verbose output.
@end table
+@comment ----------------------------------------------------------------------
+
+@node Distinguished Names, Add/Update Commands, Common keytool Options, keytool Tool
+@comment node-name, next, previous, up
+@subsection X.500 Distinguished Names
+
@anchor{dn}
-@item X.500 DISTINGUISHED NAME
A @i{Distinguished Name} (or DN) MUST be supplied with some of the @code{COMMAND}s using a @code{-dname} option. The syntax of a valid value for this option MUST follow RFC-2253 specifications. Namely the following components (with their accepted meaning) will be recognized. Note that the component name is case-insensitive:
@ftable @var
@@ -299,8 +431,27 @@ CN=host.domain.com, O=The Sample Company, L=Sydney, ST=NSW, C=AU
@*
If the @i{Distinguished Name} is required, and no valid default value can be used, the tool will prompt you to enter the information through the console.
-@item -genkey COMMAND
-Generate a new key-pair (both private and public keys), and save these credentials in the key store as a @i{Key Entry}, associated with the designated (if was specified in the @code{-alias} option) or default (if the @code{-alias} option is omitted) @i{Alias}.
+@comment ----------------------------------------------------------------------
+
+@node Add/Update Commands, Export Commands, Distinguished Names, keytool Tool
+@comment node-name, next, previous, up
+@subsection Add/Update commands
+
+@menu
+* Command -genkey:: Generate private key and self-signed certificate
+* Command -import:: Import certificates and certificate replies
+* Command -selfcert:: Generate self-signed certificate
+* Command -cacert:: Import a CA Trusted Certificate
+* Command -identitydb:: Import JDK-1 style identities
+@end menu
+
+@comment ----------------------------------------------------------------------
+
+@node Command -genkey, Command -import, Add/Update Commands, Add/Update Commands
+@comment node-name, next, previous, up
+@subsubsection @code{-genkey} command
+
+Use this command to generate a new key-pair (both private and public keys), and save these credentials in the key store as a @i{Key Entry}, associated with the designated (if was specified with the @code{-alias} option) or default (if the @code{-alias} option is omitted) @i{Alias}.
The private key material will be protected with a user-defined password (see @code{-keypass} option). The public key on the other hand will be part of a self-signed X.509 certificate, which will form a 1-element chain and will be saved in the key store.
@@ -347,8 +498,13 @@ For more details @pxref{verbose}.
@end table
-@item -import COMMAND
-Read an X.509 certificate, or a PKCS#7 @i{Certificate Reply} from a designated input source and incorporate the certificates into the key store.
+@comment ----------------------------------------------------------------------
+
+@node Command -import, Command -selfcert, Command -genkey, Add/Update Commands
+@comment node-name, next, previous, up
+@subsubsection @code{-import} command
+
+Use this command to read an X.509 certificate, or a PKCS#7 @i{Certificate Reply} from a designated input source and incorporate the certificates into the key store.
If the @i{Alias} does not already exist in the key store, the tool treats the certificate read from the input source as a new @i{Trusted Certificate}. It then attempts to discover a chain-of-trust, starting from that certificate and ending at another @i{Trusted Certificate}, already stored in the key store. If the @code{-trustcacerts} option is present, an additional key store, of type @code{JKS} named @file{cacerts}, and assumed to be present in @file{$@{JAVA_HOME@}/lib/security} will also be consulted if found --@code{$@{JAVA_HOME@}} refers to the location of an installed @i{Java Runtime Environment} (JRE). If no chain-of-trust can be established, and unless the @code{-noprompt} option has been specified, the certificate is printed to @code{STDOUT} and the user is prompted for a confirmation.
@@ -358,8 +514,8 @@ If @i{Alias} exists in the key store, the tool will treat the certificate(s) rea
@item -alias ALIAS
For more details @pxref{alias,, ALIAS}.
-@item -file FILE_NAME
-For more details @pxref{file,, FILE_NAME}.
+@item -file FILE
+For more details @pxref{file,, FILE}.
@item -keypass PASSWORD
Use this option to specify the password which the tool will use to protect the @i{Key Entry} associated with the designated @i{Alias}, when replacing this @i{Alias}' chain of certificates with that found in the certificate reply.
@@ -389,8 +545,13 @@ For more details @pxref{verbose}.
@end table
-@item -selfcert COMMAND
-Generate a self-signed X.509 version 1 certificate. The newly generated certificate will form a chain of one element which will replace the previous chain associated with the designated @i{Alias} (if @code{-alias} option was specified), or the default @i{Alias} (if @code{-alias} option was omitted).
+@comment ----------------------------------------------------------------------
+
+@node Command -selfcert, Command -cacert, Command -import, Add/Update Commands
+@comment node-name, next, previous, up
+@subsubsection @code{-selfcert} command
+
+Use this command to generate a self-signed X.509 version 1 certificate. The newly generated certificate will form a chain of one element which will replace the previous chain associated with the designated @i{Alias} (if @code{-alias} option was specified), or the default @i{Alias} (if @code{-alias} option was omitted).
@table @b
@item -alias ALIAS
@@ -429,14 +590,50 @@ For more details @pxref{verbose}.
@end table
-@item -identitydb COMMAND
+@comment ----------------------------------------------------------------------
+
+@node Command -cacert, Command -identitydb, Command -selfcert, Add/Update Commands
+@comment node-name, next, previous, up
+@subsubsection @code{-cacert} command
+
+Use this command to import, a CA certificate and add it to the key store as a @i{Trusted Certificate}. The @i{Alias} for this new entry will be constructed from the FILE's base-name after replacing hyphens and dots with underscores.
+
+This command is useful when used in a script that recursively visits a directory of CA certificates to populate a @code{cacerts.gkr} @i{Key Store} of trusted certificates which can then be used commands that specify the @code{-trustcacerts} option.
+
+@table @b
+@item -file FILE
+For more details @pxref{file,, FILE}.
+
+@item -storetype STORE_TYPE
+For more details @pxref{storetype,, STORE_TYPE}.
+
+@item -keystore URL
+For more details @pxref{keystore,, URL}.
+
+@item -storepass PASSWORD
+For more details @pxref{storepass,, PASSWORD}.
+
+@item -provider PROVIDER_CLASS_NAME
+For more details @pxref{provider,, PROVIDER_CLASS_NAME}.
+
+@item -v
+For more details @pxref{verbose}.
+
+@end table
+
+@comment ----------------------------------------------------------------------
+
+@node Command -identitydb, , Command -cacert, Add/Update Commands
+@comment node-name, next, previous, up
+@subsubsection @code{-identitydb} command
+
@b{NOT IMPLEMENTED YET}.
-Import a JDK 1.1 style Identity Database.
+Use this command to import a JDK 1.1 style Identity Database.
@table @b
-@item -file FILE_NAME
-For more details @pxref{file,, FILE_NAME}.
+@item -file FILE
+For more details @pxref{file,, FILE}.
@item -storetype STORE_TYPE
For more details @pxref{storetype,, STORE_TYPE}.
@@ -455,8 +652,24 @@ For more details @pxref{verbose}.
@end table
-@item -certreq COMMAND
-Generate a PKCS#10 @i{Certificate Signing Request} (CSR) and writes it to a designated output destination. The contents of the destination should look something like the following:
+@comment ----------------------------------------------------------------------
+
+@node Export Commands, Display Commands, Add/Update Commands, keytool Tool
+@comment node-name, next, previous, up
+@subsection Export commands
+
+@menu
+* Command -certreq:: Generate Certificate Signing Requests (CSR)
+* Command -export:: Export a certificate in a Key Store
+@end menu
+
+@comment ----------------------------------------------------------------------
+
+@node Command -certreq, Command -export, Export Commands, Export Commands
+@comment node-name, next, previous, up
+@subsubsection @code{-certreq} command
+
+Use this command to generate a PKCS#10 @i{Certificate Signing Request} (CSR) and write it to a designated output destination. The contents of the destination should look something like the following:
@example
-----BEGIN NEW CERTIFICATE REQUEST-----
@@ -476,8 +689,8 @@ For more details @pxref{alias,, ALIAS}.
@item -sigalg ALGORITHM
The canonical name of the digital signature algorithm to use for signing the certificate. If this option is omitted, a default value will be chosen based on the type of the private key associated with the designated @i{Alias}. If the private key is a @code{DSA} one, the value for the signature algorithm will be @code{SHA1withDSA}. If on the other hand the private key is an @code{RSA} one, then the tool will use @code{MD5withRSA} as the signature algorithm.
-@item -file FILE_NAME
-For more details @pxref{file,, FILE_NAME}.
+@item -file FILE
+For more details @pxref{file,, FILE}.
@item -keypass PASSWORD
Use this option to specify the password which the tool will use to unlock the @i{Key Entry} associated with the designated @i{Alias}.
@@ -504,16 +717,20 @@ Use this option to force the tool to encode a @code{NULL} DER value in the CSR a
@end table
-@item -export COMMAND
-Export a certificate stored in the key store to a designated output destination, either in binary format (if the @code{-v} option is specified), or in RFC-1421 compliant encoding (if the @code{-rfc} option is specified
-instead).
+@comment ----------------------------------------------------------------------
+
+@node Command -export, , Command -certreq, Export Commands
+@comment node-name, next, previous, up
+@subsubsection @code{-export} command
+
+Use this command to export a certificate stored in a key store to a designated output destination, either in binary format (if the @code{-v} option is specified), or in RFC-1421 compliant encoding (if the @code{-rfc} option is specified instead).
@table @b
@item -alias ALIAS
For more details @pxref{alias,, ALIAS}.
-@item -file FILE_NAME
-For more details @pxref{file,, FILE_NAME}.
+@item -file FILE
+For more details @pxref{file,, FILE}.
@item -storetype STORE_TYPE
For more details @pxref{storetype,, STORE_TYPE}.
@@ -535,8 +752,24 @@ Output the certificate in binary DER encoding. This is the default output format
@end table
-@item -list COMMAND
-Print one or all of the key store entries to @code{STDOUT}. Usually this command will only print a @i{fingerprint} of the certificate, unless either the @code{-rfc} or the @code{-v} option is specified.
+@comment ----------------------------------------------------------------------
+
+@node Display Commands, Management Commands, Export Commands, keytool Tool
+@comment node-name, next, previous, up
+@subsection Display commands
+
+@menu
+* Command -list:: Display information about one or all Aliases
+* Command -printcert:: Print a certificate or a certificate fingerprint
+@end menu
+
+@comment ----------------------------------------------------------------------
+
+@node Command -list, Command -printcert, Display Commands, Display Commands
+@comment node-name, next, previous, up
+@subsubsection @code{-list} command
+
+Use this command to print one or all of a key store entries to @code{STDOUT}. Usually this command will only print a @i{fingerprint} of the certificate, unless either the @code{-rfc} or the @code{-v} option is specified.
@table @b
@item -alias ALIAS
@@ -564,20 +797,43 @@ Output the certificate in human-readable format. If both this option and the @co
@end table
-@item -printcert COMMAND
-Read a certificate from a designated input source and print it to @code{STDOUT} in a human-readable form.
+@comment ----------------------------------------------------------------------
+
+@node Command -printcert, , Command -list, Display Commands
+@comment node-name, next, previous, up
+@subsubsection @code{-printcert} command
+
+Use this command to read a certificate from a designated input source and print it to @code{STDOUT} in a human-readable form.
@table @b
-@item -file FILE_NAME
-For more details @pxref{file,, FILE_NAME}.
+@item -file FILE
+For more details @pxref{file,, FILE}.
@item -v
For more details @pxref{verbose}.
@end table
-@item -keyclone COMMAND
-Clone an existing @i{Key Entry} and store it under a new (different) @i{Alias} protecting, its private key material with possibly a new password.
+@comment ----------------------------------------------------------------------
+
+@node Management Commands, , Display Commands, keytool Tool
+@comment node-name, next, previous, up
+@subsection Management commands
+
+@menu
+* Command -keyclone:: Clone a Key Entry in a Key Store
+* Command -storepasswd:: Change the password protecting a Key Store
+* Command -keypasswd:: Change the password protecting a Key Entry
+* Command -delete:: Remove an entry in a Key Store
+@end menu
+
+@comment ----------------------------------------------------------------------
+
+@node Command -keyclone, Command -storepasswd, Management Commands, Management Commands
+@comment node-name, next, previous, up
+@subsubsection @code{-keyclone} command
+
+Use this command to clone an existing @i{Key Entry} and store it under a new (different) @i{Alias} protecting, its private key material with possibly a new password.
@table @b
@item -alias ALIAS
@@ -611,8 +867,13 @@ For more details @pxref{verbose}.
@end table
-@item -storepasswd COMMAND
-Change the password protecting a key store.
+@comment ----------------------------------------------------------------------
+
+@node Command -storepasswd, Command -keypasswd, Command -keyclone, Management Commands
+@comment node-name, next, previous, up
+@subsubsection @code{-storepasswd} command
+
+Use this command to change the password protecting a key store.
@table @b
@item -new PASSWORD
@@ -635,14 +896,18 @@ For more details @pxref{verbose}.
@end table
-@item -keypasswd COMMAND
-Change the password protecting the private key material of a designated @i{Key Entry}.
+@comment ----------------------------------------------------------------------
+
+@node Command -keypasswd, Command -delete, Command -storepasswd, Management Commands
+@comment node-name, next, previous, up
+@subsubsection @code{-keypasswd} command
+
+Use this command to change the password protecting the private key material of a designated @i{Key Entry}.
@table @b
@item -alias ALIAS
For more details @pxref{alias,, ALIAS}.
-@item -keypass PASSWORD
Use this option to specify the password which the tool will use to unlock the @i{Key Entry} associated with the designated @i{Alias}.
If this option is omitted, the tool will first attempt to unlock the @i{Key Entry} using the same password protecting the key store. If this fails, you will then be prompted to provide a password.
@@ -667,8 +932,13 @@ For more details @pxref{verbose}.
@end table
-@item -delete COMMAND
-Delete a designated key store entry.
+@comment ----------------------------------------------------------------------
+
+@node Command -delete, , Command -keypasswd, Management Commands
+@comment node-name, next, previous, up
+@subsubsection @code{-delete} command
+
+Use this command to delete a designated key store entry.
@table @b
@item -alias ALIAS
@@ -690,7 +960,6 @@ For more details @pxref{provider,, PROVIDER_CLASS_NAME}.
For more details @pxref{verbose}.
@end table
-@end table
@comment ----------------------------------------------------------------------
@@ -709,7 +978,7 @@ Some tools --@pxref{Security Tools}-- allow using other than the English languag
@node Language Resources, Message Formats, I18N Issues, I18N Issues
@comment node-name, next, previous, up
-@section Language-Specific Resources
+@section Language-specific resources
The Tools use Java @code{ResourceBundle}s to store messages, and message templates they use at runtime to generate the message text itself, depending on the locale in use at the time.
@@ -761,7 +1030,7 @@ In the meantime, if you are willing to contribute localized versions of these re
@node Message Formats, , Language Resources, I18N Issues
@comment node-name, next, previous, up
-@section Message Formats
+@section Message formats
If you open any of the @file{messages.properties} described in the previous section, you may see properties that look like so:
diff --git a/examples/gnu/classpath/examples/swing/Demo.java b/examples/gnu/classpath/examples/swing/Demo.java
index 6447077a3..f1daaac33 100644
--- a/examples/gnu/classpath/examples/swing/Demo.java
+++ b/examples/gnu/classpath/examples/swing/Demo.java
@@ -203,6 +203,8 @@ public class Demo
boolean selected = laf.getClassName().equals(currentLaf);
lafItem.setSelected(selected);
lafMenu.add(lafItem);
+
+ lafGroup.add(lafItem);
}
// Create themes menu.
diff --git a/examples/gnu/classpath/examples/swing/FillRect.java b/examples/gnu/classpath/examples/swing/FillRect.java
index 11e208d85..7c6f140a0 100644
--- a/examples/gnu/classpath/examples/swing/FillRect.java
+++ b/examples/gnu/classpath/examples/swing/FillRect.java
@@ -20,9 +20,20 @@ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
package gnu.classpath.examples.swing;
-import java.awt.*;
-import java.awt.event.*;
-import javax.swing.*;
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Graphics;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JComponent;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.SwingUtilities;
/**
* @author Norman Hendrich
@@ -38,8 +49,9 @@ public class FillRect
Worker worker;
JLabel label;
JCheckBox translate;
+ JCheckBox lines;
- int nx = 64;
+ int nx = 128;
int ny = 64;
int matrix[][], future[][];
int generation = 0;
@@ -54,6 +66,11 @@ public class FillRect
* If true, test translation.
*/
boolean testTranslation = false;
+
+ /**
+ * If true, paint lines rather than rectangles
+ */
+ boolean paintLines;
public void actionPerformed(ActionEvent e)
{
@@ -65,7 +82,7 @@ public class FillRect
public FillRect()
{
- setSize(64, 64);
+ setSize(nx, ny);
createContent();
}
@@ -76,7 +93,7 @@ public class FillRect
JPanel p = new JPanel(new BorderLayout());
lcd = new LCDCanvas();
label = new JLabel();
- label.setText("paintComponent took 00 msec. (00000 fillRect calls)");
+ label.setText("not running");
translate = new JCheckBox("translate");
translate.addActionListener(new ActionListener()
@@ -87,12 +104,22 @@ public class FillRect
}
});
+ lines = new JCheckBox("lines");
+ lines.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent event)
+ {
+ paintLines = lines.isSelected();
+ }
+ });
+
JPanel bottom = new JPanel();
- bottom.add(label);
+ bottom.add(lines);
bottom.add(translate);
p.add(lcd, BorderLayout.CENTER);
p.add(bottom, BorderLayout.SOUTH);
+ p.add(label, BorderLayout.NORTH);
add(p);
}
@@ -143,37 +170,64 @@ public class FillRect
g.fillRect(0, 0, sx, sy);
Color pixelColor = null;
-
+
int dx, dy;
-
- for (int ix = 0; ix < nx; ix++)
+
+ if (paintLines)
{
- for (int iy = 0; iy < ny; iy++)
- {
- if (matrix[ix][iy] != 0)
- pixelColor = activePixel;
- else
- pixelColor = passivePixel;
-
- dx = 4 * ix;
- dy = 4 * iy;
- g.setColor(pixelColor);
-
- if (testTranslation)
- {
- g.translate(dx, dy);
- g.fillRect(0, 0, 3, 3);
- g.translate(-dx, -dy);
- }
- else
- g.fillRect(dx, dy, 3, 3);
- }
+ for (int ix = 0; ix < nx; ix++)
+ for (int iy = 0; iy < ny; iy++)
+ {
+ if (matrix[ix][iy] != 0)
+ pixelColor = activePixel;
+ else
+ pixelColor = passivePixel;
+
+ dx = 4 * ix;
+ dy = 4 * iy;
+ g.setColor(pixelColor);
+
+ if (testTranslation)
+ {
+ g.translate(dx, dy);
+ g.drawLine(0, 0, 5, 5);
+ g.translate(- dx, - dy);
+ }
+ else
+ g.drawLine(dx, dy, dx + 5, dy + 5);
+ }
}
+ else
+ for (int ix = 0; ix < nx; ix++)
+ {
+ for (int iy = 0; iy < ny; iy++)
+ {
+ if (matrix[ix][iy] != 0)
+ pixelColor = activePixel;
+ else
+ pixelColor = passivePixel;
+
+ dx = 4 * ix;
+ dy = 4 * iy;
+ g.setColor(pixelColor);
+
+ if (testTranslation)
+ {
+ g.translate(dx, dy);
+ g.fillRect(0, 0, 3, 3);
+ g.translate(- dx, - dy);
+ }
+ else
+ g.fillRect(dx, dy, 3, 3);
+ }
+ }
long t2 = System.currentTimeMillis();
- label.setText("paintComponent took " + (t2 - t1) + " msec. "
- + "(" + (nx * ny + 1) + " fillRect calls)");
+ label.setText("paintComponent took " + (t2 - t1) + " msec. " + "("
+ + (nx * ny + 1) + " "
+ + (paintLines ? "drawLine" : "fillRect") + " calls)");
+
}
public Dimension getPreferredSize()
diff --git a/examples/gnu/classpath/examples/swing/HtmlDemo.java b/examples/gnu/classpath/examples/swing/HtmlDemo.java
new file mode 100644
index 000000000..6ac626717
--- /dev/null
+++ b/examples/gnu/classpath/examples/swing/HtmlDemo.java
@@ -0,0 +1,165 @@
+/* HtmlDemo.java -- HTML viewer demo
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.classpath.examples.swing;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.GridLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+import javax.swing.JButton;
+import javax.swing.JComponent;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTextArea;
+import javax.swing.JTextPane;
+import javax.swing.SwingUtilities;
+
+/**
+ * Parses and displays HTML content.
+ *
+ * @author Audrius Meskauskas (audriusa@bioinformatics.org)
+ */
+public class HtmlDemo extends JPanel
+{
+
+ JTextPane html = new JTextPane();
+
+ //JTextArea text = new JTextArea("<html><body><p><img src='' alt='alt txt'></p></body></html>");
+ JTextArea text = new JTextArea("<html><body><p>nor<font color=red>ma</font>l<sup>sup</sup>normal<sub>sub</sub>normal</p></body></html>");
+
+ JPanel buttons;
+
+ public HtmlDemo()
+ {
+ super();
+ html.setContentType("text/html"); // not now.
+ createContent();
+ }
+
+ /**
+ * Returns a panel with the demo content. The panel uses a BorderLayout(), and
+ * the BorderLayout.SOUTH area is empty, to allow callers to add controls to
+ * the bottom of the panel if they want to (a close button is added if this
+ * demo is being run as a standalone demo).
+ */
+ private void createContent()
+ {
+ setLayout(new BorderLayout());
+
+ JPanel center = new JPanel();
+ GridLayout layout = new GridLayout();
+ layout.setRows(2);
+ center.setLayout(layout);
+ center.add(new JScrollPane(text));
+ center.add(new JScrollPane(html));
+
+ buttons = new JPanel();
+
+ JButton parse = new JButton("parse");
+ parse.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent event)
+ {
+ String t = text.getText();
+ System.out.println("HtmlDemo.java.createContent:Parsing started");
+ html.setText(t);
+ System.out.println("HtmlDemo.java.createContent:Parsing completed");
+ }
+ });
+
+ buttons.add(parse);
+
+ add(center, BorderLayout.CENTER);
+ add(buttons, BorderLayout.SOUTH);
+ }
+
+ /**
+ * The executable method to display the editable table.
+ *
+ * @param args
+ * unused.
+ */
+ public static void main(String[] args)
+ {
+ SwingUtilities.invokeLater
+ (new Runnable()
+ {
+ public void run()
+ {
+ HtmlDemo demo = new HtmlDemo();
+
+ JButton exit = new JButton("exit");
+ exit.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent event)
+ {
+ System.exit(0);
+ }
+ });
+
+ demo.buttons.add(exit);
+
+ JFrame frame = new JFrame();
+ frame.getContentPane().add(demo);
+ frame.setSize(new Dimension(640, 480));
+ frame.setVisible(true);
+ }
+ });
+ }
+
+ /**
+ * Returns a DemoFactory that creates a HtmlDemo.
+ *
+ * @return a DemoFactory that creates a HtmlDemo
+ */
+ public static DemoFactory createDemoFactory()
+ {
+ return new DemoFactory()
+ {
+ public JComponent createDemo()
+ {
+ return new HtmlDemo();
+ }
+ };
+ }
+}
+
diff --git a/gnu/classpath/debug/TeeInputStream.java b/gnu/classpath/debug/TeeInputStream.java
new file mode 100644
index 000000000..ef6b2ed3d
--- /dev/null
+++ b/gnu/classpath/debug/TeeInputStream.java
@@ -0,0 +1,98 @@
+/* TeeInputStream.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under terms
+of your choice, provided that you also meet, for each linked independent
+module, the terms and conditions of the license of that module. An
+independent module is a module which is not derived from or based on
+this library. If you modify this library, you may extend this exception
+to your version of the library, but you are not obligated to do so. If
+you do not wish to do so, delete this exception statement from your
+version. */
+
+package gnu.classpath.debug;
+
+import java.io.*;
+
+/**
+ * An input stream that copies all its input to a byte sink.
+ *
+ * @author Chris Burdess
+ */
+public class TeeInputStream
+ extends InputStream
+{
+
+ private final InputStream in;
+ private final OutputStream out;
+
+ /**
+ * Constructs a tee input stream.
+ * @param in the underlying input stream
+ * @param out the output sink
+ */
+ public TeeInputStream(InputStream in, OutputStream out)
+ {
+ this.in = in;
+ this.out = out;
+ }
+
+ public int read()
+ throws IOException
+ {
+ int ret = in.read();
+ out.write(ret);
+ out.flush();
+ return ret;
+ }
+
+ public int read(byte[] b, int off, int len)
+ throws IOException
+ {
+ int ret = in.read(b, off, len);
+ if (ret != -1)
+ {
+ out.write(b, off, ret);
+ out.flush();
+ }
+ return ret;
+ }
+
+ public void close()
+ throws IOException
+ {
+ in.close();
+ out.close();
+ }
+
+ public final boolean markSupported()
+ {
+ return false;
+ }
+
+}
diff --git a/gnu/classpath/debug/TeeOutputStream.java b/gnu/classpath/debug/TeeOutputStream.java
new file mode 100644
index 000000000..cff60894a
--- /dev/null
+++ b/gnu/classpath/debug/TeeOutputStream.java
@@ -0,0 +1,93 @@
+/* TeeOutputStream.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under terms
+of your choice, provided that you also meet, for each linked independent
+module, the terms and conditions of the license of that module. An
+independent module is a module which is not derived from or based on
+this library. If you modify this library, you may extend this exception
+to your version of the library, but you are not obligated to do so. If
+you do not wish to do so, delete this exception statement from your
+version. */
+
+package gnu.classpath.debug;
+
+import java.io.*;
+
+/**
+ * An output stream that copies all its output to an additional byte sink.
+ *
+ * @author Chris Burdess
+ */
+public class TeeOutputStream
+ extends OutputStream
+{
+
+ private final OutputStream out;
+ private final OutputStream sink;
+
+ /**
+ * Constructs a tee output stream.
+ * @param out the underlying output stream
+ * @param sink the output sink
+ */
+ public TeeOutputStream(OutputStream out, OutputStream sink)
+ {
+ this.out = out;
+ this.sink = sink;
+ }
+
+ public void write(int c)
+ throws IOException
+ {
+ out.write(c);
+ sink.write(c);
+ }
+
+ public void write(byte[] b, int off, int len)
+ throws IOException
+ {
+ out.write(b, off, len);
+ sink.write(b, off, len);
+ }
+
+ public void flush()
+ throws IOException
+ {
+ out.flush();
+ sink.flush();
+ }
+
+ public void close()
+ throws IOException
+ {
+ out.close();
+ sink.close();
+ }
+
+}
diff --git a/gnu/classpath/debug/TeeReader.java b/gnu/classpath/debug/TeeReader.java
new file mode 100644
index 000000000..8fa742e21
--- /dev/null
+++ b/gnu/classpath/debug/TeeReader.java
@@ -0,0 +1,98 @@
+/* TeeReader.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under terms
+of your choice, provided that you also meet, for each linked independent
+module, the terms and conditions of the license of that module. An
+independent module is a module which is not derived from or based on
+this library. If you modify this library, you may extend this exception
+to your version of the library, but you are not obligated to do so. If
+you do not wish to do so, delete this exception statement from your
+version. */
+
+package gnu.classpath.debug;
+
+import java.io.*;
+
+/**
+ * A reader that copies all characters read to an output sink.
+ *
+ * @author Chris Burdess
+ */
+public class TeeReader
+ extends Reader
+{
+
+ private final Reader in;
+ private final Writer out;
+
+ /**
+ * Constructs a tee reader.
+ * @param in the input
+ * @param out the output sink
+ */
+ public TeeReader(Reader in, Writer out)
+ {
+ this.in = in;
+ this.out = out;
+ }
+
+ public int read()
+ throws IOException
+ {
+ int ret = in.read();
+ out.write(ret);
+ out.flush();
+ return ret;
+ }
+
+ public int read(char[] b, int off, int len)
+ throws IOException
+ {
+ int ret = in.read(b, off, len);
+ if (ret != -1)
+ {
+ out.write(b, off, ret);
+ out.flush();
+ }
+ return ret;
+ }
+
+ public void close()
+ throws IOException
+ {
+ in.close();
+ out.close();
+ }
+
+ public final boolean markSupported()
+ {
+ return false;
+ }
+
+}
diff --git a/gnu/classpath/debug/TeeWriter.java b/gnu/classpath/debug/TeeWriter.java
new file mode 100644
index 000000000..f226c2165
--- /dev/null
+++ b/gnu/classpath/debug/TeeWriter.java
@@ -0,0 +1,93 @@
+/* TeeWriter.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under terms
+of your choice, provided that you also meet, for each linked independent
+module, the terms and conditions of the license of that module. An
+independent module is a module which is not derived from or based on
+this library. If you modify this library, you may extend this exception
+to your version of the library, but you are not obligated to do so. If
+you do not wish to do so, delete this exception statement from your
+version. */
+
+package gnu.classpath.debug;
+
+import java.io.*;
+
+/**
+ * A writer that copies all its output to an additional character sink.
+ *
+ * @author Chris Burdess
+ */
+public class TeeWriter
+ extends Writer
+{
+
+ private final Writer out;
+ private final Writer sink;
+
+ /**
+ * Constructs a tee writer.
+ * @param out the underlying writer
+ * @param sink the output sink
+ */
+ public TeeWriter(Writer out, Writer sink)
+ {
+ this.out = out;
+ this.sink = sink;
+ }
+
+ public void write(int c)
+ throws IOException
+ {
+ out.write(c);
+ sink.write(c);
+ }
+
+ public void write(char[] b, int off, int len)
+ throws IOException
+ {
+ out.write(b, off, len);
+ sink.write(b, off, len);
+ }
+
+ public void flush()
+ throws IOException
+ {
+ out.flush();
+ sink.flush();
+ }
+
+ public void close()
+ throws IOException
+ {
+ out.close();
+ sink.close();
+ }
+
+}
diff --git a/gnu/classpath/jdwp/processor/ClassTypeCommandSet.java b/gnu/classpath/jdwp/processor/ClassTypeCommandSet.java
index f60da7b70..a3a7ca05e 100644
--- a/gnu/classpath/jdwp/processor/ClassTypeCommandSet.java
+++ b/gnu/classpath/jdwp/processor/ClassTypeCommandSet.java
@@ -106,8 +106,12 @@ public class ClassTypeCommandSet
Class clazz = refId.getType();
Class superClazz = clazz.getSuperclass();
- ReferenceTypeId clazzId = idMan.getReferenceTypeId(superClazz);
- clazzId.write(os);
+ if (superClazz == null) {
+ os.writeLong(0L);
+ } else {
+ ReferenceTypeId clazzId = idMan.getReferenceTypeId(superClazz);
+ clazzId.write(os);
+ }
}
private void executeSetValues(ByteBuffer bb, DataOutputStream os)
diff --git a/gnu/classpath/jdwp/processor/EventRequestCommandSet.java b/gnu/classpath/jdwp/processor/EventRequestCommandSet.java
index e4b1b602e..59cfb94d3 100644
--- a/gnu/classpath/jdwp/processor/EventRequestCommandSet.java
+++ b/gnu/classpath/jdwp/processor/EventRequestCommandSet.java
@@ -147,7 +147,7 @@ public class EventRequestCommandSet
if (id == 0)
refId = null;
else
- refId = idMan.readReferenceTypeId(bb);
+ refId = idMan.getReferenceType(id);
boolean caught = (bb.get() == 0) ? false : true;
boolean unCaught = (bb.get() == 0) ? false : true;
filter = new ExceptionOnlyFilter(refId, caught, unCaught);
diff --git a/gnu/classpath/jdwp/processor/ThreadGroupReferenceCommandSet.java b/gnu/classpath/jdwp/processor/ThreadGroupReferenceCommandSet.java
index ba36251f6..103199a2b 100644
--- a/gnu/classpath/jdwp/processor/ThreadGroupReferenceCommandSet.java
+++ b/gnu/classpath/jdwp/processor/ThreadGroupReferenceCommandSet.java
@@ -103,8 +103,12 @@ public class ThreadGroupReferenceCommandSet
ObjectId oid = idMan.readObjectId(bb);
ThreadGroup group = (ThreadGroup) oid.getObject();
ThreadGroup parent = group.getParent();
- ObjectId parentId = idMan.getObjectId(parent);
- parentId.write(os);
+ if (parent == null) {
+ os.writeLong(0L);
+ } else {
+ ObjectId parentId = idMan.getObjectId(parent);
+ parentId.write(os);
+ }
}
private void executeChildren(ByteBuffer bb, DataOutputStream os)
diff --git a/gnu/java/awt/Buffers.java b/gnu/java/awt/Buffers.java
index c6ccf9191..2015634bb 100644
--- a/gnu/java/awt/Buffers.java
+++ b/gnu/java/awt/Buffers.java
@@ -144,25 +144,7 @@ public final class Buffers
*/
public static Object getData(DataBuffer buffer)
{
- if (buffer instanceof DataBufferByte)
- return ((DataBufferByte) buffer).getData();
-
- if (buffer instanceof DataBufferShort)
- return ((DataBufferShort) buffer).getData();
-
- if (buffer instanceof DataBufferUShort)
- return ((DataBufferUShort) buffer).getData();
-
- if (buffer instanceof DataBufferInt)
- return ((DataBufferInt) buffer).getData();
-
- if (buffer instanceof DataBufferFloat)
- return ((DataBufferFloat) buffer).getData();
-
- if (buffer instanceof DataBufferDouble)
- return ((DataBufferDouble) buffer).getData();
-
- throw new ClassCastException("Unknown data buffer type");
+ return getData(buffer, 0, null, 0, buffer.getSize());
}
@@ -172,46 +154,46 @@ public final class Buffers
* given destination array is null.
*/
public static Object getData(DataBuffer src, int srcOffset,
- Object dest, int destOffset,
+ Object dest, int dstOffset,
int length)
{
Object from;
- if (src instanceof DataBufferByte)
- {
- from = ((DataBufferByte) src).getData();
- if (dest == null) dest = new byte[length+destOffset];
- }
- else if (src instanceof DataBufferShort)
- {
- from = ((DataBufferShort) src).getData();
- if (dest == null) dest = new short[length+destOffset];
- }
- else if (src instanceof DataBufferUShort)
- {
- from = ((DataBufferUShort) src).getData();
- if (dest == null) dest = new short[length+destOffset];
- }
- else if (src instanceof DataBufferInt)
- {
- from = ((DataBufferInt) src).getData();
- if (dest == null) dest = new int[length+destOffset];
- }
- else if (src instanceof DataBufferFloat)
- {
- from = ((DataBufferFloat) src).getData();
- if (dest == null) dest = new float[length+destOffset];
- }
- else if (src instanceof DataBufferDouble)
- {
- from = ((DataBufferDouble) src).getData();
- if (dest == null) dest = new double[length+destOffset];
- }
- else
+ switch(src.getDataType())
{
+ case DataBuffer.TYPE_BYTE:
+ if (dest == null) dest = new byte[length+dstOffset];
+ for(int i = 0; i < length; i++)
+ ((byte[])dest)[i + dstOffset] = (byte)src.getElem(i + srcOffset);
+ break;
+
+ case DataBuffer.TYPE_DOUBLE:
+ if (dest == null) dest = new double[length+dstOffset];
+ for(int i = 0; i < length; i++)
+ ((double[])dest)[i + dstOffset] = src.getElemDouble(i + srcOffset);
+ break;
+
+ case DataBuffer.TYPE_FLOAT:
+ if (dest == null) dest = new float[length+dstOffset];
+ for(int i = 0; i < length; i++)
+ ((float[])dest)[i + dstOffset] = src.getElemFloat(i + srcOffset);
+ break;
+
+ case DataBuffer.TYPE_INT:
+ if (dest == null) dest = new int[length+dstOffset];
+ for(int i = 0; i < length; i++)
+ ((int[])dest)[i + dstOffset] = src.getElem(i + srcOffset);
+ break;
+
+ case DataBuffer.TYPE_SHORT:
+ case DataBuffer.TYPE_USHORT:
+ if (dest == null) dest = new short[length+dstOffset];
+ for(int i = 0; i < length; i++)
+ ((short[])dest)[i + dstOffset] = (short)src.getElem(i + srcOffset);
+ break;
+
+ case DataBuffer.TYPE_UNDEFINED:
throw new ClassCastException("Unknown data buffer type");
}
-
- System.arraycopy(from, srcOffset, dest, destOffset, length);
return dest;
}
diff --git a/gnu/java/awt/font/opentype/truetype/VirtualMachine.java b/gnu/java/awt/font/opentype/truetype/VirtualMachine.java
index 6f53af672..7e50b6678 100644
--- a/gnu/java/awt/font/opentype/truetype/VirtualMachine.java
+++ b/gnu/java/awt/font/opentype/truetype/VirtualMachine.java
@@ -1066,6 +1066,10 @@ class VirtualMachine
stack[sp] = ((e1 != 0) || (stack[sp] != 0)) ? 1 : 0;
break;
+ case 0x5C: // NOT
+ stack[sp] = (stack[sp] != 0) ? 0 : 1;
+ break;
+
case 0x5e: // SDB, Set Delta Base in the graphics state
deltaBase = stack[sp--];
break;
@@ -1764,7 +1768,7 @@ class VirtualMachine
/* 50 */ "LT", "LTEQ", "GT", "GTEQ",
/* 54 */ "EQ", "NEQ", "INST_56", "INST_57",
/* 58 */ "IF", "EIF", "AND", "OR",
- /* 5c */ "INST_5C", "INST_5D", "SDB", "SDS",
+ /* 5c */ "NOT", "INST_5D", "SDB", "SDS",
/* 60 */ "ADD", "SUB", "DIV", "MUL",
/* 64 */ "ABS", "NEG", "FLOOR", "CEILING",
/* 68 */ "ROUND[0]", "ROUND[1]", "ROUND[2]", "ROUND[3]",
diff --git a/gnu/java/awt/java2d/AbstractGraphics2D.java b/gnu/java/awt/java2d/AbstractGraphics2D.java
index 6408a264d..dd1865cdf 100644
--- a/gnu/java/awt/java2d/AbstractGraphics2D.java
+++ b/gnu/java/awt/java2d/AbstractGraphics2D.java
@@ -1332,8 +1332,8 @@ public abstract class AbstractGraphics2D
{
AffineTransform t = new AffineTransform();
t.translate(x, y);
- double scaleX = (double) image.getWidth(observer) / (double) width;
- double scaleY = (double) image.getHeight(observer) / (double) height;
+ double scaleX = (double) width / (double) image.getWidth(observer);
+ double scaleY = (double) height / (double) image.getHeight(observer);
t.scale(scaleX, scaleY);
return drawImage(image, t, observer);
}
@@ -1474,15 +1474,11 @@ public abstract class AbstractGraphics2D
antialias = (v == RenderingHints.VALUE_ANTIALIAS_ON);
}
- double offs = 0.5;
- if (antialias)
- offs = offs / AA_SAMPLING;
-
Rectangle2D userBounds = s.getBounds2D();
Rectangle2D deviceBounds = new Rectangle2D.Double();
- ArrayList segs = getSegments(s, transform, deviceBounds, false, offs);
+ ArrayList segs = getSegments(s, transform, deviceBounds, false);
Rectangle2D clipBounds = new Rectangle2D.Double();
- ArrayList clipSegs = getSegments(clip, transform, clipBounds, true, offs);
+ ArrayList clipSegs = getSegments(clip, transform, clipBounds, true);
segs.addAll(clipSegs);
Rectangle2D inclClipBounds = new Rectangle2D.Double();
Rectangle2D.union(clipBounds, deviceBounds, inclClipBounds);
@@ -1677,7 +1673,10 @@ public abstract class AbstractGraphics2D
// Scan all relevant lines.
int minYInt = (int) Math.ceil(icMinY);
- for (int y = minYInt; y <= maxY; y++)
+
+ Rectangle devClip = getDeviceBounds();
+ int scanlineMax = (int) Math.min(maxY, devClip.getMaxY());
+ for (int y = minYInt; y < scanlineMax; y++)
{
ArrayList bucket = edgeTable[y - minYInt];
// Update all the x intersections in the current activeEdges table
@@ -2170,8 +2169,7 @@ public abstract class AbstractGraphics2D
* @return a list of PolyEdge that form the shape in device space
*/
private ArrayList getSegments(Shape s, AffineTransform t,
- Rectangle2D deviceBounds, boolean isClip,
- double offs)
+ Rectangle2D deviceBounds, boolean isClip)
{
// Flatten the path. TODO: Determine the best flattening factor
// wrt to speed and quality.
@@ -2214,14 +2212,14 @@ public abstract class AbstractGraphics2D
else if (segType == PathIterator.SEG_CLOSE)
{
// Close the polyline.
- PolyEdge edge = new PolyEdge(segX, segY - offs,
- polyX, polyY - offs, isClip);
+ PolyEdge edge = new PolyEdge(segX, segY,
+ polyX, polyY, isClip);
segs.add(edge);
}
else if (segType == PathIterator.SEG_LINETO)
{
- PolyEdge edge = new PolyEdge(segX, segY - offs,
- seg[0], seg[1] - offs, isClip);
+ PolyEdge edge = new PolyEdge(segX, segY,
+ seg[0], seg[1], isClip);
segs.add(edge);
segX = seg[0];
segY = seg[1];
diff --git a/gnu/java/awt/java2d/PolyEdge.java b/gnu/java/awt/java2d/PolyEdge.java
index 8dbdbabcb..6c3b54688 100644
--- a/gnu/java/awt/java2d/PolyEdge.java
+++ b/gnu/java/awt/java2d/PolyEdge.java
@@ -118,6 +118,7 @@ public class PolyEdge
public String toString()
{
return "Edge: " + x0 + ", " + y0 + ", " + x1 + ", " + y1 + ", slope: "
- + slope + ", xIntersection: " + xIntersection;
+ + slope + ", xIntersection: " + xIntersection
+ + ", isClip: " + isClip;
}
}
diff --git a/gnu/java/awt/java2d/TexturePaintContext.java b/gnu/java/awt/java2d/TexturePaintContext.java
new file mode 100644
index 000000000..1a782ce07
--- /dev/null
+++ b/gnu/java/awt/java2d/TexturePaintContext.java
@@ -0,0 +1,205 @@
+/* TexturePaintContext.java -- PaintContext impl for TexturePaint
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.java2d;
+
+import java.awt.AWTError;
+import java.awt.PaintContext;
+import java.awt.Rectangle;
+import java.awt.TexturePaint;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.NoninvertibleTransformException;
+import java.awt.geom.Rectangle2D;
+import java.awt.image.BufferedImage;
+import java.awt.image.ColorModel;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+
+/**
+ * A {@link PaintContext} implementation for {@link TexturePaint}, done in
+ * pure Java.
+ *
+ * @author Roman Kennke (kennke@aicas.com)
+ */
+public class TexturePaintContext
+ implements PaintContext
+{
+
+ /**
+ * The TexturePaint object.
+ */
+ private BufferedImage image;
+
+ /**
+ * The Raster that holds the texture.
+ */
+ private WritableRaster paintRaster;
+
+ /**
+ * The transform from userspace into device space.
+ */
+ private AffineTransform transform;
+
+ /**
+ * Creates a new TexturePaintContext for the specified TexturePaint object.
+ * This initializes the Raster which is returned by
+ * {@link #getRaster(int, int, int, int)}.
+ *
+ * @param t the texture paint object
+ * @param db the bounds of the target raster in device space
+ * @param ub the bounds of the target raster in user space
+ * @param xform the transformation from user space to device space
+ */
+ public TexturePaintContext(TexturePaint t, Rectangle db,
+ Rectangle2D ub, AffineTransform xform)
+ {
+ image = t.getImage();
+
+ try
+ {
+ // Prepare transform for mapping from device space into image space.
+ // In order to achieve this we take the transform for userspace->
+ // devicespace, append the correct scale and translation according
+ // to the anchor (which gives us the image->userspace->devicespace
+ // transform), and invert that (which gives use the device->user->image
+ // transform).
+ Rectangle2D anchor = t.getAnchorRect();
+ BufferedImage image = t.getImage();
+ double scaleX = anchor.getWidth() / image.getWidth();
+ double scaleY = anchor.getHeight() / image.getHeight();
+ transform = (AffineTransform) xform.clone();
+ transform.scale(scaleX, scaleY);
+ transform.translate(-anchor.getMinX(), -anchor.getMaxX());
+ transform = transform.createInverse();
+ }
+ catch (NoninvertibleTransformException ex)
+ {
+ AWTError err =
+ new AWTError("Unexpected NoninvertibleTransformException");
+ err.initCause(ex);
+ throw err;
+ }
+ }
+
+ /**
+ * Disposes the PaintContext. Nothing is to do here, since we don't use
+ * any native resources in that implementation.
+ */
+ public void dispose()
+ {
+ // Nothing to do here.
+ }
+
+ /**
+ * Returns the color model of this PaintContext. This implementation returnes
+ * the color model used by the BufferedImage in the TexturePaint object,
+ * this avoids costly color model transformations (at least at this point).
+ *
+ * @return the color model of this PaintContext
+ */
+ public ColorModel getColorModel()
+ {
+ return image.getColorModel();
+ }
+
+ /**
+ * Returns the Raster that is used for painting.
+ *
+ * @param x1 the x location of the raster inside the user bounds of this paint
+ * context
+ * @param y1 the y location of the raster inside the user bounds of this paint
+ * context
+ * @param w the width
+ * @param h the height
+ *
+ * @return the Raster that is used for painting
+ *
+ */
+ public Raster getRaster(int x1, int y1, int w, int h)
+ {
+ ensureRasterSize(w, h);
+ int x2 = x1 + w;
+ int y2 = y1 + h;
+ float[] src = new float[2];
+ float[] dest = new float[2];
+ Raster source = image.getData();
+ int minX = source.getMinX();
+ int width = source.getWidth();
+ int minY = source.getMinY();
+ int height = source.getHeight();
+ Object pixel = null;
+ for (int y = y1; y < y2; y++)
+ {
+ for (int x = x1; x < x2; x++)
+ {
+ // Transform the coordinates from device space into image space.
+ src[0] = x;
+ src[1] = y;
+ transform.transform(src, 0, dest, 0, 1);
+ int dx = (int) dest[0];
+ int dy = (int) dest[1];
+
+ // The modulo operation gives us the replication effect.
+ dx = ((dx - minX) % width) + minX;
+ dy = ((dy - minY) % height) + minY;
+
+ // Copy the pixel.
+ pixel = source.getDataElements(dx, dy, pixel);
+ paintRaster.setDataElements(x - x1, y - y1, pixel);
+ }
+ }
+ return paintRaster;
+ }
+
+ /**
+ * Ensures that the target raster exists and has at least the specified
+ * size.
+ *
+ * @param w the requested target width
+ * @param h the requested target height
+ */
+ private void ensureRasterSize(int w, int h)
+ {
+ if (paintRaster == null || paintRaster.getWidth() < w
+ || paintRaster.getHeight() < h)
+ {
+ Raster s = image.getData();
+ paintRaster = s.createCompatibleWritableRaster(w, h);
+ }
+ }
+}
diff --git a/gnu/java/awt/peer/gtk/BufferedImageGraphics.java b/gnu/java/awt/peer/gtk/BufferedImageGraphics.java
new file mode 100644
index 000000000..d9d300d91
--- /dev/null
+++ b/gnu/java/awt/peer/gtk/BufferedImageGraphics.java
@@ -0,0 +1,258 @@
+/* BufferedImageGraphics.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.gtk;
+
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.GraphicsConfiguration;
+import java.awt.Image;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.Shape;
+import java.awt.font.GlyphVector;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Rectangle2D;
+import java.awt.image.BufferedImage;
+import java.awt.image.DataBuffer;
+import java.awt.image.DataBufferInt;
+import java.awt.image.ColorModel;
+import java.awt.image.DirectColorModel;
+import java.awt.image.RenderedImage;
+import java.awt.image.ImageObserver;
+import java.util.WeakHashMap;
+
+/**
+ * Implementation of Graphics2D on a Cairo surface.
+ *
+ * Simutanously maintains a CairoSurface and updates the
+ * BufferedImage from that after each drawing operation.
+ */
+public class BufferedImageGraphics extends CairoGraphics2D
+{
+ /**
+ * the buffered Image.
+ */
+ private BufferedImage image;
+
+ /**
+ * Image size.
+ */
+ private int imageWidth, imageHeight;
+
+ /**
+ * The cairo surface that we actually draw on.
+ */
+ CairoSurface surface;
+
+ /**
+ * Cache BufferedImageGraphics surfaces.
+ */
+ static WeakHashMap bufferedImages = new WeakHashMap();
+
+ /**
+ * Its corresponding cairo_t.
+ */
+ private long cairo_t;
+
+ /**
+ * Colormodels we recognize for fast copying.
+ */
+ static ColorModel rgb32 = new DirectColorModel(32, 0xFF0000, 0xFF00, 0xFF);
+ static ColorModel argb32 = new DirectColorModel(32, 0xFF0000, 0xFF00, 0xFF,
+ 0xFF000000);
+ private boolean hasFastCM;
+ private boolean hasAlpha;
+
+
+ public BufferedImageGraphics(BufferedImage bi)
+ {
+ this.image = bi;
+ imageWidth = bi.getWidth();
+ imageHeight = bi.getHeight();
+ if(bi.getColorModel().equals(rgb32))
+ {
+ hasFastCM = true;
+ hasAlpha = false;
+ }
+ else if(bi.getColorModel().equals(argb32))
+ {
+ hasFastCM = true;
+ hasAlpha = false;
+ }
+ else
+ hasFastCM = false;
+
+ // Cache surfaces.
+ if( bufferedImages.get( bi ) != null )
+ surface = (CairoSurface)bufferedImages.get( bi );
+ else
+ {
+ surface = new CairoSurface( imageWidth, imageHeight );
+ bufferedImages.put(bi, surface);
+ }
+
+ cairo_t = surface.newCairoContext();
+
+ DataBuffer db = bi.getRaster().getDataBuffer();
+ int[] pixels;
+ // get pixels
+
+ if(db instanceof CairoSurface)
+ pixels = ((CairoSurface)db).getPixels(imageWidth * imageHeight);
+ else
+ {
+ if( hasFastCM )
+ {
+ pixels = ((DataBufferInt)db).getData();
+ if( !hasAlpha )
+ for(int i = 0; i < pixels.length; i++)
+ pixels[i] &= 0xFFFFFFFF;
+ }
+ else
+ {
+ pixels = CairoGraphics2D.findSimpleIntegerArray
+ (image.getColorModel(),image.getData());
+ }
+ }
+ surface.setPixels( pixels );
+
+ setup( cairo_t );
+ setClip(0, 0, imageWidth, imageHeight);
+ }
+
+ BufferedImageGraphics(BufferedImageGraphics copyFrom)
+ {
+ surface = copyFrom.surface;
+ cairo_t = surface.newCairoContext();
+ imageWidth = copyFrom.imageWidth;
+ imageHeight = copyFrom.imageHeight;
+ copy( copyFrom, cairo_t );
+ setClip(0, 0, surface.width, surface.height);
+ }
+
+ /**
+ * Update a rectangle of the bufferedImage. This can be improved upon a lot.
+ */
+ private void updateBufferedImage(int x, int y, int width, int height)
+ {
+ int[] pixels = surface.getPixels(imageWidth * imageHeight);
+
+ if( x > imageWidth || y > imageHeight )
+ return;
+ // Clip edges.
+ if( x < 0 ){ width = width + x; x = 0; }
+ if( y < 0 ){ height = height + y; y = 0; }
+ if( x + width > imageWidth )
+ width = imageWidth - x;
+ if( y + height > imageHeight )
+ height = imageHeight - y;
+
+ if( !hasFastCM )
+ image.setRGB(x, y, width, height, pixels,
+ x + y * imageWidth, imageWidth);
+ else
+ System.arraycopy(pixels, y * imageWidth,
+ ((DataBufferInt)image.getRaster().getDataBuffer()).
+ getData(), y * imageWidth, height * imageWidth);
+ }
+
+ /**
+ * Abstract methods.
+ */
+ public Graphics create()
+ {
+ return new BufferedImageGraphics(this);
+ }
+
+ public GraphicsConfiguration getDeviceConfiguration()
+ {
+ return null;
+ }
+
+ protected Rectangle2D getRealBounds()
+ {
+ return new Rectangle2D.Double(0.0, 0.0, imageWidth, imageHeight);
+ }
+
+ public void copyAreaImpl(int x, int y, int width, int height, int dx, int dy)
+ {
+ surface.copyAreaNative(x, y, width, height, dx, dy, surface.width);
+ updateBufferedImage(x + dx, y + dy, width, height);
+ }
+
+ /**
+ * Overloaded methods that do actual drawing need to enter the gdk threads
+ * and also do certain things before and after.
+ */
+ public void draw(Shape s)
+ {
+ super.draw(s);
+ Rectangle r = s.getBounds();
+ updateBufferedImage(r.x, r.y, r.width, r.height);
+ }
+
+ public void fill(Shape s)
+ {
+ super.fill(s);
+ Rectangle r = s.getBounds();
+ updateBufferedImage(r.x, r.y, r.width, r.height);
+ }
+
+ public void drawRenderedImage(RenderedImage image, AffineTransform xform)
+ {
+ super.drawRenderedImage(image, xform);
+ updateBufferedImage(0, 0, imageWidth, imageHeight);
+ }
+
+ protected boolean drawImage(Image img, AffineTransform xform,
+ Color bgcolor, ImageObserver obs)
+ {
+ boolean rv = super.drawImage(img, xform, bgcolor, obs);
+ updateBufferedImage(0, 0, imageWidth, imageHeight);
+ return rv;
+ }
+
+ public void drawGlyphVector(GlyphVector gv, float x, float y)
+ {
+ super.drawGlyphVector(gv, x, y);
+ updateBufferedImage(0, 0, imageWidth, imageHeight);
+ }
+}
+
diff --git a/gnu/java/awt/peer/gtk/GdkGraphics2D.java b/gnu/java/awt/peer/gtk/CairoGraphics2D.java
index ff3555015..a76962afc 100644
--- a/gnu/java/awt/peer/gtk/GdkGraphics2D.java
+++ b/gnu/java/awt/peer/gtk/CairoGraphics2D.java
@@ -1,5 +1,5 @@
-/* GdkGraphics2D.java --
- Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
+/* CairoGraphics2D.java --
+ Copyright (C) 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,14 +38,12 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
-import gnu.classpath.Configuration;
import gnu.java.awt.ClasspathToolkit;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
-import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
@@ -58,27 +56,30 @@ import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
+import java.awt.Polygon;
import java.awt.TexturePaint;
import java.awt.Toolkit;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
+import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
-import java.awt.geom.GeneralPath;
+import java.awt.geom.Area;
+import java.awt.geom.Line2D;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
+import java.awt.geom.RoundRectangle2D;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ColorModel;
-import java.awt.image.CropImageFilter;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.DirectColorModel;
-import java.awt.image.FilteredImageSource;
import java.awt.image.ImageObserver;
+import java.awt.image.ImageProducer;
import java.awt.image.ImagingOpException;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.Raster;
@@ -90,73 +91,136 @@ import java.awt.image.renderable.RenderableImage;
import java.text.AttributedCharacterIterator;
import java.util.HashMap;
import java.util.Map;
-import java.util.Stack;
-public class GdkGraphics2D extends Graphics2D
+/**
+ * This is an abstract implementation of Graphics2D on Cairo.
+ *
+ * It should be subclassed for different Cairo contexts.
+ *
+ * Note for subclassers: Apart from the constructor (see comments below),
+ * The following abstract methods must be implemented:
+ *
+ * Graphics create()
+ * GraphicsConfiguration getDeviceConfiguration()
+ * copyArea(int x, int y, int width, int height, int dx, int dy)
+ *
+ * Also, dispose() must be overloaded to free any native datastructures
+ * used by subclass and in addition call super.dispose() to free the
+ * native cairographics2d structure and cairo_t.
+ *
+ * @author Sven de Marothy
+ */
+public abstract class CairoGraphics2D extends Graphics2D
{
- //////////////////////////////////////
- ////// State Management Methods //////
- //////////////////////////////////////
-
static
{
- if (Configuration.INIT_LOAD_LIBRARY)
- System.loadLibrary("gtkpeer");
-
- initStaticState();
+ System.loadLibrary("gtkpeer");
}
-
- static native void initStaticState();
-
- private final int native_state = GtkGenericPeer.getUniqueInteger();
- // These are package-private to avoid accessor methods.
+ /**
+ * Important: This is a pointer to the native cairographics2d structure
+ *
+ * DO NOT CHANGE WITHOUT CHANGING NATIVE CODE.
+ */
+ long nativePointer;
+
+ // Drawing state variables
+ /**
+ * The current paint
+ */
Paint paint;
+
+ /**
+ * The current stroke
+ */
Stroke stroke;
- Color fg;
- Color bg;
+
+ /*
+ * Current foreground and background color.
+ */
+ Color fg, bg;
+
+ /**
+ * Current clip shape.
+ */
Shape clip;
+
+ /**
+ * Current transform.
+ */
AffineTransform transform;
- private GtkComponentPeer component;
- // This is package-private to avoid an accessor method.
+
+ /**
+ * Current font.
+ */
Font font;
- private RenderingHints hints;
- private BufferedImage bimage;
- private boolean pixelConversionRequired;
- private int[] pixelBuffer;
- // This is package-private to avoid an accessor method.
+
+ /**
+ * The current compositing context, if any.
+ */
Composite comp;
- private Stack stateStack;
- private native void initState(GtkComponentPeer component);
- private native void initState(int width, int height);
- private native void initState(int[] pixes, int width, int height);
- private native void copyState(GdkGraphics2D g);
- public native void dispose();
- private native void cairoSurfaceSetFilter(int filter);
+ /**
+ * Rendering hint map.
+ */
+ private RenderingHints hints;
- public void finalize()
- {
- dispose();
- }
+ /**
+ * Some operations (drawing rather than filling) require that their
+ * coords be shifted to land on 0.5-pixel boundaries, in order to land on
+ * "middle of pixel" coordinates and light up complete pixels.
+ */
+ private boolean shiftDrawCalls = false;
+
+ /**
+ * Keep track if the first clip to be set, which is restored on setClip(null);
+ */
+ private boolean firstClip = true;
+ private Shape originalClip;
+
+ /**
+ * Stroke used for 3DRects
+ */
+ private static BasicStroke draw3DRectStroke = new BasicStroke();
+
+ static ColorModel rgb32 = new DirectColorModel(32, 0xFF0000, 0xFF00, 0xFF);
+ static ColorModel argb32 = new DirectColorModel(32, 0xFF0000, 0xFF00, 0xFF,
+ 0xFF000000);
- public Graphics create()
+ /**
+ * Constructor does nothing.
+ */
+ public CairoGraphics2D()
{
- return new GdkGraphics2D(this);
}
- public Graphics create(int x, int y, int width, int height)
- {
- return new GdkGraphics2D(this, x, y, width, height);
+ /**
+ * Sets up the default values and allocates the native cairographics2d structure
+ * @param cairo_t_pointer, a native pointer to a cairo_t of the context.
+ */
+ public void setup(long cairo_t_pointer)
+ {
+ nativePointer = init(cairo_t_pointer);
+ setRenderingHints(new RenderingHints(getDefaultHints()));
+ font = new Font("SansSerif", Font.PLAIN, 12);
+ setColor(Color.black);
+ setBackground(Color.white);
+ setPaint(Color.black);
+ setStroke(new BasicStroke());
+ setTransform(new AffineTransform());
}
- GdkGraphics2D(GdkGraphics2D g)
+ /**
+ * Same as above, but copies the state of another CairoGraphics2D.
+ */
+ public void copy(CairoGraphics2D g, long cairo_t_pointer)
{
- Color foreground;
-
+ nativePointer = init(cairo_t_pointer);
paint = g.paint;
stroke = g.stroke;
setRenderingHints(g.hints);
+
+ Color foreground;
if (g.fg.getAlpha() != -1)
foreground = new Color(g.fg.getRed(), g.fg.getGreen(), g.fg.getBlue(),
@@ -184,515 +248,190 @@ public class GdkGraphics2D extends Graphics2D
transform = new AffineTransform(g.transform);
font = g.font;
- component = g.component;
- copyState(g);
setColor(foreground);
setBackground(bg);
setPaint(paint);
setStroke(stroke);
setTransform(transform);
- setClip(clip);
- stateStack = new Stack();
- }
-
- GdkGraphics2D(GdkGraphics2D g, int x, int y, int widht, int height)
- {
- this(g);
- translate(x, y);
- clipRect(0, 0, widht, height);
}
- GdkGraphics2D(int width, int height)
+ /**
+ * Generic destructor - call the native dispose() method.
+ */
+ public void finalize()
{
- initState(width, height);
-
- setColor(Color.black);
- setBackground(new Color(0, 0, 0, 0));
- setPaint(getColor());
- setFont(new Font("SansSerif", Font.PLAIN, 12));
- setTransform(new AffineTransform());
- setStroke(new BasicStroke());
- setRenderingHints(getDefaultHints());
-
- stateStack = new Stack();
+ dispose();
}
- GdkGraphics2D(GtkComponentPeer component)
+ /**
+ * Disposes the native cairographics2d structure, including the
+ * cairo_t and any gradient stuff, if allocated.
+ * Subclasses should of course overload and call this if
+ * they have additional native structures.
+ */
+ public void dispose()
{
- this.component = component;
-
- initComponentGraphics2D();
+ disposeNative(nativePointer);
+ nativePointer = 0;
}
- void initComponentGraphics2D()
- {
- initState(component);
-
- setColor(component.awtComponent.getForeground());
- setBackground(component.awtComponent.getBackground());
- setPaint(getColor());
- setTransform(new AffineTransform());
- setStroke(new BasicStroke());
- setRenderingHints(getDefaultHints());
- setFont(new Font("SansSerif", Font.PLAIN, 12));
+ /**
+ * Allocate the cairographics2d structure and set the cairo_t pointer in it.
+ * @param pointer - a cairo_t pointer, casted to a long.
+ */
+ private native long init(long pointer);
- stateStack = new Stack();
- }
+ /**
+ * These are declared abstract as there may be context-specific issues.
+ */
+ public abstract Graphics create();
- GdkGraphics2D(BufferedImage bimage)
- {
- this.bimage = bimage;
- this.pixelBuffer = findSimpleIntegerArray(bimage.getColorModel(),
- bimage.getRaster());
- if (this.pixelBuffer == null)
- {
- this.pixelBuffer = new int[bimage.getRaster().getWidth() * bimage.getRaster()
- .getHeight()];
- this.pixelConversionRequired = true;
- }
- else
- {
- this.pixelConversionRequired = false;
- }
+ public abstract GraphicsConfiguration getDeviceConfiguration();
- initState(this.pixelBuffer, bimage.getWidth(), bimage.getHeight());
+ protected abstract void copyAreaImpl(int x, int y,
+ int width, int height, int dx, int dy);
- setColor(Color.black);
- setBackground(new Color(0, 0, 0, 0));
- setPaint(getColor());
- setFont(new Font("SansSerif", Font.PLAIN, 12));
- setTransform(new AffineTransform());
- setStroke(new BasicStroke());
- setRenderingHints(getDefaultHints());
- stateStack = new Stack();
+ protected abstract Rectangle2D getRealBounds();
- // draw current buffered image to the pixmap associated
- // with it, if the image is not equal to our paint buffer.
- if (pixelConversionRequired)
- drawImage(bimage, new AffineTransform(1, 0, 0, 1, 0, 0), bg, null);
- }
+ ////// Native Methods ////////////////////////////////////////////////////
- ////////////////////////////////////
- ////// Native Drawing Methods //////
- ////////////////////////////////////
+ /**
+ * Dispose of allocate native resouces.
+ */
+ public native void disposeNative(long pointer);
- // GDK drawing methods
- private native void gdkDrawDrawable(GdkGraphics2D other, int x, int y);
+ /**
+ * Draw pixels as an RGBA int matrix
+ * @param w, h - width and height
+ * @param stride - stride of the array width
+ * @param i2u - affine transform array
+ */
+ private native void drawPixels(long pointer, int[] pixels, int w, int h,
+ int stride, double[] i2u);
- // drawing utility methods
- private native void drawPixels(int[] pixels, int w, int h, int stride,
- double[] i2u);
- private native void setTexturePixels(int[] pixels, int w, int h, int stride);
- private native void setGradient(double x1, double y1, double x2, double y2,
+ private native void setGradient(long pointer, double x1, double y1,
+ double x2, double y2,
int r1, int g1, int b1, int a1, int r2,
int g2, int b2, int a2, boolean cyclic);
- // simple passthroughs to cairo
- private native void cairoSave();
- private native void cairoRestore();
- private native void cairoSetMatrix(double[] m);
- private native void cairoSetOperator(int cairoOperator);
- private native void cairoSetRGBAColor(double red, double green,
- double blue, double alpha);
- private native void cairoSetFillRule(int cairoFillRule);
- private native void cairoSetLineWidth(double width);
- private native void cairoSetLineCap(int cairoLineCap);
- private native void cairoSetLineJoin(int cairoLineJoin);
- private native void cairoSetDash(double[] dashes, int ndash, double offset);
-
- private native void cairoSetMiterLimit(double limit);
- private native void cairoNewPath();
- private native void cairoMoveTo(double x, double y);
- private native void cairoLineTo(double x, double y);
- private native void cairoCurveTo(double x1, double y1, double x2, double y2,
- double x3, double y3);
- private native void cairoRelMoveTo(double dx, double dy);
- private native void cairoRelLineTo(double dx, double dy);
- private native void cairoRelCurveTo(double dx1, double dy1, double dx2,
- double dy2, double dx3, double dy3);
- private native void cairoRectangle(double x, double y, double width,
- double height);
- private native void cairoClosePath();
- private native void cairoStroke();
- private native void cairoFill();
- private native void cairoClip();
-
- /////////////////////////////////////////////
- ////// General Drawing Support Methods //////
- /////////////////////////////////////////////
-
- private class DrawState
- {
- private Paint paint;
- private Stroke stroke;
- private Color fg;
- private Color bg;
- private Shape clip;
- private AffineTransform transform;
- private Font font;
- private Composite comp;
-
- DrawState(GdkGraphics2D g)
- {
- this.paint = g.paint;
- this.stroke = g.stroke;
- this.fg = g.fg;
- this.bg = g.bg;
- this.clip = g.clip;
- if (g.transform != null)
- this.transform = (AffineTransform) g.transform.clone();
- this.font = g.font;
- this.comp = g.comp;
- }
-
- public void restore(GdkGraphics2D g)
- {
- g.paint = this.paint;
- g.stroke = this.stroke;
- g.fg = this.fg;
- g.bg = this.bg;
- g.clip = this.clip;
- g.transform = this.transform;
- g.font = this.font;
- g.comp = this.comp;
- }
- }
-
- private void stateSave()
- {
- stateStack.push(new DrawState(this));
- cairoSave();
- }
-
- private void stateRestore()
- {
- ((DrawState) (stateStack.pop())).restore(this);
- cairoRestore();
- }
-
- // Some operations (drawing rather than filling) require that their
- // coords be shifted to land on 0.5-pixel boundaries, in order to land on
- // "middle of pixel" coordinates and light up complete pixels.
- private boolean shiftDrawCalls = false;
-
- private double shifted(double coord, boolean doShift)
- {
- if (doShift)
- return Math.floor(coord) + 0.5;
- else
- return coord;
- }
+ private native void setTexturePixels(long pointer, int[] pixels, int w,
+ int h, int stride);
- private void walkPath(PathIterator p, boolean doShift)
- {
- double x = 0;
- double y = 0;
- double[] coords = new double[6];
-
- cairoSetFillRule(p.getWindingRule());
- for (; ! p.isDone(); p.next())
- {
- int seg = p.currentSegment(coords);
- switch (seg)
- {
- case PathIterator.SEG_MOVETO:
- x = shifted(coords[0], doShift);
- y = shifted(coords[1], doShift);
- cairoMoveTo(x, y);
- break;
- case PathIterator.SEG_LINETO:
- x = shifted(coords[0], doShift);
- y = shifted(coords[1], doShift);
- cairoLineTo(x, y);
- break;
- case PathIterator.SEG_QUADTO:
- // splitting a quadratic bezier into a cubic:
- // see: http://pfaedit.sourceforge.net/bezier.html
- double x1 = x + (2.0 / 3.0) * (shifted(coords[0], doShift) - x);
- double y1 = y + (2.0 / 3.0) * (shifted(coords[1], doShift) - y);
-
- double x2 = x1 + (1.0 / 3.0) * (shifted(coords[2], doShift) - x);
- double y2 = y1 + (1.0 / 3.0) * (shifted(coords[3], doShift) - y);
-
- x = shifted(coords[2], doShift);
- y = shifted(coords[3], doShift);
- cairoCurveTo(x1, y1, x2, y2, x, y);
- break;
- case PathIterator.SEG_CUBICTO:
- x = shifted(coords[4], doShift);
- y = shifted(coords[5], doShift);
- cairoCurveTo(shifted(coords[0], doShift),
- shifted(coords[1], doShift),
- shifted(coords[2], doShift),
- shifted(coords[3], doShift), x, y);
- break;
- case PathIterator.SEG_CLOSE:
- cairoClosePath();
- break;
- }
- }
- }
-
- private Map getDefaultHints()
- {
- HashMap defaultHints = new HashMap();
-
- defaultHints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
- RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
-
- defaultHints.put(RenderingHints.KEY_STROKE_CONTROL,
- RenderingHints.VALUE_STROKE_DEFAULT);
-
- defaultHints.put(RenderingHints.KEY_FRACTIONALMETRICS,
- RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
-
- defaultHints.put(RenderingHints.KEY_ANTIALIASING,
- RenderingHints.VALUE_ANTIALIAS_OFF);
-
- defaultHints.put(RenderingHints.KEY_RENDERING,
- RenderingHints.VALUE_RENDER_DEFAULT);
-
- return defaultHints;
- }
-
- public static int[] findSimpleIntegerArray (ColorModel cm, Raster raster)
- {
- if (cm == null || raster == null)
- return null;
-
- if (! cm.getColorSpace().isCS_sRGB())
- return null;
-
- if (! (cm instanceof DirectColorModel))
- return null;
-
- DirectColorModel dcm = (DirectColorModel) cm;
-
- if (dcm.getRedMask() != 0x00FF0000 || dcm.getGreenMask() != 0x0000FF00
- || dcm.getBlueMask() != 0x000000FF)
- return null;
-
- if (! (raster instanceof WritableRaster))
- return null;
-
- if (raster.getSampleModel().getDataType() != DataBuffer.TYPE_INT)
- return null;
-
- if (! (raster.getDataBuffer() instanceof DataBufferInt))
- return null;
-
- DataBufferInt db = (DataBufferInt) raster.getDataBuffer();
-
- if (db.getNumBanks() != 1)
- return null;
-
- // Finally, we have determined that this is a single bank, [A]RGB-int
- // buffer in sRGB space. It's worth checking all this, because it means
- // that cairo can paint directly into the data buffer, which is very
- // fast compared to all the normal copying and converting.
-
- return db.getData();
- }
+ /**
+ * Set the current transform matrix
+ */
+ private native void cairoSetMatrix(long pointer, double[] m);
- private void updateBufferedImage()
- {
- if (bimage != null && pixelConversionRequired)
- {
- int height = bimage.getHeight();
- int width = bimage.getWidth();
- int index = 0;
- for (int y = 0; y < height; ++y)
- for (int x = 0; x < width; ++x)
- bimage.setRGB(x, y, pixelBuffer[index++]);
- }
- }
+ /**
+ * Set the compositing operator
+ */
+ private native void cairoSetOperator(long pointer, int cairoOperator);
- private boolean drawImage(Image img, AffineTransform xform,
- Color bgcolor, ImageObserver obs)
- {
- if (img == null)
- return false;
+ /**
+ * Sets the current color in RGBA as a 0.0-1.0 double
+ */
+ private native void cairoSetRGBAColor(long pointer, double red, double green,
+ double blue, double alpha);
- // FIXME: I'll fix this, /Sven
-// if (img instanceof GtkOffScreenImage
-// && img.getGraphics() instanceof GdkGraphics2D
-// && (xform == null || xform.getType() == AffineTransform.TYPE_IDENTITY
-// || xform.getType() == AffineTransform.TYPE_TRANSLATION))
-// {
-// // we are being asked to flush a double buffer from Gdk
-// GdkGraphics2D g2 = (GdkGraphics2D) img.getGraphics();
-// gdkDrawDrawable(g2, (int) xform.getTranslateX(),
-// (int) xform.getTranslateY());
-
-// updateBufferedImage();
-
-// return true;
-// }
-// else
- {
- // In this case, xform is an AffineTransform that transforms bounding
- // box of the specified image from image space to user space. However
- // when we pass this transform to cairo, cairo will use this transform
- // to map "user coordinates" to "pixel" coordinates, which is the
- // other way around. Therefore to get the "user -> pixel" transform
- // that cairo wants from "image -> user" transform that we currently
- // have, we will need to invert the transformation matrix.
- AffineTransform invertedXform = new AffineTransform();
+ /**
+ * Sets the current winding rule in Cairo
+ */
+ private native void cairoSetFillRule(long pointer, int cairoFillRule);
- try
- {
- invertedXform = xform.createInverse();
- if (img instanceof BufferedImage)
- {
- // draw an image which has actually been loaded
- // into memory fully
- BufferedImage b = (BufferedImage) img;
- return drawRaster(b.getColorModel(), b.getTile(0, 0),
- invertedXform, bgcolor);
- }
- else
- return this.drawImage(GdkPixbufDecoder.createBufferedImage(img
- .getSource()),
- xform, bgcolor, obs);
- }
- catch (NoninvertibleTransformException e)
- {
- throw new ImagingOpException("Unable to invert transform "
- + xform.toString());
- }
- }
- }
+ /**
+ * Set the line style, cap, join and miter limit.
+ * Cap and join parameters are in the BasicStroke enumerations.
+ */
+ private native void cairoSetLine(long pointer, double width, int cap,
+ int join, double miterLimit);
- //////////////////////////////////////////////////
- ////// Implementation of Graphics2D Methods //////
- //////////////////////////////////////////////////
+ /**
+ * Set the dash style
+ */
+ private native void cairoSetDash(long pointer, double[] dashes, int ndash,
+ double offset);
- public void draw(Shape s)
- {
- if (stroke != null && ! (stroke instanceof BasicStroke))
- {
- fill(stroke.createStrokedShape(s));
- return;
- }
+ /*
+ * Draws a Glyph Vector
+ */
+ native void cairoDrawGlyphVector(long pointer, GdkFontPeer font,
+ float x, float y, int n,
+ int[] codes, float[] positions);
- cairoNewPath();
- if (s instanceof Rectangle2D)
- {
- Rectangle2D r = (Rectangle2D) s;
- cairoRectangle(shifted(r.getX(), shiftDrawCalls),
- shifted(r.getY(), shiftDrawCalls), r.getWidth(),
- r.getHeight());
- }
- else
- walkPath(s.getPathIterator(null), shiftDrawCalls);
- cairoStroke();
+ private native void cairoRelCurveTo(long pointer, double dx1, double dy1,
+ double dx2, double dy2, double dx3,
+ double dy3);
- updateBufferedImage();
- }
+ /**
+ * Appends a rectangle to the current path
+ */
+ private native void cairoRectangle(long pointer, double x, double y,
+ double width, double height);
- public void fill(Shape s)
- {
- cairoNewPath();
- if (s instanceof Rectangle2D)
- {
- Rectangle2D r = (Rectangle2D) s;
- cairoRectangle(r.getX(), r.getY(), r.getWidth(), r.getHeight());
- }
- else
- walkPath(s.getPathIterator(null), false);
+ /**
+ * New current path
+ */
+ private native void cairoNewPath(long pointer);
- cairoFill();
+ /**
+ * Close current path
+ */
+ private native void cairoClosePath(long pointer);
- updateBufferedImage();
- }
+ /** moveTo */
+ private native void cairoMoveTo(long pointer, double x, double y);
- public void clip(Shape s)
- {
- // update it
- if (clip == null || s == null)
- clip = s;
- else if (s instanceof Rectangle2D && clip instanceof Rectangle2D)
- {
- Rectangle2D r = (Rectangle2D) s;
- Rectangle2D curr = (Rectangle2D) clip;
- clip = curr.createIntersection(r);
- }
- else
- throw new UnsupportedOperationException();
+ /** relative moveTo */
+ private native void cairoRelMoveTo(long pointer, double dx, double dy);
- // draw it
- if (clip != null)
- {
- cairoNewPath();
- if (clip instanceof Rectangle2D)
- {
- Rectangle2D r = (Rectangle2D) clip;
- cairoRectangle(r.getX(), r.getY(), r.getWidth(), r.getHeight());
- }
- else
- walkPath(clip.getPathIterator(null), false);
+ /** lineTo */
+ private native void cairoLineTo(long pointer, double x, double y);
- // cairoClosePath ();
- cairoClip();
- }
- }
+ /** relative lineTo */
+ private native void cairoRelLineTo(long pointer, double dx, double dy);
- public Paint getPaint()
- {
- return paint;
- }
+ /** Cubic curve-to */
+ private native void cairoCurveTo(long pointer, double x1, double y1,
+ double x2, double y2,
+ double x3, double y3);
- public AffineTransform getTransform()
- {
- return (AffineTransform) transform.clone();
- }
+ /**
+ * Stroke current path
+ */
+ private native void cairoStroke(long pointer);
- public void setPaint(Paint p)
- {
- if (paint == null)
- return;
+ /**
+ * Fill current path
+ */
+ private native void cairoFill(long pointer);
- paint = p;
- if (paint instanceof Color)
- {
- setColor((Color) paint);
- }
- else if (paint instanceof TexturePaint)
- {
- TexturePaint tp = (TexturePaint) paint;
- BufferedImage img = tp.getImage();
+ /**
+ * Clip current path
+ */
+ private native void cairoClip(long pointer);
- // map the image to the anchor rectangle
- int width = (int) tp.getAnchorRect().getWidth();
- int height = (int) tp.getAnchorRect().getHeight();
+ /**
+ * Save clip
+ */
+ private native void cairoPreserveClip(long pointer);
- double scaleX = width / (double) img.getWidth();
- double scaleY = width / (double) img.getHeight();
+ /**
+ * Save clip
+ */
+ private native void cairoResetClip(long pointer);
- AffineTransform at = new AffineTransform(scaleX, 0, 0, scaleY, 0, 0);
- AffineTransformOp op = new AffineTransformOp(at, getRenderingHints());
- BufferedImage texture = op.filter(img, null);
- int[] pixels = texture.getRGB(0, 0, width, height, null, 0, width);
- setTexturePixels(pixels, width, height, width);
- }
- else if (paint instanceof GradientPaint)
- {
- GradientPaint gp = (GradientPaint) paint;
- Point2D p1 = gp.getPoint1();
- Point2D p2 = gp.getPoint2();
- Color c1 = gp.getColor1();
- Color c2 = gp.getColor2();
- setGradient(p1.getX(), p1.getY(), p2.getX(), p2.getY(), c1.getRed(),
- c1.getGreen(), c1.getBlue(), c1.getAlpha(), c2.getRed(),
- c2.getGreen(), c2.getBlue(), c2.getAlpha(), gp.isCyclic());
- }
- else
- throw new java.lang.UnsupportedOperationException();
- }
+ /**
+ * Set interpolation types
+ */
+ private native void cairoSurfaceSetFilter(long pointer, int filter);
+ ///////////////////////// TRANSFORMS ///////////////////////////////////
+ /**
+ * Set the current transform
+ */
public void setTransform(AffineTransform tx)
{
transform = tx;
@@ -700,10 +439,10 @@ public class GdkGraphics2D extends Graphics2D
{
double[] m = new double[6];
transform.getMatrix(m);
- cairoSetMatrix(m);
+ cairoSetMatrix(nativePointer, m);
}
}
-
+
public void transform(AffineTransform tx)
{
if (transform == null)
@@ -717,10 +456,10 @@ public class GdkGraphics2D extends Graphics2D
// rather than degrade to bounds.
Rectangle2D r = clip.getBounds2D();
double[] coords = new double[]
- {
- r.getX(), r.getY(), r.getX() + r.getWidth(),
- r.getY() + r.getHeight()
- };
+ {
+ r.getX(), r.getY(), r.getX() + r.getWidth(),
+ r.getY() + r.getHeight()
+ };
try
{
tx.createInverse().transform(coords, 0, coords, 0, 2);
@@ -748,14 +487,13 @@ public class GdkGraphics2D extends Graphics2D
{
transform(AffineTransform.getScaleInstance(sx, sy));
}
-
+
/**
* Translate the system of the co-ordinates. As translation is a frequent
* operation, it is done in an optimised way, unlike scaling and rotating.
*/
public void translate(double tx, double ty)
{
- // 200 -> 140
if (transform != null)
transform.translate(tx, ty);
else
@@ -778,7 +516,7 @@ public class GdkGraphics2D extends Graphics2D
setTransform(transform);
}
-
+
public void translate(int x, int y)
{
translate((double) x, (double) y);
@@ -789,6 +527,102 @@ public class GdkGraphics2D extends Graphics2D
transform(AffineTransform.getShearInstance(shearX, shearY));
}
+ ///////////////////////// DRAWING STATE ///////////////////////////////////
+
+ public void clip(Shape s)
+ {
+ // Do not touch clip when s == null.
+ if (s == null)
+ return;
+
+ // If the current clip is still null, initialize it.
+ if (clip == null)
+ clip = originalClip;
+
+ // This is so common, let's optimize this.
+ if (clip instanceof Rectangle2D && s instanceof Rectangle2D)
+ {
+ Rectangle2D clipRect = (Rectangle2D) clip;
+ Rectangle2D r = (Rectangle2D) s;
+ Rectangle2D.intersect(clipRect, r, clipRect);
+ // Call setClip so that subclasses get notified.
+ setClip(clipRect);
+ }
+ else
+ {
+ Area current;
+ if (clip instanceof Area)
+ current = (Area) clip;
+ else
+ current = new Area(clip);
+
+ Area intersect;
+ if (s instanceof Area)
+ intersect = (Area) s;
+ else
+ intersect = new Area(s);
+
+ current.intersect(intersect);
+ clip = current;
+ // Call setClip so that the native side gets notified.
+ setClip(clip);
+ }
+ }
+
+ public Paint getPaint()
+ {
+ return paint;
+ }
+
+ public AffineTransform getTransform()
+ {
+ return (AffineTransform) transform.clone();
+ }
+
+ public void setPaint(Paint p)
+ {
+ if (paint == null)
+ return;
+
+ paint = p;
+ if (paint instanceof Color)
+ {
+ setColor((Color) paint);
+ }
+ else if (paint instanceof TexturePaint)
+ {
+ TexturePaint tp = (TexturePaint) paint;
+ BufferedImage img = tp.getImage();
+
+ // map the image to the anchor rectangle
+ int width = (int) tp.getAnchorRect().getWidth();
+ int height = (int) tp.getAnchorRect().getHeight();
+
+ double scaleX = (width+1) / (double) img.getWidth();
+ double scaleY = (height+1) / (double) img.getHeight();
+
+ AffineTransform at = new AffineTransform(scaleX, 0, 0, scaleY, 0, 0);
+ AffineTransformOp op = new AffineTransformOp(at, getRenderingHints());
+ BufferedImage texture = op.filter(img, null);
+ int[] pixels = texture.getRGB(0, 0, width, height, null, 0, width);
+ setTexturePixels(nativePointer, pixels, width, height, width);
+ }
+ else if (paint instanceof GradientPaint)
+ {
+ GradientPaint gp = (GradientPaint) paint;
+ Point2D p1 = gp.getPoint1();
+ Point2D p2 = gp.getPoint2();
+ Color c1 = gp.getColor1();
+ Color c2 = gp.getColor2();
+ setGradient(nativePointer, p1.getX(), p1.getY(), p2.getX(), p2.getY(),
+ c1.getRed(), c1.getGreen(), c1.getBlue(), c1.getAlpha(),
+ c2.getRed(), c2.getGreen(), c2.getBlue(), c2.getAlpha(),
+ gp.isCyclic());
+ }
+ else
+ throw new java.lang.UnsupportedOperationException();
+ }
+
public Stroke getStroke()
{
return stroke;
@@ -800,28 +634,23 @@ public class GdkGraphics2D extends Graphics2D
if (stroke instanceof BasicStroke)
{
BasicStroke bs = (BasicStroke) stroke;
- cairoSetLineCap(bs.getEndCap());
- cairoSetLineWidth(bs.getLineWidth());
- cairoSetLineJoin(bs.getLineJoin());
- cairoSetMiterLimit(bs.getMiterLimit());
+ cairoSetLine(nativePointer, bs.getLineWidth(), bs.getEndCap(),
+ bs.getLineJoin(), bs.getMiterLimit());
+
float[] dashes = bs.getDashArray();
if (dashes != null)
{
double[] double_dashes = new double[dashes.length];
for (int i = 0; i < dashes.length; i++)
double_dashes[i] = dashes[i];
- cairoSetDash(double_dashes, double_dashes.length,
+ cairoSetDash(nativePointer, double_dashes, double_dashes.length,
(double) bs.getDashPhase());
}
else
- cairoSetDash(new double[0], 0, 0.0);
+ cairoSetDash(nativePointer, new double[0], 0, 0.0);
}
}
- ////////////////////////////////////////////////
- ////// Implementation of Graphics Methods //////
- ////////////////////////////////////////////////
-
public void setPaintMode()
{
setComposite(AlphaComposite.SrcOver);
@@ -836,14 +665,22 @@ public class GdkGraphics2D extends Graphics2D
{
if (c == null)
c = Color.BLACK;
-
- if (c.equals(fg))
- return;
fg = c;
paint = c;
- cairoSetRGBAColor(fg.getRed() / 255.0, fg.getGreen() / 255.0,
- fg.getBlue() / 255.0, fg.getAlpha() / 255.0);
+ updateColor();
+ }
+
+ /**
+ * Set the current fg value as the cairo color.
+ */
+ void updateColor()
+ {
+ if (fg == null)
+ fg = Color.BLACK;
+ cairoSetRGBAColor(nativePointer, fg.getRed() / 255.0,
+ fg.getGreen() / 255.0,fg.getBlue() / 255.0,
+ fg.getAlpha() / 255.0);
}
public Color getColor()
@@ -894,81 +731,41 @@ public class GdkGraphics2D extends Graphics2D
public void setClip(int x, int y, int width, int height)
{
- setClip(new Rectangle2D.Double((double) x, (double) y, (double) width,
- (double) height));
+ if( width < 0 || height < 0 )
+ return;
+
+ setClip(new Rectangle2D.Double(x, y, width, height));
}
public void setClip(Shape s)
- {
- clip = s;
- if (clip == null)
+ {
+ // The first time the clip is set, save it as the original clip
+ // to reset to on s == null. We can rely on this being non-null
+ // because the constructor in subclasses is expected to set the
+ // initial clip properly.
+ if( firstClip )
{
- // Reset clipping.
- if (component != null)
- {
- Dimension d = component.awtComponent.getSize();
- setClip(0, 0, d.width, d.height);
- }
+ originalClip = s;
+ firstClip = false;
}
+
+ if (s == null)
+ clip = originalClip;
else
- {
- cairoNewPath();
- if (s instanceof Rectangle2D)
- {
- Rectangle2D r = (Rectangle2D) s;
- cairoRectangle(r.getX(), r.getY(), r.getWidth(), r.getHeight());
- }
- else
- walkPath(s.getPathIterator(null), false);
+ clip = s;
+ cairoResetClip(nativePointer);
- // cairoClosePath ();
- cairoClip();
+ cairoNewPath(nativePointer);
+ if (clip instanceof Rectangle2D)
+ {
+ Rectangle2D r = (Rectangle2D) clip;
+ cairoRectangle(nativePointer, r.getX(), r.getY(), r.getWidth(),
+ r.getHeight());
}
- }
-
- private static BasicStroke draw3DRectStroke = new BasicStroke();
-
- public void draw3DRect(int x, int y, int width, int height, boolean raised)
- {
- Stroke tmp = stroke;
- setStroke(draw3DRectStroke);
- super.draw3DRect(x, y, width, height, raised);
- setStroke(tmp);
- updateBufferedImage();
- }
-
- public void fill3DRect(int x, int y, int width, int height, boolean raised)
- {
- Stroke tmp = stroke;
- setStroke(draw3DRectStroke);
- super.fill3DRect(x, y, width, height, raised);
- setStroke(tmp);
- updateBufferedImage();
- }
-
- public void drawRect(int x, int y, int width, int height)
- {
- draw(new Rectangle(x, y, width, height));
- }
-
- public void fillRect(int x, int y, int width, int height)
- {
- cairoNewPath();
- cairoRectangle(x, y, width, height);
- cairoFill();
- }
-
- public void clearRect(int x, int y, int width, int height)
- {
- if (bg != null)
- cairoSetRGBAColor(bg.getRed() / 255.0, bg.getGreen() / 255.0,
- bg.getBlue() / 255.0, 1.0);
- cairoNewPath();
- cairoRectangle(x, y, width, height);
- cairoFill();
- setColor(fg);
-
- updateBufferedImage();
+ else
+ walkPath(clip.getPathIterator(null), false);
+
+ cairoClip(nativePointer);
}
public void setBackground(Color c)
@@ -983,196 +780,228 @@ public class GdkGraphics2D extends Graphics2D
return bg;
}
- private void doPolygon(int[] xPoints, int[] yPoints, int nPoints,
- boolean close, boolean fill)
+ /**
+ * Return the current composite.
+ */
+ public Composite getComposite()
{
- if (nPoints < 1)
- return;
- GeneralPath gp = new GeneralPath(PathIterator.WIND_EVEN_ODD);
- gp.moveTo((float) xPoints[0], (float) yPoints[0]);
- for (int i = 1; i < nPoints; i++)
- gp.lineTo((float) xPoints[i], (float) yPoints[i]);
+ if (comp == null)
+ return AlphaComposite.SrcOver;
+ else
+ return comp;
+ }
- if (close)
- gp.closePath();
+ /**
+ * Sets the current composite context.
+ */
+ public void setComposite(Composite comp)
+ {
+ this.comp = comp;
- Shape sh = gp;
- if (fill == false && stroke != null && ! (stroke instanceof BasicStroke))
+ if (comp instanceof AlphaComposite)
{
- sh = stroke.createStrokedShape(gp);
- fill = true;
+ AlphaComposite a = (AlphaComposite) comp;
+ cairoSetOperator(nativePointer, a.getRule());
+ Color c = getColor();
+ setColor(new Color(c.getRed(), c.getGreen(), c.getBlue(),
+ (int) (a.getAlpha() * ((float) c.getAlpha()))));
}
-
- if (fill)
- fill(sh);
else
- draw(sh);
+ {
+ // FIXME: implement general Composite support
+ throw new java.lang.UnsupportedOperationException();
+ }
}
- public void drawLine(int x1, int y1, int x2, int y2)
+ ///////////////////////// DRAWING PRIMITIVES ///////////////////////////////////
+
+ public void draw(Shape s)
{
- int[] xp = new int[2];
- int[] yp = new int[2];
+ if (stroke != null && ! (stroke instanceof BasicStroke))
+ {
+ fill(stroke.createStrokedShape(s));
+ return;
+ }
- xp[0] = x1;
- xp[1] = x2;
- yp[0] = y1;
- yp[1] = y2;
+ cairoNewPath(nativePointer);
- doPolygon(xp, yp, 2, false, false);
+ if (s instanceof Rectangle2D)
+ {
+ Rectangle2D r = (Rectangle2D) s;
+ cairoRectangle(nativePointer, shifted(r.getX(), shiftDrawCalls),
+ shifted(r.getY(), shiftDrawCalls), r.getWidth(),
+ r.getHeight());
+ }
+ else
+ walkPath(s.getPathIterator(null), shiftDrawCalls);
+ cairoStroke(nativePointer);
}
- public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)
+ public void fill(Shape s)
{
- doPolygon(xPoints, yPoints, nPoints, true, true);
+ cairoNewPath(nativePointer);
+ if (s instanceof Rectangle2D)
+ {
+ Rectangle2D r = (Rectangle2D) s;
+ cairoRectangle(nativePointer, r.getX(), r.getY(), r.getWidth(),
+ r.getHeight());
+ }
+ else
+ walkPath(s.getPathIterator(null), false);
+
+ cairoFill(nativePointer);
}
- public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
+ /**
+ * Note that the rest of the drawing methods go via fill() or draw() for the drawing,
+ * although subclasses may with to overload these methods where context-specific
+ * optimizations are possible (e.g. bitmaps and fillRect(int, int, int, int)
+ */
+
+ public void clearRect(int x, int y, int width, int height)
{
- doPolygon(xPoints, yPoints, nPoints, true, false);
+ if (bg != null)
+ cairoSetRGBAColor(nativePointer, bg.getRed() / 255.0,
+ bg.getGreen() / 255.0, bg.getBlue() / 255.0, 1.0);
+ fillRect(x, y, width, height);
+ updateColor();
}
- public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)
+ public void draw3DRect(int x, int y, int width, int height, boolean raised)
{
- doPolygon(xPoints, yPoints, nPoints, false, false);
+ Stroke tmp = stroke;
+ setStroke(draw3DRectStroke);
+ super.draw3DRect(x, y, width, height, raised);
+ setStroke(tmp);
}
- private boolean drawRaster(ColorModel cm, Raster r,
- AffineTransform imageToUser, Color bgcolor)
+ public void drawArc(int x, int y, int width, int height, int startAngle,
+ int arcAngle)
{
- if (r == null)
- return false;
-
- SampleModel sm = r.getSampleModel();
- DataBuffer db = r.getDataBuffer();
-
- if (db == null || sm == null)
- return false;
-
- if (cm == null)
- cm = ColorModel.getRGBdefault();
-
- double[] i2u = new double[6];
- if (imageToUser != null)
- imageToUser.getMatrix(i2u);
- else
- {
- i2u[0] = 1;
- i2u[1] = 0;
- i2u[2] = 0;
- i2u[3] = 1;
- i2u[4] = 0;
- i2u[5] = 0;
- }
-
- int[] pixels = findSimpleIntegerArray(cm, r);
-
- if (pixels == null)
- {
- // FIXME: I don't think this code will work correctly with a non-RGB
- // MultiPixelPackedSampleModel. Although this entire method should
- // probably be rewritten to better utilize Cairo's different supported
- // data formats.
- if (sm instanceof MultiPixelPackedSampleModel)
- {
- pixels = r.getPixels(0, 0, r.getWidth(), r.getHeight(), pixels);
- for (int i = 0; i < pixels.length; i++)
- pixels[i] = cm.getRGB(pixels[i]);
- }
- else
- {
- pixels = new int[r.getWidth() * r.getHeight()];
- for (int i = 0; i < pixels.length; i++)
- pixels[i] = cm.getRGB(db.getElem(i));
- }
- }
-
- // Change all transparent pixels in the image to the specified bgcolor,
- // or (if there's no alpha) fill in an alpha channel so that it paints
- // correctly.
- if (cm.hasAlpha())
- {
- if (bgcolor != null && cm.hasAlpha())
- for (int i = 0; i < pixels.length; i++)
- {
- if (cm.getAlpha(pixels[i]) == 0)
- pixels[i] = bgcolor.getRGB();
- }
- }
- else
- for (int i = 0; i < pixels.length; i++)
- pixels[i] |= 0xFF000000;
+ draw(new Arc2D.Double((double) x, (double) y, (double) width,
+ (double) height, (double) startAngle,
+ (double) arcAngle, Arc2D.OPEN));
+ }
- drawPixels(pixels, r.getWidth(), r.getHeight(), r.getWidth(), i2u);
+ public void drawLine(int x1, int y1, int x2, int y2)
+ {
+ draw(new Line2D.Double(x1, y1, x2, y2));
+ }
- updateBufferedImage();
-
- // Cairo seems loosing the current color.
- setColor(fg);
-
- return true;
+ public void drawRect(int x, int y, int width, int height)
+ {
+ draw(new Rectangle(x, y, width, height));
}
- public void drawRenderedImage(RenderedImage image, AffineTransform xform)
+ public void fillArc(int x, int y, int width, int height, int startAngle,
+ int arcAngle)
{
- drawRaster(image.getColorModel(), image.getData(), xform, bg);
+ fill(new Arc2D.Double((double) x, (double) y, (double) width,
+ (double) height, (double) startAngle,
+ (double) arcAngle, Arc2D.OPEN));
}
- public void drawRenderableImage(RenderableImage image, AffineTransform xform)
+ public void fillRect(int x, int y, int width, int height)
{
- drawRenderedImage(image.createRendering(new RenderContext(xform)), xform);
+ fill(new Rectangle(x, y, width, height));
}
- public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs)
+ public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)
{
- return drawImage(img, xform, bg, obs);
+ fill(new Polygon(xPoints, yPoints, nPoints));
}
- public void drawImage(BufferedImage image, BufferedImageOp op, int x, int y)
+ public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
{
- Image filtered = op.filter(image, null);
- drawImage(filtered, new AffineTransform(1f, 0f, 0f, 1f, x, y), bg, null);
+ draw(new Polygon(xPoints, yPoints, nPoints));
}
- public boolean drawImage(Image img, int x, int y, ImageObserver observer)
+ public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)
{
- return drawImage(img, new AffineTransform(1f, 0f, 0f, 1f, x, y), bg,
- observer);
+ draw(new Polygon(xPoints, yPoints, nPoints));
}
- ///////////////////////////////////////////////
- ////// Unimplemented Stubs and Overloads //////
- ///////////////////////////////////////////////
+ public void drawOval(int x, int y, int width, int height)
+ {
+ drawArc(x, y, width, height, 0, 360);
+ }
- public boolean hit(Rectangle rect, Shape text, boolean onStroke)
+ public void drawRoundRect(int x, int y, int width, int height, int arcWidth,
+ int arcHeight)
{
- throw new java.lang.UnsupportedOperationException();
+ draw(new RoundRectangle2D.Double(x, y, width, height, arcWidth, arcHeight));
}
- public GraphicsConfiguration getDeviceConfiguration()
+ public void fillOval(int x, int y, int width, int height)
{
- throw new java.lang.UnsupportedOperationException();
+ fillArc(x, y, width, height, 0, 360);
}
- public void setComposite(Composite comp)
+ public void fillRoundRect(int x, int y, int width, int height, int arcWidth,
+ int arcHeight)
{
- this.comp = comp;
+ fill(new RoundRectangle2D.Double(x, y, width, height, arcWidth, arcHeight));
+ }
- if (comp instanceof AlphaComposite)
+ /**
+ * CopyArea - performs clipping to the native surface as a convenience
+ * (requires getRealBounds). Then calls copyAreaImpl.
+ */
+ public void copyArea(int ox, int oy, int owidth, int oheight,
+ int odx, int ody)
+ {
+ Point2D pos = transform.transform(new Point2D.Double(ox, oy),
+ (Point2D) null);
+ Point2D dim = transform.transform(new Point2D.Double(ox + owidth,
+ oy + oheight),
+ (Point2D) null);
+ Point2D p2 = transform.transform(new Point2D.Double(ox + odx, oy + ody),
+ (Point2D) null);
+ int x = (int)pos.getX();
+ int y = (int)pos.getY();
+ int width = (int)(dim.getX() - pos.getX());
+ int height = (int)(dim.getY() - pos.getY());
+ int dx = (int)(p2.getX() - pos.getX());
+ int dy = (int)(p2.getY() - pos.getY());
+
+ Rectangle2D r = getRealBounds();
+
+ if( width < 0 || height < 0 )
+ return;
+ // Return if outside the surface
+ if( x + dx > r.getWidth() || y + dy > r.getHeight() )
+ return;
+
+ if( x + dx + width < r.getX() || y + dy + height < r.getY() )
+ return;
+
+ // Clip edges if necessary
+ if( x + dx < r.getX() ) // left
{
- AlphaComposite a = (AlphaComposite) comp;
- cairoSetOperator(a.getRule());
- Color c = getColor();
- setColor(new Color(c.getRed(), c.getGreen(), c.getBlue(),
- (int) (a.getAlpha() * ((float) c.getAlpha()))));
+ width = x + dx + width;
+ x = (int)r.getX() - dx;
}
- else
+
+ if( y + dy < r.getY() ) // top
{
- // FIXME: implement general Composite support
- throw new java.lang.UnsupportedOperationException();
+ height = y + dy + height;
+ y = (int)r.getY() - dy;
}
+
+ if( x + dx + width >= r.getWidth() ) // right
+ width = (int)r.getWidth() - dx - x;
+
+ if( y + dy + height >= r.getHeight() ) // bottom
+ height = (int)r.getHeight() - dy - y;
+
+ copyAreaImpl(x, y, width, height, dx, dy);
}
+ ///////////////////////// RENDERING HINTS ///////////////////////////////////
+
+ /**
+ * FIXME- support better
+ */
public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue)
{
hints.put(hintKey, hintValue);
@@ -1181,23 +1010,23 @@ public class GdkGraphics2D extends Graphics2D
|| hintKey.equals(RenderingHints.KEY_ALPHA_INTERPOLATION))
{
if (hintValue.equals(RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR))
- cairoSurfaceSetFilter(0);
+ cairoSurfaceSetFilter(nativePointer, 0);
else if (hintValue.equals(RenderingHints.VALUE_INTERPOLATION_BILINEAR))
- cairoSurfaceSetFilter(1);
+ cairoSurfaceSetFilter(nativePointer, 1);
else if (hintValue.equals(RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED))
- cairoSurfaceSetFilter(2);
+ cairoSurfaceSetFilter(nativePointer, 2);
else if (hintValue.equals(RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY))
- cairoSurfaceSetFilter(3);
+ cairoSurfaceSetFilter(nativePointer, 3);
else if (hintValue.equals(RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT))
- cairoSurfaceSetFilter(4);
+ cairoSurfaceSetFilter(nativePointer, 4);
}
shiftDrawCalls = hints.containsValue(RenderingHints.VALUE_STROKE_NORMALIZE)
- || hints.containsValue(RenderingHints.VALUE_STROKE_DEFAULT);
+ || hints.containsValue(RenderingHints.VALUE_STROKE_DEFAULT);
}
public Object getRenderingHint(RenderingHints.Key hintKey)
@@ -1213,26 +1042,26 @@ public class GdkGraphics2D extends Graphics2D
if (hints.containsKey(RenderingHints.KEY_INTERPOLATION))
{
if (hints.containsValue(RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR))
- cairoSurfaceSetFilter(0);
+ cairoSurfaceSetFilter(nativePointer, 0);
else if (hints.containsValue(RenderingHints.VALUE_INTERPOLATION_BILINEAR))
- cairoSurfaceSetFilter(1);
+ cairoSurfaceSetFilter(nativePointer, 1);
}
if (hints.containsKey(RenderingHints.KEY_ALPHA_INTERPOLATION))
{
if (hints.containsValue(RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED))
- cairoSurfaceSetFilter(2);
+ cairoSurfaceSetFilter(nativePointer, 2);
else if (hints.containsValue(RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY))
- cairoSurfaceSetFilter(3);
+ cairoSurfaceSetFilter(nativePointer, 3);
else if (hints.containsValue(RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT))
- cairoSurfaceSetFilter(4);
+ cairoSurfaceSetFilter(nativePointer, 4);
}
shiftDrawCalls = hints.containsValue(RenderingHints.VALUE_STROKE_NORMALIZE)
- || hints.containsValue(RenderingHints.VALUE_STROKE_DEFAULT);
+ || hints.containsValue(RenderingHints.VALUE_STROKE_DEFAULT);
}
public void addRenderingHints(Map hints)
@@ -1245,31 +1074,127 @@ public class GdkGraphics2D extends Graphics2D
return hints;
}
- public Composite getComposite()
+ ///////////////////////// IMAGE. METHODS ///////////////////////////////////
+
+ protected boolean drawImage(Image img, AffineTransform xform,
+ Color bgcolor, ImageObserver obs)
{
- if (comp == null)
- return AlphaComposite.SrcOver;
+ if (img == null)
+ return false;
+
+ // In this case, xform is an AffineTransform that transforms bounding
+ // box of the specified image from image space to user space. However
+ // when we pass this transform to cairo, cairo will use this transform
+ // to map "user coordinates" to "pixel" coordinates, which is the
+ // other way around. Therefore to get the "user -> pixel" transform
+ // that cairo wants from "image -> user" transform that we currently
+ // have, we will need to invert the transformation matrix.
+ AffineTransform invertedXform = new AffineTransform();
+
+ try
+ {
+ invertedXform = xform.createInverse();
+ }
+ catch (NoninvertibleTransformException e)
+ {
+ throw new ImagingOpException("Unable to invert transform "
+ + xform.toString());
+ }
+
+ // Unrecognized image - convert to a BufferedImage
+ if( !(img instanceof BufferedImage) )
+ {
+ ImageProducer source = img.getSource();
+ if (source == null)
+ return false;
+ img = Toolkit.getDefaultToolkit().createImage(source);
+ }
+
+ BufferedImage b = (BufferedImage) img;
+ DataBuffer db;
+ double[] i2u = new double[6];
+ int width = b.getWidth();
+ int height = b.getHeight();
+
+ // If this BufferedImage has a BufferedImageGraphics object,
+ // use the cached CairoSurface that BIG is drawing onto
+ if( BufferedImageGraphics.bufferedImages.get( b ) != null )
+ db = (DataBuffer)BufferedImageGraphics.bufferedImages.get( b );
else
- return comp;
+ db = b.getRaster().getDataBuffer();
+
+ invertedXform.getMatrix(i2u);
+
+ if(db instanceof CairoSurface)
+ {
+ ((CairoSurface)db).drawSurface(nativePointer, i2u);
+ return true;
+ }
+
+ if( bgcolor != null )
+ {
+ // Fill a rectangle with the background color
+ // to composite the image onto.
+ Paint oldPaint = paint;
+ AffineTransform oldTransform = transform;
+ setPaint( bgcolor );
+ setTransform( invertedXform );
+ fillRect(0, 0, width, height);
+ setTransform( oldTransform );
+ setPaint( oldPaint );
+ }
+
+ int[] pixels;
+
+ // Shortcut for easy color models.
+ if( b.getColorModel().equals(rgb32) )
+ {
+ pixels = ((DataBufferInt)db).getData();
+ for(int i = 0; i < pixels.length; i++)
+ pixels[i] |= 0xFF000000;
+ }
+ else if( b.getColorModel().equals(argb32) )
+ {
+ pixels = ((DataBufferInt)db).getData();
+ }
+ else
+ {
+ pixels = b.getRGB(0, 0, width, height,
+ null, 0, width);
+ }
+
+ drawPixels(nativePointer, pixels, width, height, width, i2u);
+
+ // Cairo seems to lose the current color which must be restored.
+ updateColor();
+ return true;
}
- public FontRenderContext getFontRenderContext()
+ public void drawRenderedImage(RenderedImage image, AffineTransform xform)
{
- return new FontRenderContext(transform, true, true);
+ drawRaster(image.getColorModel(), image.getData(), xform, null);
}
- public void copyArea(int x, int y, int width, int height, int dx, int dy)
+ public void drawRenderableImage(RenderableImage image, AffineTransform xform)
{
- GdkGraphics2D g = (GdkGraphics2D) create(x, y, width, height);
- gdkDrawDrawable(g, x + dx, y + dy);
+ drawRenderedImage(image.createRendering(new RenderContext(xform)), xform);
}
- public void drawArc(int x, int y, int width, int height, int startAngle,
- int arcAngle)
+ public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs)
{
- draw(new Arc2D.Double((double) x, (double) y, (double) width,
- (double) height, (double) startAngle,
- (double) arcAngle, Arc2D.OPEN));
+ return drawImage(img, xform, null, obs);
+ }
+
+ public void drawImage(BufferedImage image, BufferedImageOp op, int x, int y)
+ {
+ Image filtered = op.filter(image, null);
+ drawImage(filtered, new AffineTransform(1f, 0f, 0f, 1f, x, y), null, null);
+ }
+
+ public boolean drawImage(Image img, int x, int y, ImageObserver observer)
+ {
+ return drawImage(img, new AffineTransform(1f, 0f, 0f, 1f, x, y), null,
+ observer);
}
public boolean drawImage(Image img, int x, int y, Color bgcolor,
@@ -1284,6 +1209,8 @@ public class GdkGraphics2D extends Graphics2D
{
double scaleX = width / (double) img.getWidth(observer);
double scaleY = height / (double) img.getHeight(observer);
+ if( scaleX == 0 || scaleY == 0 )
+ return true;
return drawImage(img, new AffineTransform(scaleX, 0f, 0f, scaleY, x, y),
bgcolor, observer);
@@ -1292,7 +1219,7 @@ public class GdkGraphics2D extends Graphics2D
public boolean drawImage(Image img, int x, int y, int width, int height,
ImageObserver observer)
{
- return drawImage(img, x, y, width, height, bg, observer);
+ return drawImage(img, x, y, width, height, null, observer);
}
public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2,
@@ -1302,109 +1229,58 @@ public class GdkGraphics2D extends Graphics2D
if (img == null)
return false;
- Image subImage;
-
int sourceWidth = sx2 - sx1;
int sourceHeight = sy2 - sy1;
int destWidth = dx2 - dx1;
int destHeight = dy2 - dy1;
+ if(destWidth == 0 || destHeight == 0 || sourceWidth == 0 ||
+ sourceHeight == 0)
+ return true;
+
double scaleX = destWidth / (double) sourceWidth;
double scaleY = destHeight / (double) sourceHeight;
- // Get the subimage of the source enclosed in the
- // rectangle specified by sx1, sy1, sx2, sy2
-
- if (img instanceof BufferedImage)
- {
- BufferedImage b = (BufferedImage) img;
- subImage = b.getSubimage(sx1, sy1, sx2, sy2);
- }
+ // FIXME: Avoid using an AT if possible here - it's at least twice as slow.
+
+ Shape oldClip = getClip();
+ int cx, cy, cw, ch;
+ if( dx1 < dx2 )
+ { cx = dx1; cw = dx2 - dx1; }
else
- {
- // FIXME: This code currently doesn't work. Null Pointer
- // exception is thrown in this case. This happens
- // because img.getSource() always returns null, since source gets
- // never initialized when it is created with the help of
- // createImage(int width, int height).
- CropImageFilter filter = new CropImageFilter(sx1, sx2, sx2, sy2);
- FilteredImageSource src = new FilteredImageSource(img.getSource(),
- filter);
-
- subImage = Toolkit.getDefaultToolkit().createImage(src);
- }
+ { cx = dx2; cw = dx1 - dx2; }
+ if( dy1 < dy2 )
+ { cy = dy1; ch = dy2 - dy1; }
+ else
+ { cy = dy2; ch = dy1 - dy2; }
+
+ setClip( cx, cy, cw, ch );
- return drawImage(subImage,
- new AffineTransform(scaleX, 0, 0, scaleY, dx1, dy1),
- bgcolor, observer);
+ AffineTransform tx = new AffineTransform();
+ tx.translate( dx1 - sx1*scaleX, dy1 - sy1*scaleY );
+ tx.scale( scaleX, scaleY );
+
+ boolean retval = drawImage(img, tx, bgcolor, observer);
+ setClip( oldClip );
+ return retval;
}
public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2,
int sx1, int sy1, int sx2, int sy2,
ImageObserver observer)
{
- return drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, bg, observer);
- }
-
- public void drawOval(int x, int y, int width, int height)
- {
- drawArc(x, y, width, height, 0, 360);
- }
-
- public void drawRoundRect(int x, int y, int width, int height, int arcWidth,
- int arcHeight)
- {
- if (arcWidth > width)
- arcWidth = width;
- if (arcHeight > height)
- arcHeight = height;
-
- int xx = x + width - arcWidth;
- int yy = y + height - arcHeight;
-
- drawArc(x, y, arcWidth, arcHeight, 90, 90);
- drawArc(xx, y, arcWidth, arcHeight, 0, 90);
- drawArc(xx, yy, arcWidth, arcHeight, 270, 90);
- drawArc(x, yy, arcWidth, arcHeight, 180, 90);
-
- int y1 = y + arcHeight / 2;
- int y2 = y + height - arcHeight / 2;
- drawLine(x, y1, x, y2);
- drawLine(x + width, y1, x + width, y2);
-
- int x1 = x + arcWidth / 2;
- int x2 = x + width - arcWidth / 2;
- drawLine(x1, y, x2, y);
- drawLine(x1, y + height, x2, y + height);
+ return drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null, observer);
}
- // these are the most accelerated painting paths
- native void cairoDrawGlyphVector(GdkFontPeer font,
- float x, float y, int n,
- int[] codes, float[] positions);
-
- native void cairoDrawGdkTextLayout(GdkTextLayout gl,
- float x, float y);
-
- GdkFontPeer getFontPeer()
- {
- return (GdkFontPeer) getFont().getPeer();
- }
-
- public void drawGdkTextLayout(GdkTextLayout gl, float x, float y)
- {
- cairoDrawGdkTextLayout (gl, x, y);
- updateBufferedImage ();
- }
+ ///////////////////////// TEXT METHODS ////////////////////////////////////
public void drawString(String str, float x, float y)
{
if (str == null || str.length() == 0)
return;
-
- drawGlyphVector(getFont().createGlyphVector(null, str), x, y);
- updateBufferedImage ();
+ (new TextLayout( str, getFont(), getFontRenderContext() )).
+ draw(this, x, y);
}
public void drawString(String str, int x, int y)
@@ -1419,13 +1295,22 @@ public class GdkGraphics2D extends Graphics2D
public void drawGlyphVector(GlyphVector gv, float x, float y)
{
- int n = gv.getNumGlyphs ();
- int[] codes = gv.getGlyphCodes (0, n, null);
- float[] positions = gv.getGlyphPositions (0, n, null);
-
- setFont (gv.getFont ());
- cairoDrawGlyphVector (getFontPeer(), x, y, n, codes, positions);
- updateBufferedImage ();
+ if (gv instanceof FreetypeGlyphVector)
+ {
+ int n = gv.getNumGlyphs ();
+ int[] codes = gv.getGlyphCodes (0, n, null);
+ float[] positions = gv.getGlyphPositions (0, n, null);
+
+ setFont (gv.getFont ());
+ cairoDrawGlyphVector(nativePointer, (GdkFontPeer)getFont().getPeer(),
+ x, y, n, codes, positions);
+ }
+ else
+ {
+ translate(x, y);
+ fill(gv.getOutline());
+ translate(-x, -y);
+ }
}
public void drawString(AttributedCharacterIterator ci, float x, float y)
@@ -1434,52 +1319,19 @@ public class GdkGraphics2D extends Graphics2D
drawGlyphVector(gv, x, y);
}
- public void fillArc(int x, int y, int width, int height, int startAngle,
- int arcAngle)
- {
- fill(new Arc2D.Double((double) x, (double) y, (double) width,
- (double) height, (double) startAngle,
- (double) arcAngle, Arc2D.OPEN));
- }
-
- public void fillOval(int x, int y, int width, int height)
- {
- fillArc(x, y, width, height, 0, 360);
- }
-
- public void fillRoundRect(int x, int y, int width, int height, int arcWidth,
- int arcHeight)
- {
- if (arcWidth > width)
- arcWidth = width;
- if (arcHeight > height)
- arcHeight = height;
-
- int xx = x + width - arcWidth;
- int yy = y + height - arcHeight;
-
- fillArc(x, y, arcWidth, arcHeight, 90, 90);
- fillArc(xx, y, arcWidth, arcHeight, 0, 90);
- fillArc(xx, yy, arcWidth, arcHeight, 270, 90);
- fillArc(x, yy, arcWidth, arcHeight, 180, 90);
-
- fillRect(x, y + arcHeight / 2, width, height - arcHeight + 1);
- fillRect(x + arcWidth / 2, y, width - arcWidth + 1, height);
- }
-
- public Font getFont()
+ /**
+ * Should perhaps be contexct dependent, but this is left for now as an
+ * overloadable default implementation.
+ */
+ public FontRenderContext getFontRenderContext()
{
- if (font == null)
- return new Font("SansSerif", Font.PLAIN, 12);
- return font;
+ return new FontRenderContext(transform, true, true);
}
// Until such time as pango is happy to talk directly to cairo, we
// actually need to redirect some calls from the GtkFontPeer and
// GtkFontMetrics into the drawing kit and ask cairo ourselves.
- static native void releasePeerGraphicsResource(GdkFontPeer f);
-
public FontMetrics getFontMetrics()
{
return getFontMetrics(getFont());
@@ -1507,6 +1359,27 @@ public class GdkGraphics2D extends Graphics2D
.getFont(f.getName(), f.getAttributes());
}
+ public Font getFont()
+ {
+ if (font == null)
+ return new Font("SansSerif", Font.PLAIN, 12);
+ return font;
+ }
+
+ /////////////////////// MISC. PUBLIC METHODS /////////////////////////////////
+
+ public boolean hit(Rectangle rect, Shape s, boolean onStroke)
+ {
+ if( onStroke )
+ {
+ Shape stroked = stroke.createStrokedShape( s );
+ return stroked.intersects( (double)rect.x, (double)rect.y,
+ (double)rect.width, (double)rect.height );
+ }
+ return s.intersects( (double)rect.x, (double)rect.y,
+ (double)rect.width, (double)rect.height );
+ }
+
public String toString()
{
return (getClass().getName()
@@ -1514,4 +1387,219 @@ public class GdkGraphics2D extends Graphics2D
+ ",color=" + fg.toString()
+ "]");
}
+
+ ///////////////////////// PRIVATE METHODS ///////////////////////////////////
+
+ /**
+ * All the drawImage() methods eventually get delegated here if the image
+ * is not a Cairo surface.
+ *
+ * @param bgcolor - if non-null draws the background color before
+ * drawing the image.
+ */
+ private boolean drawRaster(ColorModel cm, Raster r,
+ AffineTransform imageToUser, Color bgcolor)
+ {
+ if (r == null)
+ return false;
+
+ SampleModel sm = r.getSampleModel();
+ DataBuffer db = r.getDataBuffer();
+
+ if (db == null || sm == null)
+ return false;
+
+ if (cm == null)
+ cm = ColorModel.getRGBdefault();
+
+ double[] i2u = new double[6];
+ if (imageToUser != null)
+ imageToUser.getMatrix(i2u);
+ else
+ {
+ i2u[0] = 1;
+ i2u[1] = 0;
+ i2u[2] = 0;
+ i2u[3] = 1;
+ i2u[4] = 0;
+ i2u[5] = 0;
+ }
+
+ int[] pixels = findSimpleIntegerArray(cm, r);
+
+ if (pixels == null)
+ {
+ // FIXME: I don't think this code will work correctly with a non-RGB
+ // MultiPixelPackedSampleModel. Although this entire method should
+ // probably be rewritten to better utilize Cairo's different supported
+ // data formats.
+ if (sm instanceof MultiPixelPackedSampleModel)
+ {
+ pixels = r.getPixels(0, 0, r.getWidth(), r.getHeight(), pixels);
+ for (int i = 0; i < pixels.length; i++)
+ pixels[i] = cm.getRGB(pixels[i]);
+ }
+ else
+ {
+ pixels = new int[r.getWidth() * r.getHeight()];
+ for (int i = 0; i < pixels.length; i++)
+ pixels[i] = cm.getRGB(db.getElem(i));
+ }
+ }
+
+ // Change all transparent pixels in the image to the specified bgcolor,
+ // or (if there's no alpha) fill in an alpha channel so that it paints
+ // correctly.
+ if (cm.hasAlpha())
+ {
+ if (bgcolor != null && cm.hasAlpha())
+ for (int i = 0; i < pixels.length; i++)
+ {
+ if (cm.getAlpha(pixels[i]) == 0)
+ pixels[i] = bgcolor.getRGB();
+ }
+ }
+ else
+ for (int i = 0; i < pixels.length; i++)
+ pixels[i] |= 0xFF000000;
+
+ drawPixels(nativePointer, pixels, r.getWidth(), r.getHeight(),
+ r.getWidth(), i2u);
+
+ // Cairo seems to lose the current color which must be restored.
+ updateColor();
+
+ return true;
+ }
+
+ /**
+ * Shifts coordinates by 0.5.
+ */
+ private double shifted(double coord, boolean doShift)
+ {
+ if (doShift)
+ return Math.floor(coord) + 0.5;
+ else
+ return coord;
+ }
+
+ /**
+ * Adds a pathIterator to the current Cairo path, also sets the cairo winding rule.
+ */
+ private void walkPath(PathIterator p, boolean doShift)
+ {
+ double x = 0;
+ double y = 0;
+ double[] coords = new double[6];
+
+ cairoSetFillRule(nativePointer, p.getWindingRule());
+ for (; ! p.isDone(); p.next())
+ {
+ int seg = p.currentSegment(coords);
+ switch (seg)
+ {
+ case PathIterator.SEG_MOVETO:
+ x = shifted(coords[0], doShift);
+ y = shifted(coords[1], doShift);
+ cairoMoveTo(nativePointer, x, y);
+ break;
+ case PathIterator.SEG_LINETO:
+ x = shifted(coords[0], doShift);
+ y = shifted(coords[1], doShift);
+ cairoLineTo(nativePointer, x, y);
+ break;
+ case PathIterator.SEG_QUADTO:
+ // splitting a quadratic bezier into a cubic:
+ // see: http://pfaedit.sourceforge.net/bezier.html
+ double x1 = x + (2.0 / 3.0) * (shifted(coords[0], doShift) - x);
+ double y1 = y + (2.0 / 3.0) * (shifted(coords[1], doShift) - y);
+
+ double x2 = x1 + (1.0 / 3.0) * (shifted(coords[2], doShift) - x);
+ double y2 = y1 + (1.0 / 3.0) * (shifted(coords[3], doShift) - y);
+
+ x = shifted(coords[2], doShift);
+ y = shifted(coords[3], doShift);
+ cairoCurveTo(nativePointer, x1, y1, x2, y2, x, y);
+ break;
+ case PathIterator.SEG_CUBICTO:
+ x = shifted(coords[4], doShift);
+ y = shifted(coords[5], doShift);
+ cairoCurveTo(nativePointer, shifted(coords[0], doShift),
+ shifted(coords[1], doShift),
+ shifted(coords[2], doShift),
+ shifted(coords[3], doShift), x, y);
+ break;
+ case PathIterator.SEG_CLOSE:
+ cairoClosePath(nativePointer);
+ break;
+ }
+ }
+ }
+
+ /**
+ * Used by setRenderingHints()
+ */
+ private Map getDefaultHints()
+ {
+ HashMap defaultHints = new HashMap();
+
+ defaultHints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
+ RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
+
+ defaultHints.put(RenderingHints.KEY_STROKE_CONTROL,
+ RenderingHints.VALUE_STROKE_DEFAULT);
+
+ defaultHints.put(RenderingHints.KEY_FRACTIONALMETRICS,
+ RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
+
+ defaultHints.put(RenderingHints.KEY_ANTIALIASING,
+ RenderingHints.VALUE_ANTIALIAS_OFF);
+
+ defaultHints.put(RenderingHints.KEY_RENDERING,
+ RenderingHints.VALUE_RENDER_DEFAULT);
+
+ return defaultHints;
+ }
+
+ /**
+ * Used by drawRaster and GdkPixbufDecoder
+ */
+ public static int[] findSimpleIntegerArray (ColorModel cm, Raster raster)
+ {
+ if (cm == null || raster == null)
+ return null;
+
+ if (! cm.getColorSpace().isCS_sRGB())
+ return null;
+
+ if (! (cm instanceof DirectColorModel))
+ return null;
+
+ DirectColorModel dcm = (DirectColorModel) cm;
+
+ if (dcm.getRedMask() != 0x00FF0000 || dcm.getGreenMask() != 0x0000FF00
+ || dcm.getBlueMask() != 0x000000FF)
+ return null;
+
+ if (! (raster instanceof WritableRaster))
+ return null;
+
+ if (raster.getSampleModel().getDataType() != DataBuffer.TYPE_INT)
+ return null;
+
+ if (! (raster.getDataBuffer() instanceof DataBufferInt))
+ return null;
+
+ DataBufferInt db = (DataBufferInt) raster.getDataBuffer();
+
+ if (db.getNumBanks() != 1)
+ return null;
+
+ // Finally, we have determined that this is a single bank, [A]RGB-int
+ // buffer in sRGB space. It's worth checking all this, because it means
+ // that cairo can paint directly into the data buffer, which is very
+ // fast compared to all the normal copying and converting.
+
+ return db.getData();
+ }
}
diff --git a/gnu/java/awt/peer/gtk/CairoSurface.java b/gnu/java/awt/peer/gtk/CairoSurface.java
new file mode 100644
index 000000000..8287b95f2
--- /dev/null
+++ b/gnu/java/awt/peer/gtk/CairoSurface.java
@@ -0,0 +1,315 @@
+/* CairoSurface.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.gtk;
+
+import java.awt.Graphics;
+import java.awt.Color;
+import java.awt.Image;
+import java.awt.Point;
+import java.awt.Graphics2D;
+import java.awt.GraphicsConfiguration;
+import java.awt.image.DataBuffer;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import java.awt.image.BufferedImage;
+import java.awt.image.ColorModel;
+import java.awt.image.DirectColorModel;
+import java.io.File;
+import java.io.IOException;
+import java.util.Hashtable;
+import java.util.Vector;
+import java.io.ByteArrayOutputStream;
+import java.io.BufferedInputStream;
+import java.net.URL;
+import gnu.classpath.Pointer;
+
+/**
+ * CairoSurface - wraps a Cairo surface.
+ *
+ * @author Sven de Marothy
+ */
+public class CairoSurface extends DataBuffer
+{
+ int width = -1, height = -1;
+
+ /**
+ * The native pointer to the Cairo surface.
+ */
+ long surfacePointer;
+
+ /**
+ * The native pointer to the image's data buffer
+ */
+ long bufferPointer;
+
+
+ static ColorModel nativeModel = new DirectColorModel(32,
+ 0x000000FF,
+ 0x0000FF00,
+ 0x00FF0000,
+ 0xFF000000);
+
+ /**
+ * Allocates and clears the buffer and creates the cairo surface.
+ * @param width, height - the image size
+ * @param stride - the buffer row stride.
+ */
+ private native void create(int width, int height, int stride);
+
+ /**
+ * Destroys the cairo surface and frees the buffer.
+ */
+ private native void destroy(long surfacePointer, long bufferPointer);
+
+ /**
+ * Gets buffer elements
+ */
+ private native int nativeGetElem(long bufferPointer, int i);
+
+ /**
+ * Sets buffer elements.
+ */
+ private native void nativeSetElem(long bufferPointer, int i, int val);
+
+ /**
+ * Draws this image to a given CairoGraphics context,
+ * with an affine transform given by i2u.
+ */
+ public native void nativeDrawSurface(long surfacePointer, long contextPointer,
+ double[] i2u);
+
+ public void drawSurface(long contextPointer, double[] i2u)
+ {
+ nativeDrawSurface(surfacePointer, contextPointer, i2u);
+ }
+
+ /**
+ * getPixels -return the pixels as a java array.
+ */
+ native int[] nativeGetPixels(long bufferPointer, int size);
+
+ public int[] getPixels(int size)
+ {
+ return nativeGetPixels(bufferPointer, size);
+ }
+
+ /**
+ * getPixels -return the pixels as a java array.
+ */
+ native void nativeSetPixels(long bufferPointer, int[] pixels);
+
+ public void setPixels(int[] pixels)
+ {
+ nativeSetPixels(bufferPointer, pixels);
+ }
+
+ native long getFlippedBuffer(long bufferPointer, int size);
+
+ /**
+ * Create a cairo_surface_t with specified width and height.
+ * The format will be ARGB32 with premultiplied alpha and native bit
+ * and word ordering.
+ */
+ CairoSurface(int width, int height)
+ {
+ super(DataBuffer.TYPE_INT, width * height);
+
+ if(width <= 0 || height <= 0)
+ throw new IllegalArgumentException("Image must be at least 1x1 pixels.");
+
+ this.width = width;
+ this.height = height;
+
+ create(width, height, width * 4);
+
+ if(surfacePointer == 0 || bufferPointer == 0)
+ throw new Error("Could not allocate bitmap.");
+ }
+
+ /**
+ * Create a cairo_surface_t from a GtkImage instance.
+ * (data is copied, not shared)
+ */
+ CairoSurface(GtkImage image)
+ {
+ super(DataBuffer.TYPE_INT, image.width * image.height);
+
+ if(image.width <= 0 || image.height <= 0)
+ throw new IllegalArgumentException("Image must be at least 1x1 pixels.");
+
+ width = image.width;
+ height = image.height;
+
+ create(width, height, width * 4);
+
+ if(surfacePointer == 0 || bufferPointer == 0)
+ throw new Error("Could not allocate bitmap.");
+
+ // Copy the pixel data from the GtkImage.
+ int[] data = image.getPixels();
+
+ // Swap ordering from GdkPixbuf to Cairo
+ for(int i = 0; i < data.length; i++ )
+ {
+ int alpha = (data[i] & 0xFF000000) >> 24;
+ if( alpha == 0 ) // I do not know why we need this, but it works.
+ data[i] = 0;
+ else
+ {
+ int r = (((data[i] & 0x00FF0000) >> 16) );
+ int g = (((data[i] & 0x0000FF00) >> 8) );
+ int b = ((data[i] & 0x000000FF) );
+ data[i] = (( alpha << 24 ) & 0xFF000000)
+ | (( b << 16 ) & 0x00FF0000)
+ | (( g << 8 ) & 0x0000FF00)
+ | ( r & 0x000000FF);
+ }
+ }
+
+ setPixels( data );
+ }
+
+ /**
+ * Dispose of the native data.
+ */
+ public void dispose()
+ {
+ if(surfacePointer != 0)
+ destroy(surfacePointer, bufferPointer);
+ }
+
+ /**
+ * Call dispose() to clean up any native resources allocated.
+ */
+ protected void finalize()
+ {
+ dispose();
+ }
+
+ /**
+ * Return a GtkImage from this Cairo surface.
+ */
+ public GtkImage getGtkImage()
+ {
+ return new GtkImage( width, height,
+ getFlippedBuffer(bufferPointer, width * height ));
+ }
+
+ /**
+ * Returns a BufferedImage backed by a Cairo surface.
+ */
+ public static BufferedImage getBufferedImage(int width, int height)
+ {
+ return getBufferedImage(new CairoSurface(width, height));
+ }
+
+ /**
+ * Returns a BufferedImage backed by a Cairo surface,
+ * created from a GtkImage.
+ */
+ public static BufferedImage getBufferedImage(GtkImage image)
+ {
+ return getBufferedImage(new CairoSurface(image));
+ }
+
+ /**
+ * Returns a BufferedImage backed by a Cairo surface.
+ */
+ public static BufferedImage getBufferedImage(CairoSurface surface)
+ {
+ WritableRaster raster = Raster.createPackedRaster
+ (surface, surface.width, surface.height, surface.width,
+ new int[]{ 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 },
+ new Point(0,0));
+
+ return new BufferedImage(nativeModel, raster, true, new Hashtable());
+ }
+
+ /**
+ * DataBank.getElem implementation
+ */
+ public int getElem(int bank, int i)
+ {
+ if(bank != 0 || i < 0 || i >= width*height)
+ throw new IndexOutOfBoundsException(i+" size: "+width*height);
+ return nativeGetElem(bufferPointer, i);
+ }
+
+ /**
+ * DataBank.setElem implementation
+ */
+ public void setElem(int bank, int i, int val)
+ {
+ if(bank != 0 || i < 0 || i >= width*height)
+ throw new IndexOutOfBoundsException(i+" size: "+width*height);
+ nativeSetElem(bufferPointer, i, val);
+ }
+
+ /**
+ * Return a Graphics2D drawing to the CairoSurface.
+ */
+ public Graphics2D getGraphics()
+ {
+ return new CairoSurfaceGraphics(this);
+ }
+
+ ///// Methods used by CairoSurfaceGraphics /////
+ /**
+ * Creates a cairo_t drawing context, returns the pointer as a long.
+ * Used by CairoSurfaceGraphics.
+ */
+ native long nativeNewCairoContext(long surfacePointer);
+
+ public long newCairoContext()
+ {
+ return nativeNewCairoContext(surfacePointer);
+ }
+
+ /**
+ * Copy an area of the surface. Expects parameters must be within bounds.
+ * Count on a segfault otherwise.
+ */
+ native void copyAreaNative2(long bufferPointer, int x, int y, int width,
+ int height, int dx, int dy, int stride);
+ public void copyAreaNative(int x, int y, int width,
+ int height, int dx, int dy, int stride)
+ {
+ copyAreaNative2(bufferPointer, x, y, width, height, dx, dy, stride);
+ }
+}
diff --git a/gnu/java/awt/peer/gtk/CairoSurfaceGraphics.java b/gnu/java/awt/peer/gtk/CairoSurfaceGraphics.java
new file mode 100644
index 000000000..27dab66f7
--- /dev/null
+++ b/gnu/java/awt/peer/gtk/CairoSurfaceGraphics.java
@@ -0,0 +1,101 @@
+/* CairoSurfaceGraphics.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.gtk;
+
+import java.awt.Graphics;
+import java.awt.Color;
+import java.awt.GraphicsEnvironment;
+import java.awt.Image;
+import java.awt.Point;
+import java.awt.Graphics2D;
+import java.awt.GraphicsConfiguration;
+import java.awt.geom.Rectangle2D;
+import java.awt.image.*;
+
+/**
+ * Implementation of Graphics2D on a Cairo surface.
+ */
+public class CairoSurfaceGraphics extends CairoGraphics2D
+{
+ protected CairoSurface surface;
+ private long cairo_t;
+
+ /**
+ * Create a graphics context from a cairo surface
+ */
+ public CairoSurfaceGraphics(CairoSurface surface)
+ {
+ this.surface = surface;
+ cairo_t = surface.newCairoContext();
+ setup( cairo_t );
+ setClip(0, 0, surface.width, surface.height);
+ }
+
+ /**
+ * Creates another context from a surface.
+ * Used by create().
+ */
+ private CairoSurfaceGraphics(CairoSurfaceGraphics copyFrom)
+ {
+ surface = copyFrom.surface;
+ cairo_t = surface.newCairoContext();
+ copy( copyFrom, cairo_t );
+ setClip(0, 0, surface.width, surface.height);
+ }
+
+ public Graphics create()
+ {
+ return new CairoSurfaceGraphics(this);
+ }
+
+ public GraphicsConfiguration getDeviceConfiguration()
+ {
+ return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
+ }
+
+ protected Rectangle2D getRealBounds()
+ {
+ return new Rectangle2D.Double(0.0, 0.0, surface.width, surface.height);
+ }
+
+ public void copyAreaImpl(int x, int y, int width, int height, int dx, int dy)
+ {
+ surface.copyAreaNative(x, y, width, height, dx, dy, surface.width);
+ }
+}
diff --git a/gnu/java/awt/peer/gtk/ComponentGraphics.java b/gnu/java/awt/peer/gtk/ComponentGraphics.java
new file mode 100644
index 000000000..341e514d4
--- /dev/null
+++ b/gnu/java/awt/peer/gtk/ComponentGraphics.java
@@ -0,0 +1,275 @@
+/* ComponentGraphics.java --
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.gtk;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.GraphicsConfiguration;
+import java.awt.Image;
+import java.awt.Rectangle;
+import java.awt.Shape;
+import java.awt.Point;
+import java.awt.font.FontRenderContext;
+import java.awt.font.GlyphVector;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Rectangle2D;
+import java.awt.image.BufferedImage;
+import java.awt.image.ImageObserver;
+import java.awt.image.ImagingOpException;
+import java.awt.image.RenderedImage;
+
+/**
+ * ComponentGraphics - context for drawing directly to a component,
+ * as this is an X drawable, it requires that we use GTK locks.
+ *
+ * This context draws directly to the drawable and requires xrender.
+ */
+public class ComponentGraphics extends CairoGraphics2D
+{
+ private GtkComponentPeer component;
+ protected long cairo_t;
+
+ ComponentGraphics()
+ {
+ }
+
+ private ComponentGraphics(GtkComponentPeer component)
+ {
+ this.component = component;
+ cairo_t = initState(component);
+ setup( cairo_t );
+ Rectangle bounds = component.awtComponent.getBounds();
+ setClip( new Rectangle( 0, 0, bounds.width, bounds.height) );
+ setBackground(component.awtComponent.getBackground());
+ setColor(component.awtComponent.getForeground());
+ }
+
+ private ComponentGraphics(ComponentGraphics cg)
+ {
+ component = cg.component;
+ cairo_t = initState(component);
+ copy( cg, cairo_t );
+ Rectangle bounds = component.awtComponent.getBounds();
+ setClip( new Rectangle( 0, 0, bounds.width, bounds.height) );
+ setBackground(component.awtComponent.getBackground());
+ setColor(component.awtComponent.getForeground());
+ }
+
+ /**
+ * Creates a cairo_t for the component surface and return it.
+ */
+ private native long initState(GtkComponentPeer component);
+
+ /**
+ * Destroys the component surface and calls dispose on the cairo
+ * graphics2d to destroy any super class resources.
+ */
+ public void dispose()
+ {
+ super.dispose();
+ disposeSurface(nativePointer);
+ }
+
+ /**
+ * Destroys the component surface.
+ */
+ private native void disposeSurface(long nativePointer);
+
+ /**
+ * Creates a cairo_t for a volatile image
+ */
+ protected native long initFromVolatile( long pixmapPtr, int width, int height);
+
+ /**
+ * Grab lock
+ */
+ private native void start_gdk_drawing();
+
+ /**
+ * Release lock
+ */
+ private native void end_gdk_drawing();
+
+ /**
+ * Query if the system has the XRender extension.
+ */
+ public static native boolean hasXRender();
+
+
+ private native void copyAreaNative(GtkComponentPeer component, int x, int y,
+ int width, int height, int dx, int dy);
+
+ private native void drawVolatile(GtkComponentPeer component,
+ long vimg, int x, int y,
+ int width, int height);
+
+ /**
+ * Returns a Graphics2D object for a component, either an instance of this
+ * class (if xrender is supported), or a context which copies.
+ */
+ public static Graphics2D getComponentGraphics(GtkComponentPeer component)
+ {
+ if( hasXRender() )
+ return new ComponentGraphics(component);
+
+ Rectangle r = component.awtComponent.getBounds();
+ return new ComponentGraphicsCopy(r.width, r.height, component);
+ }
+
+ public GraphicsConfiguration getDeviceConfiguration()
+ {
+ return component.getGraphicsConfiguration();
+ }
+
+ public Graphics create()
+ {
+ return new ComponentGraphics(this);
+ }
+
+ protected Rectangle2D getRealBounds()
+ {
+ return component.awtComponent.getBounds();
+ }
+
+ public void copyAreaImpl(int x, int y, int width, int height, int dx, int dy)
+ {
+ copyAreaNative(component, x, y, width, height, dx, dy);
+ }
+
+ /**
+ * Overloaded methods that do actual drawing need to enter the gdk threads
+ * and also do certain things before and after.
+ */
+ public void draw(Shape s)
+ {
+ start_gdk_drawing();
+ try
+ {
+ super.draw(s);
+ }
+ finally
+ {
+ end_gdk_drawing();
+ }
+ }
+
+ public void fill(Shape s)
+ {
+ start_gdk_drawing();
+ try
+ {
+ super.fill(s);
+ }
+ finally
+ {
+ end_gdk_drawing();
+ }
+ }
+
+ public void drawRenderedImage(RenderedImage image, AffineTransform xform)
+ {
+ start_gdk_drawing();
+ try
+ {
+ super.drawRenderedImage(image, xform);
+ }
+ finally
+ {
+ end_gdk_drawing();
+ }
+ }
+
+ protected boolean drawImage(Image img, AffineTransform xform,
+ Color bgcolor, ImageObserver obs)
+ {
+ boolean rv;
+ start_gdk_drawing();
+ try
+ {
+ rv = super.drawImage(img, xform, bgcolor, obs);
+ }
+ finally
+ {
+ end_gdk_drawing();
+ }
+ return rv;
+ }
+
+ public void drawGlyphVector(GlyphVector gv, float x, float y)
+ {
+ start_gdk_drawing();
+ try
+ {
+ super.drawGlyphVector(gv, x, y);
+ }
+ finally
+ {
+ end_gdk_drawing();
+ }
+ }
+
+ public boolean drawImage(Image img, int x, int y, ImageObserver observer)
+ {
+ if( img instanceof GtkVolatileImage )
+ {
+ GtkVolatileImage vimg = (GtkVolatileImage) img;
+ drawVolatile( component, vimg.nativePointer,
+ x, y - 20, vimg.width, vimg.height );
+ return true;
+ }
+ return super.drawImage( img, x, y, observer );
+ }
+
+ public boolean drawImage(Image img, int x, int y, int width, int height,
+ ImageObserver observer)
+ {
+ if( img instanceof GtkVolatileImage )
+ {
+ GtkVolatileImage vimg = (GtkVolatileImage) img;
+ drawVolatile( component, vimg.nativePointer, x, y - 20,
+ width, height );
+ return true;
+ }
+ return super.drawImage( img, x, y, width, height, observer );
+ }
+
+}
+
diff --git a/gnu/java/awt/peer/gtk/ComponentGraphicsCopy.java b/gnu/java/awt/peer/gtk/ComponentGraphicsCopy.java
new file mode 100644
index 000000000..286fbeac0
--- /dev/null
+++ b/gnu/java/awt/peer/gtk/ComponentGraphicsCopy.java
@@ -0,0 +1,129 @@
+/* ComponentGraphicsCopy.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.gtk;
+
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.GraphicsConfiguration;
+import java.awt.Image;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.Shape;
+import java.awt.font.GlyphVector;
+import java.awt.geom.AffineTransform;
+import java.awt.image.BufferedImage;
+import java.awt.image.DataBuffer;
+import java.awt.image.RenderedImage;
+import java.awt.image.ImageObserver;
+
+/**
+ * Implementation of Graphics2D for Components for servers which
+ * do not have xrender.
+ *
+ * A mirrored GtkImage of the component is stored in memory
+ * and copied back. Yay.
+ */
+public class ComponentGraphicsCopy extends CairoSurfaceGraphics
+{
+ private GtkComponentPeer component;
+
+ /**
+ * GtkImage sharing its data buffer with this Cairo surface.
+ */
+ private GtkImage gtkimage;
+
+ private int width, height;
+
+ native void getPixbuf( GtkComponentPeer component, GtkImage image );
+
+ native void copyPixbuf( GtkComponentPeer component, GtkImage image,
+ int x, int y, int w, int h );
+
+ public ComponentGraphicsCopy(int width, int height,
+ GtkComponentPeer component)
+ {
+ super( new CairoSurface( width, height ) );
+ this.component = component;
+ this.width = width;
+ this.height = height;
+ gtkimage = surface.getGtkImage();
+ getPixbuf( component, gtkimage );
+ }
+
+ /**
+ * Overloaded methods that do actual drawing need to enter the gdk threads
+ * and also do certain things before and after.
+ */
+ public void draw(Shape s)
+ {
+ super.draw(s);
+ Rectangle r = s.getBounds();
+ copyPixbuf(component, gtkimage, r.x, r.y, r.width, r.height);
+ }
+
+ public void fill(Shape s)
+ {
+ super.fill(s);
+ Rectangle r = s.getBounds();
+ copyPixbuf(component, gtkimage, r.x, r.y, r.width, r.height);
+ }
+
+ public void drawRenderedImage(RenderedImage image, AffineTransform xform)
+ {
+ super.drawRenderedImage(image, xform);
+ copyPixbuf(component, gtkimage, 0, 0, width, height);
+ }
+
+ protected boolean drawImage(Image img, AffineTransform xform,
+ Color bgcolor, ImageObserver obs)
+ {
+ boolean rv = super.drawImage(img, xform, bgcolor, obs);
+ copyPixbuf(component, gtkimage, 0, 0, width, height);
+ return rv;
+ }
+
+ public void drawGlyphVector(GlyphVector gv, float x, float y)
+ {
+ super.drawGlyphVector(gv, x, y);
+ Rectangle r = gv.getPixelBounds(getFontRenderContext(), x , y);
+ copyPixbuf(component, gtkimage, r.x, r.y, r.width, r.height);
+ }
+}
+
diff --git a/gnu/java/awt/peer/gtk/FreetypeGlyphVector.java b/gnu/java/awt/peer/gtk/FreetypeGlyphVector.java
new file mode 100644
index 000000000..4978c6a45
--- /dev/null
+++ b/gnu/java/awt/peer/gtk/FreetypeGlyphVector.java
@@ -0,0 +1,468 @@
+/* FreetypeGlyphVector.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.awt.peer.gtk;
+
+import java.awt.Font;
+import java.awt.Shape;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.awt.geom.GeneralPath;
+import java.awt.font.GlyphJustificationInfo;
+import java.awt.font.GlyphMetrics;
+import java.awt.font.GlyphVector;
+import java.awt.font.FontRenderContext;
+
+public class FreetypeGlyphVector extends GlyphVector
+{
+ /**
+ * The associated font and its peer.
+ */
+ private Font font;
+ private GdkFontPeer peer; // ATTN: Accessed from native code.
+
+ private Rectangle2D logicalBounds;
+
+ private float[] glyphPositions;
+ /**
+ * The string represented by this GlyphVector.
+ */
+ private String s;
+
+ /**
+ * The font render context
+ */
+ private FontRenderContext frc;
+
+ /**
+ * The total # of glyphs.
+ */
+ private int nGlyphs;
+
+ /**
+ * The glyph codes
+ */
+ private int[] glyphCodes;
+
+ /**
+ * Glyph transforms. (de facto only the translation is used)
+ */
+ private AffineTransform[] glyphTransforms;
+
+ private GlyphMetrics[] metricsCache;
+
+ /**
+ * Create a glyphvector from a given (Freetype) font and a String.
+ */
+ public FreetypeGlyphVector(Font f, String s, FontRenderContext frc)
+ {
+ this(f, s, frc, Font.LAYOUT_LEFT_TO_RIGHT);
+ }
+
+ /**
+ * Create a glyphvector from a given (Freetype) font and a String.
+ */
+ public FreetypeGlyphVector(Font f, String s, FontRenderContext frc,
+ int flags)
+ {
+ this.s = s;
+ this.font = f;
+ this.frc = frc;
+ if( !(font.getPeer() instanceof GdkFontPeer ) )
+ throw new IllegalArgumentException("Not a valid font.");
+ peer = (GdkFontPeer)font.getPeer();
+
+ getGlyphs();
+ if( flags == Font.LAYOUT_RIGHT_TO_LEFT )
+ {
+ // reverse the glyph ordering.
+ int[] temp = new int[ nGlyphs ];
+ for(int i = 0; i < nGlyphs; i++)
+ temp[ i ] = glyphCodes[ nGlyphs - i - 1];
+ glyphCodes = temp;
+ }
+ performDefaultLayout();
+ }
+
+ /**
+ * Create a glyphvector from a given set of glyph codes.
+ */
+ public FreetypeGlyphVector(Font f, int[] codes, FontRenderContext frc)
+ {
+ this.font = f;
+ this.frc = frc;
+ if( !(font.getPeer() instanceof GdkFontPeer ) )
+ throw new IllegalArgumentException("Not a valid font.");
+ peer = (GdkFontPeer)font.getPeer();
+
+ glyphCodes = new int[ codes.length ];
+ System.arraycopy(codes, 0, glyphCodes, 0, codes.length);
+ nGlyphs = glyphCodes.length;
+ performDefaultLayout();
+ }
+
+ /**
+ * Create the array of glyph codes.
+ */
+ private void getGlyphs()
+ {
+ nGlyphs = s.codePointCount( 0, s.length() );
+ glyphCodes = new int[ nGlyphs ];
+ int[] codePoints = new int[ nGlyphs ];
+ int stringIndex = 0;
+
+ for(int i = 0; i < nGlyphs; i++)
+ {
+ codePoints[i] = s.codePointAt( stringIndex );
+ // UTF32 surrogate handling
+ if( codePoints[i] != (int)s.charAt( stringIndex ) )
+ stringIndex ++;
+ stringIndex ++;
+ }
+
+ glyphCodes = getGlyphs( codePoints );
+ }
+
+ /**
+ * Returns the glyph code within the font for a given character
+ */
+ public native int[] getGlyphs(int[] codepoints);
+
+ /**
+ * Returns the kerning of a glyph pair
+ */
+ private native Point2D getKerning(int leftGlyph, int rightGlyph);
+
+ private native double[] getMetricsNative( int glyphCode );
+
+ private native GeneralPath getGlyphOutlineNative(int glyphIndex);
+
+ /**
+ * Duh, compares two instances.
+ */
+ public boolean equals(GlyphVector gv)
+ {
+ if( ! (gv instanceof FreetypeGlyphVector) )
+ return false;
+
+ return (((FreetypeGlyphVector)gv).font.equals(font) &&
+ ((FreetypeGlyphVector)gv).frc.equals(frc)
+ && ((FreetypeGlyphVector)gv).s.equals(s));
+ }
+
+ /**
+ * Returns the associated Font
+ */
+ public Font getFont()
+ {
+ return font;
+ }
+
+ /**
+ * Returns the associated FontRenderContext
+ */
+ public FontRenderContext getFontRenderContext()
+ {
+ return frc;
+ }
+
+ /**
+ * Layout the glyphs.
+ */
+ public void performDefaultLayout()
+ {
+ logicalBounds = null; // invalidate caches.
+ glyphPositions = null;
+
+ glyphTransforms = new AffineTransform[ nGlyphs ];
+ double x = 0;
+
+ for(int i = 0; i < nGlyphs; i++)
+ {
+ GlyphMetrics gm = getGlyphMetrics( i );
+ glyphTransforms[ i ] = AffineTransform.getTranslateInstance(x, 0);
+ x += gm.getAdvanceX();
+ if( i > 0 )
+ {
+ Point2D p = getKerning( glyphCodes[ i - 1 ], glyphCodes[ i ] );
+ x += p.getX();
+ }
+ }
+ }
+
+ /**
+ * Returns the code of the glyph at glyphIndex;
+ */
+ public int getGlyphCode(int glyphIndex)
+ {
+ return glyphCodes[ glyphIndex ];
+ }
+
+ /**
+ * Returns multiple glyphcodes.
+ */
+ public int[] getGlyphCodes(int beginGlyphIndex, int numEntries,
+ int[] codeReturn)
+ {
+ int[] rval;
+
+ if( codeReturn == null )
+ rval = new int[ numEntries ];
+ else
+ rval = codeReturn;
+
+ System.arraycopy(glyphCodes, beginGlyphIndex, rval, 0, numEntries);
+
+ return rval;
+ }
+
+ /**
+ * FIXME: Implement me.
+ */
+ public Shape getGlyphLogicalBounds(int glyphIndex)
+ {
+ GlyphMetrics gm = getGlyphMetrics( glyphIndex );
+ if( gm == null )
+ return null;
+ Rectangle2D r = gm.getBounds2D();
+ return new Rectangle2D.Double( r.getX() - gm.getLSB(), r.getY(),
+ gm.getAdvanceX(), r.getHeight() );
+ }
+
+ /*
+ * FIXME: Not all glyph types are supported.
+ * (The JDK doesn't really seem to do so either)
+ */
+ public void setupGlyphMetrics()
+ {
+ metricsCache = new GlyphMetrics[ nGlyphs ];
+
+ for(int i = 0; i < nGlyphs; i++)
+ {
+ GlyphMetrics gm = (GlyphMetrics)
+ peer.getGlyphMetrics( glyphCodes[ i ] );
+ if( gm == null )
+ {
+ double[] val = getMetricsNative( glyphCodes[ i ] );
+ if( val == null )
+ gm = null;
+ else
+ {
+ gm = new GlyphMetrics( true,
+ (float)val[1],
+ (float)val[2],
+ new Rectangle2D.Double
+ ( val[3], val[4],
+ val[5], val[6] ),
+ GlyphMetrics.STANDARD );
+ peer.putGlyphMetrics( glyphCodes[ i ], gm );
+ }
+ }
+ metricsCache[ i ] = gm;
+ }
+ }
+
+ /**
+ * Returns the metrics of a single glyph.
+ */
+ public GlyphMetrics getGlyphMetrics(int glyphIndex)
+ {
+ if( metricsCache == null )
+ setupGlyphMetrics();
+
+ return metricsCache[ glyphIndex ];
+ }
+
+ /**
+ * Returns the outline of a single glyph.
+ */
+ public Shape getGlyphOutline(int glyphIndex)
+ {
+ GeneralPath gp = getGlyphOutlineNative( glyphCodes[ glyphIndex ] );
+ gp.transform( glyphTransforms[ glyphIndex ] );
+ return gp;
+ }
+
+ /**
+ * Returns the position of a single glyph.
+ */
+ public Point2D getGlyphPosition(int glyphIndex)
+ {
+ return glyphTransforms[ glyphIndex ].transform( new Point2D.Double(0, 0),
+ null );
+ }
+
+ /**
+ * Returns the positions of multiple glyphs.
+ */
+ public float[] getGlyphPositions(int beginGlyphIndex, int numEntries,
+ float[] positionReturn)
+ {
+ if( glyphPositions != null )
+ return glyphPositions;
+
+ float[] rval;
+
+ if( positionReturn == null )
+ rval = new float[2 * numEntries];
+ else
+ rval = positionReturn;
+
+ for( int i = beginGlyphIndex; i < numEntries; i++ )
+ {
+ Point2D p = getGlyphPosition( i );
+ rval[i * 2] = (float)p.getX();
+ rval[i * 2 + 1] = (float)p.getY();
+ }
+
+ glyphPositions = rval;
+ return rval;
+ }
+
+ /**
+ * Returns the transform of a glyph.
+ */
+ public AffineTransform getGlyphTransform(int glyphIndex)
+ {
+ return new AffineTransform( glyphTransforms[ glyphIndex ] );
+ }
+
+ /**
+ * Returns the visual bounds of a glyph
+ * May be off by a pixel or two due to hinting/rasterization.
+ */
+ public Shape getGlyphVisualBounds(int glyphIndex)
+ {
+ return getGlyphOutline( glyphIndex ).getBounds2D();
+ }
+
+ /**
+ * Return the logical bounds of the whole thing.
+ */
+ public Rectangle2D getLogicalBounds()
+ {
+ if( nGlyphs == 0 )
+ return new Rectangle2D.Double(0, 0, 0, 0);
+ if( logicalBounds != null )
+ return logicalBounds;
+
+ Rectangle2D rect = (Rectangle2D)getGlyphLogicalBounds( 0 );
+ for( int i = 1; i < nGlyphs; i++ )
+ {
+ Rectangle2D r2 = (Rectangle2D)getGlyphLogicalBounds( i );
+ Point2D p = getGlyphPosition( i );
+ r2.setRect( p.getX(), p.getY(), r2.getWidth(), r2.getHeight() );
+ rect = rect.createUnion( r2 );
+ }
+
+ logicalBounds = rect;
+ return rect;
+ }
+
+ /**
+ * Returns the number of glyphs.
+ */
+ public int getNumGlyphs()
+ {
+ return glyphCodes.length;
+ }
+
+ /**
+ * Returns the outline of the entire GlyphVector.
+ */
+ public Shape getOutline()
+ {
+ GeneralPath path = new GeneralPath();
+ for( int i = 0; i < getNumGlyphs(); i++ )
+ path.append( getGlyphOutline( i ), false );
+ return path;
+ }
+
+ /**
+ * TODO:
+ * FreeType does not currently have an API for the JSTF table. We should
+ * probably get the table ourselves from FT and pass it to some parser
+ * which the native font peers will need.
+ */
+ public GlyphJustificationInfo getGlyphJustificationInfo(int glyphIndex)
+ {
+ return null;
+ }
+
+ /**
+ * Returns the outline of the entire vector, drawn at (x,y).
+ */
+ public Shape getOutline(float x, float y)
+ {
+ AffineTransform tx = AffineTransform.getTranslateInstance( x, y );
+ GeneralPath gp = (GeneralPath)getOutline();
+ gp.transform( tx );
+ return gp;
+ }
+
+ /**
+ * Returns the visual bounds of the entire GlyphVector.
+ * May be off by a pixel or two due to hinting/rasterization.
+ */
+ public Rectangle2D getVisualBounds()
+ {
+ return getOutline().getBounds2D();
+ }
+
+ /**
+ * Sets the position of a glyph.
+ */
+ public void setGlyphPosition(int glyphIndex, Point2D newPos)
+ {
+ // FIXME: Scaling, etc.?
+ glyphTransforms[ glyphIndex ].setToTranslation( newPos.getX(),
+ newPos.getY() );
+ logicalBounds = null;
+ glyphPositions = null;
+ }
+
+ /**
+ * Sets the transform of a single glyph.
+ */
+ public void setGlyphTransform(int glyphIndex, AffineTransform newTX)
+ {
+ glyphTransforms[ glyphIndex ].setTransform( newTX );
+ logicalBounds = null;
+ glyphPositions = null;
+ }
+}
diff --git a/gnu/java/awt/peer/gtk/GdkFontPeer.java b/gnu/java/awt/peer/gtk/GdkFontPeer.java
index 544efa3c9..f5ed8a710 100644
--- a/gnu/java/awt/peer/gtk/GdkFontPeer.java
+++ b/gnu/java/awt/peer/gtk/GdkFontPeer.java
@@ -47,27 +47,32 @@ import java.awt.FontMetrics;
import java.awt.Toolkit;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
+import java.awt.font.GlyphMetrics;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;
+import java.awt.geom.Point2D;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.nio.ByteBuffer;
+import java.util.HashMap;
public class GdkFontPeer extends ClasspathFontPeer
{
static native void initStaticState();
private final int native_state = GtkGenericPeer.getUniqueInteger ();
private static ResourceBundle bundle;
+
+ /**
+ * Cache GlyphMetrics objects.
+ */
+ private HashMap metricsCache;
static
{
- if (Configuration.INIT_LOAD_LIBRARY)
- {
- System.loadLibrary("gtkpeer");
- }
+ System.loadLibrary("gtkpeer");
initStaticState ();
@@ -90,9 +95,12 @@ public class GdkFontPeer extends ClasspathFontPeer
native void getFontMetrics(double [] metrics);
native void getTextMetrics(String str, double [] metrics);
+ native void releasePeerGraphicsResource();
+
+
protected void finalize ()
{
- GdkGraphics2D.releasePeerGraphicsResource(this);
+ releasePeerGraphicsResource();
dispose ();
}
@@ -143,6 +151,7 @@ public class GdkFontPeer extends ClasspathFontPeer
super(name, style, size);
initState ();
setFont (this.familyName, this.style, (int)this.size);
+ metricsCache = new HashMap();
}
public GdkFontPeer (String name, Map attributes)
@@ -150,6 +159,7 @@ public class GdkFontPeer extends ClasspathFontPeer
super(name, attributes);
initState ();
setFont (this.familyName, this.style, (int)this.size);
+ metricsCache = new HashMap();
}
/**
@@ -234,39 +244,41 @@ public class GdkFontPeer extends ClasspathFontPeer
return -1;
}
- private native GdkGlyphVector getGlyphVector(String txt,
- Font f,
- FontRenderContext ctx);
-
public GlyphVector createGlyphVector (Font font,
FontRenderContext ctx,
CharacterIterator i)
{
- return getGlyphVector(buildString (i), font, ctx);
+ return new FreetypeGlyphVector(font, buildString (i), ctx);
}
public GlyphVector createGlyphVector (Font font,
FontRenderContext ctx,
int[] glyphCodes)
{
- return null;
- // return new GdkGlyphVector (font, this, ctx, glyphCodes);
+ return new FreetypeGlyphVector(font, glyphCodes, ctx);
}
public byte getBaselineFor (Font font, char c)
{
- throw new UnsupportedOperationException ();
+ // FIXME: Actually check.
+ return Font.ROMAN_BASELINE;
}
- protected class GdkFontLineMetrics extends LineMetrics
+ private static class GdkFontLineMetrics extends LineMetrics
{
- FontMetrics fm;
- int nchars;
+ private FontMetrics fm;
+ private int nchars;
+ private float strikethroughOffset, strikethroughThickness,
+ underlineOffset, underlineThickness;
- public GdkFontLineMetrics (FontMetrics m, int n)
+ public GdkFontLineMetrics (GdkFontPeer fp, FontMetrics m, int n)
{
fm = m;
nchars = n;
+ strikethroughOffset = 0f;
+ underlineOffset = 0f;
+ strikethroughThickness = ((float)fp.getSize(null)) / 12f;
+ underlineThickness = strikethroughThickness;
}
public float getAscent()
@@ -275,7 +287,8 @@ public class GdkFontPeer extends ClasspathFontPeer
}
public int getBaselineIndex()
- {
+ {
+ // FIXME
return Font.ROMAN_BASELINE;
}
@@ -306,7 +319,7 @@ public class GdkFontPeer extends ClasspathFontPeer
public LineMetrics getLineMetrics (Font font, CharacterIterator ci,
int begin, int limit, FontRenderContext rc)
{
- return new GdkFontLineMetrics (getFontMetrics (font), limit - begin);
+ return new GdkFontLineMetrics (this, getFontMetrics (font), limit - begin);
}
public Rectangle2D getMaxCharBounds (Font font, FontRenderContext rc)
@@ -338,7 +351,9 @@ public class GdkFontPeer extends ClasspathFontPeer
public Rectangle2D getStringBounds (Font font, CharacterIterator ci,
int begin, int limit, FontRenderContext frc)
{
- GdkGlyphVector gv = getGlyphVector(buildString (ci, begin, limit), font, frc);
+ GlyphVector gv = new FreetypeGlyphVector( font,
+ buildString(ci, begin, limit),
+ frc);
return gv.getVisualBounds();
}
@@ -351,20 +366,15 @@ public class GdkFontPeer extends ClasspathFontPeer
char[] chars, int start, int limit,
int flags)
{
- int nchars = (limit - start) + 1;
- char[] nc = new char[nchars];
-
- for (int i = 0; i < nchars; ++i)
- nc[i] = chars[start + i];
-
- return createGlyphVector (font, frc,
- new StringCharacterIterator (new String (nc)));
+ return new FreetypeGlyphVector( font, new String( chars, start,
+ limit - start),
+ frc, flags);
}
public LineMetrics getLineMetrics (Font font, String str,
FontRenderContext frc)
{
- return new GdkFontLineMetrics (getFontMetrics (font), str.length ());
+ return new GdkFontLineMetrics (this, getFontMetrics (font), str.length ());
}
public FontMetrics getFontMetrics (Font font)
@@ -374,4 +384,20 @@ public class GdkFontPeer extends ClasspathFontPeer
return Toolkit.getDefaultToolkit().getFontMetrics (font);
}
+ /**
+ * Returns a cached GlyphMetrics object for a given glyphcode,
+ * or null if it doesn't exist in the cache.
+ */
+ GlyphMetrics getGlyphMetrics( int glyphCode )
+ {
+ return (GlyphMetrics)metricsCache.get( new Integer( glyphCode ) );
+ }
+
+ /**
+ * Put a GlyphMetrics object in the cache.
+ */
+ void putGlyphMetrics( int glyphCode, Object metrics )
+ {
+ metricsCache.put( new Integer( glyphCode ), metrics );
+ }
}
diff --git a/gnu/java/awt/peer/gtk/GdkGlyphVector.java b/gnu/java/awt/peer/gtk/GdkGlyphVector.java
deleted file mode 100644
index f0ddea43a..000000000
--- a/gnu/java/awt/peer/gtk/GdkGlyphVector.java
+++ /dev/null
@@ -1,359 +0,0 @@
-/* GdkGlyphVector.java -- Glyph vector object
- Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-package gnu.java.awt.peer.gtk;
-
-import java.awt.Font;
-import java.awt.Rectangle;
-import java.awt.Shape;
-import java.awt.font.FontRenderContext;
-import java.awt.font.GlyphJustificationInfo;
-import java.awt.font.GlyphMetrics;
-import java.awt.font.GlyphVector;
-import java.awt.geom.AffineTransform;
-import java.awt.geom.Point2D;
-import java.awt.geom.Rectangle2D;
-
-public class GdkGlyphVector extends GlyphVector
-{
-
- /* We use a simple representation for glyph vectors here. Glyph i
- * consumes 8 doubles:
- *
- * logical x: extents[ 10*i ]
- * logical y: extents[ 10*i + 1 ]
- * logical width: extents[ 10*i + 2 ]
- * logical height: extents[ 10*i + 3 ]
- *
- * visual x: extents[ 10*i + 4 ]
- * visual y: extents[ 10*i + 5 ]
- * visual width: extents[ 10*i + 6 ]
- * visual height: extents[ 10*i + 7 ]
- *
- * origin pos x: extents[ 10*i + 8 ]
- * origin pos y: extents[ 10*i + 9 ]
- *
- * as well as one int, code[i], representing the glyph code in the font.
- */
-
- double [] extents;
- int [] codes;
-
- Font font;
- FontRenderContext fontRenderContext;
-
- Rectangle2D allLogical;
- Rectangle2D allVisual;
-
- public GdkGlyphVector(double[] extents, int[] codes, Font font, FontRenderContext frc)
- {
- this.extents = extents;
- this.codes = codes;
- this.font = font;
- this.fontRenderContext = frc;
-
- allLogical = new Rectangle2D.Double();
- allVisual = new Rectangle2D.Double();
-
- for (int i = 0; i < codes.length; ++i)
- {
- allLogical.add (new Rectangle2D.Double(extents[10*i ] + extents[10*i + 8],
- extents[10*i + 1] + extents[10*i + 9],
- extents[10*i + 2],
- extents[10*i + 3]));
-
- allVisual.add (new Rectangle2D.Double(extents[10*i + 4] + extents[10*i + 8],
- extents[10*i + 5] + extents[10*i + 9],
- extents[10*i + 6],
- extents[10*i + 7]));
- }
- }
-
- /*
- geometric notes:
-
- the FRC contains a mapping from points -> pixels.
-
- typographics points are typically 1/72 of an inch.
-
- pixel displays are often around 72 dpi.
-
- so the FRC can get away with using an identity transform on a screen,
- often. behavior is documented by sun to fall back to an identity
- transform if the internal transformation is null.
-
- coordinates coming up from pango are expressed as floats -- in device
- space, so basically pixels-with-fractional-bits -- derived from their
- storage format in pango (1024ths of pixels).
-
- it is not clear from the javadocs whether the results of methods like
- getGlyphPositions ought to return coordinates in device space, or
- "point" space, or what. for now I'm returning them in device space.
-
- */
-
- public double[] getExtents()
- {
- return extents;
- }
-
- public int[] getCodes()
- {
- return codes;
- }
-
- public Font getFont ()
- {
- return font;
- }
-
- public FontRenderContext getFontRenderContext ()
- {
- return fontRenderContext;
- }
-
- public int getGlyphCharIndex (int glyphIndex)
- {
- // FIXME: currently pango does not provide glyph-by-glyph
- // reverse mapping information, so we assume a broken 1:1
- // glyph model here. This is plainly wrong.
- return glyphIndex;
- }
-
- public int[] getGlyphCharIndices (int beginGlyphIndex,
- int numEntries,
- int[] codeReturn)
- {
- int ix[] = codeReturn;
- if (ix == null)
- ix = new int[numEntries];
-
- for (int i = 0; i < numEntries; i++)
- ix[i] = getGlyphCharIndex (beginGlyphIndex + i);
- return ix;
- }
-
- public int getGlyphCode (int glyphIndex)
- {
- return codes[glyphIndex];
- }
-
- public int[] getGlyphCodes (int beginGlyphIndex, int numEntries,
- int[] codeReturn)
- {
- if (codeReturn == null)
- codeReturn = new int[numEntries];
-
- System.arraycopy(codes, beginGlyphIndex, codeReturn, 0, numEntries);
- return codeReturn;
- }
-
- public Shape getGlyphLogicalBounds (int i)
- {
- return new Rectangle2D.Double (extents[8*i], extents[8*i + 1],
- extents[8*i + 2], extents[8*i + 3]);
- }
-
- public GlyphMetrics getGlyphMetrics (int i)
- {
- // FIXME: pango does not yield vertical layout information at the
- // moment.
-
- boolean is_horizontal = true;
- double advanceX = extents[8*i + 2]; // "logical width" == advanceX
- double advanceY = 0;
-
- return new GlyphMetrics (is_horizontal,
- (float) advanceX, (float) advanceY,
- (Rectangle2D) getGlyphVisualBounds(i),
- GlyphMetrics.STANDARD);
- }
-
- public Shape getGlyphOutline (int glyphIndex)
- {
- throw new UnsupportedOperationException ();
- }
-
- public Shape getGlyphOutline (int glyphIndex, float x, float y)
- {
- throw new UnsupportedOperationException ();
- }
-
- public Rectangle getGlyphPixelBounds (int i,
- FontRenderContext renderFRC,
- float x, float y)
- {
- return new Rectangle((int) x, (int) y,
- (int) extents[8*i + 6], (int) extents[8*i + 7]);
- }
-
- public Point2D getGlyphPosition (int i)
- {
- return new Point2D.Double (extents[10*i + 8],
- extents[10*i + 9]);
- }
-
- public float[] getGlyphPositions (int beginGlyphIndex,
- int numEntries,
- float[] positionReturn)
- {
- float fx[] = positionReturn;
- if (fx == null)
- fx = new float[numEntries * 2];
-
- for (int i = 0; i < numEntries; ++i)
- {
- fx[2*i ] = (float) extents[10*i + 8];
- fx[2*i + 1] = (float) extents[10*i + 9];
- }
- return fx;
- }
-
- public AffineTransform getGlyphTransform (int glyphIndex)
- {
- // Glyphs don't have independent transforms in these simple glyph
- // vectors; docs specify null is an ok return here.
- return null;
- }
-
- public Shape getGlyphVisualBounds (int i)
- {
- return new Rectangle2D.Double(extents[8*i + 4], extents[8*i + 5],
- extents[8*i + 6], extents[8*i + 7]);
- }
-
- public int getLayoutFlags ()
- {
- return 0;
- }
-
- public Rectangle2D getLogicalBounds ()
- {
- return allLogical;
- }
-
- public int getNumGlyphs ()
- {
- return codes.length;
- }
-
- public Shape getOutline ()
- {
- throw new UnsupportedOperationException ();
- }
-
- public Rectangle getPixelBounds (FontRenderContext renderFRC,
- float x, float y)
- {
- return new Rectangle((int)x,
- (int)y,
- (int) allVisual.getWidth(),
- (int) allVisual.getHeight());
- }
-
- public Rectangle2D getVisualBounds ()
- {
- return allVisual;
- }
-
- public void performDefaultLayout ()
- {
- }
-
- public void setGlyphPosition (int i, Point2D newPos)
- {
- extents[8*i ] = newPos.getX();
- extents[8*i + 1] = newPos.getY();
-
- extents[8*i + 4] = newPos.getX();
- extents[8*i + 5] = newPos.getY();
- }
-
- public void setGlyphTransform (int glyphIndex,
- AffineTransform newTX)
- {
- // not yet.. maybe not ever?
- throw new UnsupportedOperationException ();
- }
-
- public boolean equals(GlyphVector gv)
- {
- if (gv == null)
- return false;
-
- if (! (gv instanceof GdkGlyphVector))
- return false;
-
- GdkGlyphVector ggv = (GdkGlyphVector) gv;
-
- if ((ggv.codes.length != this.codes.length)
- || (ggv.extents.length != this.extents.length))
- return false;
-
- if ((ggv.font == null && this.font != null)
- || (ggv.font != null && this.font == null)
- || (!ggv.font.equals(this.font)))
- return false;
-
- if ((ggv.fontRenderContext == null && this.fontRenderContext != null)
- || (ggv.fontRenderContext != null && this.fontRenderContext == null)
- || (!ggv.fontRenderContext.equals(this.fontRenderContext)))
- return false;
-
- for (int i = 0; i < ggv.codes.length; ++i)
- if (ggv.codes[i] != this.codes[i])
- return false;
-
- for (int i = 0; i < ggv.extents.length; ++i)
- if (ggv.extents[i] != this.extents[i])
- return false;
-
- return true;
- }
-
- public GlyphJustificationInfo getGlyphJustificationInfo(int idx)
- {
- throw new UnsupportedOperationException ();
- }
-
- public Shape getOutline(float x, float y)
- {
- throw new UnsupportedOperationException ();
- }
-
-}
diff --git a/gnu/java/awt/peer/gtk/GdkGraphicsConfiguration.java b/gnu/java/awt/peer/gtk/GdkGraphicsConfiguration.java
index 6cf7310a5..147f8f3e6 100644
--- a/gnu/java/awt/peer/gtk/GdkGraphicsConfiguration.java
+++ b/gnu/java/awt/peer/gtk/GdkGraphicsConfiguration.java
@@ -1,5 +1,5 @@
/* GdkGraphicsConfiguration.java -- describes characteristics of graphics
- Copyright (C) 2000, 2001, 2002, 2003, 2004 Free Software Foundation
+ Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006 Free Software Foundation
This file is part of GNU Classpath.
@@ -42,26 +42,33 @@ import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.ImageCapabilities;
import java.awt.Rectangle;
-import java.awt.Toolkit;
+import java.awt.Transparency;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
+import java.awt.image.DirectColorModel;
import java.awt.image.VolatileImage;
public class GdkGraphicsConfiguration
extends GraphicsConfiguration
{
GdkScreenGraphicsDevice gdkScreenGraphicsDevice;
- ColorModel cm;
- Rectangle bounds;
+
+ ColorModel opaqueColorModel;
+ ColorModel bitmaskColorModel;
+
+ ColorModel translucentColorModel;
+
public GdkGraphicsConfiguration(GdkScreenGraphicsDevice dev)
{
- this.gdkScreenGraphicsDevice = dev;
- cm = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB).getColorModel();
- bounds = ((GtkToolkit) Toolkit.getDefaultToolkit()).getBounds();
+ gdkScreenGraphicsDevice = dev;
+
+ opaqueColorModel = new DirectColorModel(32, 0xFF0000, 0xFF00, 0xFF, 0);
+ bitmaskColorModel = new DirectColorModel(32, 0xFF0000, 0xFF00, 0xFF, 0x1000000);
+ translucentColorModel = new DirectColorModel(32, 0xFF0000, 0xFF00, 0xFF, 0xFF000000);
}
public GraphicsDevice getDevice()
@@ -94,12 +101,21 @@ public class GdkGraphicsConfiguration
public ColorModel getColorModel()
{
- return cm;
+ return opaqueColorModel;
}
public ColorModel getColorModel(int transparency)
{
- return getColorModel();
+ switch (transparency)
+ {
+ case Transparency.OPAQUE:
+ return opaqueColorModel;
+ case Transparency.BITMASK:
+ return bitmaskColorModel;
+ default:
+ case Transparency.TRANSLUCENT:
+ return translucentColorModel;
+ }
}
public AffineTransform getDefaultTransform()
@@ -116,7 +132,7 @@ public class GdkGraphicsConfiguration
public Rectangle getBounds()
{
- return bounds;
+ return gdkScreenGraphicsDevice.getBounds();
}
public BufferCapabilities getBufferCapabilities()
@@ -133,8 +149,8 @@ public class GdkGraphicsConfiguration
public VolatileImage createCompatibleVolatileImage(int width, int height, int transparency)
{
- // FIXME: implement
- return null;
+ // FIXME: support the transparency argument
+ return new GtkVolatileImage(width, height);
}
}
diff --git a/gnu/java/awt/peer/gtk/GdkGraphicsEnvironment.java b/gnu/java/awt/peer/gtk/GdkGraphicsEnvironment.java
index 4b0b5d308..035819d1c 100644
--- a/gnu/java/awt/peer/gtk/GdkGraphicsEnvironment.java
+++ b/gnu/java/awt/peer/gtk/GdkGraphicsEnvironment.java
@@ -1,5 +1,5 @@
/* GdkGraphicsEnvironment.java -- information about the graphics environment
- Copyright (C) 2004, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -43,33 +43,71 @@ import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
-import java.awt.Toolkit;
import java.awt.image.BufferedImage;
+import java.awt.image.DataBuffer;
import java.util.Locale;
public class GdkGraphicsEnvironment extends GraphicsEnvironment
{
+ private final int native_state = GtkGenericPeer.getUniqueInteger ();
+
+ private GdkScreenGraphicsDevice defaultDevice;
+
+ private GdkScreenGraphicsDevice[] devices;
+
+ static
+ {
+ System.loadLibrary("gtkpeer");
+
+ initStaticState ();
+ }
+
+ static native void initStaticState();
+
public GdkGraphicsEnvironment ()
{
+ nativeInitState();
}
+
+ native void nativeInitState();
public GraphicsDevice[] getScreenDevices ()
{
- // FIXME: Support multiple screens, since GDK can.
- return new GraphicsDevice[] { new GdkScreenGraphicsDevice (this) };
+ if (devices == null)
+ {
+ devices = nativeGetScreenDevices();
+ }
+
+ return (GraphicsDevice[]) devices.clone();
}
+
+ private native GdkScreenGraphicsDevice[] nativeGetScreenDevices();
public GraphicsDevice getDefaultScreenDevice ()
{
if (GraphicsEnvironment.isHeadless ())
throw new HeadlessException ();
-
- return new GdkScreenGraphicsDevice (this);
+
+ synchronized (GdkGraphicsEnvironment.class)
+ {
+ if (defaultDevice == null)
+ {
+ defaultDevice = nativeGetDefaultScreenDevice();
+ }
+ }
+
+ return defaultDevice;
}
+
+ private native GdkScreenGraphicsDevice nativeGetDefaultScreenDevice();
public Graphics2D createGraphics (BufferedImage image)
{
- return new GdkGraphics2D (image);
+ DataBuffer db = image.getRaster().getDataBuffer();
+ if(db instanceof CairoSurface)
+ return ((CairoSurface)db).getGraphics();
+
+ return new BufferedImageGraphics( image );
}
private native int nativeGetNumFontFamilies();
@@ -80,20 +118,21 @@ public class GdkGraphicsEnvironment extends GraphicsEnvironment
throw new java.lang.UnsupportedOperationException ();
}
- public String[] getAvailableFontFamilyNames ()
- {
- String[] family_names;
- int array_size;
+ public String[] getAvailableFontFamilyNames ()
+ {
+ String[] family_names;
+ int array_size;
- array_size = nativeGetNumFontFamilies();
- family_names = new String[array_size];
+ array_size = nativeGetNumFontFamilies();
+ family_names = new String[array_size];
- nativeGetFontFamilies(family_names);
- return family_names;
- }
+ nativeGetFontFamilies(family_names);
+ return family_names;
+ }
public String[] getAvailableFontFamilyNames (Locale l)
{
throw new java.lang.UnsupportedOperationException ();
}
+
}
diff --git a/gnu/java/awt/peer/gtk/GdkPixbufDecoder.java b/gnu/java/awt/peer/gtk/GdkPixbufDecoder.java
index 72908ff5c..4e6181f0e 100644
--- a/gnu/java/awt/peer/gtk/GdkPixbufDecoder.java
+++ b/gnu/java/awt/peer/gtk/GdkPixbufDecoder.java
@@ -75,10 +75,8 @@ public class GdkPixbufDecoder extends gnu.java.awt.image.ImageDecoder
{
static
{
- if (Configuration.INIT_LOAD_LIBRARY)
- {
- System.loadLibrary("gtkpeer");
- }
+ System.loadLibrary("gtkpeer");
+
initStaticState ();
}
@@ -504,19 +502,19 @@ public class GdkPixbufDecoder extends gnu.java.awt.image.ImageDecoder
int width = ras.getWidth();
int height = ras.getHeight();
ColorModel model = image.getColorModel();
- int[] pixels = GdkGraphics2D.findSimpleIntegerArray (image.getColorModel(), ras);
+ int[] pixels = CairoGraphics2D.findSimpleIntegerArray (image.getColorModel(), ras);
if (pixels == null)
{
- BufferedImage img = new BufferedImage(width, height,
- (model != null && model.hasAlpha() ?
- BufferedImage.TYPE_INT_ARGB
- : BufferedImage.TYPE_INT_RGB));
+ BufferedImage img;
+ if(model != null && model.hasAlpha())
+ img = CairoSurface.getBufferedImage(width, height);
+ img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int[] pix = new int[4];
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
img.setRGB(x, y, model.getRGB(ras.getPixel(x, y, pix)));
- pixels = GdkGraphics2D.findSimpleIntegerArray (img.getColorModel(),
+ pixels = CairoGraphics2D.findSimpleIntegerArray (img.getColorModel(),
img.getRaster());
model = img.getColorModel();
}
@@ -586,9 +584,10 @@ public class GdkPixbufDecoder extends gnu.java.awt.image.ImageDecoder
if (bufferedImage == null)
{
- bufferedImage = new BufferedImage (width, height, (model != null && model.hasAlpha() ?
- BufferedImage.TYPE_INT_ARGB
- : BufferedImage.TYPE_INT_RGB));
+ if(model != null && model.hasAlpha())
+ bufferedImage = new BufferedImage (width, height, BufferedImage.TYPE_INT_ARGB);
+ else
+ bufferedImage = new BufferedImage (width, height, BufferedImage.TYPE_INT_RGB);
}
int pixels2[];
@@ -682,43 +681,4 @@ public class GdkPixbufDecoder extends gnu.java.awt.image.ImageDecoder
return getBufferedImage ();
}
}
-
- // remaining helper class and static method is a convenience for the Gtk
- // peers, for loading a BufferedImage in off a disk file without going
- // through the whole imageio system.
-
- public static BufferedImage createBufferedImage (String filename)
- {
- GdkPixbufReader r = new GdkPixbufReader (getReaderSpi(),
- "png", // reader auto-detects, doesn't matter
- new GdkPixbufDecoder (filename));
- return r.getBufferedImage ();
- }
-
- public static BufferedImage createBufferedImage (URL u)
- {
- GdkPixbufReader r = new GdkPixbufReader (getReaderSpi(),
- "png", // reader auto-detects, doesn't matter
- new GdkPixbufDecoder (u));
- return r.getBufferedImage ();
- }
-
- public static BufferedImage createBufferedImage (byte[] imagedata, int imageoffset,
- int imagelength)
- {
- GdkPixbufReader r = new GdkPixbufReader (getReaderSpi(),
- "png", // reader auto-detects, doesn't matter
- new GdkPixbufDecoder (imagedata,
- imageoffset,
- imagelength));
- return r.getBufferedImage ();
- }
-
- public static BufferedImage createBufferedImage (ImageProducer producer)
- {
- GdkPixbufReader r = new GdkPixbufReader (getReaderSpi(), "png" /* ignored */, null);
- producer.startProduction(r);
- return r.getBufferedImage ();
- }
-
}
diff --git a/gnu/java/awt/peer/gtk/GdkScreenGraphicsDevice.java b/gnu/java/awt/peer/gtk/GdkScreenGraphicsDevice.java
index b5d1237a4..62116a322 100644
--- a/gnu/java/awt/peer/gtk/GdkScreenGraphicsDevice.java
+++ b/gnu/java/awt/peer/gtk/GdkScreenGraphicsDevice.java
@@ -1,5 +1,5 @@
/* GdkScreenGraphicsDevice.java -- information about a screen device
- Copyright (C) 2004, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,44 +38,110 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
-import java.awt.Dimension;
import java.awt.DisplayMode;
+import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
-import java.awt.Toolkit;
+import java.awt.Rectangle;
+import java.awt.Window;
+import java.util.ArrayList;
-public class GdkScreenGraphicsDevice extends GraphicsDevice
+class GdkScreenGraphicsDevice extends GraphicsDevice
{
+ private final int native_state = GtkGenericPeer.getUniqueInteger ();
+
+ private Window fullscreenWindow;
+
+ private boolean oldWindowDecorationState;
+
+ private Rectangle oldWindowBounds;
+
+ private Rectangle bounds;
+
+ private GdkGraphicsConfiguration[] configurations;
+
+ /** The <code>GdkGraphicsEnvironment</code> instance that created this
+ * <code>GdkScreenGraphicsDevice</code>. This is only needed for native
+ * methods which need to access the 'native_state' field storing a pointer
+ * to a GdkDisplay object.
+ */
GdkGraphicsEnvironment env;
+
+ /** An identifier that is created by Gdk
+ */
+ String idString;
+
+ /** The display modes supported by this <code>GdkScreenGraphicsDevice</code>.
+ * If the array is <code>null</code> <code>nativeGetDisplayModes</code> has
+ * to be called.
+ */
+ X11DisplayMode[] displayModes;
- public GdkScreenGraphicsDevice (GdkGraphicsEnvironment e)
- {
- super ();
+ /** The non-changeable display mode of this <code>GdkScreenGraphicsDevice
+ * </code>. This field gets initialized by the {@link #init()} method. If it
+ * is still <code>null</code> afterwards, the XRandR extension is available
+ * and display mode changes are possible. If it is non-null XRandR is not
+ * available, no display mode changes are possible and no other native
+ * method must be called.
+ */
+ DisplayMode fixedDisplayMode;
+
+ static
+ {
+ System.loadLibrary("gtkpeer");
+
+ initStaticState ();
+ }
+
+ static native void initStaticState();
+
+ GdkScreenGraphicsDevice (GdkGraphicsEnvironment e)
+ {
+ super();
env = e;
+
+ configurations = new GdkGraphicsConfiguration[1];
+ configurations[0] = new GdkGraphicsConfiguration(this);
}
+ /** This method is called from the native side immediately after
+ * the constructor is run.
+ */
+ void init()
+ {
+ fixedDisplayMode = nativeGetFixedDisplayMode(env);
+ }
+
+ /** Depending on the availability of the XRandR extension the method returns
+ * the screens' non-changeable display mode or null, meaning that XRandR can
+ * handle display mode changes.
+ */
+ native DisplayMode nativeGetFixedDisplayMode(GdkGraphicsEnvironment env);
+
public int getType ()
{
+ // Gdk manages only raster screens.
return GraphicsDevice.TYPE_RASTER_SCREEN;
}
public String getIDstring ()
{
- // FIXME: query X for this string
- return "default GDK device ID string";
+ if (idString == null)
+ idString = nativeGetIDString();
+
+ return idString;
}
+
+ private native String nativeGetIDString();
public GraphicsConfiguration[] getConfigurations ()
{
- // FIXME: query X for the list of possible configurations
- return new GraphicsConfiguration [] { new GdkGraphicsConfiguration(this) };
+ return (GraphicsConfiguration[]) configurations.clone();
}
-
+
public GraphicsConfiguration getDefaultConfiguration ()
{
-
- // FIXME: query X for default configuration
- return new GdkGraphicsConfiguration(this);
+ return configurations[0];
}
@@ -89,23 +155,193 @@ public class GdkScreenGraphicsDevice extends GraphicsDevice
*/
public DisplayMode getDisplayMode()
{
- // determine display mode
- Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
- DisplayMode mode = new DisplayMode(dim.width, dim.height, 0,
- DisplayMode.REFRESH_RATE_UNKNOWN);
- return mode;
+ if (fixedDisplayMode != null)
+ return fixedDisplayMode;
+
+ synchronized (this)
+ {
+ if (displayModes == null)
+ displayModes = nativeGetDisplayModes(env);
+ }
+
+ int index = nativeGetDisplayModeIndex(env);
+ int rate = nativeGetDisplayModeRate(env);
+
+ return new DisplayMode(displayModes[index].width,
+ displayModes[index].height,
+ DisplayMode.BIT_DEPTH_MULTI,
+ rate);
+ }
+
+ native int nativeGetDisplayModeIndex(GdkGraphicsEnvironment env);
+
+ native int nativeGetDisplayModeRate(GdkGraphicsEnvironment env);
+
+ public DisplayMode[] getDisplayModes()
+ {
+ if (fixedDisplayMode != null)
+ return new DisplayMode[] { fixedDisplayMode };
+
+ synchronized (this)
+ {
+ if (displayModes == null)
+ displayModes = nativeGetDisplayModes(env);
+ }
+
+ ArrayList list = new ArrayList();
+ for(int i=0;i<displayModes.length;i++)
+ for(int j=0;j<displayModes[i].rates.length;j++)
+ list.add(new DisplayMode(displayModes[i].width,
+ displayModes[i].height,
+ DisplayMode.BIT_DEPTH_MULTI,
+ displayModes[i].rates[j]));
+
+ return (DisplayMode[]) list.toArray(new DisplayMode[list.size()]);
}
+
+ native X11DisplayMode[] nativeGetDisplayModes(GdkGraphicsEnvironment env);
/**
- * This device does not yet support fullscreen exclusive mode, so this
- * returns <code>false</code>.
+ * Real fullscreen exclusive mode is not supported.
*
* @return <code>false</code>
* @since 1.4
*/
public boolean isFullScreenSupported()
{
- return false;
+ return true;
+ }
+
+ public boolean isDisplayChangeSupported()
+ {
+ return fixedDisplayMode == null;
+ }
+
+ public void setDisplayMode(DisplayMode dm)
+ {
+ if (fixedDisplayMode != null)
+ throw new UnsupportedOperationException("Cannnot change display mode.");
+
+ if (dm == null)
+ throw new IllegalArgumentException("DisplayMode must not be null.");
+
+ synchronized (this)
+ {
+ if (displayModes == null)
+ displayModes = nativeGetDisplayModes(env);
+ }
+
+ for (int i=0; i<displayModes.length; i++)
+ if (displayModes[i].width == dm.getWidth()
+ && displayModes[i].height == dm.getHeight())
+ {
+ synchronized (this)
+ {
+ nativeSetDisplayMode(env,
+ i,
+ (short) dm.getRefreshRate());
+
+ bounds = null;
+ }
+
+ return;
+ }
+
+ throw new IllegalArgumentException("Mode not supported by this device.");
+ }
+
+ native void nativeSetDisplayMode(GdkGraphicsEnvironment env,
+ int index, short rate);
+
+ /** A class that simply encapsulates the X11 display mode data.
+ */
+ static class X11DisplayMode
+ {
+ short[] rates;
+ int width;
+ int height;
+
+ X11DisplayMode(int width, int height, short[] rates)
+ {
+ this.width = width;
+ this.height = height;
+ this.rates = rates;
+ }
+
+ }
+
+ public void setFullScreenWindow(Window w)
+ {
+ // Bring old fullscreen window back into its original state.
+ if (fullscreenWindow != null && w != fullscreenWindow)
+ {
+ if (fullscreenWindow instanceof Frame)
+ {
+ // Decoration state can only be switched when the peer is
+ // non-existent. That means we have to dispose the
+ // Frame.
+ Frame f = (Frame) fullscreenWindow;
+ if (oldWindowDecorationState != f.isUndecorated())
+ {
+ f.dispose();
+ f.setUndecorated(oldWindowDecorationState);
+ }
+ }
+
+ fullscreenWindow.setBounds(oldWindowBounds);
+
+ if (!fullscreenWindow.isVisible())
+ fullscreenWindow.setVisible(true);
+ }
+
+ // If applicable remove decoration, then maximize the window and
+ // bring it to the foreground.
+ if (w != null)
+ {
+ if (w instanceof Frame)
+ {
+ Frame f = (Frame) w;
+ oldWindowDecorationState = f.isUndecorated();
+ if (!oldWindowDecorationState)
+ {
+ f.dispose();
+ f.setUndecorated(true);
+ }
+ }
+
+ oldWindowBounds = w.getBounds();
+
+ DisplayMode dm = getDisplayMode();
+
+ w.setBounds(0, 0, dm.getWidth(), dm.getHeight());
+
+ if (!w.isVisible())
+ w.setVisible(true);
+
+ w.requestFocus();
+ w.toFront();
+
+ }
+
+ fullscreenWindow = w;
+ }
+
+ public Window getFullScreenWindow()
+ {
+ return fullscreenWindow;
+ }
+
+ Rectangle getBounds()
+ {
+ synchronized(this)
+ {
+ if (bounds == null)
+ bounds = nativeGetBounds();
+ }
+
+ return bounds;
}
+
+ native Rectangle nativeGetBounds();
}
diff --git a/gnu/java/awt/peer/gtk/GdkTextLayout.java b/gnu/java/awt/peer/gtk/GdkTextLayout.java
index 9189bd4b7..a8765222e 100644
--- a/gnu/java/awt/peer/gtk/GdkTextLayout.java
+++ b/gnu/java/awt/peer/gtk/GdkTextLayout.java
@@ -1,5 +1,5 @@
/* GdkTextLayout.java
- Copyright (C) 2003, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2003, 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -70,20 +70,26 @@ public class GdkTextLayout
// native side, plumbing, etc.
static
{
- if (Configuration.INIT_LOAD_LIBRARY)
- {
- System.loadLibrary("gtkpeer");
- }
+ System.loadLibrary("gtkpeer");
+
initStaticState ();
}
private native void setText(String str);
+ private native void setFont(GdkFontPeer font);
private native void getExtents(double[] inkExtents,
double[] logExtents);
private native void indexToPos(int idx, double[] pos);
+
private native void initState ();
+
private native void dispose ();
+
+ private native void cairoDrawGdkTextLayout(long cg2d, float x, float y);
+
static native void initStaticState();
+
private final int native_state = GtkGenericPeer.getUniqueInteger ();
+
protected void finalize ()
{
dispose ();
@@ -99,6 +105,15 @@ public class GdkTextLayout
initState();
attributedString = str;
fontRenderContext = frc;
+ AttributedCharacterIterator aci = str.getIterator();
+ char[] chars = new char[aci.getEndIndex() - aci.getBeginIndex()];
+ for(int i = aci.getBeginIndex(); i < aci.getEndIndex(); i++)
+ chars[i] = aci.setIndex(i);
+ setText(new String(chars));
+
+ Object fnt = aci.getAttribute(TextAttribute.FONT);
+ if (fnt != null && fnt instanceof Font)
+ setFont( (GdkFontPeer) ((Font)fnt).getPeer() );
}
protected class CharacterIteratorProxy
@@ -201,9 +216,7 @@ public class GdkTextLayout
public void draw (Graphics2D g2, float x, float y)
{
- // we share pango structures directly with GdkGraphics2D
- GdkGraphics2D gg2 = (GdkGraphics2D) g2;
- gg2.drawGdkTextLayout(this, x, y);
+ cairoDrawGdkTextLayout(((CairoGraphics2D) g2).nativePointer, x, y);
}
public TextHitInfo getStrongCaret (TextHitInfo hit1,
diff --git a/gnu/java/awt/peer/gtk/GtkComponentPeer.java b/gnu/java/awt/peer/gtk/GtkComponentPeer.java
index 3e464ab1a..625855f01 100644
--- a/gnu/java/awt/peer/gtk/GtkComponentPeer.java
+++ b/gnu/java/awt/peer/gtk/GtkComponentPeer.java
@@ -207,13 +207,7 @@ public class GtkComponentPeer extends GtkGenericPeer
public Image createImage (int width, int height)
{
- Image image;
- image = new BufferedImage (width, height, BufferedImage.TYPE_INT_RGB);
-
- Graphics g = image.getGraphics();
- g.setColor(getBackground());
- g.fillRect(0, 0, width, height);
- return image;
+ return CairoSurface.getBufferedImage(width, height);
}
public void disable ()
@@ -240,7 +234,7 @@ public class GtkComponentPeer extends GtkGenericPeer
// never return null.
public Graphics getGraphics ()
{
- return new GdkGraphics2D (this);
+ return ComponentGraphics.getComponentGraphics(this);
}
public Point getLocationOnScreen ()
@@ -703,7 +697,7 @@ public class GtkComponentPeer extends GtkGenericPeer
// on which this component is displayed.
public VolatileImage createVolatileImage (int width, int height)
{
- return new GtkVolatileImage (width, height);
+ return new GtkVolatileImage (this, width, height, null);
}
// Creates buffers used in a buffering strategy.
@@ -713,7 +707,7 @@ public class GtkComponentPeer extends GtkGenericPeer
// numBuffers == 2 implies double-buffering, meaning one back
// buffer and one front buffer.
if (numBuffers == 2)
- backBuffer = new GtkVolatileImage(awtComponent.getWidth(),
+ backBuffer = new GtkVolatileImage(this, awtComponent.getWidth(),
awtComponent.getHeight(),
caps.getBackBufferCapabilities());
else
diff --git a/gnu/java/awt/peer/gtk/GtkImage.java b/gnu/java/awt/peer/gtk/GtkImage.java
index 83ce2cbef..ef96518a1 100644
--- a/gnu/java/awt/peer/gtk/GtkImage.java
+++ b/gnu/java/awt/peer/gtk/GtkImage.java
@@ -57,14 +57,7 @@ import java.net.URL;
import gnu.classpath.Pointer;
/**
- * GtkImage - wraps a GdkPixbuf or GdkPixmap.
- *
- * The constructor GtkImage(int, int) creates an 'off-screen' GdkPixmap,
- * this can be drawn to (it's a GdkDrawable), and correspondingly, you can
- * create a GdkGraphics object for it.
- *
- * This corresponds to the Image implementation returned by
- * Component.createImage(int, int).
+ * GtkImage - wraps a GdkPixbuf.
*
* A GdkPixbuf is 'on-screen' and the gdk cannot draw to it,
* this is used for the other constructors (and other createImage methods), and
@@ -88,9 +81,10 @@ public class GtkImage extends Image
boolean isLoaded;
/**
- * Pointer to the GdkPixbuf
+ * Pointer to the GdkPixbuf -
+ * don't change the name without changing the native code.
*/
- Pointer pixmap;
+ Pointer pixbuf;
/**
* Observer queue.
@@ -98,11 +92,6 @@ public class GtkImage extends Image
Vector observers;
/**
- * If offScreen is set, a GdkBitmap is wrapped and not a Pixbuf.
- */
- boolean offScreen;
-
- /**
* Error flag for loading.
*/
boolean errorLoading;
@@ -122,71 +111,64 @@ public class GtkImage extends Image
0xFF000000);
/**
+ * The singleton GtkImage that is returned on errors by GtkToolkit.
+ */
+ private static GtkImage errorImage;
+
+ /**
+ * Lock that should be held for all gdkpixbuf operations. We don't use
+ * the global gdk_threads_enter/leave functions in most places since
+ * most gdkpixbuf operations can be done in parallel to drawing and
+ * manipulating gtk widgets.
+ */
+ static Object pixbufLock = new Object();
+
+ /**
+ * Allocate a PixBuf from a given ARGB32 buffer pointer.
+ */
+ private native void initFromBuffer( long bufferPointer );
+
+ /**
* Returns a copy of the pixel data as a java array.
- * Should be called with the GdkPixbufDecoder.pixbufLock held.
+ * Should be called with the pixbufLock held.
*/
- private native int[] getPixels();
+ native int[] getPixels();
/**
* Sets the pixel data from a java array.
- * Should be called with the GdkPixbufDecoder.pixbufLock held.
+ * Should be called with the pixbufLock held.
*/
private native void setPixels(int[] pixels);
/**
* Loads an image using gdk-pixbuf from a file.
- * Should be called with the GdkPixbufDecoder.pixbufLock held.
+ * Should be called with the pixbufLock held.
*/
private native boolean loadPixbuf(String name);
/**
* Loads an image using gdk-pixbuf from data.
- * Should be called with the GdkPixbufDecoder.pixbufLock held.
+ * Should be called with the pixbufLock held.
*/
private native boolean loadImageFromData(byte[] data);
/**
- * Allocates a Gtk Pixbuf or pixmap
- * Should be called with the GdkPixbufDecoder.pixbufLock held.
+ * Allocates a Gtk Pixbuf
+ * Should be called with the pixbufLock held.
*/
- private native void createPixmap();
+ private native void createPixbuf();
/**
* Frees the above.
- * Should be called with the GdkPixbufDecoder.pixbufLock held.
- */
- private native void freePixmap();
-
- /**
- * Sets the pixmap to scaled copy of src image. hints are rendering hints.
- * Should be called with the GdkPixbufDecoder.pixbufLock held.
- */
- private native void createScaledPixmap(GtkImage src, int hints);
-
- /**
- * Draws the image, optionally scaled and composited.
- * Should be called with the GdkPixbufDecoder.pixbufLock held.
- * Also acquires global gdk lock for drawing.
+ * Should be called with the pixbufLock held.
*/
- private native void drawPixelsScaled (GdkGraphics2D gc,
- int bg_red, int bg_green, int bg_blue,
- int x, int y, int width, int height,
- boolean composite);
+ private native void freePixbuf();
/**
- * Draws the image, optionally scaled flipped and composited.
- * Should be called with the GdkPixbufDecoder.pixbufLock held.
- * Also acquires global gdk lock for drawing.
+ * Sets the pixbuf to scaled copy of src image. hints are rendering hints.
+ * Should be called with the pixbufLock held.
*/
- private native void drawPixelsScaledFlipped (GdkGraphics2D gc,
- int bg_red, int bg_green,
- int bg_blue,
- boolean flipX, boolean flipY,
- int srcX, int srcY,
- int srcWidth, int srcHeight,
- int dstX, int dstY,
- int dstWidth, int dstHeight,
- boolean composite);
+ private native void createScaledPixbuf(GtkImage src, int hints);
/**
* Constructs a GtkImage from an ImageProducer. Asynchronity is handled in
@@ -202,7 +184,6 @@ public class GtkImage extends Image
source = producer;
errorLoading = false;
source.startProduction(new GtkImageConsumer(this, source));
- offScreen = false;
}
/**
@@ -215,7 +196,6 @@ public class GtkImage extends Image
{
isLoaded = true;
observers = null;
- offScreen = false;
props = new Hashtable();
errorLoading = false;
}
@@ -231,7 +211,7 @@ public class GtkImage extends Image
try
{
String path = f.getCanonicalPath();
- synchronized(GdkPixbufDecoder.pixbufLock)
+ synchronized(pixbufLock)
{
if (loadPixbuf(f.getCanonicalPath()) != true)
throw new IllegalArgumentException("Couldn't load image: "
@@ -249,7 +229,6 @@ public class GtkImage extends Image
isLoaded = true;
observers = null;
- offScreen = false;
props = new Hashtable();
}
@@ -261,7 +240,7 @@ public class GtkImage extends Image
*/
public GtkImage (byte[] data)
{
- synchronized(GdkPixbufDecoder.pixbufLock)
+ synchronized(pixbufLock)
{
if (loadImageFromData (data) != true)
throw new IllegalArgumentException ("Couldn't load image.");
@@ -269,7 +248,6 @@ public class GtkImage extends Image
isLoaded = true;
observers = null;
- offScreen = false;
props = new Hashtable();
errorLoading = false;
}
@@ -301,7 +279,7 @@ public class GtkImage extends Image
throw new IllegalArgumentException ("Couldn't load image.");
}
byte[] array = baos.toByteArray();
- synchronized(GdkPixbufDecoder.pixbufLock)
+ synchronized(pixbufLock)
{
if (loadImageFromData(array) != true)
throw new IllegalArgumentException ("Couldn't load image.");
@@ -313,23 +291,6 @@ public class GtkImage extends Image
}
/**
- * Constructs an empty GtkImage.
- */
- public GtkImage (int width, int height)
- {
- this.width = width;
- this.height = height;
- props = new Hashtable();
- isLoaded = true;
- observers = null;
- offScreen = true;
- synchronized(GdkPixbufDecoder.pixbufLock)
- {
- createPixmap();
- }
- }
-
- /**
* Constructs a scaled version of the src bitmap, using the GDK.
*/
private GtkImage (GtkImage src, int width, int height, int hints)
@@ -339,12 +300,11 @@ public class GtkImage extends Image
props = new Hashtable();
isLoaded = true;
observers = null;
- offScreen = false;
// Use the GDK scaling method.
- synchronized(GdkPixbufDecoder.pixbufLock)
+ synchronized(pixbufLock)
{
- createScaledPixmap(src, hints);
+ createScaledPixbuf(src, hints);
}
}
@@ -354,19 +314,30 @@ public class GtkImage extends Image
*/
GtkImage (Pointer pixbuf)
{
- pixmap = pixbuf;
- synchronized(GdkPixbufDecoder.pixbufLock)
+ this.pixbuf = pixbuf;
+ synchronized(pixbufLock)
{
createFromPixbuf();
}
isLoaded = true;
observers = null;
- offScreen = false;
props = new Hashtable();
}
- // The singleton GtkImage that is returned on errors by GtkToolkit.
- private static GtkImage errorImage;
+ /**
+ * Wraps a buffer with a GtkImage.
+ *
+ * @param bufferPointer a pointer to an ARGB32 buffer
+ */
+ GtkImage(int width, int height, long bufferPointer)
+ {
+ this.width = width;
+ this.height = height;
+ props = new Hashtable();
+ isLoaded = true;
+ observers = null;
+ initFromBuffer( bufferPointer );
+ }
/**
* Returns an empty GtkImage with the errorLoading flag set.
@@ -385,7 +356,7 @@ public class GtkImage extends Image
/**
* Native helper function for constructor that takes a pixbuf Pointer.
- * Should be called with the GdkPixbufDecoder.pixbufLock held.
+ * Should be called with the pixbufLock held.
*/
private native void createFromPixbuf();
@@ -407,9 +378,9 @@ public class GtkImage extends Image
isLoaded = true;
deliver();
- synchronized(GdkPixbufDecoder.pixbufLock)
+ synchronized(pixbufLock)
{
- createPixmap();
+ createPixbuf();
setPixels(pixels);
}
}
@@ -450,30 +421,28 @@ public class GtkImage extends Image
return null;
int[] pixels;
- synchronized(GdkPixbufDecoder.pixbufLock)
+ synchronized (pixbufLock)
{
- pixels = getPixels();
+ if (!errorLoading)
+ pixels = getPixels();
+ else
+ return null;
}
return new MemoryImageSource(width, height, nativeModel, pixels,
0, width);
}
/**
- * Creates a GdkGraphics context for this pixmap.
+ * Does nothing. Should not be called.
*/
public Graphics getGraphics ()
{
- if (!isLoaded)
- return null;
- if (offScreen)
- return null; // FIXME: (Graphics) new GdkGraphics(this);
- else
- throw new IllegalAccessError("This method only works for off-screen"
- +" Images.");
+ throw new IllegalAccessError("This method only works for off-screen"
+ +" Images.");
}
/**
- * Returns a scaled instance of this pixmap.
+ * Returns a scaled instance of this pixbuf.
*/
public Image getScaledInstance(int width,
int height,
@@ -500,9 +469,9 @@ public class GtkImage extends Image
{
observers = new Vector();
isLoaded = false;
- synchronized(GdkPixbufDecoder.pixbufLock)
+ synchronized(pixbufLock)
{
- freePixmap();
+ freePixbuf();
}
source.startProduction(new GtkImageConsumer(this, source));
}
@@ -512,9 +481,9 @@ public class GtkImage extends Image
{
if (isLoaded)
{
- synchronized(GdkPixbufDecoder.pixbufLock)
+ synchronized(pixbufLock)
{
- freePixmap();
+ freePixbuf();
}
}
}
@@ -535,104 +504,6 @@ public class GtkImage extends Image
return ImageObserver.ALLBITS | ImageObserver.WIDTH | ImageObserver.HEIGHT;
}
- // Drawing methods ////////////////////////////////////////////////
-
- /**
- * Draws an image with eventual scaling/transforming.
- */
- public boolean drawImage (GdkGraphics2D g, int dx1, int dy1, int dx2, int dy2,
- int sx1, int sy1, int sx2, int sy2,
- Color bgcolor, ImageObserver observer)
- {
- if (addObserver(observer))
- return false;
-
- boolean flipX = (dx1 > dx2)^(sx1 > sx2);
- boolean flipY = (dy1 > dy2)^(sy1 > sy2);
- int dstWidth = Math.abs (dx2 - dx1);
- int dstHeight = Math.abs (dy2 - dy1);
- int srcWidth = Math.abs (sx2 - sx1);
- int srcHeight = Math.abs (sy2 - sy1);
- int srcX = (sx1 < sx2) ? sx1 : sx2;
- int srcY = (sy1 < sy2) ? sy1 : sy2;
- int dstX = (dx1 < dx2) ? dx1 : dx2;
- int dstY = (dy1 < dy2) ? dy1 : dy2;
-
- // Clipping. This requires the dst to be scaled as well,
- if (srcWidth > width)
- {
- dstWidth = (int)((double)dstWidth*((double)width/(double)srcWidth));
- srcWidth = width - srcX;
- }
-
- if (srcHeight > height)
- {
- dstHeight = (int)((double)dstHeight*((double)height/(double)srcHeight));
- srcHeight = height - srcY;
- }
-
- if (srcWidth + srcX > width)
- {
- dstWidth = (int)((double)dstWidth * (double)(width - srcX)/(double)srcWidth);
- srcWidth = width - srcX;
- }
-
- if (srcHeight + srcY > height)
- {
- dstHeight = (int)((double)dstHeight * (double)(width - srcY)/(double)srcHeight);
- srcHeight = height - srcY;
- }
-
- if ( this.width <= 0 || this.height <= 0 )
- return true;
-
- if ( srcWidth <= 0 || srcHeight <= 0 || dstWidth <= 0 || dstHeight <= 0)
- return true;
-
- synchronized(GdkPixbufDecoder.pixbufLock)
- {
- if(bgcolor != null)
- drawPixelsScaledFlipped (g, bgcolor.getRed (), bgcolor.getGreen (),
- bgcolor.getBlue (),
- flipX, flipY,
- srcX, srcY,
- srcWidth, srcHeight,
- dstX, dstY,
- dstWidth, dstHeight,
- true);
- else
- drawPixelsScaledFlipped (g, 0, 0, 0, flipX, flipY,
- srcX, srcY, srcWidth, srcHeight,
- dstX, dstY, dstWidth, dstHeight,
- false);
- }
- return true;
- }
-
- /**
- * Draws an image to the GdkGraphics context, at (x,y) scaled to
- * width and height, with optional compositing with a background color.
- */
- public boolean drawImage (GdkGraphics2D g, int x, int y, int width, int height,
- Color bgcolor, ImageObserver observer)
- {
- if (addObserver(observer))
- return false;
-
- if ( this.width <= 0 || this.height <= 0 )
- return true;
-
- synchronized(GdkPixbufDecoder.pixbufLock)
- {
- if(bgcolor != null)
- drawPixelsScaled(g, bgcolor.getRed (), bgcolor.getGreen (),
- bgcolor.getBlue (), x, y, width, height, true);
- else
- drawPixelsScaled(g, 0, 0, 0, x, y, width, height, false);
- }
-
- return true;
- }
// Private methods ////////////////////////////////////////////////
diff --git a/gnu/java/awt/peer/gtk/GtkToolkit.java b/gnu/java/awt/peer/gtk/GtkToolkit.java
index 8e342cb92..163fc52f7 100644
--- a/gnu/java/awt/peer/gtk/GtkToolkit.java
+++ b/gnu/java/awt/peer/gtk/GtkToolkit.java
@@ -88,8 +88,7 @@ public class GtkToolkit extends gnu.java.awt.ClasspathToolkit
static
{
- if (Configuration.INIT_LOAD_LIBRARY)
- System.loadLibrary("gtkpeer");
+ System.loadLibrary("gtkpeer");
int portableNativeSync;
String portNatSyncProp =
@@ -160,7 +159,7 @@ public class GtkToolkit extends gnu.java.awt.ClasspathToolkit
Image image;
try
{
- image = GdkPixbufDecoder.createBufferedImage(filename);
+ image = CairoSurface.getBufferedImage( new GtkImage( filename ) );
}
catch (IllegalArgumentException iae)
{
@@ -174,8 +173,8 @@ public class GtkToolkit extends gnu.java.awt.ClasspathToolkit
Image image;
try
{
- image = GdkPixbufDecoder.createBufferedImage(url);
- }
+ image = CairoSurface.getBufferedImage( new GtkImage( url ) );
+ }
catch (IllegalArgumentException iae)
{
image = null;
@@ -185,10 +184,13 @@ public class GtkToolkit extends gnu.java.awt.ClasspathToolkit
public Image createImage (ImageProducer producer)
{
+ if (producer == null)
+ return null;
+
Image image;
try
{
- image = GdkPixbufDecoder.createBufferedImage(producer);
+ image = CairoSurface.getBufferedImage( new GtkImage( producer ) );
}
catch (IllegalArgumentException iae)
{
@@ -203,9 +205,9 @@ public class GtkToolkit extends gnu.java.awt.ClasspathToolkit
Image image;
try
{
- image = GdkPixbufDecoder.createBufferedImage(imagedata,
- imageoffset,
- imagelength);
+ byte[] data = new byte[ imagelength ];
+ System.arraycopy(imagedata, imageoffset, data, 0, imagelength);
+ image = CairoSurface.getBufferedImage( new GtkImage( data ) );
}
catch (IllegalArgumentException iae)
{
@@ -222,7 +224,7 @@ public class GtkToolkit extends gnu.java.awt.ClasspathToolkit
*/
public ImageProducer createImageProducer(URL url)
{
- return new GdkPixbufDecoder(url);
+ return createImage( url ).getSource();
}
/**
diff --git a/gnu/java/awt/peer/gtk/GtkVolatileImage.java b/gnu/java/awt/peer/gtk/GtkVolatileImage.java
index 496090a09..f38007f19 100644
--- a/gnu/java/awt/peer/gtk/GtkVolatileImage.java
+++ b/gnu/java/awt/peer/gtk/GtkVolatileImage.java
@@ -1,4 +1,4 @@
-/* GtkVolatileImage.java -- a hardware-accelerated image buffer
+/* GtkVolatileImage.java -- wraps an X pixmap
Copyright (C) 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
import java.awt.ImageCapabilities;
+import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.image.BufferedImage;
@@ -46,44 +47,82 @@ import java.awt.image.VolatileImage;
public class GtkVolatileImage extends VolatileImage
{
- private int width;
- private int height;
+ int width, height;
private ImageCapabilities caps;
- public GtkVolatileImage(int width, int height)
+ /**
+ * Don't touch, accessed from native code.
+ */
+ long nativePointer;
+
+ native long init(GtkComponentPeer component, int width, int height);
+
+ native void destroy(long pointer);
+
+ native int[] nativeGetPixels(long pointer);
+ public int[] getPixels()
{
- this(width, height, null);
+ return nativeGetPixels(nativePointer);
}
- public GtkVolatileImage(int width, int height, ImageCapabilities caps)
+ native void nativeCopyArea(long pointer, int x, int y, int w, int h, int dx,
+ int dy );
+ public void copyArea(int x, int y, int w, int h, int dx, int dy)
+ {
+ nativeCopyArea(nativePointer, x, y, w, h, dx, dy);
+ }
+
+ native void nativeDrawVolatile(long pointer, long srcPtr, int x, int y,
+ int w, int h );
+ public void drawVolatile(long srcPtr, int x, int y, int w, int h )
+ {
+ nativeDrawVolatile(nativePointer, srcPtr, x, y, w, h);
+ }
+
+ public GtkVolatileImage(GtkComponentPeer component,
+ int width, int height, ImageCapabilities caps)
{
this.width = width;
this.height = height;
this.caps = caps;
+ nativePointer = init( component, width, height );
}
- // FIXME: should return a buffered image snapshot of the accelerated
- // visual
- public BufferedImage getSnapshot()
+ public GtkVolatileImage(int width, int height, ImageCapabilities caps)
{
- return null;
+ this(null, width, height, caps);
}
- public int getWidth()
+ public GtkVolatileImage(int width, int height)
{
- return width;
+ this(null, width, height, null);
}
- public int getHeight()
+ public void finalize()
{
- return height;
+ dispose();
+ }
+
+ public void dispose()
+ {
+ destroy(nativePointer);
+ }
+
+ public BufferedImage getSnapshot()
+ {
+ CairoSurface cs = new CairoSurface( width, height );
+ cs.setPixels( getPixels() );
+ return CairoSurface.getBufferedImage( cs );
+ }
+
+ public Graphics getGraphics()
+ {
+ return createGraphics();
}
- // FIXME: should return a graphics wrapper around this image's
- // visual
public Graphics2D createGraphics()
{
- return null;
+ return new VolatileImageGraphics( this );
}
public int validate(GraphicsConfiguration gc)
@@ -101,18 +140,28 @@ public class GtkVolatileImage extends VolatileImage
return caps;
}
- public synchronized Object getProperty (String name, ImageObserver observer)
+ public int getWidth()
{
- return null;
+ return width;
+ }
+
+ public int getHeight()
+ {
+ return height;
}
- public synchronized int getWidth (ImageObserver observer)
+ public int getWidth(java.awt.image.ImageObserver observer)
{
return width;
}
- public synchronized int getHeight (ImageObserver observer)
+ public int getHeight(java.awt.image.ImageObserver observer)
{
return height;
}
+
+ public Object getProperty(String name, ImageObserver observer)
+ {
+ return null;
+ }
}
diff --git a/gnu/java/awt/peer/gtk/VolatileImageGraphics.java b/gnu/java/awt/peer/gtk/VolatileImageGraphics.java
new file mode 100644
index 000000000..f45c0e0b9
--- /dev/null
+++ b/gnu/java/awt/peer/gtk/VolatileImageGraphics.java
@@ -0,0 +1,127 @@
+/* VolatileImageGraphics.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.gtk;
+
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.GraphicsConfiguration;
+import java.awt.Image;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.Shape;
+import java.awt.font.GlyphVector;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Rectangle2D;
+import java.awt.image.BufferedImage;
+import java.awt.image.DataBuffer;
+import java.awt.image.DataBufferInt;
+import java.awt.image.ColorModel;
+import java.awt.image.DirectColorModel;
+import java.awt.image.RenderedImage;
+import java.awt.image.ImageObserver;
+import java.util.WeakHashMap;
+
+public class VolatileImageGraphics extends ComponentGraphics
+{
+ private GtkVolatileImage owner;
+
+ public VolatileImageGraphics(GtkVolatileImage img)
+ {
+ this.owner = img;
+ cairo_t = initFromVolatile( owner.nativePointer, img.width, img.height );
+ setup( cairo_t );
+ setClip( new Rectangle( 0, 0, img.width, img.height) );
+ }
+
+ private VolatileImageGraphics(VolatileImageGraphics copy)
+ {
+ this.owner = copy.owner;
+ cairo_t = initFromVolatile(owner.nativePointer, owner.width, owner.height);
+ copy( copy, cairo_t );
+ clipRect(0, 0, owner.width, owner.height);
+ }
+
+ public void copyAreaImpl(int x, int y, int width, int height, int dx, int dy)
+ {
+ owner.copyArea(x, y, width, height, dx, dy);
+ }
+
+ public GraphicsConfiguration getDeviceConfiguration()
+ {
+ return null;
+ }
+
+ public Graphics create()
+ {
+ return new VolatileImageGraphics( this );
+ }
+
+
+ public boolean drawImage(Image img, int x, int y, ImageObserver observer)
+ {
+ if( img instanceof GtkVolatileImage )
+ {
+ owner.drawVolatile( ((GtkVolatileImage)img).nativePointer,
+ x, y,
+ ((GtkVolatileImage)img).width,
+ ((GtkVolatileImage)img).height );
+ return true;
+ }
+ return super.drawImage( img, x, y, observer );
+ }
+
+ public boolean drawImage(Image img, int x, int y, int width, int height,
+ ImageObserver observer)
+ {
+ if( img instanceof GtkVolatileImage )
+ {
+ owner.drawVolatile( ((GtkVolatileImage)img).nativePointer,
+ x, y, width, height );
+ return true;
+ }
+ return super.drawImage( img, x, y, width, height, observer );
+ }
+
+ protected Rectangle2D getRealBounds()
+ {
+ return new Rectangle2D.Double(0, 0, owner.width, owner.height);
+ }
+}
+
diff --git a/gnu/java/awt/peer/qt/QtToolkit.java b/gnu/java/awt/peer/qt/QtToolkit.java
index 591b52803..73652f8df 100644
--- a/gnu/java/awt/peer/qt/QtToolkit.java
+++ b/gnu/java/awt/peer/qt/QtToolkit.java
@@ -136,8 +136,7 @@ public class QtToolkit extends ClasspathToolkit
{
eventQueue = new EventQueue();
repaintThread = new QtRepaintThread();
- if (Configuration.INIT_LOAD_LIBRARY)
- System.loadLibrary("qtpeer");
+ System.loadLibrary("qtpeer");
String theme = null;
try
diff --git a/gnu/java/awt/print/JavaPrinterGraphics.java b/gnu/java/awt/print/JavaPrinterGraphics.java
index af31309ed..9a3db0125 100644
--- a/gnu/java/awt/print/JavaPrinterGraphics.java
+++ b/gnu/java/awt/print/JavaPrinterGraphics.java
@@ -37,7 +37,7 @@ exception statement from your version. */
package gnu.java.awt.print;
-import gnu.java.awt.peer.gtk.GtkImage;
+import gnu.java.awt.peer.gtk.CairoSurface;
import java.awt.Color;
import java.awt.Font;
@@ -185,7 +185,7 @@ public class JavaPrinterGraphics extends Graphics implements PrinterGraphics
// FIXME: This should at least be BufferedImage.
// Fix once we have a working B.I.
// Graphics2D should also be supported of course.
- image = new GtkImage(xSize, ySize);
+ image = CairoSurface.getBufferedImage(xSize, ySize);
g = image.getGraphics();
setColor(Color.white);
diff --git a/gnu/java/io/PlatformHelper.java b/gnu/java/io/PlatformHelper.java
index 79ce6e8f4..e54c56da9 100644
--- a/gnu/java/io/PlatformHelper.java
+++ b/gnu/java/io/PlatformHelper.java
@@ -1,5 +1,5 @@
/* PlatformHelper.java -- Isolate OS-specific IO helper methods and variables
- Copyright (C) 1998, 2002 Free Software Foundation, Inc.
+ Copyright (C) 1998, 2002, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -97,98 +97,6 @@ public class PlatformHelper
}
/**
- * This routine canonicalizes input param "path" to formal path representation
- * for current platform, including interpreting ".." and "." .
- */
- public static final String toCanonicalForm(String path)
- {
- /*??
- if(path.indexOf('.') < 0 && path.indexOf("..") < 0)
- return path;
- */
- String tmppath = path.replace('/', separatorChar);
- StringBuffer canonpath;
-
- int i;
-
- if ((i = beginWithRootPathPrefix(tmppath)) == 0 )
- return path;
-
- /* The original
- "canonpath = new StringBuffer(tmppath.substring(0, i))"
- isn't very efficient because StringBuffer's
- ensureCapacity_unsynchronized will fail definitely each time
- and will enlarge buffer and copy contents. .
- */
- canonpath = new StringBuffer(INITIAL_MAX_PATH);
- canonpath.append(tmppath.substring(0, i));
- tmppath = tmppath.substring(i);
- // pathdepth==0 indicates there're only root path in the buffer
- int pathdepth = 0;
-
- StringTokenizer st = new StringTokenizer(tmppath, separator);
-
- // Traverse each element of the path, handling "." and ".."
- // Should handle "~" too?
- if (st.hasMoreTokens())
- do
- {
- String s = st.nextToken();
-
- // Handle "." or an empty element.
- if (s.equals(".") || s.equals(""))
- continue;
-
- // Handle ".." by deleting the last element from the path
- if (s.equals(".."))
- {
- if (pathdepth == 0)
- continue;
-
- // Strip of trailing separator
- canonpath.setLength(canonpath.length() - 1/*separator.length()*/);
- String tmpstr = canonpath.toString();
- int idx = tmpstr.lastIndexOf(separator);
-
- if ((idx == -1) || ((idx + 1/*separator.length()*/) > tmpstr.length()))
- //throw new IOException("Can't happen error");
- return path; // Shouldn't happen
-
- canonpath.setLength(idx + 1/*separator.length()*/);
- pathdepth--;
- continue;
- }
-
- canonpath.append(s);
- pathdepth++; //now it's more than root path
-
- if (st.hasMoreTokens())
- canonpath.append(separator);
- }
- while (st.hasMoreTokens());
-
- if (endWithSeparator(path))
- canonpath.append(separator);
-
- String tmpstr = canonpath.toString();
- //if (pathdepth > 0 && endWithSeparator(tmpstr) )
- // tmpstr = tmpstr.substring(0, tmpstr.length() - 1/*separator.length()*/);
-
- return tmpstr;
- }
-
- /**
- * This routine canonicalizes input param "path" to formal path representation
- * for current platform, and normalize all separators to "sepchar".
- */
- public static final String toCanonicalForm(String path, char sepchar)
- {
- String tmpstr = toCanonicalForm(path);
- tmpstr = tmpstr.replace(separatorChar, sepchar);
- return tmpstr;
- }
-
- /**
* This routine checks whether input param "path" ends with separator
*/
public static final boolean endWithSeparator(String path)
diff --git a/gnu/java/nio/charset/Provider.java b/gnu/java/nio/charset/Provider.java
index ad3b1da84..b56e5a90e 100644
--- a/gnu/java/nio/charset/Provider.java
+++ b/gnu/java/nio/charset/Provider.java
@@ -155,9 +155,9 @@ public final class Provider extends CharsetProvider
/**
* Load non-mandatory charsets.
*/
- private void loadExtended ()
+ private synchronized void loadExtended ()
{
- if(extendedLoaded)
+ if (extendedLoaded)
return;
addCharset (new ISO_8859_3 ()); // ISO-8859-3 aka ISO-LATIN-3
@@ -165,6 +165,12 @@ public final class Provider extends CharsetProvider
addCharset (new ISO_8859_8 ()); // ISO-8859-8 (Hebrew)
// Some more codepages
+ addCharset (new Cp424());
+ addCharset (new Cp437());
+ addCharset (new Cp737());
+ addCharset (new Cp775());
+ addCharset (new Cp850());
+ addCharset (new Cp852());
addCharset (new Cp855()); // IBM Cyrillic
addCharset (new Cp857()); // IBM Turkish
addCharset (new Cp860()); // MSDOS Portugese
@@ -176,6 +182,24 @@ public final class Provider extends CharsetProvider
addCharset (new Cp866()); // MSDOS Russian
addCharset (new Cp869()); // IBM modern Greek
addCharset (new Cp874()); // IBM Thai
+
+ addCharset (new MacCentralEurope());
+ addCharset (new MacCroatian());
+ addCharset (new MacCyrillic());
+ addCharset (new MacDingbat());
+ addCharset (new MacGreek());
+ addCharset (new MacIceland());
+ addCharset (new MacRoman());
+ addCharset (new MacRomania());
+ addCharset (new MacSymbol());
+ addCharset (new MacThai());
+ addCharset (new MacTurkish());
+ addCharset (new MS874());
+
+ addCharset (new Windows1255());
+ addCharset (new Windows1256());
+ addCharset (new Windows1258());
+
extendedLoaded = true;
}
@@ -199,7 +223,7 @@ public final class Provider extends CharsetProvider
public Charset charsetForName (String charsetName)
{
Charset cs = (Charset) charsets.get(canonicalNames.get(charsetName.toLowerCase()));
- if(cs == null && !extendedLoaded)
+ if (cs == null)
{
loadExtended();
cs = (Charset) charsets.get(canonicalNames.get(charsetName.toLowerCase()));
diff --git a/gnu/java/security/PolicyFile.java b/gnu/java/security/PolicyFile.java
index 3064f041b..8404eeb98 100644
--- a/gnu/java/security/PolicyFile.java
+++ b/gnu/java/security/PolicyFile.java
@@ -1,5 +1,5 @@
/* PolicyFile.java -- policy file reader
- Copyright (C) 2004, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -148,7 +148,7 @@ public final class PolicyFile extends Policy
// Constants and fields.
// -------------------------------------------------------------------------
- private static final Logger logger = SystemLogger.SYSTEM;
+ protected static final Logger logger = SystemLogger.SYSTEM;
private static final String DEFAULT_POLICY =
SystemProperties.getProperty("java.home")
diff --git a/gnu/java/security/Properties.java b/gnu/java/security/Properties.java
index 860b7d928..4e8bc01ea 100644
--- a/gnu/java/security/Properties.java
+++ b/gnu/java/security/Properties.java
@@ -38,13 +38,15 @@ exception statement from your version. */
package gnu.java.security;
+import gnu.classpath.Configuration;
+
import java.io.FileInputStream;
import java.io.IOException;
-import java.io.PrintWriter;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.PropertyPermission;
+import java.util.logging.Logger;
/**
* <p>A global object containing build-specific properties that affect the
@@ -52,25 +54,7 @@ import java.util.PropertyPermission;
*/
public final class Properties
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "Properties";
-
- private static final boolean DEBUG = false;
-
- // private static final int debuglevel = 9;
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(final String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(Properties.class.getName());
public static final String VERSION = "gnu.crypto.version";
public static final String PROPERTIES_FILE = "gnu.crypto.properties.file";
@@ -300,9 +284,8 @@ public final class Properties
}
catch (SecurityException se)
{
- if (DEBUG)
- debug("Reading property " + PROPERTIES_FILE
- + " not allowed. Ignored.");
+ if (Configuration.DEBUG)
+ log.fine("Reading property " + PROPERTIES_FILE + " not allowed. Ignored.");
}
if (propFile != null)
{
@@ -316,14 +299,14 @@ public final class Properties
}
catch (IOException ioe)
{
- if (DEBUG)
- debug("IO error reading " + propFile + ": " + ioe.getMessage());
+ if (Configuration.DEBUG)
+ log.fine("IO error reading " + propFile + ": " + ioe.getMessage());
}
catch (SecurityException se)
{
- if (DEBUG)
- debug("Security error reading " + propFile + ": "
- + se.getMessage());
+ if (Configuration.DEBUG)
+ log.fine("Security error reading " + propFile + ": "
+ + se.getMessage());
}
}
@@ -350,8 +333,8 @@ public final class Properties
}
catch (SecurityException x)
{
- if (DEBUG)
- debug("SecurityManager forbids reading system properties. Ignored");
+ if (Configuration.DEBUG)
+ log.fine("SecurityManager forbids reading system properties. Ignored");
}
if (s != null)
{
@@ -360,14 +343,14 @@ public final class Properties
// hide valid value set previously
if (s.equals(TRUE) || s.equals(FALSE))
{
- if (DEBUG)
- debug("Setting " + name + " to '" + s + "'");
+ if (Configuration.DEBUG)
+ log.fine("Setting " + name + " to '" + s + "'");
props.put(name, s);
}
else
{
- if (DEBUG)
- debug("Invalid value for -D" + name + ": " + s + ". Ignored");
+ if (Configuration.DEBUG)
+ log.fine("Invalid value for -D" + name + ": " + s + ". Ignored");
}
}
}
diff --git a/gnu/java/security/Registry.java b/gnu/java/security/Registry.java
index 0cb925135..9d8ceac8d 100644
--- a/gnu/java/security/Registry.java
+++ b/gnu/java/security/Registry.java
@@ -177,6 +177,9 @@ public interface Registry
/** TLSv1 padding scheme. */
String TLS1_PAD = "tls1";
+ /** ISO 10126-2 padding scheme. */
+ String ISO10126_PAD = "iso10126";
+
// Pseudo-random number generators..........................................
/** (Apparently) RC4 keystream PRNG. */
diff --git a/gnu/java/security/hash/Whirlpool.java b/gnu/java/security/hash/Whirlpool.java
index b10fa53cd..ee40d92b3 100644
--- a/gnu/java/security/hash/Whirlpool.java
+++ b/gnu/java/security/hash/Whirlpool.java
@@ -38,9 +38,12 @@ exception statement from your version. */
package gnu.java.security.hash;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
+import java.util.logging.Logger;
+
/**
* Whirlpool, a new 512-bit hashing function operating on messages less than
* 2 ** 256 bits in length. The function structure is designed according to the
@@ -61,16 +64,7 @@ import gnu.java.security.util.Util;
*/
public final class Whirlpool extends BaseHash
{
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 3;
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(Whirlpool.class.getName());
private static final int BLOCK_SIZE = 64; // inner block size in bytes
/** The digest of the 0-bit long message. */
@@ -183,95 +177,87 @@ public final class Whirlpool extends BaseHash
^ (T7[i++] & 0x00000000000000FFL);
time = System.currentTimeMillis() - time;
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- System.out.println("==========");
- System.out.println();
- System.out.println("Static data");
- System.out.println();
-
- System.out.println();
- System.out.println("T0[]:");
+ log.fine("Static data");
+ log.fine("T0[]:");
+ StringBuilder sb;
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T0[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T0[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T1[]:");
+ log.fine("T1[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T1[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T1[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T2[]:");
+ log.fine("T2[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T2[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T2[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T3[]:");
+ log.fine("T3[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T3[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T3[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T4[]:");
+ log.fine("\nT4[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T4[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T4[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T5[]:");
+ log.fine("T5[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T5[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T5[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T6[]:");
+ log.fine("T6[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T5[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T5[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T7[]:");
+ log.fine("T7[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T5[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T5[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("rc[]:");
+ log.fine("rc[]:");
for (i = 0; i < R; i++)
- System.out.println("0x" + Util.toString(rc[i]));
-
- System.out.println();
+ log.fine("0x" + Util.toString(rc[i]));
- System.out.println();
- System.out.println("Total initialization time: " + time + " ms.");
- System.out.println();
+ log.fine("Total initialization time: " + time + " ms.");
}
}
diff --git a/gnu/java/security/jce/sig/EncodedKeyFactory.java b/gnu/java/security/jce/sig/EncodedKeyFactory.java
index 60152c279..bfee6cc76 100644
--- a/gnu/java/security/jce/sig/EncodedKeyFactory.java
+++ b/gnu/java/security/jce/sig/EncodedKeyFactory.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.security.jce.sig;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.key.dss.DSSPrivateKey;
import gnu.java.security.key.dss.DSSPublicKey;
@@ -196,7 +197,8 @@ public class EncodedKeyFactory
protected PublicKey engineGeneratePublic(KeySpec keySpec)
throws InvalidKeySpecException
{
- log.entering(this.getClass().getName(), "engineGeneratePublic()", keySpec);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineGeneratePublic()", keySpec);
PublicKey result = null;
if (keySpec instanceof DSAPublicKeySpec)
@@ -220,8 +222,9 @@ public class EncodedKeyFactory
}
catch (InvalidParameterException ignored)
{
- log.log(Level.FINE, "Exception in DSSPublicKey.valueOf(). Ignore",
- ignored);
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "Exception in DSSPublicKey.valueOf(). Ignore",
+ ignored);
}
if (! ok) // try RSA
@@ -232,23 +235,25 @@ public class EncodedKeyFactory
}
catch (InvalidParameterException ignored)
{
- log.log(Level.FINE,
- "Exception in GnuRSAPublicKey.valueOf(). Ignore",
- ignored);
+ if (Configuration.DEBUG)
+ log.log(Level.FINE,
+ "Exception in GnuRSAPublicKey.valueOf(). Ignore",
+ ignored);
}
if (! ok) // try DH
result = decodeDHPublicKey(input);
}
-
- log.exiting(this.getClass().getName(), "engineGeneratePublic()", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineGeneratePublic()", result);
return result;
}
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
throws InvalidKeySpecException
{
- log.entering(this.getClass().getName(), "engineGeneratePrivate()", keySpec);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineGeneratePrivate()", keySpec);
PrivateKey result = null;
if (keySpec instanceof DSAPrivateKeySpec)
@@ -272,8 +277,9 @@ public class EncodedKeyFactory
}
catch (InvalidParameterException ignored)
{
- log.log(Level.FINE, "Exception in DSSPrivateKey.valueOf(). Ignore",
- ignored);
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "Exception in DSSPrivateKey.valueOf(). Ignore",
+ ignored);
}
if (! ok) // try RSA
@@ -284,16 +290,17 @@ public class EncodedKeyFactory
}
catch (InvalidParameterException ignored)
{
- log.log(Level.FINE,
- "Exception in GnuRSAPrivateKey.valueOf(). Ignore",
- ignored);
+ if (Configuration.DEBUG)
+ log.log(Level.FINE,
+ "Exception in GnuRSAPrivateKey.valueOf(). Ignore",
+ ignored);
}
if (! ok) // try DH
result = decodeDHPrivateKey(input);
}
-
- log.exiting(this.getClass().getName(), "engineGeneratePrivate()", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineGeneratePrivate()", result);
return result;
}
diff --git a/gnu/java/security/jce/sig/SignatureAdapter.java b/gnu/java/security/jce/sig/SignatureAdapter.java
index 4dcbe78e5..724cc260e 100644
--- a/gnu/java/security/jce/sig/SignatureAdapter.java
+++ b/gnu/java/security/jce/sig/SignatureAdapter.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.security.jce.sig;
+import gnu.classpath.Configuration;
import gnu.java.security.sig.BaseSignature;
import gnu.java.security.sig.ISignature;
import gnu.java.security.sig.ISignatureCodec;
@@ -223,7 +224,8 @@ class SignatureAdapter extends SignatureSpi implements Cloneable
public boolean engineVerify(byte[] sigBytes) throws SignatureException
{
- log.entering("SignatureAdapter", "engineVerify");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineVerify");
Object signature = codec.decodeSignature(sigBytes);
boolean result = false;
@@ -235,8 +237,8 @@ class SignatureAdapter extends SignatureSpi implements Cloneable
{
throw new SignatureException(String.valueOf(x));
}
-
- log.exiting("SignatureAdapter", "engineVerify", new Boolean(result));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineVerify", Boolean.valueOf(result));
return result;
}
diff --git a/gnu/java/security/key/dss/DSSKeyPairGenerator.java b/gnu/java/security/key/dss/DSSKeyPairGenerator.java
index 5aa746147..ca24f36c5 100644
--- a/gnu/java/security/key/dss/DSSKeyPairGenerator.java
+++ b/gnu/java/security/key/dss/DSSKeyPairGenerator.java
@@ -38,12 +38,12 @@ exception statement from your version. */
package gnu.java.security.key.dss;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.hash.Sha160;
import gnu.java.security.key.IKeyPairGenerator;
import gnu.java.security.util.PRNG;
-import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.PrivateKey;
@@ -51,6 +51,7 @@ import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.DSAParameterSpec;
import java.util.Map;
+import java.util.logging.Logger;
/**
* <p>A key-pair generator for asymetric keys to use in conjunction with the DSS
@@ -63,26 +64,7 @@ import java.util.Map;
*/
public class DSSKeyPairGenerator implements IKeyPairGenerator
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "dss";
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 5;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(DSSKeyPairGenerator.class.getName());
/** The BigInteger constant 2. */
private static final BigInteger TWO = new BigInteger("2");
@@ -361,14 +343,14 @@ public class DSSKeyPairGenerator implements IKeyPairGenerator
p = params[FIPS186.DSA_PARAMS_P];
e = params[FIPS186.DSA_PARAMS_E];
g = params[FIPS186.DSA_PARAMS_G];
- if (DEBUG && debuglevel > 0)
+ if (Configuration.DEBUG)
{
- debug("seed: " + seed.toString(16));
- debug("counter: " + counter.intValue());
- debug("q: " + q.toString(16));
- debug("p: " + p.toString(16));
- debug("e: " + e.toString(16));
- debug("g: " + g.toString(16));
+ log.fine("seed: " + seed.toString(16));
+ log.fine("counter: " + counter.intValue());
+ log.fine("q: " + q.toString(16));
+ log.fine("p: " + p.toString(16));
+ log.fine("e: " + e.toString(16));
+ log.fine("g: " + g.toString(16));
}
}
diff --git a/gnu/java/security/key/dss/DSSKeyPairPKCS8Codec.java b/gnu/java/security/key/dss/DSSKeyPairPKCS8Codec.java
index 3a115b963..166178fe4 100644
--- a/gnu/java/security/key/dss/DSSKeyPairPKCS8Codec.java
+++ b/gnu/java/security/key/dss/DSSKeyPairPKCS8Codec.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.security.key.dss;
+import gnu.classpath.Configuration;
import gnu.java.security.OID;
import gnu.java.security.Registry;
import gnu.java.security.der.DER;
@@ -184,7 +185,8 @@ public class DSSKeyPairPKCS8Codec
*/
public PrivateKey decodePrivateKey(byte[] input)
{
- log.entering("DSSKeyPairPKCS8Codec", "decodePrivateKey");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "decodePrivateKey");
if (input == null)
throw new InvalidParameterException("Input bytes MUST NOT be null");
@@ -226,9 +228,11 @@ public class DSSKeyPairPKCS8Codec
g = (BigInteger) val.getValue();
val = der.read();
- log.finest("val = " + val);
+ if (Configuration.DEBUG)
+ log.fine("val = " + val);
byte[] xBytes = (byte[]) val.getValue();
- log.finest(Util.dumpString(xBytes, "xBytes: "));
+ if (Configuration.DEBUG)
+ log.fine(Util.dumpString(xBytes, "xBytes: "));
DERReader der2 = new DERReader(xBytes);
val = der2.read();
DerUtil.checkIsBigInteger(val, "Wrong X field");
@@ -240,8 +244,8 @@ public class DSSKeyPairPKCS8Codec
y.initCause(e);
throw y;
}
-
- log.exiting("DSSKeyPairPKCS8Codec", "decodePrivateKey");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "decodePrivateKey");
return new DSSPrivateKey(Registry.PKCS8_ENCODING_ID, p, q, g, x);
}
}
diff --git a/gnu/java/security/key/dss/DSSPrivateKey.java b/gnu/java/security/key/dss/DSSPrivateKey.java
index fe59cb6d7..a9374557b 100644
--- a/gnu/java/security/key/dss/DSSPrivateKey.java
+++ b/gnu/java/security/key/dss/DSSPrivateKey.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.security.key.dss;
+import gnu.classpath.Configuration;
import gnu.classpath.SystemProperties;
import gnu.java.security.Registry;
import gnu.java.security.key.IKeyPairCodec;
@@ -53,11 +54,6 @@ import java.security.interfaces.DSAPrivateKey;
*/
public class DSSPrivateKey extends DSSKey implements PrivateKey, DSAPrivateKey
{
- // Constants and variables
- // -------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
-
/**
* <p>A randomly or pseudorandomly generated integer with <code>0 &lt; x &lt;
* q</code>.</p>
@@ -210,7 +206,8 @@ public class DSSPrivateKey extends DSSKey implements PrivateKey, DSAPrivateKey
String ls = SystemProperties.getProperty("line.separator");
str = new StringBuilder(this.getClass().getName()).append("(")
.append(super.toString()).append(",").append(ls)
- .append("x=0x").append(DEBUG ? x.toString(16) : "**...*").append(ls)
+ .append("x=0x").append(Configuration.DEBUG ? x.toString(16)
+ : "**...*").append(ls)
.append(")").toString();
}
diff --git a/gnu/java/security/key/rsa/GnuRSAPrivateKey.java b/gnu/java/security/key/rsa/GnuRSAPrivateKey.java
index 920534487..bd39ee657 100644
--- a/gnu/java/security/key/rsa/GnuRSAPrivateKey.java
+++ b/gnu/java/security/key/rsa/GnuRSAPrivateKey.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.security.key.rsa;
+import gnu.classpath.Configuration;
import gnu.classpath.SystemProperties;
import gnu.java.security.Registry;
import gnu.java.security.key.IKeyPairCodec;
@@ -61,11 +62,6 @@ import java.security.interfaces.RSAPrivateKey;
public class GnuRSAPrivateKey extends GnuRSAKey implements PrivateKey,
RSAPrivateCrtKey
{
- // Constants and variables
- // -------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
-
/** The first prime divisor of the modulus. */
private final BigInteger p;
@@ -307,12 +303,18 @@ public class GnuRSAPrivateKey extends GnuRSAKey implements PrivateKey,
String ls = SystemProperties.getProperty("line.separator");
str = new StringBuilder(this.getClass().getName()).append("(")
.append(super.toString()).append(",").append(ls)
- .append("d=0x").append(DEBUG ? d.toString(16) : "**...*").append(ls)
- .append("p=0x").append(DEBUG ? p.toString(16) : "**...*").append(ls)
- .append("q=0x").append(DEBUG ? q.toString(16) : "**...*").append(ls)
- .append("dP=0x").append(DEBUG ? dP.toString(16) : "**...*").append(ls)
- .append("dQ=0x").append(DEBUG ? dQ.toString(16) : "**...*").append(ls)
- .append("qInv=0x").append(DEBUG ? qInv.toString(16) : "**...*").append(ls)
+ .append("d=0x").append(Configuration.DEBUG ? d.toString(16)
+ : "**...*").append(ls)
+ .append("p=0x").append(Configuration.DEBUG ? p.toString(16)
+ : "**...*").append(ls)
+ .append("q=0x").append(Configuration.DEBUG ? q.toString(16)
+ : "**...*").append(ls)
+ .append("dP=0x").append(Configuration.DEBUG ? dP.toString(16)
+ : "**...*").append(ls)
+ .append("dQ=0x").append(Configuration.DEBUG ? dQ.toString(16)
+ : "**...*").append(ls)
+ .append("qInv=0x").append(Configuration.DEBUG ? qInv.toString(16)
+ : "**...*").append(ls)
.append(")").toString();
}
return str;
diff --git a/gnu/java/security/key/rsa/RSAKeyPairGenerator.java b/gnu/java/security/key/rsa/RSAKeyPairGenerator.java
index 39063381f..127b3eac4 100644
--- a/gnu/java/security/key/rsa/RSAKeyPairGenerator.java
+++ b/gnu/java/security/key/rsa/RSAKeyPairGenerator.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.security.key.rsa;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.key.IKeyPairGenerator;
import gnu.java.security.util.PRNG;
@@ -152,8 +153,8 @@ public class RSAKeyPairGenerator implements IKeyPairGenerator
*/
public void setup(Map attributes)
{
- log.entering(this.getClass().getName(), "setup", attributes);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "setup", attributes);
// do we have a SecureRandom, or should we use our own?
rnd = (SecureRandom) attributes.get(SOURCE_OF_RANDOMNESS);
@@ -181,8 +182,8 @@ public class RSAKeyPairGenerator implements IKeyPairGenerator
Integer formatID = (Integer) attributes.get(PREFERRED_ENCODING_FORMAT);
preferredFormat = formatID == null ? DEFAULT_ENCODING_FORMAT
: formatID.intValue();
-
- log.exiting(this.getClass().getName(), "setup");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "setup");
}
/**
@@ -193,7 +194,8 @@ public class RSAKeyPairGenerator implements IKeyPairGenerator
*/
public KeyPair generate()
{
- log.entering(this.getClass().getName(), "generate");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "generate");
BigInteger p, q, n, d;
@@ -243,7 +245,8 @@ public class RSAKeyPairGenerator implements IKeyPairGenerator
PrivateKey secK = new GnuRSAPrivateKey(preferredFormat, p, q, e, d);
KeyPair result = new KeyPair(pubK, secK);
- log.exiting(this.getClass().getName(), "generate", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "generate", result);
return result;
}
diff --git a/gnu/java/security/key/rsa/RSAKeyPairPKCS8Codec.java b/gnu/java/security/key/rsa/RSAKeyPairPKCS8Codec.java
index 0b9809032..14a0a063c 100644
--- a/gnu/java/security/key/rsa/RSAKeyPairPKCS8Codec.java
+++ b/gnu/java/security/key/rsa/RSAKeyPairPKCS8Codec.java
@@ -38,15 +38,7 @@ exception statement from your version. */
package gnu.java.security.key.rsa;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.math.BigInteger;
-import java.security.InvalidParameterException;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.util.ArrayList;
-import java.util.logging.Logger;
-
+import gnu.classpath.Configuration;
import gnu.java.security.OID;
import gnu.java.security.Registry;
import gnu.java.security.der.DER;
@@ -56,6 +48,15 @@ import gnu.java.security.der.DERWriter;
import gnu.java.security.key.IKeyPairCodec;
import gnu.java.security.util.DerUtil;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.InvalidParameterException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.util.ArrayList;
+import java.util.logging.Logger;
+
/**
* An implementation of an {@link IKeyPairCodec} that knows how to encode /
* decode PKCS#8 ASN.1 external representation of RSA private keys.
@@ -122,7 +123,8 @@ public class RSAKeyPairPKCS8Codec
*/
public byte[] encodePrivateKey(PrivateKey key)
{
- log.entering(this.getClass().getName(), "encodePrivateKey()", key);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "encodePrivateKey()", key);
if (! (key instanceof GnuRSAPrivateKey))
throw new InvalidParameterException("Wrong key type");
@@ -190,8 +192,8 @@ public class RSAKeyPairPKCS8Codec
y.initCause(x);
throw y;
}
-
- log.exiting(this.getClass().getName(), "encodePrivateKey()", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "encodePrivateKey()", result);
return result;
}
@@ -213,7 +215,8 @@ public class RSAKeyPairPKCS8Codec
*/
public PrivateKey decodePrivateKey(byte[] input)
{
- log.entering(this.getClass().getName(), "decodePrivateKey()", input);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "decodePrivateKey()", input);
if (input == null)
throw new InvalidParameterException("Input bytes MUST NOT be null");
@@ -287,7 +290,8 @@ public class RSAKeyPairPKCS8Codec
PrivateKey result = new GnuRSAPrivateKey(Registry.PKCS8_ENCODING_ID, n, e,
d, p, q, dP, dQ, qInv);
- log.exiting(this.getClass().getName(), "decodePrivateKey()", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "decodePrivateKey()", result);
return result;
}
}
diff --git a/gnu/java/security/key/rsa/RSAKeyPairX509Codec.java b/gnu/java/security/key/rsa/RSAKeyPairX509Codec.java
index 882d9c7b2..87c5c3a6d 100644
--- a/gnu/java/security/key/rsa/RSAKeyPairX509Codec.java
+++ b/gnu/java/security/key/rsa/RSAKeyPairX509Codec.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.security.key.rsa;
+import gnu.classpath.Configuration;
import gnu.java.security.OID;
import gnu.java.security.Registry;
import gnu.java.security.der.BitString;
@@ -114,7 +115,8 @@ public class RSAKeyPairX509Codec
*/
public byte[] encodePublicKey(PublicKey key)
{
- log.entering(this.getClass().getName(), "encodePublicKey()", key);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "encodePublicKey()", key);
if (! (key instanceof GnuRSAPublicKey))
throw new InvalidParameterException("key");
@@ -160,8 +162,8 @@ public class RSAKeyPairX509Codec
y.initCause(x);
throw y;
}
-
- log.exiting(this.getClass().getName(), "encodePublicKey()", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "encodePublicKey()", result);
return result;
}
@@ -183,7 +185,8 @@ public class RSAKeyPairX509Codec
*/
public PublicKey decodePublicKey(byte[] input)
{
- log.entering(this.getClass().getName(), "decodePublicKey()", input);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "decodePublicKey()", input);
if (input == null)
throw new InvalidParameterException("Input bytes MUST NOT be null");
@@ -235,7 +238,8 @@ public class RSAKeyPairX509Codec
}
PublicKey result = new GnuRSAPublicKey(Registry.X509_ENCODING_ID, n, e);
- log.exiting(this.getClass().getName(), "decodePublicKey()", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "decodePublicKey()", result);
return result;
}
diff --git a/gnu/java/security/pkcs/PKCS7SignedData.java b/gnu/java/security/pkcs/PKCS7SignedData.java
index 0781f4ba9..de2b2f679 100644
--- a/gnu/java/security/pkcs/PKCS7SignedData.java
+++ b/gnu/java/security/pkcs/PKCS7SignedData.java
@@ -37,6 +37,7 @@ exception statement from your version. */
package gnu.java.security.pkcs;
+import gnu.classpath.Configuration;
import gnu.java.security.OID;
import gnu.java.security.ber.BER;
import gnu.java.security.ber.BEREncodingException;
@@ -52,9 +53,7 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-
import java.math.BigInteger;
-
import java.security.cert.CRL;
import java.security.cert.CRLException;
import java.security.cert.Certificate;
@@ -62,7 +61,6 @@ import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509CRL;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
@@ -174,21 +172,22 @@ public class PKCS7SignedData
if (!val.isConstructed())
throw new BEREncodingException("malformed SignedData");
- log.finest("SignedData: " + val);
+ if (Configuration.DEBUG)
+ log.fine("SignedData: " + val);
val = ber.read();
if (val.getTag() != BER.INTEGER)
throw new BEREncodingException("expecting Version");
version = (BigInteger) val.getValue();
-
- log.finest(" Version: " + version);
+ if (Configuration.DEBUG)
+ log.fine(" Version: " + version);
digestAlgorithms = new HashSet();
val = ber.read();
if (!val.isConstructed())
throw new BEREncodingException("malformed DigestAlgorithmIdentifiers");
-
- log.finest(" DigestAlgorithmIdentifiers: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" DigestAlgorithmIdentifiers: " + val);
int count = 0;
DERValue val2 = ber.read();
while (val2 != BER.END_OF_SEQUENCE &&
@@ -196,14 +195,14 @@ public class PKCS7SignedData
{
if (!val2.isConstructed())
throw new BEREncodingException("malformed AlgorithmIdentifier");
-
- log.finest(" AlgorithmIdentifier: " + val2);
+ if (Configuration.DEBUG)
+ log.fine(" AlgorithmIdentifier: " + val2);
count += val2.getEncodedLength();
val2 = ber.read();
if (val2.getTag() != BER.OBJECT_IDENTIFIER)
throw new BEREncodingException("malformed AlgorithmIdentifier");
-
- log.finest(" digestAlgorithmIdentifiers OID: " + val2.getValue());
+ if (Configuration.DEBUG)
+ log.fine(" digestAlgorithmIdentifiers OID: " + val2.getValue());
List algId = new ArrayList(2);
algId.add(val2.getValue());
val2 = ber.read();
@@ -224,23 +223,27 @@ public class PKCS7SignedData
else
algId.add(null);
- log.finest(" digestAlgorithmIdentifiers params: ");
- log.finest(Util.dumpString((byte[]) algId.get(1),
- " digestAlgorithmIdentifiers params: "));
+ if (Configuration.DEBUG)
+ {
+ log.fine(" digestAlgorithmIdentifiers params: ");
+ log.fine(Util.dumpString((byte[]) algId.get(1),
+ " digestAlgorithmIdentifiers params: "));
+ }
digestAlgorithms.add(algId);
}
val = ber.read();
if (!val.isConstructed())
throw new BEREncodingException("malformed ContentInfo");
-
- log.finest(" ContentInfo: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" ContentInfo: " + val);
val2 = ber.read();
if (val2.getTag() != BER.OBJECT_IDENTIFIER)
throw new BEREncodingException("malformed ContentType");
contentType = (OID) val2.getValue();
- log.finest(" ContentType OID: " + contentType);
+ if (Configuration.DEBUG)
+ log.fine(" ContentType OID: " + contentType);
if (BERValue.isIndefinite(val)
|| (val.getLength() > 0 && val.getLength() > val2.getEncodedLength()))
{
@@ -252,17 +255,18 @@ public class PKCS7SignedData
val2 = ber.read();
}
}
-
- log.finest(" Content: ");
- log.finest(Util.dumpString(content, " Content: "));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine(" Content: ");
+ log.fine(Util.dumpString(content, " Content: "));
+ }
val = ber.read();
if (val.getTag() == 0)
{
if (!val.isConstructed())
throw new BEREncodingException("malformed ExtendedCertificatesAndCertificates");
-
- log.finest(" ExtendedCertificatesAndCertificates: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" ExtendedCertificatesAndCertificates: " + val);
count = 0;
val2 = ber.read();
List certs = new LinkedList();
@@ -271,7 +275,8 @@ public class PKCS7SignedData
{
Certificate cert =
x509.generateCertificate(new ByteArrayInputStream(val2.getEncoded()));
- log.finest(" Certificate: " + cert);
+ if (Configuration.DEBUG)
+ log.fine(" Certificate: " + cert);
certs.add(cert);
count += val2.getEncodedLength();
ber.skip(val2.getLength());
@@ -286,8 +291,8 @@ public class PKCS7SignedData
{
if (!val.isConstructed())
throw new BEREncodingException("malformed CertificateRevocationLists");
-
- log.finest(" CertificateRevocationLists: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" CertificateRevocationLists: " + val);
count = 0;
val2 = ber.read();
List crls = new LinkedList();
@@ -295,7 +300,8 @@ public class PKCS7SignedData
(val.getLength() > 0 && val.getLength() > count))
{
CRL crl = x509.generateCRL(new ByteArrayInputStream(val2.getEncoded()));
- log.finest(" CRL: " + crl);
+ if (Configuration.DEBUG)
+ log.fine(" CRL: " + crl);
crls.add(crl);
count += val2.getEncodedLength();
ber.skip(val2.getLength());
@@ -309,8 +315,8 @@ public class PKCS7SignedData
signerInfos = new HashSet();
if (!val.isConstructed())
throw new BEREncodingException("malformed SignerInfos");
-
- log.finest(" SignerInfos: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" SignerInfos: " + val);
// FIXME read this more carefully.
// Since we are just reading a file (probably) we just read until we
diff --git a/gnu/java/security/pkcs/SignerInfo.java b/gnu/java/security/pkcs/SignerInfo.java
index 7b38bfefd..662bcc3b7 100644
--- a/gnu/java/security/pkcs/SignerInfo.java
+++ b/gnu/java/security/pkcs/SignerInfo.java
@@ -37,6 +37,7 @@ exception statement from your version. */
package gnu.java.security.pkcs;
+import gnu.classpath.Configuration;
import gnu.java.security.OID;
import gnu.java.security.ber.BER;
import gnu.java.security.ber.BEREncodingException;
@@ -50,7 +51,6 @@ import gnu.java.security.util.Util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.logging.Logger;
@@ -101,7 +101,8 @@ public class SignerInfo
public SignerInfo(BERReader ber) throws IOException
{
DERValue val = ber.read();
- log.finest("SignerInfo: " + val);
+ if (Configuration.DEBUG)
+ log.fine("SignerInfo: " + val);
if (!val.isConstructed())
throw new BEREncodingException("malformed SignerInfo");
@@ -110,13 +111,13 @@ public class SignerInfo
throw new BEREncodingException("malformed Version");
version = (BigInteger) val.getValue();
- log.finest(" Version: " + version);
+ log.fine(" Version: " + version);
val = ber.read();
if (!val.isConstructed())
throw new BEREncodingException("malformed IssuerAndSerialNumber");
-
- log.finest(" IssuerAndSerialNumber: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" IssuerAndSerialNumber: " + val);
val = ber.read();
if (!val.isConstructed())
@@ -124,20 +125,22 @@ public class SignerInfo
issuer = new X500Principal(val.getEncoded());
ber.skip(val.getLength());
- log.finest(" Issuer: " + issuer);
+ if (Configuration.DEBUG)
+ log.fine(" Issuer: " + issuer);
val = ber.read();
if (val.getTag() != BER.INTEGER)
throw new BEREncodingException("malformed SerialNumber");
serialNumber = (BigInteger) val.getValue();
- log.finest(" SerialNumber: " + serialNumber);
+ if (Configuration.DEBUG)
+ log.fine(" SerialNumber: " + serialNumber);
val = ber.read();
if (!val.isConstructed())
throw new BEREncodingException("malformed DigestAlgorithmIdentifier");
-
- log.finest(" DigestAlgorithmIdentifier: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" DigestAlgorithmIdentifier: " + val);
int count = 0;
DERValue val2 = ber.read();
@@ -145,7 +148,8 @@ public class SignerInfo
throw new BEREncodingException("malformed AlgorithmIdentifier");
digestAlgorithmId = (OID) val2.getValue();
- log.finest(" digestAlgorithm OID: " + digestAlgorithmId);
+ if (Configuration.DEBUG)
+ log.fine(" digestAlgorithm OID: " + digestAlgorithmId);
if (BERValue.isIndefinite(val))
{
@@ -170,10 +174,12 @@ public class SignerInfo
else
digestAlgorithmParams = null;
- log.finest(" digestAlgorithm params: ");
- log.finest(Util.dumpString(digestAlgorithmParams,
- " digestAlgorithm params: "));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine(" digestAlgorithm params: ");
+ log.fine(Util.dumpString(digestAlgorithmParams,
+ " digestAlgorithm params: "));
+ }
val = ber.read();
if (val.getTag() == 0)
{
@@ -187,21 +193,24 @@ public class SignerInfo
else
authenticatedAttributes = null;
- log.finest(" AuthenticatedAttributes: ");
- log.finest(Util.dumpString(authenticatedAttributes,
- " AuthenticatedAttributes: "));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine(" AuthenticatedAttributes: ");
+ log.fine(Util.dumpString(authenticatedAttributes,
+ " AuthenticatedAttributes: "));
+ }
if (!val.isConstructed())
throw new BEREncodingException("malformed DigestEncryptionAlgorithmIdentifier");
-
- log.finest(" DigestEncryptionAlgorithmIdentifier: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" DigestEncryptionAlgorithmIdentifier: " + val);
count = 0;
val2 = ber.read();
if (val2.getTag() != BER.OBJECT_IDENTIFIER)
throw new BEREncodingException("malformed AlgorithmIdentifier");
digestEncryptionAlgorithmId = (OID) val2.getValue();
- log.finest(" digestEncryptionAlgorithm OID: " + digestEncryptionAlgorithmId);
+ if (Configuration.DEBUG)
+ log.fine(" digestEncryptionAlgorithm OID: " + digestEncryptionAlgorithmId);
if (BERValue.isIndefinite(val))
{
@@ -226,27 +235,33 @@ public class SignerInfo
else
digestEncryptionAlgorithmParams = null;
- log.finest(" digestEncryptionAlgorithm params: ");
- log.finest(Util.dumpString(digestEncryptionAlgorithmParams,
- " digestEncryptionAlgorithm params: "));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine(" digestEncryptionAlgorithm params: ");
+ log.fine(Util.dumpString(digestEncryptionAlgorithmParams,
+ " digestEncryptionAlgorithm params: "));
+ }
val = ber.read();
if (val.getTag() != BER.OCTET_STRING)
throw new BEREncodingException("malformed EncryptedDigest");
encryptedDigest = (byte[]) val.getValue();
- log.finest(" EncryptedDigest: ");
- log.finest(Util.dumpString(encryptedDigest, " EncryptedDigest: "));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine(" EncryptedDigest: ");
+ log.fine(Util.dumpString(encryptedDigest, " EncryptedDigest: "));
+ }
if (ber.peek() == 1)
unauthenticatedAttributes = ber.read().getEncoded();
else
unauthenticatedAttributes = null;
- log.finest(" UnauthenticatedAttributes: ");
- log.finest(Util.dumpString(unauthenticatedAttributes,
- " UnauthenticatedAttributes: "));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine(" UnauthenticatedAttributes: ");
+ log.fine(Util.dumpString(unauthenticatedAttributes,
+ " UnauthenticatedAttributes: "));
+ }
if (ber.peek() == 0)
ber.read();
}
diff --git a/gnu/java/security/provider/PKIXCertPathValidatorImpl.java b/gnu/java/security/provider/PKIXCertPathValidatorImpl.java
index 880163731..3680f2fae 100644
--- a/gnu/java/security/provider/PKIXCertPathValidatorImpl.java
+++ b/gnu/java/security/provider/PKIXCertPathValidatorImpl.java
@@ -1,5 +1,5 @@
/* PKIXCertPathValidatorImpl.java -- PKIX certificate path validator.
- Copyright (C) 2004, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.security.provider;
+import gnu.classpath.Configuration;
import gnu.java.security.OID;
import gnu.java.security.Registry;
import gnu.java.security.key.dss.DSSPublicKey;
@@ -81,6 +82,7 @@ import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
+import java.util.logging.Logger;
/**
* An implementation of the Public Key Infrastructure's X.509
@@ -94,17 +96,7 @@ import java.util.Set;
*/
public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
{
-
- // Constants.
- // -------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
- private static void debug (String msg)
- {
- System.err.print (">> PKIXCertPathValidatorImpl: ");
- System.err.println (msg);
- }
-
+ private static final Logger log = Logger.getLogger(PKIXCertPathValidatorImpl.class.getName());
public static final String ANY_POLICY = "2.5.29.32.0";
// Constructor.
@@ -435,7 +427,7 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
* @param crl The CRL being checked.
* @param path The path this CRL is being checked against.
* @param now The value to use as 'now'.
- * @param pubKeySubject The subject of the public key.
+ * @param pubKeyCert The certificate authenticating the public key.
* @param pubKey The public key to check.
* @return True if the CRL is acceptable.
*/
@@ -603,7 +595,8 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
boolean explicitPolicy)
throws CertPathValidatorException
{
- if (DEBUG) debug("updatePolicyTree depth == " + depth);
+ if (Configuration.DEBUG)
+ log.fine("updatePolicyTree depth == " + depth);
Set nodes = new HashSet();
LinkedList stack = new LinkedList();
Iterator current = null;
@@ -614,15 +607,18 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
while (current.hasNext())
{
PolicyNodeImpl p = (PolicyNodeImpl) current.next();
- if (DEBUG) debug("visiting node == " + p);
+ if (Configuration.DEBUG)
+ log.fine("visiting node == " + p);
if (p.getDepth() == depth - 1)
{
- if (DEBUG) debug("added node");
+ if (Configuration.DEBUG)
+ log.fine("added node");
nodes.add(p);
}
else
{
- if (DEBUG) debug("skipped node");
+ if (Configuration.DEBUG)
+ log.fine("skipped node");
stack.addLast(current);
current = p.getChildren();
}
@@ -646,16 +642,21 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
else
cp = Collections.EMPTY_LIST;
boolean match = false;
- if (DEBUG) debug("nodes are == " + nodes);
- if (DEBUG) debug("cert policies are == " + cp);
+ if (Configuration.DEBUG)
+ {
+ log.fine("nodes are == " + nodes);
+ log.fine("cert policies are == " + cp);
+ }
for (Iterator it = nodes.iterator(); it.hasNext(); )
{
PolicyNodeImpl parent = (PolicyNodeImpl) it.next();
- if (DEBUG) debug("adding policies to " + parent);
+ if (Configuration.DEBUG)
+ log.fine("adding policies to " + parent);
for (Iterator it2 = cp.iterator(); it2.hasNext(); )
{
OID policy = (OID) it2.next();
- if (DEBUG) debug("trying to add policy == " + policy);
+ if (Configuration.DEBUG)
+ log.fine("trying to add policy == " + policy);
if (policy.toString().equals(ANY_POLICY) &&
params.isAnyPolicyInhibited())
continue;
@@ -691,13 +692,15 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
private boolean checkExplicitPolicy (int depth, List explicitPolicies)
{
- if (DEBUG) debug ("checkExplicitPolicy depth=" + depth);
+ if (Configuration.DEBUG)
+ log.fine("checkExplicitPolicy depth=" + depth);
for (Iterator it = explicitPolicies.iterator(); it.hasNext(); )
{
int[] i = (int[]) it.next();
int caDepth = i[0];
int limit = i[1];
- if (DEBUG) debug (" caDepth=" + caDepth + " limit=" + limit);
+ if (Configuration.DEBUG)
+ log.fine(" caDepth=" + caDepth + " limit=" + limit);
if (depth - caDepth >= limit)
return true;
}
diff --git a/gnu/java/security/sig/ISignature.java b/gnu/java/security/sig/ISignature.java
index e77f39d2c..9ad853a29 100644
--- a/gnu/java/security/sig/ISignature.java
+++ b/gnu/java/security/sig/ISignature.java
@@ -71,9 +71,9 @@ public interface ISignature extends Cloneable
/**
* Property name of an optional {@link java.security.SecureRandom},
- * {@link java.util.Random}, or {@link gnu.crypto.prng.IRandom} instance to
+ * {@link java.util.Random}, or {@link gnu.java.security.prng.IRandom} instance to
* use. The default is to use a classloader singleton from
- * {@link gnu.crypto.util.PRNG}.
+ * {@link gnu.java.security.util.PRNG}.
*/
public static final String SOURCE_OF_RANDOMNESS = "gnu.crypto.sig.prng";
diff --git a/gnu/java/security/sig/rsa/EMSA_PSS.java b/gnu/java/security/sig/rsa/EMSA_PSS.java
index c1c9760ed..0b93abab7 100644
--- a/gnu/java/security/sig/rsa/EMSA_PSS.java
+++ b/gnu/java/security/sig/rsa/EMSA_PSS.java
@@ -38,12 +38,13 @@ exception statement from your version. */
package gnu.java.security.sig.rsa;
+import gnu.classpath.Configuration;
import gnu.java.security.hash.HashFactory;
import gnu.java.security.hash.IMessageDigest;
import gnu.java.security.util.Util;
-import java.io.PrintWriter;
import java.util.Arrays;
+import java.util.logging.Logger;
/**
* <p>An implementation of the EMSA-PSS encoding/decoding scheme.</p>
@@ -70,26 +71,7 @@ import java.util.Arrays;
*/
public class EMSA_PSS implements Cloneable
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "emsa-pss";
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 5;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(EMSA_PSS.class.getName());
/** The underlying hash function to use with this instance. */
private IMessageDigest hash;
@@ -202,10 +184,10 @@ public class EMSA_PSS implements Cloneable
System.arraycopy(salt, 0, DB, emLen - sLen - hLen - 1, sLen);
// 9. Let dbMask = MGF(H, emLen - hLen - 1).
byte[] dbMask = MGF(H, emLen - hLen - 1);
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- debug("dbMask (encode): " + Util.toString(dbMask));
- debug("DB (encode): " + Util.toString(DB));
+ log.fine("dbMask (encode): " + Util.toString(dbMask));
+ log.fine("DB (encode): " + Util.toString(DB));
}
// 10. Let maskedDB = DB XOR dbMask.
for (i = 0; i < DB.length; i++)
@@ -244,12 +226,12 @@ public class EMSA_PSS implements Cloneable
*/
public boolean decode(byte[] mHash, byte[] EM, int emBits, int sLen)
{
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- debug("mHash: " + Util.toString(mHash));
- debug("EM: " + Util.toString(EM));
- debug("emBits: " + String.valueOf(emBits));
- debug("sLen: " + String.valueOf(sLen));
+ log.fine("mHash: " + Util.toString(mHash));
+ log.fine("EM: " + Util.toString(EM));
+ log.fine("emBits: " + String.valueOf(emBits));
+ log.fine("sLen: " + String.valueOf(sLen));
}
if (sLen < 0)
{
@@ -262,19 +244,15 @@ public class EMSA_PSS implements Cloneable
// 2. Let mHash = Hash(M), an octet string of length hLen.
if (hLen != mHash.length)
{
- if (DEBUG && debuglevel > 8)
- {
- debug("hLen != mHash.length; hLen: " + String.valueOf(hLen));
- }
+ if (Configuration.DEBUG)
+ log.fine("hLen != mHash.length; hLen: " + String.valueOf(hLen));
throw new IllegalArgumentException("wrong hash");
}
// 3. If emBits < 8.hLen + 8.sLen + 9, output 'decoding error' and stop.
if (emBits < (8 * hLen + 8 * sLen + 9))
{
- if (DEBUG && debuglevel > 8)
- {
- debug("emBits < (8hLen + 8sLen + 9); sLen: " + String.valueOf(sLen));
- }
+ if (Configuration.DEBUG)
+ log.fine("emBits < (8hLen + 8sLen + 9); sLen: " + String.valueOf(sLen));
throw new IllegalArgumentException("decoding error");
}
int emLen = (emBits + 7) / 8;
@@ -282,10 +260,8 @@ public class EMSA_PSS implements Cloneable
// output 'inconsistent' and stop.
if ((EM[EM.length - 1] & 0xFF) != 0xBC)
{
- if (DEBUG && debuglevel > 8)
- {
- debug("EM does not end with 0xBC");
- }
+ if (Configuration.DEBUG)
+ log.fine("EM does not end with 0xBC");
return false;
}
// 5. Let maskedDB be the leftmost emLen ? hLen ? 1 octets of EM, and let
@@ -294,10 +270,8 @@ public class EMSA_PSS implements Cloneable
// maskedDB are not all equal to zero, output 'inconsistent' and stop.
if ((EM[0] & (0xFF << (8 - (8 * emLen - emBits)))) != 0)
{
- if (DEBUG && debuglevel > 8)
- {
- debug("Leftmost 8emLen - emBits bits of EM are not 0s");
- }
+ if (Configuration.DEBUG)
+ log.fine("Leftmost 8emLen - emBits bits of EM are not 0s");
return false;
}
byte[] DB = new byte[emLen - hLen - 1];
@@ -314,10 +288,10 @@ public class EMSA_PSS implements Cloneable
}
// 9. Set the leftmost 8.emLen ? emBits bits of DB to zero.
DB[0] &= (0xFF >>> (8 * emLen - emBits));
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- debug("dbMask (decode): " + Util.toString(dbMask));
- debug("DB (decode): " + Util.toString(DB));
+ log.fine("dbMask (decode): " + Util.toString(dbMask));
+ log.fine("DB (decode): " + Util.toString(DB));
}
// 10. If the emLen -hLen -sLen -2 leftmost octets of DB are not zero or
// if the octet at position emLen -hLen -sLen -1 is not equal to 0x01,
@@ -329,20 +303,16 @@ public class EMSA_PSS implements Cloneable
{
if (DB[i] != 0)
{
- if (DEBUG && debuglevel > 8)
- {
- debug("DB[" + String.valueOf(i) + "] != 0x00");
- }
+ if (Configuration.DEBUG)
+ log.fine("DB[" + String.valueOf(i) + "] != 0x00");
return false;
}
}
if (DB[i] != 0x01)
{ // i == emLen -hLen -sLen -2
- if (DEBUG && debuglevel > 8)
- {
- debug("DB's byte at position (emLen -hLen -sLen -2); i.e. "
- + String.valueOf(i) + " is not 0x01");
- }
+ if (Configuration.DEBUG)
+ log.fine("DB's byte at position (emLen -hLen -sLen -2); i.e. "
+ + String.valueOf(i) + " is not 0x01");
return false;
}
// 11. Let salt be the last sLen octets of DB.
diff --git a/gnu/java/security/sig/rsa/RSAPSSSignature.java b/gnu/java/security/sig/rsa/RSAPSSSignature.java
index 7ec62568a..3e9cad452 100644
--- a/gnu/java/security/sig/rsa/RSAPSSSignature.java
+++ b/gnu/java/security/sig/rsa/RSAPSSSignature.java
@@ -38,18 +38,19 @@ exception statement from your version. */
package gnu.java.security.sig.rsa;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.hash.HashFactory;
import gnu.java.security.hash.IMessageDigest;
import gnu.java.security.sig.BaseSignature;
import gnu.java.security.util.Util;
-import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
+import java.util.logging.Logger;
/**
* <p>The RSA-PSS signature scheme is a public-key encryption scheme combining
@@ -73,26 +74,7 @@ import java.security.interfaces.RSAPublicKey;
*/
public class RSAPSSSignature extends BaseSignature
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "rsa-pss";
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 1;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(RSAPSSSignature.class.getName());
/** The underlying EMSA-PSS instance for this object. */
private EMSA_PSS pss;
@@ -201,10 +183,8 @@ public class RSAPSSSignature extends BaseSignature
byte[] salt = new byte[sLen];
this.nextRandomBytes(salt);
byte[] EM = pss.encode(md.digest(), modBits - 1, salt);
- if (DEBUG && debuglevel > 8)
- {
- debug("EM (sign): " + Util.toString(EM));
- }
+ if (Configuration.DEBUG)
+ log.fine("EM (sign): " + Util.toString(EM));
// 2. Convert the encoded message EM to an integer message representative
// m (see Section 1.2.2): m = OS2IP(EM).
BigInteger m = new BigInteger(1, EM);
@@ -262,10 +242,8 @@ public class RSAPSSSignature extends BaseSignature
int emBits = modBits - 1;
int emLen = (emBits + 7) / 8;
byte[] EM = m.toByteArray();
- if (DEBUG && debuglevel > 8)
- {
- debug("EM (verify): " + Util.toString(EM));
- }
+ if (Configuration.DEBUG)
+ log.fine("EM (verify): " + Util.toString(EM));
if (EM.length > emLen)
{
return false;
diff --git a/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java b/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java
index 2be79165f..1ae295e36 100644
--- a/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java
+++ b/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java
@@ -44,7 +44,7 @@ import gnu.java.security.sig.ISignatureCodec;
import java.io.ByteArrayOutputStream;
/**
- * <p>An object that implements the {@link gnu.crypto.sig.ISignatureCodec}
+ * <p>An object that implements the {@link ISignatureCodec}
* operations for the <i>Raw</i> format to use with RSA-PSS signatures.</p>
*/
public class RSAPSSSignatureRawCodec implements ISignatureCodec
diff --git a/gnu/java/security/util/Base64.java b/gnu/java/security/util/Base64.java
index f9998c38f..6c4657b7c 100644
--- a/gnu/java/security/util/Base64.java
+++ b/gnu/java/security/util/Base64.java
@@ -38,8 +38,10 @@ exception statement from your version. */
package gnu.java.security.util;
-import java.io.PrintWriter;
+import gnu.classpath.Configuration;
+
import java.io.UnsupportedEncodingException;
+import java.util.logging.Logger;
/**
* Most of this implementation is from Robert Harder's public domain Base64
@@ -47,26 +49,7 @@ import java.io.UnsupportedEncodingException;
*/
public class Base64
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "Base64";
-
- private static final boolean DEBUG = true;
-
- private static final int debuglevel = 9;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(Base64.class.getName());
/** Maximum line length (76) of Base64 output. */
private static final int MAX_LINE_LENGTH = 76;
@@ -383,12 +366,12 @@ public class Base64
}
catch (Exception x)
{
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- debug("" + src[sOffset] + ": " + (DECODABET[src[sOffset]]));
- debug("" + src[sOffset + 1] + ": " + (DECODABET[src[sOffset + 1]]));
- debug("" + src[sOffset + 2] + ": " + (DECODABET[src[sOffset + 2]]));
- debug("" + src[sOffset + 3] + ": " + (DECODABET[src[sOffset + 3]]));
+ log.fine("" + src[sOffset ] + ": " + (DECODABET[src[sOffset ]]));
+ log.fine("" + src[sOffset + 1] + ": " + (DECODABET[src[sOffset + 1]]));
+ log.fine("" + src[sOffset + 2] + ": " + (DECODABET[src[sOffset + 2]]));
+ log.fine("" + src[sOffset + 3] + ": " + (DECODABET[src[sOffset + 3]]));
}
return -1;
}
diff --git a/gnu/java/security/util/ExpirableObject.java b/gnu/java/security/util/ExpirableObject.java
index 2d4452015..c14b75957 100644
--- a/gnu/java/security/util/ExpirableObject.java
+++ b/gnu/java/security/util/ExpirableObject.java
@@ -51,7 +51,7 @@ import javax.security.auth.Destroyable;
* once a timeout elapses, will automatically call the {@link
* Destroyable#destroy()} method.
*
- * <p>Concrete subclasses must implement the {@link doDestroy()} method
+ * <p>Concrete subclasses must implement the {@link #doDestroy()} method
* instead of {@link Destroyable#destroy()}; the behavior of that method
* should match exactly the behavior desired of <code>destroy()</code>.
*
@@ -111,7 +111,7 @@ public abstract class ExpirableObject implements Destroyable
// -------------------------------------------------------------------------
/**
- * Destroys this object. This method calls {@link doDestroy}, then, if
+ * Destroys this object. This method calls {@link #doDestroy}, then, if
* no exception is thrown, cancels the task that would destroy this object
* when the timeout is reached.
*
diff --git a/gnu/java/security/util/Prime2.java b/gnu/java/security/util/Prime2.java
index 6e46f5fca..49e4072f6 100644
--- a/gnu/java/security/util/Prime2.java
+++ b/gnu/java/security/util/Prime2.java
@@ -38,37 +38,20 @@ exception statement from your version. */
package gnu.java.security.util;
-import java.io.PrintWriter;
+import gnu.classpath.Configuration;
+
import java.lang.ref.WeakReference;
import java.math.BigInteger;
import java.util.Map;
import java.util.WeakHashMap;
+import java.util.logging.Logger;
/**
* <p>A collection of prime number related utilities used in this library.</p>
*/
public class Prime2
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "prime";
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 5;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(Prime2.class.getName());
private static final int DEFAULT_CERTAINTY = 20; // XXX is this a good value?
private static final BigInteger ZERO = BigInteger.ZERO;
@@ -116,7 +99,7 @@ public class Prime2
}
}
time += System.currentTimeMillis();
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
StringBuffer sb;
for (int i = 0; i < (SMALL_PRIME_COUNT / 10); i++)
@@ -126,13 +109,13 @@ public class Prime2
{
sb.append(String.valueOf(SMALL_PRIME[i * 10 + j])).append(" ");
}
- debug(sb.toString());
+ log.fine(sb.toString());
}
}
- if (DEBUG && debuglevel > 4)
+ if (Configuration.DEBUG)
{
- debug("Generating first " + String.valueOf(SMALL_PRIME_COUNT)
- + " primes took: " + String.valueOf(time) + " ms.");
+ log.fine("Generating first " + String.valueOf(SMALL_PRIME_COUNT)
+ + " primes took: " + String.valueOf(time) + " ms.");
}
}
@@ -169,17 +152,13 @@ public class Prime2
prime = SMALL_PRIME[i];
if (w.mod(prime).equals(ZERO))
{
- if (DEBUG && debuglevel > 4)
- {
- debug(prime.toString(16) + " | " + w.toString(16) + "...");
- }
+ if (Configuration.DEBUG)
+ log.fine(prime.toString(16) + " | " + w.toString(16) + "...");
return true;
}
}
- if (DEBUG && debuglevel > 4)
- {
- debug(w.toString(16) + " has no small prime divisors...");
- }
+ if (Configuration.DEBUG)
+ log.fine(w.toString(16) + " has no small prime divisors...");
return false;
}
@@ -361,8 +340,8 @@ public class Prime2
for (int i = 0; i < SMALL_PRIME_COUNT; i++)
if (w.equals(SMALL_PRIME[i]))
{
- if (DEBUG && debuglevel > 4)
- debug(w.toString(16) + " is a small prime");
+ if (Configuration.DEBUG)
+ log.fine(w.toString(16) + " is a small prime");
return true;
}
@@ -370,16 +349,16 @@ public class Prime2
WeakReference obj = (WeakReference) knownPrimes.get(w);
if (obj != null && w.equals(obj.get()))
{
- if (DEBUG && debuglevel > 4)
- debug("found in known primes");
+ if (Configuration.DEBUG)
+ log.fine("found in known primes");
return true;
}
// trial division with first 1000 primes
if (hasSmallPrimeDivisor(w))
{
- if (DEBUG && debuglevel > 4)
- debug(w.toString(16) + " has a small prime divisor. Rejected...");
+ if (Configuration.DEBUG)
+ log.fine(w.toString(16) + " has a small prime divisor. Rejected...");
return false;
}
@@ -411,7 +390,7 @@ public class Prime2
private static final void debugBI(String msg, BigInteger bn)
{
- if (DEBUG && debuglevel > 4)
- debug("*** " + msg + ": 0x" + bn.toString(16));
+ if (Configuration.DEBUG)
+ log.fine("*** " + msg + ": 0x" + bn.toString(16));
}
}
diff --git a/gnu/java/security/util/SimpleList.java b/gnu/java/security/util/SimpleList.java
index b2525c4b8..8636b4e14 100644
--- a/gnu/java/security/util/SimpleList.java
+++ b/gnu/java/security/util/SimpleList.java
@@ -61,7 +61,7 @@ public final class SimpleList extends AbstractList
/**
* Create a singleton list.
*
- * @param e1 The first element.
+ * @param element The first element.
*/
public SimpleList(final Object element)
{
diff --git a/gnu/java/security/x509/Util.java b/gnu/java/security/x509/Util.java
index d27392026..1bd268a51 100644
--- a/gnu/java/security/x509/Util.java
+++ b/gnu/java/security/x509/Util.java
@@ -1,5 +1,5 @@
/* Util.java -- Miscellaneous utility methods.
- Copyright (C) 2004 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -155,7 +155,7 @@ public final class Util
}
/**
- * See {@link #hexDump(byte[],int,int)}.
+ * See {@link #hexDump(byte[],int,int,String)}.
*/
public static String hexDump(byte[] buf, String prefix)
{
diff --git a/gnu/java/security/x509/X509CRL.java b/gnu/java/security/x509/X509CRL.java
index 5b2d3b141..d8cbe988b 100644
--- a/gnu/java/security/x509/X509CRL.java
+++ b/gnu/java/security/x509/X509CRL.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.security.x509;
+import gnu.classpath.Configuration;
import gnu.java.security.OID;
import gnu.java.security.der.BitString;
import gnu.java.security.der.DER;
@@ -64,6 +65,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
+import java.util.logging.Logger;
import javax.security.auth.x500.X500Principal;
@@ -75,20 +77,7 @@ import javax.security.auth.x500.X500Principal;
public class X509CRL extends java.security.cert.X509CRL
implements GnuPKIExtension
{
-
- // Constants and fields.
- // ------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
- private static void debug(String msg)
- {
- if (DEBUG)
- {
- System.err.print(">> X509CRL: ");
- System.err.println(msg);
- }
- }
-
+ private static final Logger log = Logger.getLogger(X509CRL.class.getName());
private static final OID ID_DSA = new OID("1.2.840.10040.4.1");
private static final OID ID_DSA_WITH_SHA1 = new OID("1.2.840.10040.4.3");
private static final OID ID_RSA = new OID("1.2.840.113549.1.1.1");
@@ -350,7 +339,8 @@ public class X509CRL extends java.security.cert.X509CRL
// CertificateList ::= SEQUENCE {
DERReader der = new DERReader(in);
DERValue val = der.read();
- debug("start CertificateList len == " + val.getLength());
+ if (Configuration.DEBUG)
+ log.fine("start CertificateList len == " + val.getLength());
if (!val.isConstructed())
throw new IOException("malformed CertificateList");
encoded = val.getEncoded();
@@ -359,7 +349,8 @@ public class X509CRL extends java.security.cert.X509CRL
val = der.read();
if (!val.isConstructed())
throw new IOException("malformed TBSCertList");
- debug("start tbsCertList len == " + val.getLength());
+ if (Configuration.DEBUG)
+ log.fine("start tbsCertList len == " + val.getLength());
tbsCRLBytes = val.getEncoded();
// version Version OPTIONAL,
@@ -372,19 +363,23 @@ public class X509CRL extends java.security.cert.X509CRL
}
else
version = 1;
- debug("read version == " + version);
+ if (Configuration.DEBUG)
+ log.fine("read version == " + version);
// signature AlgorithmIdentifier,
- debug("start AlgorithmIdentifier len == " + val.getLength());
+ if (Configuration.DEBUG)
+ log.fine("start AlgorithmIdentifier len == " + val.getLength());
if (!val.isConstructed())
throw new IOException("malformed AlgorithmIdentifier");
DERValue algIdVal = der.read();
algId = (OID) algIdVal.getValue();
- debug("read object identifier == " + algId);
+ if (Configuration.DEBUG)
+ log.fine("read object identifier == " + algId);
if (val.getLength() > algIdVal.getEncodedLength())
{
val = der.read();
- debug("read parameters len == " + val.getEncodedLength());
+ if (Configuration.DEBUG)
+ log.fine("read parameters len == " + val.getEncodedLength());
algParams = val.getEncoded();
if (val.isConstructed())
in.skip(val.getLength());
@@ -394,18 +389,21 @@ public class X509CRL extends java.security.cert.X509CRL
val = der.read();
issuerDN = new X500DistinguishedName(val.getEncoded());
der.skip(val.getLength());
- debug("read issuer == " + issuerDN);
+ if (Configuration.DEBUG)
+ log.fine("read issuer == " + issuerDN);
// thisUpdate Time,
thisUpdate = (Date) der.read().getValue();
- debug("read thisUpdate == " + thisUpdate);
+ if (Configuration.DEBUG)
+ log.fine("read thisUpdate == " + thisUpdate);
// nextUpdate Time OPTIONAL,
val = der.read();
if (val.getValue() instanceof Date)
{
nextUpdate = (Date) val.getValue();
- debug("read nextUpdate == " + nextUpdate);
+ if (Configuration.DEBUG)
+ log.fine("read nextUpdate == " + nextUpdate);
val = der.read();
}
@@ -433,7 +431,8 @@ public class X509CRL extends java.security.cert.X509CRL
DERValue exts = der.read();
if (!exts.isConstructed())
throw new IOException("malformed Extensions");
- debug("start Extensions len == " + exts.getLength());
+ if (Configuration.DEBUG)
+ log.fine("start Extensions len == " + exts.getLength());
int len = 0;
while (len < exts.getLength())
{
@@ -444,32 +443,42 @@ public class X509CRL extends java.security.cert.X509CRL
extensions.put(e.getOid(), e);
der.skip(ext.getLength());
len += ext.getEncodedLength();
- debug("current count == " + len);
+ if (Configuration.DEBUG)
+ log.fine("current count == " + len);
}
val = der.read();
}
- debug("read tag == " + val.getTag());
+ if (Configuration.DEBUG)
+ log.fine("read tag == " + val.getTag());
if (!val.isConstructed())
throw new IOException("malformed AlgorithmIdentifier");
- debug("start AlgorithmIdentifier len == " + val.getLength());
+ if (Configuration.DEBUG)
+ log.fine("start AlgorithmIdentifier len == " + val.getLength());
DERValue sigAlgVal = der.read();
- debug("read tag == " + sigAlgVal.getTag());
+ if (Configuration.DEBUG)
+ log.fine("read tag == " + sigAlgVal.getTag());
if (sigAlgVal.getTag() != DER.OBJECT_IDENTIFIER)
throw new IOException("malformed AlgorithmIdentifier");
sigAlg = (OID) sigAlgVal.getValue();
- debug("signature id == " + sigAlg);
- debug("sigAlgVal length == " + sigAlgVal.getEncodedLength());
+ if (Configuration.DEBUG)
+ {
+ log.fine("signature id == " + sigAlg);
+ log.fine("sigAlgVal length == " + sigAlgVal.getEncodedLength());
+ }
if (val.getLength() > sigAlgVal.getEncodedLength())
{
val = der.read();
- debug("sig params tag = " + val.getTag() + " len == " + val.getEncodedLength());
+ if (Configuration.DEBUG)
+ log.fine("sig params tag = " + val.getTag() + " len == "
+ + val.getEncodedLength());
sigAlgParams = (byte[]) val.getEncoded();
if (val.isConstructed())
in.skip(val.getLength());
}
val = der.read();
- debug("read tag = " + val.getTag());
+ if (Configuration.DEBUG)
+ log.fine("read tag = " + val.getTag());
rawSig = val.getEncoded();
signature = ((BitString) val.getValue()).toByteArray();
}
diff --git a/gnu/java/security/x509/X509CRLEntry.java b/gnu/java/security/x509/X509CRLEntry.java
index a3bcfdea8..f3f3a93d6 100644
--- a/gnu/java/security/x509/X509CRLEntry.java
+++ b/gnu/java/security/x509/X509CRLEntry.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.security.x509;
+import gnu.classpath.Configuration;
import gnu.java.security.OID;
import gnu.java.security.der.DERReader;
import gnu.java.security.der.DERValue;
@@ -53,6 +54,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
+import java.util.logging.Logger;
/**
* A single entry in a X.509 certificate revocation list.
@@ -63,20 +65,7 @@ import java.util.Set;
class X509CRLEntry extends java.security.cert.X509CRLEntry
implements GnuPKIExtension
{
-
- // Constants and fields.
- // ------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
- private static void debug(String msg)
- {
- if (DEBUG)
- {
- System.err.print(">> X509CRLEntry: ");
- System.err.println(msg);
- }
- }
-
+ private static final Logger log = Logger.getLogger(X509CRLEntry.class.getName());
/** The DER encoded form of this CRL entry. */
private byte[] encoded;
@@ -230,26 +219,29 @@ class X509CRLEntry extends java.security.cert.X509CRLEntry
{
// RevokedCertificate ::= SEQUENCE {
DERValue entry = der.read();
- debug("start CRL entry len == " + entry.getLength());
+ if (Configuration.DEBUG)
+ log.fine("start CRL entry len == " + entry.getLength());
if (!entry.isConstructed())
throw new IOException("malformed revokedCertificate");
encoded = entry.getEncoded();
int len = 0;
-
- debug("encoded entry:\n" + Util.hexDump(encoded, ">>>> "));
+ if (Configuration.DEBUG)
+ log.fine("encoded entry:\n" + Util.hexDump(encoded, ">>>> "));
// userCertificate CertificateSerialNumber,
DERValue val = der.read();
serialNo = (BigInteger) val.getValue();
len += val.getEncodedLength();
- debug("userCertificate == " + serialNo + " current count == " + len);
+ if (Configuration.DEBUG)
+ log.fine("userCertificate == " + serialNo + " current count == " + len);
// revocationDate Time,
val = der.read();
revocationDate = (Date) val.getValue();
len += val.getEncodedLength();
- debug("revocationDate == " + revocationDate + " current count == " + len);
-
+ if (Configuration.DEBUG)
+ log.fine("revocationDate == " + revocationDate + " current count == "
+ + len);
// crlEntryExtensions Extensions OPTIONAL
// -- if present MUST be v2
if (len < entry.getLength())
@@ -259,19 +251,22 @@ class X509CRLEntry extends java.security.cert.X509CRLEntry
DERValue exts = der.read();
if (!exts.isConstructed())
throw new IOException("malformed Extensions");
- debug("start Extensions len == " + exts.getLength());
+ if (Configuration.DEBUG)
+ log.fine("start Extensions len == " + exts.getLength());
len = 0;
while (len < exts.getLength())
{
val = der.read();
if (!val.isConstructed())
throw new IOException("malformed Extension");
- debug("start Extension len == " + val.getLength());
+ if (Configuration.DEBUG)
+ log.fine("start Extension len == " + val.getLength());
Extension e = new Extension(val.getEncoded());
extensions.put(e.getOid(), e);
der.skip(val.getLength());
len += val.getEncodedLength();
- debug("current count == " + len);
+ if (Configuration.DEBUG)
+ log.fine("current count == " + len);
}
}
}
diff --git a/gnu/java/security/x509/ext/Extension.java b/gnu/java/security/x509/ext/Extension.java
index 97097a2f3..4deafe23e 100644
--- a/gnu/java/security/x509/ext/Extension.java
+++ b/gnu/java/security/x509/ext/Extension.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.security.x509.ext;
+import gnu.classpath.Configuration;
import gnu.java.security.OID;
import gnu.java.security.der.DER;
import gnu.java.security.der.DERReader;
@@ -48,20 +49,11 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import java.util.logging.Logger;
public class Extension
{
-
- // Fields.
- // -------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
- private static void debug(String msg)
- {
- System.err.print(">> Extension: ");
- System.err.println(msg);
- }
-
+ private static final Logger log = Logger.getLogger(Extension.class.getName());
/**
* This extension's object identifier.
*/
@@ -97,7 +89,8 @@ public class Extension
// Extension ::= SEQUENCE {
DERValue val = der.read();
- if (DEBUG) debug("read val tag == " + val.getTag() + " len == " + val.getLength());
+ if (Configuration.DEBUG)
+ log.fine("read val tag == " + val.getTag() + " len == " + val.getLength());
if (!val.isConstructed())
throw new IOException("malformed Extension");
@@ -106,7 +99,8 @@ public class Extension
if (val.getTag() != DER.OBJECT_IDENTIFIER)
throw new IOException("expecting OBJECT IDENTIFIER");
oid = (OID) val.getValue();
- if (DEBUG) debug("read oid == " + oid);
+ if (Configuration.DEBUG)
+ log.fine("read oid == " + oid);
// critical BOOLEAN DEFAULT FALSE,
val = der.read();
@@ -117,7 +111,8 @@ public class Extension
}
else
critical = false;
- if (DEBUG) debug("is critical == " + critical);
+ if (Configuration.DEBUG)
+ log.fine("is critical == " + critical);
// extnValue OCTET STRING }
if (val.getTag() != DER.OCTET_STRING)
@@ -181,7 +176,8 @@ public class Extension
value = new Value(encval);
isSupported = false;
}
- if (DEBUG) debug("read value == " + value);
+ if (Configuration.DEBUG)
+ log.fine("read value == " + value);
}
public Extension (final OID oid, final Value value, final boolean critical)
diff --git a/gnu/java/security/x509/ext/GeneralNames.java b/gnu/java/security/x509/ext/GeneralNames.java
index dae94cd9f..81c090f4c 100644
--- a/gnu/java/security/x509/ext/GeneralNames.java
+++ b/gnu/java/security/x509/ext/GeneralNames.java
@@ -1,5 +1,5 @@
/* GeneralNames.java -- the GeneralNames object
- Copyright (C) 2004 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -42,7 +42,6 @@ import gnu.java.security.OID;
import gnu.java.security.der.DER;
import gnu.java.security.der.DERReader;
import gnu.java.security.der.DERValue;
-import gnu.java.security.x509.X500DistinguishedName;
import java.io.IOException;
import java.net.InetAddress;
diff --git a/gnu/regexp/BacktrackStack.java b/gnu/java/util/regex/BacktrackStack.java
index 0fc73f044..d711945e4 100644
--- a/gnu/regexp/BacktrackStack.java
+++ b/gnu/java/util/regex/BacktrackStack.java
@@ -36,7 +36,7 @@ obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
/**
* An instance of this class represents a stack
diff --git a/gnu/regexp/CharIndexed.java b/gnu/java/util/regex/CharIndexed.java
index 8aedc49f6..6cd857e3b 100644
--- a/gnu/regexp/CharIndexed.java
+++ b/gnu/java/util/regex/CharIndexed.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
/**
* Defines the interface used internally so that different types of source
diff --git a/gnu/regexp/CharIndexedCharArray.java b/gnu/java/util/regex/CharIndexedCharArray.java
index 96a609beb..6f74c992f 100644
--- a/gnu/regexp/CharIndexedCharArray.java
+++ b/gnu/java/util/regex/CharIndexedCharArray.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
import java.nio.CharBuffer;
class CharIndexedCharArray extends CharIndexedCharSequence {
diff --git a/gnu/regexp/CharIndexedCharSequence.java b/gnu/java/util/regex/CharIndexedCharSequence.java
index 5bbe4abfe..2eb753b0f 100644
--- a/gnu/regexp/CharIndexedCharSequence.java
+++ b/gnu/java/util/regex/CharIndexedCharSequence.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
import java.io.Serializable;
class CharIndexedCharSequence implements CharIndexed, Serializable {
diff --git a/gnu/regexp/CharIndexedInputStream.java b/gnu/java/util/regex/CharIndexedInputStream.java
index 290a94e7f..77cd1abd5 100644
--- a/gnu/regexp/CharIndexedInputStream.java
+++ b/gnu/java/util/regex/CharIndexedInputStream.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
diff --git a/gnu/regexp/CharIndexedString.java b/gnu/java/util/regex/CharIndexedString.java
index 24982659b..fab6d7836 100644
--- a/gnu/regexp/CharIndexedString.java
+++ b/gnu/java/util/regex/CharIndexedString.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
class CharIndexedString extends CharIndexedCharSequence {
CharIndexedString(String str, int index) {
diff --git a/gnu/regexp/CharIndexedStringBuffer.java b/gnu/java/util/regex/CharIndexedStringBuffer.java
index d6b03bba5..10005b668 100644
--- a/gnu/regexp/CharIndexedStringBuffer.java
+++ b/gnu/java/util/regex/CharIndexedStringBuffer.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
class CharIndexedStringBuffer extends CharIndexedCharSequence {
diff --git a/gnu/regexp/RE.java b/gnu/java/util/regex/RE.java
index e0665f097..cd12aab8f 100644
--- a/gnu/regexp/RE.java
+++ b/gnu/java/util/regex/RE.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Locale;
diff --git a/gnu/regexp/REException.java b/gnu/java/util/regex/REException.java
index 73f86fa8a..4104fbcd8 100644
--- a/gnu/regexp/REException.java
+++ b/gnu/java/util/regex/REException.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
import java.text.MessageFormat;
diff --git a/gnu/regexp/REFilterInputStream.java b/gnu/java/util/regex/REFilterInputStream.java
index 485de5660..abe86308b 100644
--- a/gnu/regexp/REFilterInputStream.java
+++ b/gnu/java/util/regex/REFilterInputStream.java
@@ -36,7 +36,7 @@ obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
import java.io.FilterInputStream;
import java.io.InputStream;
diff --git a/gnu/regexp/REMatch.java b/gnu/java/util/regex/REMatch.java
index 140a9c43e..3ff5ad794 100644
--- a/gnu/regexp/REMatch.java
+++ b/gnu/java/util/regex/REMatch.java
@@ -36,7 +36,7 @@ obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
import java.io.Serializable;
/**
diff --git a/gnu/regexp/REMatchEnumeration.java b/gnu/java/util/regex/REMatchEnumeration.java
index f164a69af..bc700beac 100644
--- a/gnu/regexp/REMatchEnumeration.java
+++ b/gnu/java/util/regex/REMatchEnumeration.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.NoSuchElementException;
diff --git a/gnu/regexp/RESyntax.java b/gnu/java/util/regex/RESyntax.java
index 81fd999bf..b66b32f58 100644
--- a/gnu/regexp/RESyntax.java
+++ b/gnu/java/util/regex/RESyntax.java
@@ -36,7 +36,7 @@ obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
import java.io.Serializable;
import java.util.BitSet;
diff --git a/gnu/regexp/REToken.java b/gnu/java/util/regex/REToken.java
index f2abc029f..155c01878 100644
--- a/gnu/regexp/REToken.java
+++ b/gnu/java/util/regex/REToken.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
import java.io.Serializable;
abstract class REToken implements Serializable, Cloneable {
diff --git a/gnu/regexp/RETokenAny.java b/gnu/java/util/regex/RETokenAny.java
index a37d9561b..b99a54717 100644
--- a/gnu/regexp/RETokenAny.java
+++ b/gnu/java/util/regex/RETokenAny.java
@@ -36,7 +36,7 @@ obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
final class RETokenAny extends REToken {
/** True if '.' can match a newline (RE_DOT_NEWLINE) */
diff --git a/gnu/regexp/RETokenBackRef.java b/gnu/java/util/regex/RETokenBackRef.java
index 25ef9522e..3a912f9bb 100644
--- a/gnu/regexp/RETokenBackRef.java
+++ b/gnu/java/util/regex/RETokenBackRef.java
@@ -36,7 +36,7 @@ obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
final class RETokenBackRef extends REToken {
private int num;
diff --git a/gnu/regexp/RETokenChar.java b/gnu/java/util/regex/RETokenChar.java
index 1b3a74855..92d3efcf8 100644
--- a/gnu/regexp/RETokenChar.java
+++ b/gnu/java/util/regex/RETokenChar.java
@@ -36,7 +36,7 @@ obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
final class RETokenChar extends REToken {
private char[] ch;
diff --git a/gnu/regexp/RETokenEnd.java b/gnu/java/util/regex/RETokenEnd.java
index deb2fc54d..c846415e1 100644
--- a/gnu/regexp/RETokenEnd.java
+++ b/gnu/java/util/regex/RETokenEnd.java
@@ -36,7 +36,7 @@ obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
final class RETokenEnd extends REToken {
/**
diff --git a/gnu/regexp/RETokenEndOfPreviousMatch.java b/gnu/java/util/regex/RETokenEndOfPreviousMatch.java
index 167d10b5f..ea5580e16 100644
--- a/gnu/regexp/RETokenEndOfPreviousMatch.java
+++ b/gnu/java/util/regex/RETokenEndOfPreviousMatch.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
class RETokenEndOfPreviousMatch extends RETokenStart {
diff --git a/gnu/regexp/RETokenEndSub.java b/gnu/java/util/regex/RETokenEndSub.java
index fca01c7f3..57a146d03 100644
--- a/gnu/regexp/RETokenEndSub.java
+++ b/gnu/java/util/regex/RETokenEndSub.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
final class RETokenEndSub extends REToken {
RETokenEndSub(int subIndex) {
diff --git a/gnu/regexp/RETokenIndependent.java b/gnu/java/util/regex/RETokenIndependent.java
index 8bb95c654..48f865612 100644
--- a/gnu/regexp/RETokenIndependent.java
+++ b/gnu/java/util/regex/RETokenIndependent.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
/**
* @author Ito Kazumitsu
diff --git a/gnu/regexp/RETokenLookAhead.java b/gnu/java/util/regex/RETokenLookAhead.java
index 009872c2f..134f17c60 100644
--- a/gnu/regexp/RETokenLookAhead.java
+++ b/gnu/java/util/regex/RETokenLookAhead.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
/**
* @since gnu.regexp 1.1.3
diff --git a/gnu/regexp/RETokenLookBehind.java b/gnu/java/util/regex/RETokenLookBehind.java
index 8311d1a7a..a01a15bc9 100644
--- a/gnu/regexp/RETokenLookBehind.java
+++ b/gnu/java/util/regex/RETokenLookBehind.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
/**
* @author Ito Kazumitsu
diff --git a/gnu/regexp/RETokenNamedProperty.java b/gnu/java/util/regex/RETokenNamedProperty.java
index 6147e87dc..a286c5be8 100644
--- a/gnu/regexp/RETokenNamedProperty.java
+++ b/gnu/java/util/regex/RETokenNamedProperty.java
@@ -36,7 +36,7 @@ obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
final class RETokenNamedProperty extends REToken {
String name;
diff --git a/gnu/regexp/RETokenOneOf.java b/gnu/java/util/regex/RETokenOneOf.java
index f747d5917..bccc78311 100644
--- a/gnu/regexp/RETokenOneOf.java
+++ b/gnu/java/util/regex/RETokenOneOf.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
import java.util.Vector;
import java.util.Stack;
diff --git a/gnu/regexp/RETokenPOSIX.java b/gnu/java/util/regex/RETokenPOSIX.java
index dbea98aee..072989583 100644
--- a/gnu/regexp/RETokenPOSIX.java
+++ b/gnu/java/util/regex/RETokenPOSIX.java
@@ -36,7 +36,7 @@ obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
final class RETokenPOSIX extends REToken {
int type;
diff --git a/gnu/regexp/RETokenRange.java b/gnu/java/util/regex/RETokenRange.java
index 9d3da324e..8a65f77f1 100644
--- a/gnu/regexp/RETokenRange.java
+++ b/gnu/java/util/regex/RETokenRange.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
final class RETokenRange extends REToken {
private char lo, hi;
diff --git a/gnu/regexp/RETokenRepeated.java b/gnu/java/util/regex/RETokenRepeated.java
index 1bad4c792..531c4a311 100644
--- a/gnu/regexp/RETokenRepeated.java
+++ b/gnu/java/util/regex/RETokenRepeated.java
@@ -36,7 +36,7 @@ obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
// import java.util.Vector;
// import java.util.Stack;
diff --git a/gnu/regexp/RETokenStart.java b/gnu/java/util/regex/RETokenStart.java
index b992bd661..56bc36129 100644
--- a/gnu/regexp/RETokenStart.java
+++ b/gnu/java/util/regex/RETokenStart.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
class RETokenStart extends REToken {
private String newline; // matches after a newline
diff --git a/gnu/regexp/RETokenWordBoundary.java b/gnu/java/util/regex/RETokenWordBoundary.java
index 1810339b8..538c6bef4 100644
--- a/gnu/regexp/RETokenWordBoundary.java
+++ b/gnu/java/util/regex/RETokenWordBoundary.java
@@ -36,7 +36,7 @@ obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
/**
* Represents a combination lookahead/lookbehind for POSIX [:alnum:].
diff --git a/gnu/regexp/UncheckedRE.java b/gnu/java/util/regex/UncheckedRE.java
index e67121138..73a67c657 100644
--- a/gnu/regexp/UncheckedRE.java
+++ b/gnu/java/util/regex/UncheckedRE.java
@@ -35,7 +35,7 @@ this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
-package gnu.regexp;
+package gnu.java.util.regex;
/**
* UncheckedRE is a subclass of RE that allows programmers an easier means
@@ -51,7 +51,7 @@ package gnu.regexp;
* regular expressions for the syntax specified.
*
* @author <A HREF="mailto:wes@cacas.org">Wes Biggs</A>
- * @see gnu.regexp.RE
+ * @see gnu.java.util.regex.RE
* @since gnu.regexp 1.1.4
*/
diff --git a/gnu/javax/crypto/RSACipherImpl.java b/gnu/javax/crypto/RSACipherImpl.java
index 0a4c29db6..9c8c52931 100644
--- a/gnu/javax/crypto/RSACipherImpl.java
+++ b/gnu/javax/crypto/RSACipherImpl.java
@@ -215,10 +215,11 @@ public class RSACipherImpl extends CipherSpi
if (dec[0] != 0x02)
throw new BadPaddingException ("expected padding type 2");
int i;
- for (i = 1; i < dec.length && dec[i] != 0x00; i++);
- int len = dec.length - i;
+ for (i = 1; i < dec.length && dec[i] != 0x00; i++)
+ ; // keep incrementing i
+ int len = dec.length - i - 1; // skip the 0x00 byte
byte[] result = new byte[len];
- System.arraycopy (dec, i, result, 0, len);
+ System.arraycopy (dec, i + 1, result, 0, len);
pos = 0;
return result;
}
diff --git a/gnu/javax/crypto/assembly/Cascade.java b/gnu/javax/crypto/assembly/Cascade.java
index 678a7e730..a35d66886 100644
--- a/gnu/javax/crypto/assembly/Cascade.java
+++ b/gnu/javax/crypto/assembly/Cascade.java
@@ -60,7 +60,7 @@ import java.util.Set;
* of identical ciphers).</p>
*
* <p>The term "block ciphers" used above refers to implementations of
- * {@link gnu.crypto.mode.IMode}, including the {@link gnu.crypto.mode.ECB}
+ * {@link gnu.javax.crypto.mode.IMode}, including the {@link gnu.javax.crypto.mode.ECB}
* mode which basically exposes a symmetric-key block cipher algorithm as a
* <i>Mode</i> of Operations.</p>
*
diff --git a/gnu/javax/crypto/assembly/Direction.java b/gnu/javax/crypto/assembly/Direction.java
index 58b59a630..935b9618e 100644
--- a/gnu/javax/crypto/assembly/Direction.java
+++ b/gnu/javax/crypto/assembly/Direction.java
@@ -45,9 +45,9 @@ package gnu.javax.crypto.assembly;
*
* <p>The possible values for this type are two:</p>
* <ol>
- * <li>FORWARD: equivalent to {@link gnu.crypto.mode.IMode#ENCRYPTION}, and
+ * <li>FORWARD: equivalent to {@link gnu.javax.crypto.mode.IMode#ENCRYPTION}, and
* its inverse value</li>
- * <li>REVERSED: equivalent to {@link gnu.crypto.mode.IMode#DECRYPTION}.</li>
+ * <li>REVERSED: equivalent to {@link gnu.javax.crypto.mode.IMode#DECRYPTION}.</li>
* </ol>
*/
public final class Direction
diff --git a/gnu/javax/crypto/assembly/Transformer.java b/gnu/javax/crypto/assembly/Transformer.java
index 80430dc19..74a619af0 100644
--- a/gnu/javax/crypto/assembly/Transformer.java
+++ b/gnu/javax/crypto/assembly/Transformer.java
@@ -47,7 +47,7 @@ import java.util.Map;
* <p>A <code>Transformer</code> is an abstract representation of a two-way
* <i>transformation</i> that can be chained together with other instances of
* this type. Examples of such transformations in this library are:
- * {@link Cascade} cipher, {@link gnu.crypto.pad.IPad} algorithm, and a
+ * {@link Cascade} cipher, {@link gnu.javax.crypto.pad.IPad} algorithm, and a
* ZLib-based deflater/inflater algorithm. A special implementation of a
* <code>Transformer</code> to close a chain is also provided.</p>
*
diff --git a/gnu/javax/crypto/cipher/Anubis.java b/gnu/javax/crypto/cipher/Anubis.java
index ca4e8edfe..ed55d23c2 100644
--- a/gnu/javax/crypto/cipher/Anubis.java
+++ b/gnu/javax/crypto/cipher/Anubis.java
@@ -38,14 +38,15 @@ exception statement from your version. */
package gnu.javax.crypto.cipher;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
-//import java.io.PrintWriter;
import java.security.InvalidKeyException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
+import java.util.logging.Logger;
/**
* <p>Anubis is a 128-bit block cipher that accepts a variable-length key. The
@@ -65,23 +66,7 @@ import java.util.Iterator;
*/
public final class Anubis extends BaseCipher
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- // private static final String NAME = "anubis";
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 9;
-
- // private static final PrintWriter err = new PrintWriter(System.out, true);
- // private static void debug(String s) {
- // err.println(">>> "+NAME+": "+s);
- // }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(Anubis.class.getName());
private static final int DEFAULT_BLOCK_SIZE = 16; // in bytes
private static final int DEFAULT_KEY_SIZE = 16; // in bytes
@@ -189,84 +174,62 @@ public final class Anubis extends BaseCipher
time = System.currentTimeMillis() - time;
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- System.out.println("==========");
- System.out.println();
- System.out.println("Static data");
- System.out.println();
-
- System.out.println();
- System.out.println("T0[]:");
+ log.fine("Static data");
+ log.fine("T0[]:");
+ StringBuilder sb;
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (t = 0; t < 4; t++)
- {
- System.out.print("0x" + Util.toString(T0[i * 4 + t]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T0[i * 4 + t])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T1[]:");
+ log.fine("T1[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (t = 0; t < 4; t++)
- {
- System.out.print("0x" + Util.toString(T1[i * 4 + t]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T1[i * 4 + t])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T2[]:");
+ log.fine("T2[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (t = 0; t < 4; t++)
- {
- System.out.print("0x" + Util.toString(T2[i * 4 + t]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T2[i * 4 + t])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T3[]:");
+ log.fine("T3[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (t = 0; t < 4; t++)
- {
- System.out.print("0x" + Util.toString(T3[i * 4 + t]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T3[i * 4 + t])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T4[]:");
+ log.fine("T4[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (t = 0; t < 4; t++)
- {
- System.out.print("0x" + Util.toString(T4[i * 4 + t]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T4[i * 4 + t])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T5[]:");
+ log.fine("T5[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (t = 0; t < 4; t++)
- {
- System.out.print("0x" + Util.toString(T5[i * 4 + t]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T5[i * 4 + t])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("rc[]:");
+ log.fine("rc[]:");
for (i = 0; i < 18; i++)
- {
- System.out.println("0x" + Util.toString(rc[i]));
- }
- System.out.println();
-
- System.out.println();
- System.out.println("Total initialization time: " + time + " ms.");
- System.out.println();
+ log.fine("0x" + Util.toString(rc[i]));
+ log.fine("Total initialization time: " + time + " ms.");
}
}
@@ -315,12 +278,9 @@ public final class Anubis extends BaseCipher
a1 = b1;
a2 = b2;
a3 = b3;
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("T" + r + "=" + Util.toString(a0)
- + Util.toString(a1) + Util.toString(a2)
- + Util.toString(a3));
- }
+ if (Configuration.DEBUG)
+ log.fine("T" + r + "=" + Util.toString(a0) + Util.toString(a1)
+ + Util.toString(a2) + Util.toString(a3));
}
// last round function
@@ -346,11 +306,8 @@ public final class Anubis extends BaseCipher
out[j++] = (byte) (S[a2 & 0xFF] ^ (tt >>> 8));
out[j] = (byte) (S[a3 & 0xFF] ^ tt);
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("T=" + Util.toString(out, j - 15, 16));
- System.out.println();
- }
+ if (Configuration.DEBUG)
+ log.fine("T=" + Util.toString(out, j - 15, 16) + "\n");
}
// Instance methods
@@ -517,29 +474,26 @@ public final class Anubis extends BaseCipher
}
}
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- System.out.println();
- System.out.println("Key schedule");
- System.out.println();
- System.out.println("Ke[]:");
+ log.fine("Key schedule");
+ log.fine("Ke[]:");
+ StringBuilder sb;
for (r = 0; r < R + 1; r++)
{
- System.out.print("#" + r + ": ");
+ sb = new StringBuilder("#").append(r).append(": ");
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(Ke[r][j]) + ", ");
- System.out.println();
+ sb.append("0x").append(Util.toString(Ke[r][j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("Kd[]:");
+ log.fine("Kd[]:");
for (r = 0; r < R + 1; r++)
{
- System.out.print("#" + r + ": ");
+ sb = new StringBuilder("#").append(r).append(": ");
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(Kd[r][j]) + ", ");
- System.out.println();
+ sb.append("0x").append(Util.toString(Kd[r][j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
}
return new Object[] { Ke, Kd };
diff --git a/gnu/javax/crypto/cipher/BaseCipher.java b/gnu/javax/crypto/cipher/BaseCipher.java
index 9d62311ed..db72e0f3a 100644
--- a/gnu/javax/crypto/cipher/BaseCipher.java
+++ b/gnu/javax/crypto/cipher/BaseCipher.java
@@ -38,12 +38,14 @@ exception statement from your version. */
package gnu.javax.crypto.cipher;
-import gnu.java.security.util.Util;
+import gnu.classpath.Configuration;
import java.security.InvalidKeyException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
/**
* <p>A basic abstract class to facilitate implementing symmetric key block
@@ -51,10 +53,7 @@ import java.util.Map;
*/
public abstract class BaseCipher implements IBlockCipher, IBlockCipherSpi
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(BaseCipher.class.getName());
/** The canonical name prefix of the cipher. */
protected String name;
@@ -265,7 +264,8 @@ public abstract class BaseCipher implements IBlockCipher, IBlockCipherSpi
}
catch (Exception x)
{
- x.printStackTrace(System.err);
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "Exception in testSymmetry() for " + name(), x);
return false;
}
}
@@ -297,7 +297,8 @@ public abstract class BaseCipher implements IBlockCipher, IBlockCipherSpi
}
catch (Exception x)
{
- x.printStackTrace(System.err);
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "Exception in testKat() for " + name(), x);
return false;
}
}
diff --git a/gnu/javax/crypto/cipher/IBlockCipherSpi.java b/gnu/javax/crypto/cipher/IBlockCipherSpi.java
index 6fe07ca7f..046f43f6f 100644
--- a/gnu/javax/crypto/cipher/IBlockCipherSpi.java
+++ b/gnu/javax/crypto/cipher/IBlockCipherSpi.java
@@ -43,7 +43,7 @@ import java.util.Iterator;
/**
* <p>Package-private interface exposing mandatory methods to be implemented by
- * concrete {@link gnu.crypto.cipher.BaseCipher} sub-classes.</p>
+ * concrete {@link gnu.javax.crypto.cipher.BaseCipher} sub-classes.</p>
*/
interface IBlockCipherSpi extends Cloneable
{
diff --git a/gnu/javax/crypto/cipher/Khazad.java b/gnu/javax/crypto/cipher/Khazad.java
index 3a95874da..385e2646b 100644
--- a/gnu/javax/crypto/cipher/Khazad.java
+++ b/gnu/javax/crypto/cipher/Khazad.java
@@ -38,14 +38,15 @@ exception statement from your version. */
package gnu.javax.crypto.cipher;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
-//import java.io.PrintWriter;
import java.security.InvalidKeyException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
+import java.util.logging.Logger;
/**
* <p>Khazad is a 64-bit (legacy-level) block cipher that accepts a 128-bit key.
@@ -65,23 +66,7 @@ import java.util.Iterator;
*/
public final class Khazad extends BaseCipher
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- // private static final String NAME = "khazad";
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 9;
-
- // private static final PrintWriter err = new PrintWriter(System.out, true);
- // private static void debug(String s) {
- // err.println(">>> "+NAME+": "+s);
- // }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(Khazad.class.getName());
private static final int DEFAULT_BLOCK_SIZE = 8; // in bytes
private static final int DEFAULT_KEY_SIZE = 16; // in bytes
@@ -194,86 +179,78 @@ public final class Khazad extends BaseCipher
time = System.currentTimeMillis() - time;
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- System.out.println("==========");
- System.out.println();
- System.out.println("Static data");
- System.out.println();
-
- System.out.println();
- System.out.println("T0[]:");
+ log.fine("Static data");
+ log.fine("T0[]:");
+ StringBuilder b;
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T0[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T0[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("T1[]:");
+ log.fine("T1[]:");
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T1[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T1[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("T2[]:");
+ log.fine("T2[]:");
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T2[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T2[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("T3[]:");
+ log.fine("T3[]:");
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T3[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T3[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("T4[]:");
+ log.fine("T4[]:");
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T4[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T4[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("T5[]:");
+ log.fine("T5[]:");
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T5[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T5[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("T6[]:");
+ log.fine("T6[]:");
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T6[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T6[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("T7[]:");
+ log.fine("T7[]:");
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T7[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T7[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("rc[]:");
+ log.fine("rc[]:");
for (i = 0; i < R + 1; i++)
- System.out.print("0x" + Util.toString(rc[i][0])
- + Util.toString(rc[i][1]));
- System.out.println();
-
- System.out.println("Total initialization time: " + time + " ms.");
- System.out.println();
+ log.fine("0x" + Util.toString(rc[i][0]) + Util.toString(rc[i][1]));
+ log.fine("Total initialization time: " + time + " ms.");
}
}
@@ -313,12 +290,8 @@ public final class Khazad extends BaseCipher
^ T6[(a0 >>> 8) & 0xFF] ^ T7[a0 & 0xFF] ^ k1;
a0 = b0;
a1 = b1;
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("T" + r + "=" + Util.toString(a0)
- + Util.toString(a1));
- }
+ if (Configuration.DEBUG)
+ log.fine("T" + r + "=" + Util.toString(a0) + Util.toString(a1));
}
// sigma(K[R]) o gamma applied to previous output
@@ -333,12 +306,8 @@ public final class Khazad extends BaseCipher
out[j++] = (byte) (S[(a1 >>> 16) & 0xFF] ^ (k1 >>> 16));
out[j++] = (byte) (S[(a1 >>> 8) & 0xFF] ^ (k1 >>> 8));
out[j] = (byte) (S[a1 & 0xFF] ^ k1);
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("T=" + Util.toString(out, j - 7, 8));
- System.out.println();
- }
+ if (Configuration.DEBUG)
+ log.fine("T=" + Util.toString(out, j - 7, 8) + "\n");
}
// Instance methods
@@ -458,26 +427,17 @@ public final class Khazad extends BaseCipher
^ T7[S[kr0 & 0xFF] & 0xFF];
}
}
-
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- System.out.println();
- System.out.println("Key schedule");
- System.out.println();
- System.out.println("Ke[]:");
+ log.fine("Key schedule");
+ log.fine("Ke[]:");
for (r = 0; r < R + 1; r++)
- {
- System.out.println("#" + r + ": 0x" + Util.toString(Ke[r][0])
- + Util.toString(Ke[r][1]));
- }
- System.out.println();
- System.out.println("Kd[]:");
+ log.fine("#" + r + ": 0x"
+ + Util.toString(Ke[r][0]) + Util.toString(Ke[r][1]));
+ log.fine("Kd[]:");
for (r = 0; r < R + 1; r++)
- {
- System.out.println("#" + r + ": 0x" + Util.toString(Kd[r][0])
- + Util.toString(Kd[r][1]));
- }
- System.out.println();
+ log.fine("#" + r + ": 0x"
+ + Util.toString(Kd[r][0]) + Util.toString(Kd[r][1]));
}
return new Object[] { Ke, Kd };
diff --git a/gnu/javax/crypto/cipher/Rijndael.java b/gnu/javax/crypto/cipher/Rijndael.java
index bcd1872fc..d830cd66d 100644
--- a/gnu/javax/crypto/cipher/Rijndael.java
+++ b/gnu/javax/crypto/cipher/Rijndael.java
@@ -38,14 +38,15 @@ exception statement from your version. */
package gnu.javax.crypto.cipher;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
-//import java.io.PrintWriter;
import java.security.InvalidKeyException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
+import java.util.logging.Logger;
/**
* <p>Rijndael --pronounced Reindaal-- is the AES. It is a variable block-size
@@ -63,23 +64,7 @@ import java.util.Iterator;
*/
public final class Rijndael extends BaseCipher
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- // private static final String NAME = "rijndael";
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 9;
-
- // private static final PrintWriter err = new PrintWriter(System.out, true);
- // private static void debug(String s) {
- // err.println(">>> "+NAME+": "+s);
- // }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(Rijndael.class.getName());
private static final int DEFAULT_BLOCK_SIZE = 16; // in bytes
private static final int DEFAULT_KEY_SIZE = 16; // in bytes
@@ -222,169 +207,134 @@ public final class Rijndael extends BaseCipher
}
time = System.currentTimeMillis() - time;
-
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- System.out.println("==========");
- System.out.println();
- System.out.println("Static Data");
- System.out.println();
- System.out.println("S[]:");
+ log.fine("Static Data");
+ log.fine("S[]:");
+ StringBuilder sb;
for (i = 0; i < 16; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 16; j++)
- {
- System.out.print("0x" + Util.toString(S[i * 16 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(S[i * 16 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("Si[]:");
+ log.fine("Si[]:");
for (i = 0; i < 16; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 16; j++)
- {
- System.out.print("0x" + Util.toString(Si[i * 16 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(Si[i * 16 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T1[]:");
+ log.fine("T1[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T1[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T1[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T2[]:");
+ log.fine("T2[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T2[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T2[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T3[]:");
+ log.fine("T3[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T3[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T3[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T4[]:");
+ log.fine("T4[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T4[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T4[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T5[]:");
+ log.fine("T5[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T5[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T5[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T6[]:");
+ log.fine("T6[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T6[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T6[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T7[]:");
+ log.fine("T7[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T7[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T7[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T8[]:");
+ log.fine("T8[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T8[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T8[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("U1[]:");
+ log.fine("U1[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(U1[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(U1[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("U2[]:");
+ log.fine("U2[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(U2[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(U2[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("U3[]:");
+ log.fine("U3[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(U3[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(U3[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("U4[]:");
+ log.fine("U4[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.println("0x" + Util.toString(U4[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(U4[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("rcon[]:");
+ log.fine("rcon[]:");
for (i = 0; i < 5; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 6; j++)
- {
- System.out.print("0x" + Util.toString(rcon[i * 6 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(rcon[i * 6 + j])).append(", ");
+ log.fine(sb.toString());
}
-
- System.out.println();
- System.out.println("Total initialization time: " + time + " ms.");
- System.out.println();
+ log.fine("Total initialization time: " + time + " ms.");
}
}
@@ -454,11 +404,8 @@ public final class Rijndael extends BaseCipher
}
System.arraycopy(a, 0, t, 0, BC);
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("CT" + r + "=" + Util.toString(t));
- }
+ if (Configuration.DEBUG)
+ log.fine("CT" + r + "=" + Util.toString(t));
}
for (i = 0; i < BC; i++)
@@ -469,12 +416,8 @@ public final class Rijndael extends BaseCipher
out[outOffset++] = (byte) (S[(t[(i + s2) % BC] >>> 8) & 0xFF] ^ (tt >>> 8));
out[outOffset++] = (byte) (S[t[(i + s3) % BC] & 0xFF] ^ tt);
}
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("CT=" + Util.toString(out, outOffset - bs + 1, bs));
- System.out.println();
- }
+ if (Configuration.DEBUG)
+ log.fine("CT=" + Util.toString(out, outOffset - bs, bs));
}
private static void rijndaelDecrypt(byte[] in, int inOffset, byte[] out,
@@ -510,11 +453,8 @@ public final class Rijndael extends BaseCipher
}
System.arraycopy(a, 0, t, 0, BC);
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("PT" + r + "=" + Util.toString(t));
- }
+ if (Configuration.DEBUG)
+ log.fine("PT" + r + "=" + Util.toString(t));
}
for (i = 0; i < BC; i++)
@@ -525,12 +465,8 @@ public final class Rijndael extends BaseCipher
out[outOffset++] = (byte) (Si[(t[(i + s2) % BC] >>> 8) & 0xFF] ^ (tt >>> 8));
out[outOffset++] = (byte) (Si[t[(i + s3) % BC] & 0xFF] ^ tt);
}
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("PT=" + Util.toString(out, outOffset - bs + 1, bs));
- System.out.println();
- }
+ if (Configuration.DEBUG)
+ log.fine("PT=" + Util.toString(out, outOffset - bs, bs));
}
private static void aesEncrypt(byte[] in, int i, byte[] out, int j, Object key)
@@ -565,15 +501,10 @@ public final class Rijndael extends BaseCipher
t1 = a1;
t2 = a2;
t3 = a3;
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("CT" + r + "=" + Util.toString(t0)
- + Util.toString(t1) + Util.toString(t2)
- + Util.toString(t3));
- }
+ if (Configuration.DEBUG)
+ log.fine("CT" + r + "=" + Util.toString(t0) + Util.toString(t1)
+ + Util.toString(t2) + Util.toString(t3));
}
-
// last round is special
Ker = Ke[ROUNDS];
int tt = Ker[0];
@@ -596,12 +527,8 @@ public final class Rijndael extends BaseCipher
out[j++] = (byte) (S[(t0 >>> 16) & 0xFF] ^ (tt >>> 16));
out[j++] = (byte) (S[(t1 >>> 8) & 0xFF] ^ (tt >>> 8));
out[j++] = (byte) (S[t2 & 0xFF] ^ tt);
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("CT=" + Util.toString(out, j - 15, 16));
- System.out.println();
- }
+ if (Configuration.DEBUG)
+ log.fine("CT=" + Util.toString(out, j - 16, 16));
}
private static void aesDecrypt(byte[] in, int i, byte[] out, int j, Object key)
@@ -636,15 +563,10 @@ public final class Rijndael extends BaseCipher
t1 = a1;
t2 = a2;
t3 = a3;
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("PT" + r + "=" + Util.toString(t0)
- + Util.toString(t1) + Util.toString(t2)
- + Util.toString(t3));
- }
+ if (Configuration.DEBUG)
+ log.fine("PT" + r + "=" + Util.toString(t0) + Util.toString(t1)
+ + Util.toString(t2) + Util.toString(t3));
}
-
// last round is special
Kdr = Kd[ROUNDS];
int tt = Kdr[0];
@@ -667,12 +589,8 @@ public final class Rijndael extends BaseCipher
out[j++] = (byte) (Si[(t2 >>> 16) & 0xFF] ^ (tt >>> 16));
out[j++] = (byte) (Si[(t1 >>> 8) & 0xFF] ^ (tt >>> 8));
out[j++] = (byte) (Si[t0 & 0xFF] ^ tt);
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("PT=" + Util.toString(out, j - 15, 16));
- System.out.println();
- }
+ if (Configuration.DEBUG)
+ log.fine("PT=" + Util.toString(out, j - 16, 16));
}
// Instance methods
diff --git a/gnu/javax/crypto/cipher/Twofish.java b/gnu/javax/crypto/cipher/Twofish.java
index f5565d4b4..d6747608c 100644
--- a/gnu/javax/crypto/cipher/Twofish.java
+++ b/gnu/javax/crypto/cipher/Twofish.java
@@ -38,14 +38,15 @@ exception statement from your version. */
package gnu.javax.crypto.cipher;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
-//import java.io.PrintWriter;
import java.security.InvalidKeyException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
+import java.util.logging.Logger;
/**
* <p>Twofish is a balanced 128-bit Feistel cipher, consisting of 16 rounds. In
@@ -68,23 +69,7 @@ import java.util.Iterator;
*/
public final class Twofish extends BaseCipher
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- // private static final String NAME = "twofish";
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 9;
-
- // private static final PrintWriter err = new PrintWriter(System.out, true);
- // private static void debug(String s) {
- // err.println(">>> "+NAME+": "+s);
- // }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(Twofish.class.getName());
private static final int DEFAULT_BLOCK_SIZE = 16; // in bytes
private static final int DEFAULT_KEY_SIZE = 16; // in bytes
@@ -265,62 +250,43 @@ public final class Twofish extends BaseCipher
time = System.currentTimeMillis() - time;
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- System.out.println("==========");
- System.out.println();
- System.out.println("Static Data");
- System.out.println();
- System.out.println("MDS[0][]:");
+ log.fine("Static Data");
+ log.fine("MDS[0][]:");
+ StringBuilder sb;
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(MDS[0][i * 4 + j])
- + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(MDS[0][i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
-
- System.out.println();
- System.out.println("MDS[1][]:");
+ log.fine("MDS[1][]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(MDS[1][i * 4 + j])
- + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(MDS[1][i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
-
- System.out.println();
- System.out.println("MDS[2][]:");
+ log.fine("MDS[2][]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(MDS[2][i * 4 + j])
- + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(MDS[2][i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
-
- System.out.println();
- System.out.println("MDS[3][]:");
+ log.fine("MDS[3][]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(MDS[3][i * 4 + j])
- + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(MDS[3][i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
-
- System.out.println();
- System.out.println("Total initialization time: " + time + " ms.");
- System.out.println();
+ log.fine("Total initialization time: " + time + " ms.");
}
}
@@ -630,64 +596,49 @@ public final class Twofish extends BaseCipher
^ b3(k0)];
}
}
-
- if (DEBUG && debuglevel > 7)
+ if (Configuration.DEBUG)
{
- System.out.println("S-box[]:");
+ StringBuilder sb;
+ log.fine("S-box[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(sBox[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(sBox[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
+ log.fine("");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(sBox[256 + i * 4 + j])
- + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(sBox[256 + i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
+ log.fine("");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(sBox[512 + i * 4 + j])
- + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(sBox[512 + i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
+ log.fine("");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(sBox[768 + i * 4 + j])
- + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(sBox[768 + i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("User (odd, even) keys --> S-Box keys:");
+ log.fine("User (odd, even) keys --> S-Box keys:");
for (i = 0; i < k64Cnt; i++)
- {
- System.out.println("0x" + Util.toString(k32o[i]) + " 0x"
- + Util.toString(k32e[i]) + " --> 0x"
- + Util.toString(sBoxKey[k64Cnt - 1 - i]));
- }
- System.out.println();
- System.out.println("Round keys:");
+ log.fine("0x" + Util.toString(k32o[i]) + " 0x" + Util.toString(k32e[i])
+ + " --> 0x" + Util.toString(sBoxKey[k64Cnt - 1 - i]));
+ log.fine("Round keys:");
for (i = 0; i < ROUND_SUBKEYS + 2 * ROUNDS; i += 2)
- {
- System.out.println("0x" + Util.toString(subKeys[i]) + " 0x"
- + Util.toString(subKeys[i + 1]));
- }
- System.out.println();
+ log.fine("0x" + Util.toString(subKeys[i])
+ + " 0x" + Util.toString(subKeys[i + 1]));
}
return new Object[] { sBox, subKeys };
@@ -704,12 +655,8 @@ public final class Twofish extends BaseCipher
Object[] sk = (Object[]) sessionKey; // extract S-box and session key
int[] sBox = (int[]) sk[0];
int[] sKey = (int[]) sk[1];
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("PT=" + Util.toString(in, inOffset, bs));
- }
-
+ if (Configuration.DEBUG)
+ log.fine("PT=" + Util.toString(in, inOffset, bs));
int x0 = (in[inOffset++] & 0xFF) | (in[inOffset++] & 0xFF) << 8
| (in[inOffset++] & 0xFF) << 16 | (in[inOffset++] & 0xFF) << 24;
int x1 = (in[inOffset++] & 0xFF) | (in[inOffset++] & 0xFF) << 8
@@ -723,12 +670,9 @@ public final class Twofish extends BaseCipher
x1 ^= sKey[INPUT_WHITEN + 1];
x2 ^= sKey[INPUT_WHITEN + 2];
x3 ^= sKey[INPUT_WHITEN + 3];
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("PTw=" + Util.toString(x0) + Util.toString(x1)
- + Util.toString(x2) + Util.toString(x3));
- }
-
+ if (Configuration.DEBUG)
+ log.fine("PTw=" + Util.toString(x0) + Util.toString(x1)
+ + Util.toString(x2) + Util.toString(x3));
int t0, t1;
int k = ROUND_SUBKEYS;
for (int R = 0; R < ROUNDS; R += 2)
@@ -739,36 +683,26 @@ public final class Twofish extends BaseCipher
x2 = x2 >>> 1 | x2 << 31;
x3 = x3 << 1 | x3 >>> 31;
x3 ^= t0 + 2 * t1 + sKey[k++];
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("CT" + (R) + "=" + Util.toString(x0)
- + Util.toString(x1) + Util.toString(x2)
- + Util.toString(x3));
- }
-
+ if (Configuration.DEBUG)
+ log.fine("CT" + (R) + "=" + Util.toString(x0) + Util.toString(x1)
+ + Util.toString(x2) + Util.toString(x3));
t0 = Fe32(sBox, x2, 0);
t1 = Fe32(sBox, x3, 3);
x0 ^= t0 + t1 + sKey[k++];
x0 = x0 >>> 1 | x0 << 31;
x1 = x1 << 1 | x1 >>> 31;
x1 ^= t0 + 2 * t1 + sKey[k++];
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("CT" + (R + 1) + "=" + Util.toString(x0)
- + Util.toString(x1) + Util.toString(x2)
- + Util.toString(x3));
- }
+ if (Configuration.DEBUG)
+ log.fine("CT" + (R + 1) + "=" + Util.toString(x0) + Util.toString(x1)
+ + Util.toString(x2) + Util.toString(x3));
}
x2 ^= sKey[OUTPUT_WHITEN];
x3 ^= sKey[OUTPUT_WHITEN + 1];
x0 ^= sKey[OUTPUT_WHITEN + 2];
x1 ^= sKey[OUTPUT_WHITEN + 3];
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("CTw=" + Util.toString(x0) + Util.toString(x1)
- + Util.toString(x2) + Util.toString(x3));
- }
-
+ if (Configuration.DEBUG)
+ log.fine("CTw=" + Util.toString(x0) + Util.toString(x1)
+ + Util.toString(x2) + Util.toString(x3));
out[outOffset++] = (byte) x2;
out[outOffset++] = (byte) (x2 >>> 8);
out[outOffset++] = (byte) (x2 >>> 16);
@@ -785,12 +719,8 @@ public final class Twofish extends BaseCipher
out[outOffset++] = (byte) (x1 >>> 8);
out[outOffset++] = (byte) (x1 >>> 16);
out[outOffset] = (byte) (x1 >>> 24);
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("CT=" + Util.toString(out, outOffset - 15, 16));
- System.out.println();
- }
+ if (Configuration.DEBUG)
+ log.fine("CT=" + Util.toString(out, outOffset - 15, 16) + "\n");
}
public void decrypt(byte[] in, int inOffset, byte[] out, int outOffset,
@@ -804,12 +734,8 @@ public final class Twofish extends BaseCipher
Object[] sk = (Object[]) sessionKey; // extract S-box and session key
int[] sBox = (int[]) sk[0];
int[] sKey = (int[]) sk[1];
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("CT=" + Util.toString(in, inOffset, bs));
- }
-
+ if (Configuration.DEBUG)
+ log.fine("CT=" + Util.toString(in, inOffset, bs));
int x2 = (in[inOffset++] & 0xFF) | (in[inOffset++] & 0xFF) << 8
| (in[inOffset++] & 0xFF) << 16 | (in[inOffset++] & 0xFF) << 24;
int x3 = (in[inOffset++] & 0xFF) | (in[inOffset++] & 0xFF) << 8
@@ -823,12 +749,9 @@ public final class Twofish extends BaseCipher
x3 ^= sKey[OUTPUT_WHITEN + 1];
x0 ^= sKey[OUTPUT_WHITEN + 2];
x1 ^= sKey[OUTPUT_WHITEN + 3];
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("CTw=" + Util.toString(x2) + Util.toString(x3)
- + Util.toString(x0) + Util.toString(x1));
- }
-
+ if (Configuration.DEBUG)
+ log.fine("CTw=" + Util.toString(x2) + Util.toString(x3)
+ + Util.toString(x0) + Util.toString(x1));
int k = ROUND_SUBKEYS + 2 * ROUNDS - 1;
int t0, t1;
for (int R = 0; R < ROUNDS; R += 2)
@@ -839,36 +762,26 @@ public final class Twofish extends BaseCipher
x1 = x1 >>> 1 | x1 << 31;
x0 = x0 << 1 | x0 >>> 31;
x0 ^= t0 + t1 + sKey[k--];
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("PT" + (ROUNDS - R) + "=" + Util.toString(x2)
- + Util.toString(x3) + Util.toString(x0)
- + Util.toString(x1));
- }
-
+ if (Configuration.DEBUG)
+ log.fine("PT" + (ROUNDS - R) + "=" + Util.toString(x2)
+ + Util.toString(x3) + Util.toString(x0) + Util.toString(x1));
t0 = Fe32(sBox, x0, 0);
t1 = Fe32(sBox, x1, 3);
x3 ^= t0 + 2 * t1 + sKey[k--];
x3 = x3 >>> 1 | x3 << 31;
x2 = x2 << 1 | x2 >>> 31;
x2 ^= t0 + t1 + sKey[k--];
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("PT" + (ROUNDS - R - 1) + "="
- + Util.toString(x2) + Util.toString(x3)
- + Util.toString(x0) + Util.toString(x1));
- }
+ if (Configuration.DEBUG)
+ log.fine("PT" + (ROUNDS - R - 1) + "=" + Util.toString(x2)
+ + Util.toString(x3) + Util.toString(x0) + Util.toString(x1));
}
x0 ^= sKey[INPUT_WHITEN];
x1 ^= sKey[INPUT_WHITEN + 1];
x2 ^= sKey[INPUT_WHITEN + 2];
x3 ^= sKey[INPUT_WHITEN + 3];
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("PTw=" + Util.toString(x2) + Util.toString(x3)
- + Util.toString(x0) + Util.toString(x1));
- }
-
+ if (Configuration.DEBUG)
+ log.fine("PTw=" + Util.toString(x2) + Util.toString(x3)
+ + Util.toString(x0) + Util.toString(x1));
out[outOffset++] = (byte) x0;
out[outOffset++] = (byte) (x0 >>> 8);
out[outOffset++] = (byte) (x0 >>> 16);
@@ -885,12 +798,8 @@ public final class Twofish extends BaseCipher
out[outOffset++] = (byte) (x3 >>> 8);
out[outOffset++] = (byte) (x3 >>> 16);
out[outOffset] = (byte) (x3 >>> 24);
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("PT=" + Util.toString(out, outOffset - 15, 16));
- System.out.println();
- }
+ if (Configuration.DEBUG)
+ log.fine("PT=" + Util.toString(out, outOffset - 15, 16) + "\n");
}
public boolean selfTest()
diff --git a/gnu/javax/crypto/jce/cipher/CipherAdapter.java b/gnu/javax/crypto/jce/cipher/CipherAdapter.java
index 5eaa31b77..f8adedce7 100644
--- a/gnu/javax/crypto/jce/cipher/CipherAdapter.java
+++ b/gnu/javax/crypto/jce/cipher/CipherAdapter.java
@@ -118,9 +118,9 @@ class CipherAdapter extends CipherSpi
/**
* <p>Protected constructor to be called by subclasses. The cipher name
- * argument should be the appropriate one listed in {@link gnu.crypto.Registry}.
+ * argument should be the appropriate one listed in {@link gnu.java.security.Registry}.
* The basic cipher instance is created, along with an instance of the
- * {@link gnu.crypto.mode.ECB} mode and no padding.</p>
+ * {@link gnu.javax.crypto.mode.ECB} mode and no padding.</p>
*
* @param cipherName The cipher to instantiate.
* @param blockLen The block length to use.
diff --git a/gnu/javax/crypto/jce/key/AnubisSecretKeyFactoryImpl.java b/gnu/javax/crypto/jce/key/AnubisSecretKeyFactoryImpl.java
index f9725eae0..6442cd696 100644
--- a/gnu/javax/crypto/jce/key/AnubisSecretKeyFactoryImpl.java
+++ b/gnu/javax/crypto/jce/key/AnubisSecretKeyFactoryImpl.java
@@ -38,13 +38,6 @@ exception statement from your version. */
package gnu.javax.crypto.jce.key;
-import java.security.InvalidKeyException;
-import java.security.spec.InvalidKeySpecException;
-
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactorySpi;
-import javax.crypto.spec.SecretKeySpec;
-
public class AnubisSecretKeyFactoryImpl extends SecretKeyFactoryImpl
{
public AnubisSecretKeyFactoryImpl()
diff --git a/gnu/javax/crypto/jce/key/BlowfishSecretKeyFactoryImpl.java b/gnu/javax/crypto/jce/key/BlowfishSecretKeyFactoryImpl.java
index 4b3620bc1..91f97af36 100644
--- a/gnu/javax/crypto/jce/key/BlowfishSecretKeyFactoryImpl.java
+++ b/gnu/javax/crypto/jce/key/BlowfishSecretKeyFactoryImpl.java
@@ -38,13 +38,6 @@ exception statement from your version. */
package gnu.javax.crypto.jce.key;
-import java.security.InvalidKeyException;
-import java.security.spec.InvalidKeySpecException;
-
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactorySpi;
-import javax.crypto.spec.SecretKeySpec;
-
public class BlowfishSecretKeyFactoryImpl extends SecretKeyFactoryImpl
{
public BlowfishSecretKeyFactoryImpl()
diff --git a/gnu/javax/crypto/jce/key/Cast5SecretKeyFactoryImpl.java b/gnu/javax/crypto/jce/key/Cast5SecretKeyFactoryImpl.java
index 4bd31711e..048b54474 100644
--- a/gnu/javax/crypto/jce/key/Cast5SecretKeyFactoryImpl.java
+++ b/gnu/javax/crypto/jce/key/Cast5SecretKeyFactoryImpl.java
@@ -38,13 +38,6 @@ exception statement from your version. */
package gnu.javax.crypto.jce.key;
-import java.security.InvalidKeyException;
-import java.security.spec.InvalidKeySpecException;
-
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactorySpi;
-import javax.crypto.spec.SecretKeySpec;
-
public class Cast5SecretKeyFactoryImpl extends SecretKeyFactoryImpl
{
public Cast5SecretKeyFactoryImpl()
diff --git a/gnu/javax/crypto/jce/key/KhazadSecretKeyFactoryImpl.java b/gnu/javax/crypto/jce/key/KhazadSecretKeyFactoryImpl.java
index c86e01110..6c7ab42f7 100644
--- a/gnu/javax/crypto/jce/key/KhazadSecretKeyFactoryImpl.java
+++ b/gnu/javax/crypto/jce/key/KhazadSecretKeyFactoryImpl.java
@@ -37,13 +37,6 @@ exception statement from your version. */
package gnu.javax.crypto.jce.key;
-import java.security.InvalidKeyException;
-import java.security.spec.InvalidKeySpecException;
-
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactorySpi;
-import javax.crypto.spec.SecretKeySpec;
-
public class KhazadSecretKeyFactoryImpl extends SecretKeyFactoryImpl
{
public KhazadSecretKeyFactoryImpl()
diff --git a/gnu/javax/crypto/jce/key/RijndaelSecretKeyFactoryImpl.java b/gnu/javax/crypto/jce/key/RijndaelSecretKeyFactoryImpl.java
index 4aab584a2..d46191644 100644
--- a/gnu/javax/crypto/jce/key/RijndaelSecretKeyFactoryImpl.java
+++ b/gnu/javax/crypto/jce/key/RijndaelSecretKeyFactoryImpl.java
@@ -37,13 +37,6 @@ exception statement from your version. */
package gnu.javax.crypto.jce.key;
-import java.security.InvalidKeyException;
-import java.security.spec.InvalidKeySpecException;
-
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactorySpi;
-import javax.crypto.spec.SecretKeySpec;
-
public class RijndaelSecretKeyFactoryImpl extends SecretKeyFactoryImpl
{
public RijndaelSecretKeyFactoryImpl()
diff --git a/gnu/javax/crypto/jce/key/SerpentSecretKeyFactoryImpl.java b/gnu/javax/crypto/jce/key/SerpentSecretKeyFactoryImpl.java
index 6e80671fa..9f06bf329 100644
--- a/gnu/javax/crypto/jce/key/SerpentSecretKeyFactoryImpl.java
+++ b/gnu/javax/crypto/jce/key/SerpentSecretKeyFactoryImpl.java
@@ -37,13 +37,6 @@ exception statement from your version. */
package gnu.javax.crypto.jce.key;
-import java.security.InvalidKeyException;
-import java.security.spec.InvalidKeySpecException;
-
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactorySpi;
-import javax.crypto.spec.SecretKeySpec;
-
public class SerpentSecretKeyFactoryImpl extends SecretKeyFactoryImpl
{
public SerpentSecretKeyFactoryImpl()
diff --git a/gnu/javax/crypto/jce/key/SquareSecretKeyFactoryImpl.java b/gnu/javax/crypto/jce/key/SquareSecretKeyFactoryImpl.java
index d1d5d5514..fce7375b3 100644
--- a/gnu/javax/crypto/jce/key/SquareSecretKeyFactoryImpl.java
+++ b/gnu/javax/crypto/jce/key/SquareSecretKeyFactoryImpl.java
@@ -37,13 +37,6 @@ exception statement from your version. */
package gnu.javax.crypto.jce.key;
-import java.security.InvalidKeyException;
-import java.security.spec.InvalidKeySpecException;
-
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactorySpi;
-import javax.crypto.spec.SecretKeySpec;
-
public class SquareSecretKeyFactoryImpl extends SecretKeyFactoryImpl
{
public SquareSecretKeyFactoryImpl()
diff --git a/gnu/javax/crypto/jce/key/TwofishSecretKeyFactoryImpl.java b/gnu/javax/crypto/jce/key/TwofishSecretKeyFactoryImpl.java
index e6ca80b63..a182d4116 100644
--- a/gnu/javax/crypto/jce/key/TwofishSecretKeyFactoryImpl.java
+++ b/gnu/javax/crypto/jce/key/TwofishSecretKeyFactoryImpl.java
@@ -37,13 +37,6 @@ exception statement from your version. */
package gnu.javax.crypto.jce.key;
-import java.security.InvalidKeyException;
-import java.security.spec.InvalidKeySpecException;
-
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactorySpi;
-import javax.crypto.spec.SecretKeySpec;
-
public class TwofishSecretKeyFactoryImpl extends SecretKeyFactoryImpl
{
public TwofishSecretKeyFactoryImpl()
diff --git a/gnu/javax/crypto/jce/keyring/GnuKeyring.java b/gnu/javax/crypto/jce/keyring/GnuKeyring.java
index 5eeb2a306..ba89912f3 100644
--- a/gnu/javax/crypto/jce/keyring/GnuKeyring.java
+++ b/gnu/javax/crypto/jce/keyring/GnuKeyring.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.javax.crypto.jce.keyring;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.javax.crypto.keyring.GnuPrivateKeyring;
import gnu.javax.crypto.keyring.GnuPublicKeyring;
@@ -90,7 +91,8 @@ public class GnuKeyring
public Enumeration engineAliases()
{
- log.entering(this.getClass().getName(), "engineAliases");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineAliases");
ensureLoaded();
Enumeration result;
if (privateKR == null)
@@ -106,7 +108,8 @@ public class GnuKeyring
alias = alias.trim();
if (alias.length() > 0)
{
- log.finest("Adding alias (from private keyring): " + alias);
+ if (Configuration.DEBUG)
+ log.fine("Adding alias (from private keyring): " + alias);
aliases.add(alias);
}
}
@@ -119,64 +122,69 @@ public class GnuKeyring
alias = alias.trim();
if (alias.length() > 0)
{
- log.finest("Adding alias (from public keyring): " + alias);
+ if (Configuration.DEBUG)
+ log.fine("Adding alias (from public keyring): " + alias);
aliases.add(alias);
}
}
}
- log.finest("Will enumerate: " + aliases);
+ if (Configuration.DEBUG)
+ log.fine("Will enumerate: " + aliases);
result = Collections.enumeration(aliases);
}
- log.exiting(this.getClass().getName(), "engineAliases");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineAliases");
return result;
}
public boolean engineContainsAlias(String alias)
{
- log.entering(this.getClass().getName(), "engineContainsAlias", alias);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineContainsAlias", alias);
ensureLoaded();
boolean inPrivateKR = privateKR.containsAlias(alias);
- log.finest("inPrivateKR=" + inPrivateKR);
+ if (Configuration.DEBUG)
+ log.fine("inPrivateKR=" + inPrivateKR);
boolean inPublicKR = publicKR.containsAlias(alias);
- log.finest("inPublicKR=" + inPublicKR);
+ if (Configuration.DEBUG)
+ log.fine("inPublicKR=" + inPublicKR);
boolean result = inPrivateKR || inPublicKR;
-
- log.exiting(this.getClass().getName(), "engineContainsAlias",
- Boolean.valueOf(result));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineContainsAlias",
+ Boolean.valueOf(result));
return result;
}
public void engineDeleteEntry(String alias)
{
- log.entering(this.getClass().getName(), "engineDeleteEntry", alias);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineDeleteEntry", alias);
ensureLoaded();
if (privateKR.containsAlias(alias))
privateKR.remove(alias);
else if (publicKR.containsAlias(alias))
publicKR.remove(alias);
- else
- log.finer("Unknwon alias: " + alias);
-
- log.exiting(this.getClass().getName(), "engineDeleteEntry");
+ else if (Configuration.DEBUG)
+ log.fine("Unknwon alias: " + alias);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineDeleteEntry");
}
public Certificate engineGetCertificate(String alias)
{
- log.entering(this.getClass().getName(), "engineGetCertificate", alias);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineGetCertificate", alias);
ensureLoaded();
Certificate result = publicKR.getCertificate(alias);
-
- log.exiting(this.getClass().getName(), "engineGetCertificate", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineGetCertificate", result);
return result;
}
public String engineGetCertificateAlias(Certificate cert)
{
- log.entering(this.getClass().getName(), "engineGetCertificateAlias", cert);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineGetCertificateAlias", cert);
ensureLoaded();
String result = null;
for (Enumeration aliases = publicKR.aliases(); aliases.hasMoreElements();)
@@ -189,16 +197,17 @@ public class GnuKeyring
break;
}
}
-
- log.exiting(this.getClass().getName(), "engineGetCertificateAlias", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineGetCertificateAlias", result);
return result;
}
public void engineSetCertificateEntry(String alias, Certificate cert)
throws KeyStoreException
{
- log.entering(this.getClass().getName(), "engineSetCertificateEntry",
- new Object[] { alias, cert });
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineSetCertificateEntry",
+ new Object[] { alias, cert });
ensureLoaded();
if (privateKR.containsAlias(alias))
throw new KeyStoreException("Alias [" + alias
@@ -206,43 +215,46 @@ public class GnuKeyring
+ "Trusted Certificate Entry");
if (publicKR.containsCertificate(alias))
{
- log.fine("Public keyring already contains Alias [" + alias
- + "]. Will remove it");
+ if (Configuration.DEBUG)
+ log.fine("Public keyring already contains Alias [" + alias
+ + "]. Will remove it");
publicKR.remove(alias);
}
-
publicKR.putCertificate(alias, cert);
- log.exiting(this.getClass().getName(), "engineSetCertificateEntry");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineSetCertificateEntry");
}
public Certificate[] engineGetCertificateChain(String alias)
{
- log.entering(this.getClass().getName(), "engineGetCertificateChain", alias);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineGetCertificateChain", alias);
ensureLoaded();
Certificate[] result = privateKR.getCertPath(alias);
-
- log.exiting(this.getClass().getName(), "engineGetCertificateChain", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineGetCertificateChain", result);
return result;
}
public Date engineGetCreationDate(String alias)
{
- log.entering(this.getClass().getName(), "engineGetCreationDate", alias);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineGetCreationDate", alias);
ensureLoaded();
Date result = getCreationDate(alias, privateKR);
if (result == null)
result = getCreationDate(alias, publicKR);
- log.exiting(this.getClass().getName(), "engineGetCreationDate", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineGetCreationDate", result);
return result;
}
public Key engineGetKey(String alias, char[] password)
throws UnrecoverableKeyException
{
- log.entering(this.getClass().getName(), "engineGetKey", alias);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineGetKey", alias);
ensureLoaded();
Key result = null;
if (password == null)
@@ -253,8 +265,9 @@ public class GnuKeyring
else if (privateKR.containsPrivateKey(alias))
result = privateKR.getPrivateKey(alias, password);
- log.exiting(this.getClass().getName(), "engineGetKey",
- result == null ? "null" : result.getClass().getName());
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineGetKey",
+ result == null ? "null" : result.getClass().getName());
return result;
}
@@ -262,8 +275,9 @@ public class GnuKeyring
Certificate[] chain)
throws KeyStoreException
{
- log.entering(this.getClass().getName(), "engineSetKeyEntry",
- new Object[] { alias, key.getClass().getName(), chain });
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineSetKeyEntry",
+ new Object[] { alias, key.getClass().getName(), chain });
ensureLoaded();
if (publicKR.containsAlias(alias))
throw new KeyStoreException("Alias [" + alias
@@ -282,48 +296,52 @@ public class GnuKeyring
+ key.getClass().getName());
privateKR.remove(alias);
privateKR.putCertPath(alias, chain);
- log.finest("About to put private key in keyring...");
+ if (Configuration.DEBUG)
+ log.fine("About to put private key in keyring...");
privateKR.putPrivateKey(alias, key, password);
}
- log.exiting(this.getClass().getName(), "engineSetKeyEntry");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineSetKeyEntry");
}
public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain)
throws KeyStoreException
{
KeyStoreException x = new KeyStoreException("method not supported");
- log.throwing(this.getClass().getName(), "engineSetKeyEntry(3)", x);
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "engineSetKeyEntry(3)", x);
throw x;
}
public boolean engineIsCertificateEntry(String alias)
{
- log.entering(this.getClass().getName(), "engineIsCertificateEntry", alias);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineIsCertificateEntry", alias);
ensureLoaded();
boolean result = publicKR.containsCertificate(alias);
-
- log.exiting(this.getClass().getName(), "engineIsCertificateEntry",
- Boolean.valueOf(result));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineIsCertificateEntry",
+ Boolean.valueOf(result));
return result;
}
public boolean engineIsKeyEntry(String alias)
{
- log.entering(this.getClass().getName(), "engineIsKeyEntry", alias);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineIsKeyEntry", alias);
ensureLoaded();
boolean result = privateKR.containsPublicKey(alias)
|| privateKR.containsPrivateKey(alias);
-
- log.exiting(this.getClass().getName(), "engineIsKeyEntry",
- Boolean.valueOf(result));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineIsKeyEntry",
+ Boolean.valueOf(result));
return result;
}
public void engineLoad(InputStream in, char[] password) throws IOException
{
- log.entering(this.getClass().getName(), "engineLoad");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineLoad");
if (in != null)
{
if (! in.markSupported())
@@ -336,12 +354,14 @@ public class GnuKeyring
createNewKeyrings();
loaded = true;
- log.exiting(this.getClass().getName(), "engineLoad");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineLoad");
}
public void engineStore(OutputStream out, char[] password) throws IOException
{
- log.entering(this.getClass().getName(), "engineStore");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineStore");
ensureLoaded();
HashMap attr = new HashMap();
attr.put(IKeyring.KEYRING_DATA_OUT, out);
@@ -349,17 +369,20 @@ public class GnuKeyring
privateKR.store(attr);
publicKR.store(attr);
- log.exiting(this.getClass().getName(), "engineStore");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineStore");
}
public int engineSize()
{
- log.entering(this.getClass().getName(), "engineSize");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineSize");
int result = 0;
for (Enumeration e = engineAliases(); e.hasMoreElements(); result++)
e.nextElement();
- log.exiting(this.getClass().getName(), "engineSize", Integer.valueOf(result));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineSize", Integer.valueOf(result));
return result;
}
@@ -386,8 +409,8 @@ public class GnuKeyring
private void loadPrivateKeyring(InputStream in, char[] password)
throws MalformedKeyringException, IOException
{
- log.entering(this.getClass().getName(), "loadPrivateKeyring");
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "loadPrivateKeyring");
in.mark(5);
for (int i = 0; i < 4; i++)
if (in.read() != Registry.GKR_MAGIC[i])
@@ -403,8 +426,8 @@ public class GnuKeyring
attr.put(IKeyring.KEYRING_PASSWORD, password);
privateKR = new GnuPrivateKeyring();
privateKR.load(attr);
-
- log.exiting(this.getClass().getName(), "loadPrivateKeyring");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "loadPrivateKeyring");
}
/**
@@ -418,8 +441,8 @@ public class GnuKeyring
private void loadPublicKeyring(InputStream in, char[] password)
throws MalformedKeyringException, IOException
{
- log.entering(this.getClass().getName(), "loadPublicKeyring");
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "loadPublicKeyring");
in.mark(5);
for (int i = 0; i < 4; i++)
if (in.read() != Registry.GKR_MAGIC[i])
@@ -435,8 +458,8 @@ public class GnuKeyring
attr.put(IKeyring.KEYRING_PASSWORD, password);
publicKR = new GnuPublicKeyring();
publicKR.load(attr);
-
- log.exiting(this.getClass().getName(), "loadPublicKeyring");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "loadPublicKeyring");
}
/**
@@ -450,9 +473,9 @@ public class GnuKeyring
*/
private Date getCreationDate(String alias, IKeyring keyring)
{
- log.entering(this.getClass().getName(), "getCreationDate",
- new Object[] { alias, keyring });
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "getCreationDate",
+ new Object[] { alias, keyring });
Date result = null;
if (keyring != null)
for (Iterator it = keyring.get(alias).iterator(); it.hasNext();)
@@ -464,19 +487,19 @@ public class GnuKeyring
break;
}
}
-
- log.exiting(this.getClass().getName(), "getCreationDate", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "getCreationDate", result);
return result;
}
/** Create empty keyrings. */
private void createNewKeyrings()
{
- log.entering(this.getClass().getName(), "createNewKeyrings");
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "createNewKeyrings");
privateKR = new GnuPrivateKeyring("HMAC-SHA-1", 20, "AES", "OFB", 16);
publicKR = new GnuPublicKeyring("HMAC-SHA-1", 20);
-
- log.exiting(this.getClass().getName(), "createNewKeyrings");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "createNewKeyrings");
}
}
diff --git a/gnu/javax/crypto/jce/mac/OMacImpl.java b/gnu/javax/crypto/jce/mac/OMacImpl.java
index f91902ae5..bf30d8e13 100644
--- a/gnu/javax/crypto/jce/mac/OMacImpl.java
+++ b/gnu/javax/crypto/jce/mac/OMacImpl.java
@@ -39,7 +39,6 @@ exception statement from your version. */
package gnu.javax.crypto.jce.mac;
import gnu.java.security.Registry;
-import javax.crypto.MacSpi;
public abstract class OMacImpl extends MacAdapter
{
diff --git a/gnu/javax/crypto/jce/prng/CSPRNGSpi.java b/gnu/javax/crypto/jce/prng/CSPRNGSpi.java
index c0aa015b0..acc0c8e84 100644
--- a/gnu/javax/crypto/jce/prng/CSPRNGSpi.java
+++ b/gnu/javax/crypto/jce/prng/CSPRNGSpi.java
@@ -38,10 +38,9 @@ exception statement from your version. */
package gnu.javax.crypto.jce.prng;
-import gnu.java.security.Registry;
-import gnu.javax.crypto.prng.CSPRNG;
import gnu.java.security.prng.IRandom;
import gnu.java.security.prng.LimitReachedException;
+import gnu.javax.crypto.prng.CSPRNG;
import java.net.MalformedURLException;
import java.security.SecureRandomSpi;
diff --git a/gnu/javax/crypto/jce/prng/ICMRandomSpi.java b/gnu/javax/crypto/jce/prng/ICMRandomSpi.java
index d04b782f9..9be46e055 100644
--- a/gnu/javax/crypto/jce/prng/ICMRandomSpi.java
+++ b/gnu/javax/crypto/jce/prng/ICMRandomSpi.java
@@ -38,16 +38,17 @@ exception statement from your version. */
package gnu.javax.crypto.jce.prng;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
+import gnu.java.security.prng.LimitReachedException;
import gnu.javax.crypto.cipher.IBlockCipher;
import gnu.javax.crypto.prng.ICMGenerator;
-import gnu.java.security.prng.LimitReachedException;
-import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.SecureRandomSpi;
import java.util.HashMap;
import java.util.Random;
+import java.util.logging.Logger;
/**
* <p>An <em>Adapter</em> class around {@link ICMGenerator} to allow using this
@@ -55,26 +56,7 @@ import java.util.Random;
*/
public class ICMRandomSpi extends SecureRandomSpi
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "ICMRandomSpi";
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 0;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(ICMRandomSpi.class.getName());
/** Class-wide prng to generate random material for the underlying prng.*/
private static final ICMGenerator prng; // blank final
static
@@ -106,8 +88,8 @@ public class ICMRandomSpi extends SecureRandomSpi
private static void resetLocalPRNG()
{
- if (DEBUG && debuglevel > 8)
- debug(">>> resetLocalPRNG()");
+ if (Configuration.DEBUG)
+ log.entering(ICMRandomSpi.class.getName(), "resetLocalPRNG");
HashMap attributes = new HashMap();
attributes.put(ICMGenerator.CIPHER, Registry.AES_CIPHER);
byte[] key = new byte[128 / 8]; // AES default key size
@@ -131,8 +113,8 @@ public class ICMRandomSpi extends SecureRandomSpi
attributes.put(ICMGenerator.SEGMENT_INDEX, new BigInteger(1, index));
prng.setup(attributes);
- if (DEBUG && debuglevel > 8)
- debug("<<< resetLocalPRNG()");
+ if (Configuration.DEBUG)
+ log.exiting(ICMRandomSpi.class.getName(), "resetLocalPRNG");
}
// Instance methods
@@ -142,25 +124,25 @@ public class ICMRandomSpi extends SecureRandomSpi
public byte[] engineGenerateSeed(int numBytes)
{
- if (DEBUG && debuglevel > 8)
- debug(">>> engineGenerateSeed()");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineGenerateSeed");
if (numBytes < 1)
{
- if (DEBUG && debuglevel > 8)
- debug("<<< engineGenerateSeed()");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineGenerateSeed");
return new byte[0];
}
byte[] result = new byte[numBytes];
this.engineNextBytes(result);
- if (DEBUG && debuglevel > 8)
- debug("<<< engineGenerateSeed()");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineGenerateSeed");
return result;
}
public void engineNextBytes(byte[] bytes)
{
- if (DEBUG && debuglevel > 8)
- debug(">>> engineNextBytes()");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineNextBytes");
if (!adaptee.isInitialised())
{
this.engineSetSeed(new byte[0]);
@@ -175,23 +157,22 @@ public class ICMRandomSpi extends SecureRandomSpi
}
catch (LimitReachedException x)
{ // reseed the generator
- if (DEBUG)
+ if (Configuration.DEBUG)
{
- debug(LIMIT_REACHED_MSG + String.valueOf(x));
- x.printStackTrace(err);
- debug(RESEED);
+ log.fine(LIMIT_REACHED_MSG + String.valueOf(x));
+ log.fine(RESEED);
}
resetLocalPRNG();
}
}
- if (DEBUG && debuglevel > 8)
- debug("<<< engineNextBytes()");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineNextBytes");
}
public void engineSetSeed(byte[] seed)
{
- if (DEBUG && debuglevel > 8)
- debug(">>> engineSetSeed()");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineSetSeed");
// compute the total number of random bytes required to setup adaptee
int materialLength = 0;
materialLength += 16; // key material size
@@ -224,10 +205,10 @@ public class ICMRandomSpi extends SecureRandomSpi
}
catch (LimitReachedException x)
{
- if (DEBUG)
+ if (Configuration.DEBUG)
{
- debug(MSG + String.valueOf(x));
- debug(RETRY);
+ log.fine(MSG + String.valueOf(x));
+ log.fine(RETRY);
}
}
}
@@ -254,7 +235,7 @@ public class ICMRandomSpi extends SecureRandomSpi
attributes.put(ICMGenerator.SEGMENT_INDEX, new BigInteger(1, index));
adaptee.init(attributes);
- if (DEBUG && debuglevel > 8)
- debug("<<< engineSetSeed()");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineSetSeed");
}
} \ No newline at end of file
diff --git a/gnu/javax/crypto/jce/prng/UMacRandomSpi.java b/gnu/javax/crypto/jce/prng/UMacRandomSpi.java
index 7dad68b2f..5c60a21d8 100644
--- a/gnu/javax/crypto/jce/prng/UMacRandomSpi.java
+++ b/gnu/javax/crypto/jce/prng/UMacRandomSpi.java
@@ -38,15 +38,16 @@ exception statement from your version. */
package gnu.javax.crypto.jce.prng;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
-import gnu.javax.crypto.cipher.IBlockCipher;
import gnu.java.security.prng.LimitReachedException;
+import gnu.javax.crypto.cipher.IBlockCipher;
import gnu.javax.crypto.prng.UMacGenerator;
-import java.io.PrintWriter;
import java.security.SecureRandomSpi;
import java.util.HashMap;
import java.util.Random;
+import java.util.logging.Logger;
/**
* <p>An <em>Adapter</em> class around {@link UMacGenerator} to allow using this
@@ -54,24 +55,7 @@ import java.util.Random;
*/
public class UMacRandomSpi extends SecureRandomSpi
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "UMacRandomSpi";
-
- private static final boolean DEBUG = false;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(UMacRandomSpi.class.getName());
/** Class-wide prng to generate random material for the underlying prng.*/
private static final UMacGenerator prng; // blank final
static
@@ -181,10 +165,10 @@ public class UMacRandomSpi extends SecureRandomSpi
}
catch (LimitReachedException x)
{
- if (DEBUG)
+ if (Configuration.DEBUG)
{
- debug(MSG + String.valueOf(x));
- debug(RETRY);
+ log.fine(MSG + String.valueOf(x));
+ log.fine(RETRY);
}
}
}
diff --git a/gnu/javax/crypto/jce/spec/TMMHParameterSpec.java b/gnu/javax/crypto/jce/spec/TMMHParameterSpec.java
index 0ebec0991..a3b5f26e8 100644
--- a/gnu/javax/crypto/jce/spec/TMMHParameterSpec.java
+++ b/gnu/javax/crypto/jce/spec/TMMHParameterSpec.java
@@ -45,7 +45,7 @@ import java.security.spec.AlgorithmParameterSpec;
/**
* This class represents the algorithm parameters for the Truncated
* Multi-Modular Hash function for use with JCE-derived instances of
- * {@link gnu.crypto.mac.TMMH16}.
+ * {@link gnu.javax.crypto.mac.TMMH16}.
*
* <p>This class is little more than a container for the key stream, tag
* length, and prefix parameters for the TMMH algorithm.
diff --git a/gnu/javax/crypto/key/dh/GnuDHKeyPairGenerator.java b/gnu/javax/crypto/key/dh/GnuDHKeyPairGenerator.java
index 5626a2979..1cf1eb14d 100644
--- a/gnu/javax/crypto/key/dh/GnuDHKeyPairGenerator.java
+++ b/gnu/javax/crypto/key/dh/GnuDHKeyPairGenerator.java
@@ -38,18 +38,19 @@ exception statement from your version. */
package gnu.javax.crypto.key.dh;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.hash.Sha160;
import gnu.java.security.key.IKeyPairGenerator;
import gnu.java.security.util.PRNG;
-import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.Map;
+import java.util.logging.Logger;
import javax.crypto.spec.DHGenParameterSpec;
import javax.crypto.spec.DHParameterSpec;
@@ -66,26 +67,7 @@ import javax.crypto.spec.DHParameterSpec;
*/
public class GnuDHKeyPairGenerator implements IKeyPairGenerator
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "dh";
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 5;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(GnuDHKeyPairGenerator.class.getName());
/**
* Property name of an optional {@link SecureRandom} instance to use. The
* default is to use a classloader singleton from {@link PRNG}.
@@ -240,14 +222,14 @@ public class GnuDHKeyPairGenerator implements IKeyPairGenerator
p = params[RFC2631.DH_PARAMS_P];
j = params[RFC2631.DH_PARAMS_J];
g = params[RFC2631.DH_PARAMS_G];
- if (DEBUG && debuglevel > 0)
+ if (Configuration.DEBUG)
{
- debug("seed: 0x" + seed.toString(16));
- debug("counter: " + counter.intValue());
- debug("q: 0x" + q.toString(16));
- debug("p: 0x" + p.toString(16));
- debug("j: 0x" + j.toString(16));
- debug("g: 0x" + g.toString(16));
+ log.fine("seed: 0x" + seed.toString(16));
+ log.fine("counter: " + counter.intValue());
+ log.fine("q: 0x" + q.toString(16));
+ log.fine("p: 0x" + p.toString(16));
+ log.fine("j: 0x" + j.toString(16));
+ log.fine("g: 0x" + g.toString(16));
}
}
diff --git a/gnu/javax/crypto/key/dh/GnuDHPrivateKey.java b/gnu/javax/crypto/key/dh/GnuDHPrivateKey.java
index 0e71623b9..70b684b77 100644
--- a/gnu/javax/crypto/key/dh/GnuDHPrivateKey.java
+++ b/gnu/javax/crypto/key/dh/GnuDHPrivateKey.java
@@ -154,7 +154,7 @@ public class GnuDHPrivateKey extends GnuDHKey implements DHPrivateKey
* @return the byte sequence encoding this key according to the designated
* format.
* @exception IllegalArgumentException if the format is not supported.
- * @see gnu.crypto.key.dh.DHKeyPairRawCodec
+ * @see DHKeyPairRawCodec
*/
public byte[] getEncoded(int format)
{
diff --git a/gnu/javax/crypto/key/srp6/SRPKeyPairGenerator.java b/gnu/javax/crypto/key/srp6/SRPKeyPairGenerator.java
index 2957fc3c8..cf1a9cf75 100644
--- a/gnu/javax/crypto/key/srp6/SRPKeyPairGenerator.java
+++ b/gnu/javax/crypto/key/srp6/SRPKeyPairGenerator.java
@@ -38,16 +38,17 @@ exception statement from your version. */
package gnu.javax.crypto.key.srp6;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.key.IKeyPairGenerator;
import gnu.java.security.util.PRNG;
import gnu.java.security.util.Prime2;
-import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.SecureRandom;
import java.util.Map;
+import java.util.logging.Logger;
/**
*
@@ -60,26 +61,7 @@ import java.util.Map;
*/
public class SRPKeyPairGenerator implements IKeyPairGenerator
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "srp";
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 5;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(SRPKeyPairGenerator.class.getName());
private static final BigInteger ZERO = BigInteger.ZERO;
private static final BigInteger ONE = BigInteger.ONE;
@@ -235,11 +217,11 @@ public class SRPKeyPairGenerator implements IKeyPairGenerator
BigInteger q = params[0];
N = params[1];
g = params[2];
- if (DEBUG && debuglevel > 0)
+ if (Configuration.DEBUG)
{
- debug("q: " + q.toString(16));
- debug("N: " + N.toString(16));
- debug("g: " + g.toString(16));
+ log.fine("q: " + q.toString(16));
+ log.fine("N: " + N.toString(16));
+ log.fine("g: " + g.toString(16));
}
}
diff --git a/gnu/javax/crypto/keyring/AuthenticatedEntry.java b/gnu/javax/crypto/keyring/AuthenticatedEntry.java
index 22b42b3ea..fa77c6ec6 100644
--- a/gnu/javax/crypto/keyring/AuthenticatedEntry.java
+++ b/gnu/javax/crypto/keyring/AuthenticatedEntry.java
@@ -38,25 +38,20 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
+import gnu.java.security.Registry;
+import gnu.javax.crypto.mac.IMac;
+import gnu.javax.crypto.mac.MacFactory;
+import gnu.javax.crypto.mac.MacOutputStream;
+
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
-
import java.security.InvalidKeyException;
-
import java.util.Arrays;
-import java.util.Date;
-import java.util.Iterator;
import java.util.HashMap;
-import java.util.List;
-
-import gnu.java.security.Registry;
-import gnu.javax.crypto.mac.IMac;
-import gnu.javax.crypto.mac.MacFactory;
-import gnu.javax.crypto.mac.MacInputStream;
-import gnu.javax.crypto.mac.MacOutputStream;
+import java.util.Iterator;
public final class AuthenticatedEntry extends MaskableEnvelopeEntry implements
Registry
diff --git a/gnu/javax/crypto/keyring/CertPathEntry.java b/gnu/javax/crypto/keyring/CertPathEntry.java
index ef62347ec..f9e523b2c 100644
--- a/gnu/javax/crypto/keyring/CertPathEntry.java
+++ b/gnu/javax/crypto/keyring/CertPathEntry.java
@@ -40,14 +40,11 @@ package gnu.javax.crypto.keyring;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
-import java.io.DataOutputStream;
import java.io.IOException;
-
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
-
import java.util.Date;
/**
diff --git a/gnu/javax/crypto/keyring/CertificateEntry.java b/gnu/javax/crypto/keyring/CertificateEntry.java
index 95a708ac5..67ac7bf4b 100644
--- a/gnu/javax/crypto/keyring/CertificateEntry.java
+++ b/gnu/javax/crypto/keyring/CertificateEntry.java
@@ -39,13 +39,11 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
import java.io.DataInputStream;
-import java.io.DataOutputStream;
import java.io.IOException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
import java.util.Date;
/**
diff --git a/gnu/javax/crypto/keyring/EncryptedEntry.java b/gnu/javax/crypto/keyring/EncryptedEntry.java
index fad5f54b2..a47a3c6fa 100644
--- a/gnu/javax/crypto/keyring/EncryptedEntry.java
+++ b/gnu/javax/crypto/keyring/EncryptedEntry.java
@@ -38,21 +38,6 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-
-import java.security.InvalidKeyException;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.HashMap;
-import java.util.List;
-
import gnu.java.security.Registry;
import gnu.javax.crypto.cipher.CipherFactory;
import gnu.javax.crypto.cipher.IBlockCipher;
@@ -62,6 +47,15 @@ import gnu.javax.crypto.pad.IPad;
import gnu.javax.crypto.pad.PadFactory;
import gnu.javax.crypto.pad.WrongPaddingException;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.security.InvalidKeyException;
+import java.util.HashMap;
+import java.util.Iterator;
+
public class EncryptedEntry extends MaskableEnvelopeEntry implements Registry
{
diff --git a/gnu/javax/crypto/keyring/Entry.java b/gnu/javax/crypto/keyring/Entry.java
index 2f311271a..a2e7e5d21 100644
--- a/gnu/javax/crypto/keyring/Entry.java
+++ b/gnu/javax/crypto/keyring/Entry.java
@@ -38,6 +38,8 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
+import gnu.classpath.Configuration;
+
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
@@ -179,7 +181,8 @@ public abstract class Entry
{
throw new IOException("corrupt length");
}
- log.finest("About to instantiate new payload byte array for " + this);
+ if (Configuration.DEBUG)
+ log.fine("About to instantiate new payload byte array for " + this);
payload = new byte[len];
in.readFully(payload);
}
diff --git a/gnu/javax/crypto/keyring/EnvelopeEntry.java b/gnu/javax/crypto/keyring/EnvelopeEntry.java
index 2a57a23da..5e6d38312 100644
--- a/gnu/javax/crypto/keyring/EnvelopeEntry.java
+++ b/gnu/javax/crypto/keyring/EnvelopeEntry.java
@@ -38,6 +38,8 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
+import gnu.classpath.Configuration;
+
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
@@ -94,17 +96,20 @@ public abstract class EnvelopeEntry extends Entry
*/
public void add(Entry entry)
{
- log.entering(this.getClass().getName(), "add", entry);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "add", entry);
if (! containsEntry(entry))
{
if (entry instanceof EnvelopeEntry)
((EnvelopeEntry) entry).setContainingEnvelope(this);
entries.add(entry);
- log.finest("Payload is " + (payload == null ? "" : "not ") + "null");
+ if (Configuration.DEBUG)
+ log.fine("Payload is " + (payload == null ? "" : "not ") + "null");
makeAliasList();
}
- log.exiting(this.getClass().getName(), "add");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "add");
}
/**
@@ -117,9 +122,11 @@ public abstract class EnvelopeEntry extends Entry
*/
public boolean containsAlias(String alias)
{
- log.entering(this.getClass().getName(), "containsAlias", alias);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "containsAlias", alias);
String aliases = getAliasList();
- log.finest("aliases = [" + aliases + "]");
+ if (Configuration.DEBUG)
+ log.fine("aliases = [" + aliases + "]");
boolean result = false;
if (aliases != null)
{
@@ -131,7 +138,9 @@ public abstract class EnvelopeEntry extends Entry
break;
}
}
- log.exiting(this.getClass().getName(), "containsAlias", Boolean.valueOf(result));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "containsAlias",
+ Boolean.valueOf(result));
return result;
}
@@ -182,8 +191,8 @@ public abstract class EnvelopeEntry extends Entry
*/
public List get(String alias)
{
- log.entering(this.getClass().getName(), "get", alias);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "get", alias);
List result = new LinkedList();
for (Iterator it = entries.iterator(); it.hasNext();)
{
@@ -199,13 +208,14 @@ public abstract class EnvelopeEntry extends Entry
MaskableEnvelopeEntry mee = (MaskableEnvelopeEntry) ee;
if (mee.isMasked())
{
- log.finer("Processing masked entry: " + mee);
+ if (Configuration.DEBUG)
+ log.fine("Processing masked entry: " + mee);
result.add(mee);
continue;
}
}
-
- log.finer("Processing unmasked entry: " + ee);
+ if (Configuration.DEBUG)
+ log.fine("Processing unmasked entry: " + ee);
result.addAll(ee.get(alias));
}
else if (e instanceof PrimitiveEntry)
@@ -215,8 +225,8 @@ public abstract class EnvelopeEntry extends Entry
result.add(e);
}
}
-
- log.exiting(this.getClass().getName(), "get", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "get", result);
return result;
}
@@ -247,7 +257,8 @@ public abstract class EnvelopeEntry extends Entry
*/
public boolean remove(Entry entry)
{
- log.entering(this.getClass().getName(), "remove", entry);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "remove", entry);
boolean ret = false;
for (Iterator it = entries.iterator(); it.hasNext();)
{
@@ -278,12 +289,15 @@ public abstract class EnvelopeEntry extends Entry
}
if (ret)
{
- log.finest("State before: " + this);
+ if (Configuration.DEBUG)
+ log.fine("State before: " + this);
payload = null;
makeAliasList();
- log.finest("State after: " + this);
+ if (Configuration.DEBUG)
+ log.fine("State after: " + this);
}
- log.exiting(this.getClass().getName(), "remove", Boolean.valueOf(ret));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "remove", Boolean.valueOf(ret));
return ret;
}
@@ -298,7 +312,8 @@ public abstract class EnvelopeEntry extends Entry
*/
public boolean remove(String alias)
{
- log.entering(this.getClass().getName(), "remove", alias);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "remove", alias);
boolean result = false;
for (Iterator it = entries.iterator(); it.hasNext();)
{
@@ -320,12 +335,15 @@ public abstract class EnvelopeEntry extends Entry
}
if (result)
{
- log.finest("State before: " + this);
+ if (Configuration.DEBUG)
+ log.fine("State before: " + this);
payload = null;
makeAliasList();
- log.finest("State after: " + this);
+ if (Configuration.DEBUG)
+ log.fine("State after: " + this);
}
- log.exiting(this.getClass().getName(), "remove", Boolean.valueOf(result));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "remove", Boolean.valueOf(result));
return result;
}
@@ -410,7 +428,8 @@ public abstract class EnvelopeEntry extends Entry
private void makeAliasList()
{
- log.entering(this.getClass().getName(), "makeAliasList");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "makeAliasList");
if (! entries.isEmpty())
{
StringBuilder buf = new StringBuilder();
@@ -423,7 +442,7 @@ public abstract class EnvelopeEntry extends Entry
aliasOrList = ((EnvelopeEntry) entry).getAliasList();
else if (entry instanceof PrimitiveEntry)
aliasOrList = ((PrimitiveEntry) entry).getAlias();
- else
+ else if (Configuration.DEBUG)
log.fine("Entry with no Alias. Ignored: " + entry);
if (aliasOrList != null)
@@ -439,10 +458,12 @@ public abstract class EnvelopeEntry extends Entry
}
String aliasList = buf.toString();
properties.put("alias-list", aliasList);
- log.finer("alias-list=[" + aliasList + "]");
+ if (Configuration.DEBUG)
+ log.fine("alias-list=[" + aliasList + "]");
if (containingEnvelope != null)
containingEnvelope.makeAliasList();
}
- log.exiting(this.getClass().getName(), "makeAliasList");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "makeAliasList");
}
}
diff --git a/gnu/javax/crypto/keyring/GnuPrivateKeyring.java b/gnu/javax/crypto/keyring/GnuPrivateKeyring.java
index bd5a96227..5b6829e7b 100644
--- a/gnu/javax/crypto/keyring/GnuPrivateKeyring.java
+++ b/gnu/javax/crypto/keyring/GnuPrivateKeyring.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import java.io.DataInputStream;
@@ -105,7 +106,8 @@ public class GnuPrivateKeyring extends BaseKeyring implements IPrivateKeyring
public boolean containsPrivateKey(String alias)
{
- log.entering(this.getClass().getName(), "containsPrivateKey", alias);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "containsPrivateKey", alias);
boolean result = false;
if (containsAlias(alias))
for (Iterator it = get(alias).iterator(); it.hasNext();)
@@ -114,15 +116,17 @@ public class GnuPrivateKeyring extends BaseKeyring implements IPrivateKeyring
result = true;
break;
}
- log.exiting(this.getClass().getName(), "containsPrivateKey",
- Boolean.valueOf(result));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "containsPrivateKey",
+ Boolean.valueOf(result));
return result;
}
public Key getPrivateKey(String alias, char[] password)
throws UnrecoverableKeyException
{
- log.entering(this.getClass().getName(), "getPrivateKey", alias);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "getPrivateKey", alias);
Key result = null;
if (containsAlias(alias))
{
@@ -130,15 +134,16 @@ public class GnuPrivateKeyring extends BaseKeyring implements IPrivateKeyring
for (Iterator it = get(alias).iterator(); it.hasNext();)
{
Entry e = (Entry) it.next();
- log.finest("Entry: " + e);
+ if (Configuration.DEBUG)
+ log.finest("Entry: " + e);
if (e instanceof PasswordAuthenticatedEntry)
{
e1 = (PasswordAuthenticatedEntry) e;
break;
}
}
-
- log.finest("e1 = " + e1);
+ if (Configuration.DEBUG)
+ log.fine("e1 = " + e1);
if (e1 != null)
{
try
@@ -147,7 +152,8 @@ public class GnuPrivateKeyring extends BaseKeyring implements IPrivateKeyring
}
catch (Exception e)
{
- log.throwing(this.getClass().getName(), "getPrivateKey", e);
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "getPrivateKey", e);
throw new UnrecoverableKeyException("authentication failed");
}
@@ -186,23 +192,25 @@ public class GnuPrivateKeyring extends BaseKeyring implements IPrivateKeyring
}
}
}
- log.exiting(this.getClass().getName(), "getPrivateKey",
- result == null ? "null" : result.getClass().getName());
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "getPrivateKey",
+ result == null ? "null" : result.getClass().getName());
return result;
}
public void putPrivateKey(String alias, Key key, char[] password)
{
- log.entering(this.getClass().getName(), "putPrivateKey",
- new Object[] { alias, key.getClass().getName() });
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "putPrivateKey",
+ new Object[] { alias, key.getClass().getName() });
if (! containsPrivateKey(alias))
{
alias = fixAlias(alias);
Properties p = new Properties();
p.put("alias", alias);
PrivateKeyEntry pke = new PrivateKeyEntry(key, new Date(), p);
-
- log.finest("About to encrypt the key...");
+ if (Configuration.DEBUG)
+ log.fine("About to encrypt the key...");
PasswordEncryptedEntry enc;
enc = new PasswordEncryptedEntry(cipher, mode, keylen, new Properties());
enc.add(pke);
@@ -212,12 +220,13 @@ public class GnuPrivateKeyring extends BaseKeyring implements IPrivateKeyring
}
catch (IOException x)
{
- log.log(Level.FINER, "Exception while encrypting the key. "
- + "Rethrow as IllegalArgumentException", x);
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "Exception while encrypting the key. "
+ + "Rethrow as IllegalArgumentException", x);
throw new IllegalArgumentException(x.toString());
}
-
- log.finest("About to authenticate the encrypted key...");
+ if (Configuration.DEBUG)
+ log.fine("About to authenticate the encrypted key...");
PasswordAuthenticatedEntry auth;
auth = new PasswordAuthenticatedEntry(mac, maclen, new Properties());
auth.add(enc);
@@ -227,22 +236,25 @@ public class GnuPrivateKeyring extends BaseKeyring implements IPrivateKeyring
}
catch (IOException x)
{
- log.log(Level.FINER, "Exception while authenticating the encrypted "
- + "key. Rethrow as IllegalArgumentException", x);
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "Exception while authenticating the encrypted "
+ + "key. Rethrow as IllegalArgumentException", x);
throw new IllegalArgumentException(x.toString());
}
keyring.add(auth);
}
- else
- log.finer("Keyring already contains alias: " + alias);
+ else if (Configuration.DEBUG)
+ log.fine("Keyring already contains alias: " + alias);
- log.exiting(this.getClass().getName(), "putPrivateKey");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "putPrivateKey");
}
public boolean containsPublicKey(String alias)
{
- log.entering(this.getClass().getName(), "containsPublicKey", alias);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "containsPublicKey", alias);
boolean result = false;
if (containsAlias(alias))
for (Iterator it = get(alias).iterator(); it.hasNext();)
@@ -251,14 +263,16 @@ public class GnuPrivateKeyring extends BaseKeyring implements IPrivateKeyring
result = true;
break;
}
- log.exiting(this.getClass().getName(), "containsPublicKey",
- Boolean.valueOf(result));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "containsPublicKey",
+ Boolean.valueOf(result));
return result;
}
public PublicKey getPublicKey(String alias)
{
- log.entering(this.getClass().getName(), "getPublicKey", alias);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "getPublicKey", alias);
PublicKey result = null;
if (containsAlias(alias))
for (Iterator it = get(alias).iterator(); it.hasNext();)
@@ -270,30 +284,34 @@ public class GnuPrivateKeyring extends BaseKeyring implements IPrivateKeyring
break;
}
}
- log.exiting(this.getClass().getName(), "getPublicKey",
- result == null ? "null" : result.getClass().getName());
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "getPublicKey",
+ result == null ? "null" : result.getClass().getName());
return result;
}
public void putPublicKey(String alias, PublicKey key)
{
- log.entering(this.getClass().getName(), "putPublicKey",
- new Object[] { alias, key.getClass().getName() });
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "putPublicKey",
+ new Object[] { alias, key.getClass().getName() });
if (! containsPublicKey(alias))
{
Properties p = new Properties();
p.put("alias", fixAlias(alias));
add(new PublicKeyEntry(key, new Date(), p));
}
- else
- log.finer("Keyring already contains alias: " + alias);
+ else if (Configuration.DEBUG)
+ log.fine("Keyring already contains alias: " + alias);
- log.exiting(this.getClass().getName(), "putPublicKey");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "putPublicKey");
}
public boolean containsCertPath(String alias)
{
- log.entering(this.getClass().getName(), "containsCertPath", alias);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "containsCertPath", alias);
boolean result = false;
if (containsAlias(alias))
for (Iterator it = get(alias).iterator(); it.hasNext();)
@@ -302,14 +320,16 @@ public class GnuPrivateKeyring extends BaseKeyring implements IPrivateKeyring
result = true;
break;
}
- log.exiting(this.getClass().getName(), "containsCertPath",
- Boolean.valueOf(result));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "containsCertPath",
+ Boolean.valueOf(result));
return result;
}
public Certificate[] getCertPath(String alias)
{
- log.entering(this.getClass().getName(), "getCertPath", alias);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "getCertPath", alias);
Certificate[] result = null;
if (containsAlias(alias))
for (Iterator it = get(alias).iterator(); it.hasNext();)
@@ -321,29 +341,33 @@ public class GnuPrivateKeyring extends BaseKeyring implements IPrivateKeyring
break;
}
}
- log.exiting(this.getClass().getName(), "getCertPath", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "getCertPath", result);
return result;
}
public void putCertPath(String alias, Certificate[] path)
{
- log.entering(this.getClass().getName(), "putCertPath",
- new Object[] { alias, path });
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "putCertPath",
+ new Object[] { alias, path });
if (! containsCertPath(alias))
{
Properties p = new Properties();
p.put("alias", fixAlias(alias));
add(new CertPathEntry(path, new Date(), p));
}
- else
- log.finer("Keyring already contains alias: " + alias);
+ else if (Configuration.DEBUG)
+ log.fine("Keyring already contains alias: " + alias);
- log.exiting(this.getClass().getName(), "putCertPath");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "putCertPath");
}
protected void load(InputStream in, char[] password) throws IOException
{
- log.entering(this.getClass().getName(), "load");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "load");
if (in.read() != USAGE)
throw new MalformedKeyringException("incompatible keyring usage");
@@ -352,14 +376,17 @@ public class GnuPrivateKeyring extends BaseKeyring implements IPrivateKeyring
keyring = PasswordAuthenticatedEntry.decode(new DataInputStream(in),
password);
- log.exiting(this.getClass().getName(), "load");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "load");
}
protected void store(OutputStream out, char[] password) throws IOException
{
- log.entering(this.getClass().getName(), "store");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "store");
out.write(USAGE);
keyring.encode(new DataOutputStream(out), password);
- log.exiting(this.getClass().getName(), "store");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "store");
}
}
diff --git a/gnu/javax/crypto/keyring/GnuPublicKeyring.java b/gnu/javax/crypto/keyring/GnuPublicKeyring.java
index 7e1182bc1..0828ca1a1 100644
--- a/gnu/javax/crypto/keyring/GnuPublicKeyring.java
+++ b/gnu/javax/crypto/keyring/GnuPublicKeyring.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import java.io.DataInputStream;
@@ -77,7 +78,8 @@ public class GnuPublicKeyring extends BaseKeyring implements IPublicKeyring
public boolean containsCertificate(String alias)
{
- log.entering(this.getClass().getName(), "containsCertificate", alias);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "containsCertificate", alias);
boolean result = false;
if (containsAlias(alias))
for (Iterator it = get(alias).iterator(); it.hasNext();)
@@ -86,14 +88,16 @@ public class GnuPublicKeyring extends BaseKeyring implements IPublicKeyring
result = true;
break;
}
- log.exiting(this.getClass().getName(), "containsCertificate",
- Boolean.valueOf(result));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "containsCertificate",
+ Boolean.valueOf(result));
return result;
}
public Certificate getCertificate(String alias)
{
- log.entering(this.getClass().getName(), "getCertificate", alias);
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "getCertificate", alias);
Certificate result = null;
if (containsAlias(alias))
for (Iterator it = get(alias).iterator(); it.hasNext();)
@@ -105,29 +109,33 @@ public class GnuPublicKeyring extends BaseKeyring implements IPublicKeyring
break;
}
}
- log.exiting(this.getClass().getName(), "getCertificate", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "getCertificate", result);
return result;
}
public void putCertificate(String alias, Certificate cert)
{
- log.entering(this.getClass().getName(), "putCertificate",
- new Object[] { alias, cert });
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "putCertificate",
+ new Object[] { alias, cert });
if (! containsCertificate(alias))
{
Properties p = new Properties();
p.put("alias", fixAlias(alias));
add(new CertificateEntry(cert, new Date(), p));
}
- else
- log.finer("Keyring already contains alias: " + alias);
+ else if (Configuration.DEBUG)
+ log.fine("Keyring already contains alias: " + alias);
- log.exiting(this.getClass().getName(), "putCertificate");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "putCertificate");
}
protected void load(InputStream in, char[] password) throws IOException
{
- log.entering(this.getClass().getName(), "load");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "load");
if (in.read() != USAGE)
throw new MalformedKeyringException("incompatible keyring usage");
@@ -136,14 +144,17 @@ public class GnuPublicKeyring extends BaseKeyring implements IPublicKeyring
DataInputStream dis = new DataInputStream(in);
keyring = PasswordAuthenticatedEntry.decode(dis, password);
- log.exiting(this.getClass().getName(), "load");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "load");
}
protected void store(OutputStream out, char[] password) throws IOException
{
- log.entering(this.getClass().getName(), "store");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "store");
out.write(USAGE);
keyring.encode(new DataOutputStream(out), password);
- log.exiting(this.getClass().getName(), "store");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "store");
}
}
diff --git a/gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java b/gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java
index 96d4fc4db..e9713b369 100644
--- a/gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java
+++ b/gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.prng.IRandom;
import gnu.java.security.prng.LimitReachedException;
@@ -146,10 +147,12 @@ public final class PasswordAuthenticatedEntry extends MaskableEnvelopeEntry
public void verify(char[] password)
{
- log.entering(this.getClass().getName(), "verify");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "verify");
if (isMasked() && payload != null)
{
- log.finest("payload to verify: " + Util.dumpString(payload));
+ if (Configuration.DEBUG)
+ log.fine("payload to verify: " + Util.dumpString(payload));
long tt = - System.currentTimeMillis();
IMac m = null;
try
@@ -184,16 +187,20 @@ public final class PasswordAuthenticatedEntry extends MaskableEnvelopeEntry
}
tt += System.currentTimeMillis();
- log.finer("Verified in " + tt + "ms.");
+ if (Configuration.DEBUG)
+ log.fine("Verified in " + tt + "ms.");
}
- else
- log.finer("Skip verification; " + (isMasked() ? "null payload" : "unmasked"));
- log.exiting(this.getClass().getName(), "verify");
+ else if (Configuration.DEBUG)
+ log.fine("Skip verification; " + (isMasked() ? "null payload" : "unmasked"));
+
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "verify");
}
public void authenticate(char[] password) throws IOException
{
- log.entering(this.getClass().getName(), "authenticate");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "authenticate");
long tt = - System.currentTimeMillis();
long t1 = - System.currentTimeMillis();
@@ -203,7 +210,8 @@ public final class PasswordAuthenticatedEntry extends MaskableEnvelopeEntry
byte[] salt = new byte[8];
PRNG.getInstance().nextBytes(salt);
t1 += System.currentTimeMillis();
- log.finer("-- Generated salt in " + t1 + "ms.");
+ if (Configuration.DEBUG)
+ log.fine("-- Generated salt in " + t1 + "ms.");
properties.put("salt", Util.toString(salt));
IMac m = getMac(password);
ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
@@ -212,21 +220,27 @@ public final class PasswordAuthenticatedEntry extends MaskableEnvelopeEntry
for (Iterator it = entries.iterator(); it.hasNext();)
{
Entry entry = (Entry) it.next();
- log.finer("-- About to authenticate one " + entry);
+ if (Configuration.DEBUG)
+ log.fine("-- About to authenticate one " + entry);
t1 = - System.currentTimeMillis();
entry.encode(out2);
t1 += System.currentTimeMillis();
- log.finer("-- Authenticated an Entry in " + t1 + "ms.");
+ if (Configuration.DEBUG)
+ log.fine("-- Authenticated an Entry in " + t1 + "ms.");
}
bout.write(m.digest());
payload = bout.toByteArray();
- log.finest("authenticated payload: " + Util.dumpString(payload));
+ if (Configuration.DEBUG)
+ log.fine("authenticated payload: " + Util.dumpString(payload));
setMasked(true);
tt += System.currentTimeMillis();
- log.finer("Authenticated in " + tt + "ms.");
- log.exiting(this.getClass().getName(), "authenticate");
+ if (Configuration.DEBUG)
+ {
+ log.fine("Authenticated in " + tt + "ms.");
+ log.exiting(this.getClass().getName(), "authenticate");
+ }
}
public void encode(DataOutputStream out, char[] password) throws IOException
@@ -249,7 +263,8 @@ public final class PasswordAuthenticatedEntry extends MaskableEnvelopeEntry
private IMac getMac(char[] password) throws MalformedKeyringException
{
- log.entering(this.getClass().getName(), "getMac");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "getMac");
String saltString = properties.get("salt");
if (saltString == null)
throw new MalformedKeyringException("no salt");
@@ -303,7 +318,8 @@ public final class PasswordAuthenticatedEntry extends MaskableEnvelopeEntry
{
throw new Error(shouldNotHappen.toString());
}
- log.exiting(this.getClass().getName(), "getMac");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "getMac");
return mac;
}
}
diff --git a/gnu/javax/crypto/keyring/PasswordEncryptedEntry.java b/gnu/javax/crypto/keyring/PasswordEncryptedEntry.java
index 24ab98266..71c18d855 100644
--- a/gnu/javax/crypto/keyring/PasswordEncryptedEntry.java
+++ b/gnu/javax/crypto/keyring/PasswordEncryptedEntry.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.prng.IRandom;
import gnu.java.security.prng.LimitReachedException;
@@ -132,7 +133,8 @@ public class PasswordEncryptedEntry extends MaskableEnvelopeEntry implements
public void decrypt(char[] password) throws IllegalArgumentException,
WrongPaddingException
{
- log.entering(this.getClass().getName(), "decrypt");
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "decrypt");
if (isMasked() && payload != null)
{
long tt = - System.currentTimeMillis();
@@ -162,23 +164,27 @@ public class PasswordEncryptedEntry extends MaskableEnvelopeEntry implements
throw new IllegalArgumentException("decryption failed");
}
tt += System.currentTimeMillis();
- log.finer("Decrypted in " + tt + "ms.");
+ log.fine("Decrypted in " + tt + "ms.");
}
- else
- log.finer("Skip decryption; " + (isMasked() ? "null payload" : "unmasked"));
- log.exiting(this.getClass().getName(), "decrypt");
+ else if (Configuration.DEBUG)
+ log.fine("Skip decryption; " + (isMasked() ? "null payload" : "unmasked"));
+
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "decrypt");
}
public void encrypt(char[] password) throws IOException
{
- log.entering(this.getClass().getName(), "encrypt", String.valueOf(password));
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "encrypt", String.valueOf(password));
long tt = - System.currentTimeMillis();
long t1 = - System.currentTimeMillis();
byte[] salt = new byte[8];
PRNG.getInstance().nextBytes(salt);
t1 += System.currentTimeMillis();
- log.finer("-- Generated salt in " + t1 + "ms.");
+ if (Configuration.DEBUG)
+ log.fine("-- Generated salt in " + t1 + "ms.");
properties.put("salt", Util.toString(salt));
IMode mode = getMode(password, IMode.ENCRYPTION);
IPad pad = PadFactory.getInstance("PKCS7");
@@ -188,11 +194,13 @@ public class PasswordEncryptedEntry extends MaskableEnvelopeEntry implements
for (Iterator it = entries.iterator(); it.hasNext();)
{
Entry entry = (Entry) it.next();
- log.finer("-- About to encode one " + entry);
+ if (Configuration.DEBUG)
+ log.fine("-- About to encode one " + entry);
t1 = - System.currentTimeMillis();
entry.encode(out2);
t1 += System.currentTimeMillis();
- log.finer("-- Encoded an Entry in " + t1 + "ms.");
+ if (Configuration.DEBUG)
+ log.fine("-- Encoded an Entry in " + t1 + "ms.");
}
byte[] plaintext = bout.toByteArray();
byte[] padding = pad.pad(plaintext, 0, plaintext.length);
@@ -212,8 +220,11 @@ public class PasswordEncryptedEntry extends MaskableEnvelopeEntry implements
setMasked(true);
tt += System.currentTimeMillis();
- log.finer("Encrypted in " + tt + "ms.");
- log.exiting(this.getClass().getName(), "encrypt");
+ if (Configuration.DEBUG)
+ {
+ log.fine("Encrypted in " + tt + "ms.");
+ log.exiting(this.getClass().getName(), "encrypt");
+ }
}
public void encode(DataOutputStream out, char[] password) throws IOException
@@ -226,7 +237,8 @@ public class PasswordEncryptedEntry extends MaskableEnvelopeEntry implements
{
if (payload == null)
{
- log.fine("Null payload: " + this);
+ if (Configuration.DEBUG)
+ log.fine("Null payload: " + this);
throw new IllegalStateException("not encrypted");
}
}
diff --git a/gnu/javax/crypto/keyring/PublicKeyEntry.java b/gnu/javax/crypto/keyring/PublicKeyEntry.java
index 528e70cc6..bc09445fd 100644
--- a/gnu/javax/crypto/keyring/PublicKeyEntry.java
+++ b/gnu/javax/crypto/keyring/PublicKeyEntry.java
@@ -38,22 +38,19 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-
-import java.security.PublicKey;
-import java.security.KeyFactory;
-import java.security.spec.X509EncodedKeySpec;
-
-import java.util.Date;
-
import gnu.java.security.key.IKeyPairCodec;
import gnu.java.security.key.KeyPairCodecFactory;
import gnu.java.security.key.dss.DSSPublicKey;
import gnu.java.security.key.rsa.GnuRSAPublicKey;
import gnu.javax.crypto.key.dh.GnuDHPublicKey;
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.security.KeyFactory;
+import java.security.PublicKey;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Date;
+
public final class PublicKeyEntry extends PrimitiveEntry
{
diff --git a/gnu/javax/crypto/mac/OMAC.java b/gnu/javax/crypto/mac/OMAC.java
index c83320a1b..b7edb5cdd 100644
--- a/gnu/javax/crypto/mac/OMAC.java
+++ b/gnu/javax/crypto/mac/OMAC.java
@@ -38,18 +38,18 @@ exception statement from your version. */
package gnu.javax.crypto.mac;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
import gnu.javax.crypto.cipher.CipherFactory;
import gnu.javax.crypto.cipher.IBlockCipher;
import gnu.javax.crypto.mode.IMode;
-import gnu.javax.crypto.mode.ModeFactory;
import java.security.InvalidKeyException;
-
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
+import java.util.logging.Logger;
/**
* <p>The One-Key CBC MAC, OMAC. This message authentication code is based on
@@ -64,18 +64,7 @@ import java.util.Map;
*/
public class OMAC implements IMac
{
-
- // Constants and fields.
- // ------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
-
- private static void debug(String msg)
- {
- System.out.print(">>> OMAC: ");
- System.out.println(msg);
- }
-
+ private static final Logger log = Logger.getLogger(OMAC.class.getName());
private static final byte C1 = (byte) 0x87;
private static final byte C2 = 0x1b;
@@ -159,12 +148,8 @@ public class OMAC implements IMac
byte[] L = new byte[blockSize];
cipher.encryptBlock(L, 0, L, 0);
-
- if (DEBUG)
- {
- debug("L = " + Util.toString(L).toLowerCase());
- }
-
+ if (Configuration.DEBUG)
+ log.fine("L = " + Util.toString(L).toLowerCase());
if (Lu != null)
{
Arrays.fill(Lu, (byte) 0);
@@ -216,11 +201,8 @@ public class OMAC implements IMac
+ blockSize);
}
}
- if (DEBUG)
- {
- debug("Lu = " + Util.toString(Lu).toLowerCase());
- }
-
+ if (Configuration.DEBUG)
+ log.fine("Lu = " + Util.toString(Lu).toLowerCase());
msb = (Lu[0] & 0x80) != 0;
for (int i = 0; i < blockSize; i++)
{
@@ -241,11 +223,8 @@ public class OMAC implements IMac
Lu2[Lu2.length - 1] ^= C2;
}
}
- if (DEBUG)
- {
- debug("Lu2 = " + Util.toString(Lu2).toLowerCase());
- }
-
+ if (Configuration.DEBUG)
+ log.fine("Lu2 = " + Util.toString(Lu2).toLowerCase());
if (M != null)
{
Arrays.fill(M, (byte) 0);
diff --git a/gnu/javax/crypto/mode/BaseMode.java b/gnu/javax/crypto/mode/BaseMode.java
index 0a9ab2dab..f230cbd72 100644
--- a/gnu/javax/crypto/mode/BaseMode.java
+++ b/gnu/javax/crypto/mode/BaseMode.java
@@ -146,7 +146,7 @@ public abstract class BaseMode implements IMode
* of the method(s) available in the factory class.</p>
*
* @return the default value, in bytes, of the mode's block size.
- * @see gnu.crypto.mode.ModeFactory
+ * @see ModeFactory
*/
public int defaultBlockSize()
{
diff --git a/gnu/javax/crypto/mode/CTR.java b/gnu/javax/crypto/mode/CTR.java
index 49f4b9f3c..264d5399d 100644
--- a/gnu/javax/crypto/mode/CTR.java
+++ b/gnu/javax/crypto/mode/CTR.java
@@ -40,10 +40,8 @@ package gnu.javax.crypto.mode;
import gnu.java.security.Registry;
import gnu.java.security.util.Sequence;
-
import gnu.javax.crypto.cipher.IBlockCipher;
-import java.math.BigInteger;
import java.util.Arrays;
import java.util.Iterator;
diff --git a/gnu/javax/crypto/pad/BasePad.java b/gnu/javax/crypto/pad/BasePad.java
index 49c5d050a..b54c77078 100644
--- a/gnu/javax/crypto/pad/BasePad.java
+++ b/gnu/javax/crypto/pad/BasePad.java
@@ -38,18 +38,19 @@ exception statement from your version. */
package gnu.javax.crypto.pad;
+import gnu.classpath.Configuration;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
/**
- * <p>An abstract class to facilitate implementing padding algorithms.</p>
+ * An abstract class to facilitate implementing padding algorithms.
*/
public abstract class BasePad implements IPad
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(BasePad.class.getName());
/** The canonical name prefix of the padding algorithm. */
protected String name;
-
/** The block size, in bytes, for this instance. */
protected int blockSize;
@@ -98,42 +99,73 @@ public abstract class BasePad implements IPad
blockSize = -1;
}
+ /**
+ * A default implementation of a correctness test that exercises the padder
+ * implementation, using block sizes varying from 2 to 256 bytes.
+ *
+ * @return <code>true</code> if the concrete implementation correctly unpads
+ * what it pads for all tested block sizes. Returns <code>false</code>
+ * if the test fails for any block size.
+ */
public boolean selfTest()
{
+ final byte[] in = new byte[1024];
+ for (int bs = 2; bs < 256; bs++)
+ if (! test1BlockSize(bs, in))
+ return false;
+ return true;
+ }
+
+ /**
+ * The basic symmetric test for a padder given a specific block size.
+ * <p>
+ * The code ensures that the implementation is capable of unpadding what it
+ * pads.
+ *
+ * @param size the block size to test.
+ * @param buffer a work buffer. It is exposed as an argument for this method
+ * to reduce un-necessary object allocations.
+ * @return <code>true</code> if the test passes; <code>false</code>
+ * otherwise.
+ */
+ protected boolean test1BlockSize(int size, byte[] buffer)
+ {
byte[] padBytes;
final int offset = 5;
- final int limit = 1024;
- final byte[] in = new byte[limit];
- for (int bs = 2; bs < 256; bs++)
+ final int limit = buffer.length;
+
+ this.init(size);
+ for (int i = 0; i < limit - offset - blockSize; i++)
{
- this.init(bs);
- for (int i = 0; i < limit - offset - blockSize; i++)
+ padBytes = pad(buffer, offset, i);
+ if (((i + padBytes.length) % blockSize) != 0)
{
- padBytes = pad(in, offset, i);
- if (((i + padBytes.length) % blockSize) != 0)
- {
- new RuntimeException(name()).printStackTrace(System.err);
- return false;
- }
-
- System.arraycopy(padBytes, 0, in, offset + i, padBytes.length);
- try
- {
- if (padBytes.length != unpad(in, offset, i + padBytes.length))
- {
- new RuntimeException(name()).printStackTrace(System.err);
- return false;
- }
- }
- catch (WrongPaddingException x)
+ if (Configuration.DEBUG)
+ log.log(Level.SEVERE,
+ "Length of padded text MUST be a multiple of " + blockSize,
+ new RuntimeException(name()));
+ return false;
+ }
+ System.arraycopy(padBytes, 0, buffer, offset + i, padBytes.length);
+ try
+ {
+ if (padBytes.length != unpad(buffer, offset, i + padBytes.length))
{
- x.printStackTrace(System.err);
+ if (Configuration.DEBUG)
+ log.log(Level.SEVERE,
+ "IPad [" + name() + "] failed symmetric operation",
+ new RuntimeException(name()));
return false;
}
}
- this.reset();
+ catch (WrongPaddingException x)
+ {
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "test1BlockSize", x);
+ return false;
+ }
}
-
+ this.reset();
return true;
}
diff --git a/gnu/javax/crypto/pad/IPad.java b/gnu/javax/crypto/pad/IPad.java
index 4b4c925e6..9cef4f78b 100644
--- a/gnu/javax/crypto/pad/IPad.java
+++ b/gnu/javax/crypto/pad/IPad.java
@@ -44,7 +44,7 @@ package gnu.javax.crypto.pad;
* <p>Padding algorithms serve to <i>pad</i> and <i>unpad</i> byte arrays usually
* as the last step in an <i>encryption</i> or respectively a <i>decryption</i>
* operation. Their input buffers are usually those processed by instances of
- * {@link gnu.crypto.mode.IMode} and/or {@link gnu.crypto.cipher.IBlockCipher}.</p>
+ * {@link gnu.javax.crypto.mode.IMode} and/or {@link gnu.javax.crypto.cipher.IBlockCipher}.</p>
*/
public interface IPad
{
diff --git a/gnu/javax/crypto/pad/ISO10126.java b/gnu/javax/crypto/pad/ISO10126.java
new file mode 100644
index 000000000..8e8c59254
--- /dev/null
+++ b/gnu/javax/crypto/pad/ISO10126.java
@@ -0,0 +1,109 @@
+/* ISO10126.java -- An implementation of the ISO 10126-2 padding scheme
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
+USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.crypto.pad;
+
+import gnu.java.security.Registry;
+import gnu.java.security.util.PRNG;
+
+/**
+ * The implementation of the ISO 10126-2 padding algorithm.
+ * <p>
+ * The last byte of the padding block is the number of padding bytes, all other
+ * padding bytes are random.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.w3.org/TR/xmlenc-core/">XML Encryption Syntax and
+ * Processing</a> Section "5.2 Block Encryption Algorithms"; "Padding".</li>
+ * </ol>
+ */
+public final class ISO10126
+ extends BasePad
+{
+ /** Used to generate random numbers for padding bytes. */
+ private PRNG prng;
+
+ ISO10126()
+ {
+ super(Registry.ISO10126_PAD);
+ prng = PRNG.getInstance();
+ }
+
+ public void setup()
+ {
+ // Nothing to do here
+ }
+
+ public byte[] pad(byte[] in, int offset, int length)
+ {
+ int padLength = blockSize - (length % blockSize);
+ final byte[] pad = new byte[padLength];
+
+ // generate random numbers for the padding bytes except for the last byte
+ prng.nextBytes(pad, 0, padLength - 1);
+ // the last byte contains the number of padding bytes
+ pad[padLength - 1] = (byte) padLength;
+
+ return pad;
+ }
+
+ public int unpad(byte[] in, int offset, int length)
+ throws WrongPaddingException
+ {
+ // the last byte contains the number of padding bytes
+ int padLength = in[offset + length - 1] & 0xFF;
+ if (padLength > length)
+ throw new WrongPaddingException();
+
+ return padLength;
+ }
+
+ /**
+ * The default self-test in the super-class would take too long to finish
+ * with this type of padder --due to the large amount of random data needed.
+ * We override the default test and replace it with a simple one for a 16-byte
+ * block-size (default AES block-size). The Mauve test TestOfISO10126 will
+ * exercise all block-sizes that the default self-test uses for the other
+ * padders.
+ */
+ public boolean selfTest()
+ {
+ return test1BlockSize(16, new byte[1024]);
+ }
+}
diff --git a/gnu/javax/crypto/pad/PKCS1_V1_5.java b/gnu/javax/crypto/pad/PKCS1_V1_5.java
index 03c3d61a3..874908493 100644
--- a/gnu/javax/crypto/pad/PKCS1_V1_5.java
+++ b/gnu/javax/crypto/pad/PKCS1_V1_5.java
@@ -38,12 +38,14 @@ exception statement from your version. */
package gnu.javax.crypto.pad;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.sig.rsa.EME_PKCS1_V1_5;
import gnu.java.security.util.PRNG;
import gnu.java.security.util.Util;
-import java.io.PrintWriter;
+import java.util.logging.Level;
+import java.util.logging.Logger;
/**
* <p>A padding algorithm implementation of the EME-PKCS1-V1.5 encoding/decoding
@@ -63,26 +65,7 @@ import java.io.PrintWriter;
*/
public class PKCS1_V1_5 extends BasePad
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = Registry.EME_PKCS1_V1_5_PAD;
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 9;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(final String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(PKCS1_V1_5.class.getName());
private EME_PKCS1_V1_5 codec;
// Constructor(s)
@@ -92,7 +75,7 @@ public class PKCS1_V1_5 extends BasePad
* <p>Trivial package-private constructor for use by the <i>Factory</i> class.
* </p>
*
- * @see gnu.crypto.pad.PadFactory
+ * @see PadFactory
*/
PKCS1_V1_5()
{
@@ -117,10 +100,8 @@ public class PKCS1_V1_5 extends BasePad
final byte[] EM = codec.encode(M);
final byte[] result = new byte[blockSize - length];
System.arraycopy(EM, 0, result, 0, result.length);
- if (DEBUG && debuglevel > 8)
- {
- debug("padding: 0x" + Util.toString(result));
- }
+ if (Configuration.DEBUG)
+ log.fine("padding: 0x" + Util.toString(result));
return result;
}
@@ -130,10 +111,8 @@ public class PKCS1_V1_5 extends BasePad
final byte[] EM = new byte[length];
System.arraycopy(in, offset, EM, 0, length);
final int result = length - codec.decode(EM).length;
- if (DEBUG && debuglevel > 8)
- {
- debug("padding length: " + String.valueOf(result));
- }
+ if (Configuration.DEBUG)
+ log.fine("padding length: " + String.valueOf(result));
return result;
}
@@ -156,7 +135,10 @@ public class PKCS1_V1_5 extends BasePad
p = pad(M, 0, j);
if (j + p.length != blockSize)
{
- new RuntimeException(name()).printStackTrace(System.err);
+ if (Configuration.DEBUG)
+ log.log(Level.SEVERE,
+ "Length of padded text MUST be a multiple of " + blockSize,
+ new RuntimeException(name()));
return false;
}
@@ -166,13 +148,17 @@ public class PKCS1_V1_5 extends BasePad
{
if (p.length != unpad(EM, 0, blockSize))
{
- new RuntimeException(name()).printStackTrace(System.err);
+ if (Configuration.DEBUG)
+ log.log(Level.SEVERE,
+ "Failed symmetric operation",
+ new RuntimeException(name()));
return false;
}
}
catch (WrongPaddingException x)
{
- x.printStackTrace(System.err);
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "selfTest", x);
return false;
}
}
diff --git a/gnu/javax/crypto/pad/PKCS7.java b/gnu/javax/crypto/pad/PKCS7.java
index 5697aff27..d9084d13f 100644
--- a/gnu/javax/crypto/pad/PKCS7.java
+++ b/gnu/javax/crypto/pad/PKCS7.java
@@ -38,10 +38,11 @@ exception statement from your version. */
package gnu.javax.crypto.pad;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
-import java.io.PrintWriter;
+import java.util.logging.Logger;
/**
* <p>The implementation of the PKCS7 padding algorithm.</p>
@@ -60,33 +61,12 @@ import java.io.PrintWriter;
*/
public final class PKCS7 extends BasePad
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "pkcs7";
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 9;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
+ private static final Logger log = Logger.getLogger(PKCS7.class.getName());
/**
* Trivial package-private constructor for use by the <i>Factory</i> class.<p>
*
- * @see gnu.crypto.pad.PadFactory
+ * @see PadFactory
*/
PKCS7()
{
@@ -119,11 +99,8 @@ public final class PKCS7 extends BasePad
{
result[i++] = (byte) padLength;
}
-
- if (DEBUG && debuglevel > 8)
- {
- debug("padding: 0x" + Util.toString(result));
- }
+ if (Configuration.DEBUG)
+ log.fine("padding: 0x" + Util.toString(result));
return result;
}
@@ -139,11 +116,8 @@ public final class PKCS7 extends BasePad
throw new WrongPaddingException();
}
}
-
- if (DEBUG && debuglevel > 8)
- {
- debug("padding length: " + String.valueOf(result));
- }
+ if (Configuration.DEBUG)
+ log.fine("padding length: " + result);
return result;
}
} \ No newline at end of file
diff --git a/gnu/javax/crypto/pad/PadFactory.java b/gnu/javax/crypto/pad/PadFactory.java
index 913d69dcb..76ae934b6 100644
--- a/gnu/javax/crypto/pad/PadFactory.java
+++ b/gnu/javax/crypto/pad/PadFactory.java
@@ -49,12 +49,8 @@ import java.util.Set;
*/
public class PadFactory implements Registry
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
+ /** Collection of padding algorithm names --cached for speed. */
+ private static Set names;
/** Trivial constructor to enforce Singleton pattern. */
private PadFactory()
@@ -104,6 +100,10 @@ public class PadFactory implements Registry
{
result = new TLS1();
}
+ else if (pad.equals(ISO10126_PAD))
+ {
+ result = new ISO10126();
+ }
if (result != null && !result.selfTest())
{
@@ -114,24 +114,25 @@ public class PadFactory implements Registry
}
/**
- * <p>Returns a {@link java.util.Set} of names of padding algorithms
- * supported by this <i>Factory</i>.</p>
+ * Returns a {@link java.util.Set} of names of padding algorithms
+ * supported by this <i>Factory</i>.
*
* @return a {@link Set} of padding algorithm names (Strings).
*/
public static final Set getNames()
{
- HashSet hs = new HashSet();
- hs.add(PKCS5_PAD);
- hs.add(PKCS7_PAD);
- hs.add(TBC_PAD);
- hs.add(EME_PKCS1_V1_5_PAD);
- hs.add(SSL3_PAD);
- hs.add(TLS1_PAD);
-
- return Collections.unmodifiableSet(hs);
+ if (names == null)
+ {
+ HashSet hs = new HashSet();
+ hs.add(PKCS5_PAD);
+ hs.add(PKCS7_PAD);
+ hs.add(TBC_PAD);
+ hs.add(EME_PKCS1_V1_5_PAD);
+ hs.add(SSL3_PAD);
+ hs.add(TLS1_PAD);
+ hs.add(ISO10126_PAD);
+ names = Collections.unmodifiableSet(hs);
+ }
+ return names;
}
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/gnu/javax/crypto/pad/TBC.java b/gnu/javax/crypto/pad/TBC.java
index 25c3e4286..64fea18fd 100644
--- a/gnu/javax/crypto/pad/TBC.java
+++ b/gnu/javax/crypto/pad/TBC.java
@@ -38,10 +38,11 @@ exception statement from your version. */
package gnu.javax.crypto.pad;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
-import java.io.PrintWriter;
+import java.util.logging.Logger;
/**
* <p>The implementation of the Trailing Bit Complement (TBC) padding algorithm.</p>
@@ -59,33 +60,12 @@ import java.io.PrintWriter;
*/
public final class TBC extends BasePad
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "tbc";
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 9;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
+ private static final Logger log = Logger.getLogger(TBC.class.getName());
/**
* Trivial package-private constructor for use by the <i>Factory</i> class.<p>
*
- * @see gnu.crypto.pad.PadFactory
+ * @see PadFactory
*/
TBC()
{
@@ -123,10 +103,8 @@ public final class TBC extends BasePad
}
} // else it's already set to zeroes by virtue of initialisation
- if (DEBUG && debuglevel > 8)
- {
- debug("padding: 0x" + Util.toString(result));
- }
+ if (Configuration.DEBUG)
+ log.fine("padding: 0x" + Util.toString(result));
return result;
}
@@ -146,11 +124,8 @@ public final class TBC extends BasePad
{
throw new WrongPaddingException();
}
-
- if (DEBUG && debuglevel > 8)
- {
- debug("padding length: " + String.valueOf(result));
- }
+ if (Configuration.DEBUG)
+ log.fine("padding length: " + result);
return result;
}
} \ No newline at end of file
diff --git a/gnu/javax/crypto/pad/TLS1.java b/gnu/javax/crypto/pad/TLS1.java
index 00a538f88..eb7e22d5d 100644
--- a/gnu/javax/crypto/pad/TLS1.java
+++ b/gnu/javax/crypto/pad/TLS1.java
@@ -38,8 +38,6 @@ exception statement from your version. */
package gnu.javax.crypto.pad;
-import gnu.java.security.util.Util;
-
/**
* The padding scheme used by the Transport Layer Security protocol,
* version 1. This padding scheme is used in the block-ciphered struct,
diff --git a/gnu/javax/crypto/prng/CSPRNG.java b/gnu/javax/crypto/prng/CSPRNG.java
index 6585dcb90..0e39f0f5a 100644
--- a/gnu/javax/crypto/prng/CSPRNG.java
+++ b/gnu/javax/crypto/prng/CSPRNG.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.javax.crypto.prng;
+import gnu.classpath.Configuration;
import gnu.java.security.Properties;
import gnu.java.security.Registry;
import gnu.java.security.hash.HashFactory;
@@ -48,7 +49,6 @@ import gnu.java.security.prng.IRandom;
import gnu.java.security.prng.LimitReachedException;
import gnu.java.security.util.SimpleList;
import gnu.java.security.util.Util;
-
import gnu.javax.crypto.cipher.CipherFactory;
import gnu.javax.crypto.cipher.IBlockCipher;
@@ -56,15 +56,11 @@ import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintStream;
-
import java.net.MalformedURLException;
import java.net.URL;
-
import java.security.AccessController;
import java.security.InvalidKeyException;
import java.security.PrivilegedAction;
-
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
@@ -73,6 +69,8 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
+import java.util.logging.Level;
+import java.util.logging.Logger;
/**
* <p>An entropy pool-based pseudo-random number generator based on the PRNG
@@ -89,18 +87,7 @@ import java.util.StringTokenizer;
*/
public class CSPRNG extends BasePRNG
{
-
- // Constants and fields.
- // -------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
-
- private static void debug(String msg)
- {
- System.err.print(">>> CSPRNG: ");
- System.err.println(msg);
- }
-
+ private static final Logger log = Logger.getLogger(CSPRNG.class.getName());
/**
* Property name for the list of files to read for random values. The
* mapped value is a list with the following values:
@@ -114,7 +101,7 @@ public class CSPRNG extends BasePRNG
* <li>A {@link String}, indicating the path to the file.</li>
* </ol>
*
- * @see gnu.crypto.util.SimpleList
+ * @see gnu.java.security.util.SimpleList
*/
public static final String FILE_SOURCES = "gnu.crypto.prng.pool.files";
@@ -332,7 +319,7 @@ public class CSPRNG extends BasePRNG
* and its arguments.</p></dd>
*
* <dt>gnu.crypto.cspring.other</dt>
- * <dd><p>These properties are other sources, passed as the {@link OTHER_SOURCES}
+ * <dd><p>These properties are other sources, passed as the {@link #OTHER_SOURCES}
* parameter of the instance. The property value must be the full name
* of a class that implements the {@link EntropySource} interface and has a
* public no-argument constructor.</p></dd>
@@ -485,34 +472,25 @@ public class CSPRNG extends BasePRNG
public void setup(Map attrib)
{
List list = null;
-
- if (DEBUG)
- {
- debug(String.valueOf(attrib));
- }
+ if (Configuration.DEBUG)
+ log.fine("attrib=" + String.valueOf(attrib));
try
{
list = (List) attrib.get(FILE_SOURCES);
- if (DEBUG)
- {
- debug(String.valueOf(list));
- }
+ if (Configuration.DEBUG)
+ log.fine("list=" + String.valueOf(list));
if (list != null)
{
files.clear();
for (Iterator it = list.iterator(); it.hasNext();)
{
List l = (List) it.next();
- if (DEBUG)
- {
- debug("l=" + l);
- }
+ if (Configuration.DEBUG)
+ log.fine("l=" + l);
if (l.size() != 4)
{
- if (DEBUG)
- {
- debug("file list too small: " + l.size());
- }
+ if (Configuration.DEBUG)
+ log.fine("file list too small: " + l.size());
throw new IllegalArgumentException("invalid file list");
}
Double quality = (Double) l.get(0);
@@ -525,37 +503,28 @@ public class CSPRNG extends BasePRNG
}
catch (ClassCastException cce)
{
- if (DEBUG)
- {
- debug("bad file list: " + cce.getMessage());
- cce.printStackTrace();
- }
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "bad file list", cce);
throw new IllegalArgumentException("invalid file list");
}
try
{
list = (List) attrib.get(URL_SOURCES);
- if (DEBUG)
- {
- debug(String.valueOf(list));
- }
+ if (Configuration.DEBUG)
+ log.fine("list=" + String.valueOf(list));
if (list != null)
{
urls.clear();
for (Iterator it = list.iterator(); it.hasNext();)
{
List l = (List) it.next();
- if (DEBUG)
- {
- debug("l=" + l);
- }
+ if (Configuration.DEBUG)
+ log.fine("l=" + l);
if (l.size() != 4)
{
- if (DEBUG)
- {
- debug("URL list too small: " + l.size());
- }
+ if (Configuration.DEBUG)
+ log.fine("URL list too small: " + l.size());
throw new IllegalArgumentException("invalid URL list");
}
Double quality = (Double) l.get(0);
@@ -568,37 +537,28 @@ public class CSPRNG extends BasePRNG
}
catch (ClassCastException cce)
{
- if (DEBUG)
- {
- debug("bad URL list: " + cce.getMessage());
- cce.printStackTrace();
- }
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "bad URL list", cce);
throw new IllegalArgumentException("invalid URL list");
}
try
{
list = (List) attrib.get(PROGRAM_SOURCES);
- if (DEBUG)
- {
- debug(String.valueOf(list));
- }
+ if (Configuration.DEBUG)
+ log.fine("list=" + String.valueOf(list));
if (list != null)
{
progs.clear();
for (Iterator it = list.iterator(); it.hasNext();)
{
List l = (List) it.next();
- if (DEBUG)
- {
- debug("l=" + l);
- }
+ if (Configuration.DEBUG)
+ log.fine("l=" + l);
if (l.size() != 4)
{
- if (DEBUG)
- {
- debug("program list too small: " + l.size());
- }
+ if (Configuration.DEBUG)
+ log.fine("program list too small: " + l.size());
throw new IllegalArgumentException("invalid program list");
}
Double quality = (Double) l.get(0);
@@ -611,31 +571,24 @@ public class CSPRNG extends BasePRNG
}
catch (ClassCastException cce)
{
- if (DEBUG)
- {
- debug("bad program list: " + cce.getMessage());
- cce.printStackTrace();
- }
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "bad program list", cce);
throw new IllegalArgumentException("invalid program list");
}
try
{
list = (List) attrib.get(OTHER_SOURCES);
- if (DEBUG)
- {
- debug(String.valueOf(list));
- }
+ if (Configuration.DEBUG)
+ log.fine("list=" + String.valueOf(list));
if (list != null)
{
other.clear();
for (Iterator it = list.iterator(); it.hasNext();)
{
EntropySource src = (EntropySource) it.next();
- if (DEBUG)
- {
- debug("src=" + src);
- }
+ if (Configuration.DEBUG)
+ log.fine("src=" + src);
if (src == null)
{
throw new NullPointerException("null source in source list");
@@ -679,16 +632,12 @@ public class CSPRNG extends BasePRNG
public void fillBlock() throws LimitReachedException
{
- if (DEBUG)
- {
- debug("fillBlock");
- }
+ if (Configuration.DEBUG)
+ log.fine("fillBlock");
if (getQuality() < 100.0)
{
- if (DEBUG)
- {
- debug("doing slow poll");
- }
+ if (Configuration.DEBUG)
+ log.fine("doing slow poll");
slowPoll();
}
@@ -764,10 +713,10 @@ public class CSPRNG extends BasePRNG
{
throw new ArrayIndexOutOfBoundsException();
}
- if (DEBUG)
+ if (Configuration.DEBUG)
{
- debug("adding random bytes:");
- debug(Util.toString(buf, off, len));
+ log.fine("adding random bytes:");
+ log.fine(Util.toString(buf, off, len));
}
final int count = off + len;
for (int i = off; i < count; i++)
@@ -790,10 +739,8 @@ public class CSPRNG extends BasePRNG
*/
public synchronized void addRandomByte(byte b)
{
- if (DEBUG)
- {
- debug("adding byte " + Integer.toHexString(b));
- }
+ if (Configuration.DEBUG)
+ log.fine("adding byte " + Integer.toHexString(b));
pool[index++] ^= b;
if (index >= pool.length)
{
@@ -807,18 +754,14 @@ public class CSPRNG extends BasePRNG
synchronized void addQuality(double quality)
{
- if (DEBUG)
- {
- debug("adding quality " + quality);
- }
+ if (Configuration.DEBUG)
+ log.fine("adding quality " + quality);
if (this.quality < 100)
{
this.quality += quality;
}
- if (DEBUG)
- {
- debug("quality now " + this.quality);
- }
+ if (Configuration.DEBUG)
+ log.fine("quality now " + this.quality);
}
synchronized double getQuality()
@@ -928,11 +871,9 @@ public class CSPRNG extends BasePRNG
private void slowPoll() throws LimitReachedException
{
- if (DEBUG)
- {
- debug("poller is alive? "
- + (pollerThread == null ? false : pollerThread.isAlive()));
- }
+ if (Configuration.DEBUG)
+ log.fine("poller is alive? "
+ + (pollerThread == null ? false : pollerThread.isAlive()));
if (pollerThread == null || !pollerThread.isAlive())
{
boolean interrupted = false;
@@ -956,12 +897,9 @@ public class CSPRNG extends BasePRNG
// and there in insufficient randomness, throw an exception.
if (!interrupted && blocking && quality < 100.0)
{
- if (DEBUG)
- {
- debug("insufficient quality: " + quality);
- }
- throw new LimitReachedException(
- "insufficient randomness was polled");
+ if (Configuration.DEBUG)
+ log.fine("insufficient quality: " + quality);
+ throw new LimitReachedException("insufficient randomness was polled");
}
}
}
@@ -994,7 +932,7 @@ public class CSPRNG extends BasePRNG
// Field.
// -----------------------------------------------------------------------
- private byte counter;
+ protected byte counter;
// Constructor.
// -----------------------------------------------------------------------
@@ -1059,11 +997,11 @@ public class CSPRNG extends BasePRNG
public void run()
{
running = true;
- if (DEBUG)
+ if (Configuration.DEBUG)
{
- debug("files: " + files);
- debug("URLs: " + urls);
- debug("progs: " + progs);
+ log.fine("files: " + files);
+ log.fine("URLs: " + urls);
+ log.fine("progs: " + progs);
}
Iterator files_it = files.iterator();
Iterator urls_it = urls.iterator();
@@ -1085,10 +1023,8 @@ public class CSPRNG extends BasePRNG
try
{
List l = (List) files_it.next();
- if (DEBUG)
- {
- debug(l.toString());
- }
+ if (Configuration.DEBUG)
+ log.fine(l.toString());
double qual = ((Double) l.get(0)).doubleValue();
int offset = ((Integer) l.get(1)).intValue();
int count = ((Integer) l.get(2)).intValue();
@@ -1105,18 +1041,13 @@ public class CSPRNG extends BasePRNG
pool.addRandomBytes(buf, 0, len);
pool.addQuality(qual * ((double) len / (double) count));
}
- if (DEBUG)
- {
- debug("got " + len + " bytes from " + src);
- }
+ if (Configuration.DEBUG)
+ log.fine("got " + len + " bytes from " + src);
}
catch (Exception x)
{
- if (DEBUG)
- {
- debug(x.toString());
- x.printStackTrace();
- }
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "run", x);
}
}
@@ -1130,10 +1061,8 @@ public class CSPRNG extends BasePRNG
try
{
List l = (List) urls_it.next();
- if (DEBUG)
- {
- debug(l.toString());
- }
+ if (Configuration.DEBUG)
+ log.fine(l.toString());
double qual = ((Double) l.get(0)).doubleValue();
int offset = ((Integer) l.get(1)).intValue();
int count = ((Integer) l.get(2)).intValue();
@@ -1150,18 +1079,13 @@ public class CSPRNG extends BasePRNG
pool.addRandomBytes(buf, 0, len);
pool.addQuality(qual * ((double) len / (double) count));
}
- if (DEBUG)
- {
- debug("got " + len + " bytes from " + src);
- }
+ if (Configuration.DEBUG)
+ log.fine("got " + len + " bytes from " + src);
}
catch (Exception x)
{
- if (DEBUG)
- {
- debug(x.toString());
- x.printStackTrace();
- }
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "run", x);
}
}
@@ -1176,10 +1100,8 @@ public class CSPRNG extends BasePRNG
try
{
List l = (List) prog_it.next();
- if (DEBUG)
- {
- debug(l.toString());
- }
+ if (Configuration.DEBUG)
+ log.finer(l.toString());
double qual = ((Double) l.get(0)).doubleValue();
int offset = ((Integer) l.get(1)).intValue();
int count = ((Integer) l.get(2)).intValue();
@@ -1200,18 +1122,13 @@ public class CSPRNG extends BasePRNG
}
proc.destroy();
proc.waitFor();
- if (DEBUG)
- {
- debug("got " + len + " bytes from " + src);
- }
+ if (Configuration.DEBUG)
+ log.fine("got " + len + " bytes from " + src);
}
catch (Exception x)
{
- if (DEBUG)
- {
- debug(x.toString());
- x.printStackTrace();
- }
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "run", x);
try
{
if (proc != null)
@@ -1243,18 +1160,13 @@ public class CSPRNG extends BasePRNG
}
pool.addRandomBytes(buf, 0, buf.length);
pool.addQuality(src.quality());
- if (DEBUG)
- {
- debug("got " + buf.length + " bytes from " + src);
- }
+ if (Configuration.DEBUG)
+ log.fine("got " + buf.length + " bytes from " + src);
}
catch (Exception x)
{
- if (DEBUG)
- {
- debug(x.toString());
- x.printStackTrace();
- }
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "run", x);
}
}
}
diff --git a/gnu/javax/crypto/sasl/SaslInputStream.java b/gnu/javax/crypto/sasl/SaslInputStream.java
index 57eb2b5c5..14de9e12f 100644
--- a/gnu/javax/crypto/sasl/SaslInputStream.java
+++ b/gnu/javax/crypto/sasl/SaslInputStream.java
@@ -38,12 +38,13 @@ exception statement from your version. */
package gnu.javax.crypto.sasl;
+import gnu.classpath.Configuration;
import gnu.java.security.util.Util;
+import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
-import java.io.IOException;
-import java.io.PrintWriter;
+import java.util.logging.Logger;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
@@ -55,41 +56,11 @@ import javax.security.sasl.SaslServer;
*/
public class SaslInputStream extends InputStream
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "SaslOutputStream";
-
- private static final String ERROR = "ERROR";
-
- private static final String WARN = " WARN";
-
- // private static final String INFO = " INFO";
- private static final String TRACE = "DEBUG";
-
- private static final boolean DEBUG = true;
-
- private static final int debuglevel = 3;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String level, Object obj)
- {
- err.println("[" + level + "] " + NAME + ": " + String.valueOf(obj));
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(SaslInputStream.class.getName());
private SaslClient client;
-
private SaslServer server;
-
private int maxRawSendSize;
-
private InputStream source;
-
private byte[] internalBuf;
// Constructor(s)
@@ -168,7 +139,6 @@ public class SaslInputStream extends InputStream
else
{
byte[] tmp = new byte[internalBuf.length - 1];
- // System.arraycopy(internalBuf, 0, tmp, 0, tmp.length);
System.arraycopy(internalBuf, 1, tmp, 0, tmp.length);
internalBuf = tmp;
}
@@ -241,32 +211,22 @@ public class SaslInputStream extends InputStream
*/
public int read(byte[] b, int off, int len) throws IOException
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> read(b, " + String.valueOf(off) + ", "
- + String.valueOf(len) + ")");
-
- if (b == null)
- {
- throw new NullPointerException("b");
- }
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "read",
+ new Object[] { b, Integer.valueOf(off), Integer.valueOf(len) });
if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length)
|| ((off + len) < 0))
- {
- throw new IndexOutOfBoundsException("off=" + String.valueOf(off)
- + ", len=" + String.valueOf(len)
- + ", b.length="
- + String.valueOf(b.length));
- }
+ throw new IndexOutOfBoundsException("off=" + off
+ + ", len=" + len
+ + ", b.length=" + b.length);
if (len == 0)
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== read() --> 0");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "read", Integer.valueOf(0));
return 0;
}
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Available: " + String.valueOf(available()));
-
+ if (Configuration.DEBUG)
+ log.finer("Available: " + available());
int result = 0;
if (internalBuf == null || internalBuf.length < 1)
try
@@ -274,21 +234,24 @@ public class SaslInputStream extends InputStream
internalBuf = readSaslBuffer();
if (internalBuf == null)
{
- if (DEBUG && debuglevel > 4)
- debug(WARN, "Underlying stream empty. Returning -1");
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== read() --> -1");
+ if (Configuration.DEBUG)
+ {
+ log.finer("Underlying stream empty. Returning -1");
+ log.exiting(this.getClass().getName(), "read",
+ Integer.valueOf(-1));
+ }
return -1;
}
}
catch (InterruptedIOException x)
{
- if (DEBUG && debuglevel > 6)
- debug(TRACE, x);
- if (DEBUG && debuglevel > 4)
- debug(WARN, "Reading thread was interrupted. Returning -1");
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== read() --> -1");
+ if (Configuration.DEBUG)
+ {
+ log.finer("Reading thread was interrupted. Returning -1");
+ log.throwing(this.getClass().getName(), "read", x);
+ log.exiting(this.getClass().getName(), "read",
+ Integer.valueOf(-1));
+ }
return -1;
}
@@ -328,8 +291,8 @@ public class SaslInputStream extends InputStream
data = readSaslBuffer();
if (data == null)
{
- if (DEBUG && debuglevel > 4)
- debug(WARN, "Underlying stream exhausted. Breaking...");
+ if (Configuration.DEBUG)
+ log.finer("Underlying stream exhausted. Breaking...");
break;
}
@@ -352,18 +315,16 @@ public class SaslInputStream extends InputStream
}
else
{ // nothing much we can do except return what we have
- if (DEBUG && debuglevel > 4)
- debug(WARN,
- "Not enough bytes in source to read a buffer. Breaking...");
+ if (Configuration.DEBUG)
+ log.finer("Not enough bytes in source to read a buffer. Breaking...");
break;
}
}
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Remaining: "
- + (internalBuf == null ? 0 : internalBuf.length));
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== read() --> " + String.valueOf(result));
+ if (Configuration.DEBUG)
+ {
+ log.finer("Remaining: " + (internalBuf == null ? 0 : internalBuf.length));
+ log.exiting(this.getClass().getName(), "read()", String.valueOf(result));
+ }
return result;
}
@@ -379,9 +340,8 @@ public class SaslInputStream extends InputStream
*/
private byte[] readSaslBuffer() throws IOException
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> readSaslBuffer()");
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "readSaslBuffer()");
int realLength; // check if we read as many bytes as we're supposed to
byte[] result = new byte[4];
try
@@ -389,32 +349,27 @@ public class SaslInputStream extends InputStream
realLength = source.read(result);
if (realLength == -1)
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== readSaslBuffer() --> null");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "readSaslBuffer");
return null;
}
}
catch (IOException x)
{
- if (DEBUG && debuglevel > 0)
- debug(ERROR, x);
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "readSaslBuffer", x);
throw x;
}
if (realLength != 4)
- {
- throw new IOException("Was expecting 4 but found "
- + String.valueOf(realLength));
- }
+ throw new IOException("Was expecting 4 but found " + realLength);
int bufferLength = result[0] << 24 | (result[1] & 0xFF) << 16
| (result[2] & 0xFF) << 8 | (result[3] & 0xFF);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "SASL buffer size: " + bufferLength);
+ if (Configuration.DEBUG)
+ log.finer("SASL buffer size: " + bufferLength);
if (bufferLength > maxRawSendSize || bufferLength < 0)
- {
- throw new SaslEncodingException("SASL buffer (security layer) too long");
- }
+ throw new SaslEncodingException("SASL buffer (security layer) too long");
result = new byte[bufferLength];
try
@@ -423,37 +378,34 @@ public class SaslInputStream extends InputStream
}
catch (IOException x)
{
- if (DEBUG && debuglevel > 0)
- debug(ERROR, x);
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "readSaslBuffer", x);
throw x;
}
if (realLength != bufferLength)
- throw new IOException("Was expecting " + String.valueOf(bufferLength)
- + " but found " + String.valueOf(realLength));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Incoming buffer (before security) (hex): "
- + Util.dumpString(result));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Incoming buffer (before security) (str): \""
- + new String(result) + "\"");
-
- if (client != null)
+ throw new IOException("Was expecting " + bufferLength
+ + " but found " + realLength);
+ if (Configuration.DEBUG)
{
- result = client.unwrap(result, 0, realLength);
+ log.finer("Incoming buffer (before security) (hex): "
+ + Util.dumpString(result));
+ log.finer("Incoming buffer (before security) (str): \""
+ + new String(result) + "\"");
}
+ if (client != null)
+ result = client.unwrap(result, 0, realLength);
else
+ result = server.unwrap(result, 0, realLength);
+
+ if (Configuration.DEBUG)
{
- result = server.unwrap(result, 0, realLength);
+ log.finer("Incoming buffer (after security) (hex): "
+ + Util.dumpString(result));
+ log.finer("Incoming buffer (after security) (str): \""
+ + new String(result) + "\"");
+ log.exiting(this.getClass().getName(), "readSaslBuffer");
}
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Incoming buffer (after security) (hex): "
- + Util.dumpString(result));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Incoming buffer (after security) (str): \""
- + new String(result) + "\"");
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== readSaslBuffer()");
return result;
}
} \ No newline at end of file
diff --git a/gnu/javax/crypto/sasl/SaslOutputStream.java b/gnu/javax/crypto/sasl/SaslOutputStream.java
index 699720137..9d2aa020d 100644
--- a/gnu/javax/crypto/sasl/SaslOutputStream.java
+++ b/gnu/javax/crypto/sasl/SaslOutputStream.java
@@ -38,11 +38,12 @@ exception statement from your version. */
package gnu.javax.crypto.sasl;
+import gnu.classpath.Configuration;
import gnu.java.security.util.Util;
-import java.io.OutputStream;
import java.io.IOException;
-import java.io.PrintWriter;
+import java.io.OutputStream;
+import java.util.logging.Logger;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
@@ -54,37 +55,10 @@ import javax.security.sasl.SaslServer;
*/
public class SaslOutputStream extends OutputStream
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "SaslOutputStream";
-
- // private static final String ERROR = "ERROR";
- // private static final String WARN = " WARN";
- // private static final String INFO = " INFO";
- private static final String TRACE = "DEBUG";
-
- private static final boolean DEBUG = true;
-
- private static final int debuglevel = 3;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String level, Object obj)
- {
- err.println("[" + level + "] " + NAME + ": " + String.valueOf(obj));
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(SaslOutputStream.class.getName());
private SaslClient client;
-
private SaslServer server;
-
private int maxRawSendSize;
-
private OutputStream dest;
// Constructor(s)
@@ -148,52 +122,45 @@ public class SaslOutputStream extends OutputStream
*/
public void write(byte[] b, int off, int len) throws IOException
{
- if (b == null)
- {
- throw new NullPointerException("b");
- }
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "write");
if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length)
|| ((off + len) < 0))
- {
- throw new IndexOutOfBoundsException("off=" + String.valueOf(off)
- + ", len=" + String.valueOf(len)
- + ", b.length="
- + String.valueOf(b.length));
- }
+ throw new IndexOutOfBoundsException("off=" + off
+ + ", len=" + len
+ + ", b.length=" + b.length);
if (len == 0)
{
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "write");
return;
}
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> write()");
-
int chunckSize, length, chunck = 1;
byte[] output = null, result;
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "About to wrap " + String.valueOf(len) + " byte(s)...");
+ if (Configuration.DEBUG)
+ log.finer("About to wrap " + len + " byte(s)...");
while (len > 0)
{
chunckSize = (len > maxRawSendSize ? maxRawSendSize : len);
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Outgoing buffer (before security) (hex): "
- + Util.dumpString(b, off, chunckSize));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Outgoing buffer (before security) (str): \""
- + new String(b, off, chunckSize) + "\"");
-
+ if (Configuration.DEBUG)
+ {
+ log.finer("Outgoing buffer (before security) (hex): "
+ + Util.dumpString(b, off, chunckSize));
+ log.finer("Outgoing buffer (before security) (str): \""
+ + new String(b, off, chunckSize) + "\"");
+ }
if (client != null)
output = client.wrap(b, off, chunckSize);
else
output = server.wrap(b, off, chunckSize);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Outgoing buffer (after security) (hex): "
- + Util.dumpString(output));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Outgoing buffer (after security) (str): \""
- + new String(output) + "\"");
-
+ if (Configuration.DEBUG)
+ {
+ log.finer("Outgoing buffer (after security) (hex): "
+ + Util.dumpString(output));
+ log.finer("Outgoing buffer (after security) (str): \""
+ + new String(output) + "\"");
+ }
length = output.length;
result = new byte[length + 4];
result[0] = (byte) (length >>> 24);
@@ -206,13 +173,12 @@ public class SaslOutputStream extends OutputStream
off += chunckSize;
len -= chunckSize;
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Wrapped chunck #" + String.valueOf(chunck));
+ if (Configuration.DEBUG)
+ log.finer("Wrapped chunck #" + chunck);
chunck++;
}
-
dest.flush();
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== write()");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "write");
}
} \ No newline at end of file
diff --git a/gnu/javax/crypto/sasl/SaslUtil.java b/gnu/javax/crypto/sasl/SaslUtil.java
index e70312c0d..cb8d88e69 100644
--- a/gnu/javax/crypto/sasl/SaslUtil.java
+++ b/gnu/javax/crypto/sasl/SaslUtil.java
@@ -40,7 +40,6 @@ package gnu.javax.crypto.sasl;
import gnu.java.security.util.Util;
-import java.math.BigInteger;
import java.security.MessageDigest;
/**
diff --git a/gnu/javax/crypto/sasl/srp/PasswordFile.java b/gnu/javax/crypto/sasl/srp/PasswordFile.java
index 1628a4167..70a4bb65c 100644
--- a/gnu/javax/crypto/sasl/srp/PasswordFile.java
+++ b/gnu/javax/crypto/sasl/srp/PasswordFile.java
@@ -39,7 +39,6 @@ exception statement from your version. */
package gnu.javax.crypto.sasl.srp;
import gnu.java.security.Registry;
-import gnu.java.security.hash.IMessageDigest;
import gnu.java.security.util.Util;
import gnu.javax.crypto.key.srp6.SRPAlgorithm;
import gnu.javax.crypto.sasl.NoSuchUserException;
@@ -50,9 +49,9 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
+import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
-import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
diff --git a/gnu/javax/crypto/sasl/srp/SRPClient.java b/gnu/javax/crypto/sasl/srp/SRPClient.java
index 1a1664ff7..0430342eb 100644
--- a/gnu/javax/crypto/sasl/srp/SRPClient.java
+++ b/gnu/javax/crypto/sasl/srp/SRPClient.java
@@ -38,147 +38,84 @@ exception statement from your version. */
package gnu.javax.crypto.sasl.srp;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.hash.MD5;
import gnu.java.security.util.PRNG;
import gnu.java.security.util.Util;
-
+import gnu.javax.crypto.assembly.Direction;
+import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
import gnu.javax.crypto.key.IKeyAgreementParty;
import gnu.javax.crypto.key.IncomingMessage;
-import gnu.javax.crypto.key.KeyAgreementFactory;
import gnu.javax.crypto.key.KeyAgreementException;
+import gnu.javax.crypto.key.KeyAgreementFactory;
import gnu.javax.crypto.key.OutgoingMessage;
import gnu.javax.crypto.key.srp6.SRP6KeyAgreement;
-import gnu.javax.crypto.assembly.Direction;
-import gnu.javax.crypto.cipher.CipherFactory;
-import gnu.javax.crypto.cipher.IBlockCipher;
import gnu.javax.crypto.sasl.ClientMechanism;
import gnu.javax.crypto.sasl.IllegalMechanismStateException;
import gnu.javax.crypto.sasl.InputBuffer;
import gnu.javax.crypto.sasl.IntegrityException;
import gnu.javax.crypto.sasl.OutputBuffer;
-
import gnu.javax.security.auth.Password;
-import java.io.IOException;
-import java.io.PrintWriter;
import java.io.ByteArrayOutputStream;
+import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
+import java.util.logging.Logger;
+import javax.security.auth.DestroyFailedException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
-import javax.security.auth.DestroyFailedException;
import javax.security.sasl.AuthenticationException;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;
/**
- * <p>The SASL-SRP client-side mechanism.</p>
+ * The SASL-SRP client-side mechanism.
*/
public class SRPClient extends ClientMechanism implements SaslClient
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "SRPClient";
-
- // private static final String ERROR = "ERROR";
- // private static final String WARN = " WARN";
- private static final String INFO = " INFO";
-
- private static final String TRACE = "DEBUG";
-
- private static final boolean DEBUG = true;
-
- private static final int debuglevel = 3;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(final String level, final Object obj)
- {
- err.println("[" + level + "] " + NAME + ": " + String.valueOf(obj));
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // private static final HashMap uid2ctx = new HashMap();
-
+ private static final Logger log = Logger.getLogger(SRPClient.class.getName());
private String uid; // the unique key for this type of client
-
private String U; // the authentication identity
-
BigInteger N, g, A, B;
-
private Password password; // the authentication credentials
-
private byte[] s; // the user's salt
-
private byte[] cIV, sIV; // client+server IVs, when confidentiality is on
-
private byte[] M1, M2; // client+server evidences
-
private byte[] cn, sn; // client's and server's nonce
-
private SRP srp; // SRP algorithm instance used by this client
-
private byte[] sid; // session ID when re-used
-
private int ttl; // session time-to-live in seconds
-
private byte[] sCB; // the peer's channel binding data
-
private String L; // available options
-
private String o;
-
private String chosenIntegrityAlgorithm;
-
private String chosenConfidentialityAlgorithm;
-
private int rawSendSize = Registry.SASL_BUFFER_MAX_LIMIT;
-
private byte[] K; // shared session key
-
private boolean replayDetection = true; // whether Replay Detection is on
-
private int inCounter = 0; // messages sequence numbers
-
private int outCounter = 0;
-
private IALG inMac, outMac; // if !null, use for integrity
-
private CALG inCipher, outCipher; // if !null, use for confidentiality
-
private IKeyAgreementParty clientHandler = KeyAgreementFactory.getPartyAInstance(Registry.SRP_SASL_KA);
-
/** Our default source of randomness. */
private PRNG prng = null;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public SRPClient()
{
super(Registry.SASL_SRP_MECHANISM);
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // abstract methods implementation -----------------------------------------
-
protected void initMechanism() throws SaslException
{
// we shall keep track of the sid (and the security context of this
@@ -195,9 +132,8 @@ public class SRPClient extends ClientMechanism implements SaslClient
b = protocol.getBytes();
md.update(b, 0, b.length);
if (channelBinding.length > 0)
- {
- md.update(channelBinding, 0, channelBinding.length);
- }
+ md.update(channelBinding, 0, channelBinding.length);
+
uid = Util.toBase64(md.digest());
if (ClientStore.instance().isAlive(uid))
{
@@ -253,8 +189,6 @@ public class SRPClient extends ClientMechanism implements SaslClient
sn = null;
}
- // javax.security.sasl.SaslClient interface implementation -----------------
-
public boolean hasInitialResponse()
{
return true;
@@ -282,7 +216,7 @@ public class SRPClient extends ClientMechanism implements SaslClient
}
return result;
case 2: // should only occur if session re-use was rejected
- if (!complete)
+ if (! complete)
{
state++;
return receiveEvidence(challenge);
@@ -296,22 +230,15 @@ public class SRPClient extends ClientMechanism implements SaslClient
protected byte[] engineUnwrap(final byte[] incoming, final int offset,
final int len) throws SaslException
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> engineUnwrap()");
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineUnwrap");
if (inMac == null && inCipher == null)
- {
- throw new IllegalStateException("connection is not protected");
- }
-
+ throw new IllegalStateException("connection is not protected");
// at this point one, or both, of confidentiality and integrity protection
// services are active.
-
final byte[] result;
try
{
- // final InputBuffer frameIn = InputBuffer.getInstance(incoming, offset, len);
- // result = frameIn.getEOS();
if (inMac != null)
{ // integrity bytes are at the end of the stream
final int macBytesCount = inMac.length();
@@ -320,16 +247,14 @@ public class SRPClient extends ClientMechanism implements SaslClient
final byte[] received_mac = new byte[macBytesCount];
System.arraycopy(incoming, offset + payloadLength, received_mac, 0,
macBytesCount);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got C (received MAC): "
- + Util.dumpString(received_mac));
- // inMac.update(result);
+ if (Configuration.DEBUG)
+ log.fine("Got C (received MAC): " + Util.dumpString(received_mac));
inMac.update(incoming, offset, payloadLength);
if (replayDetection)
{
inCounter++;
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "inCounter=" + String.valueOf(inCounter));
+ if (Configuration.DEBUG)
+ log.fine("inCounter=" + inCounter);
inMac.update(new byte[] { (byte) (inCounter >>> 24),
(byte) (inCounter >>> 16),
(byte) (inCounter >>> 8),
@@ -337,170 +262,106 @@ public class SRPClient extends ClientMechanism implements SaslClient
}
final byte[] computed_mac = inMac.doFinal();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Computed MAC: " + Util.dumpString(computed_mac));
+ if (Configuration.DEBUG)
+ log.fine("Computed MAC: " + Util.dumpString(computed_mac));
if (!Arrays.equals(received_mac, computed_mac))
- {
- throw new IntegrityException("engineUnwrap()");
- }
-
+ throw new IntegrityException("engineUnwrap()");
// deal with the payload, which can be either plain or encrypted
if (inCipher != null)
- {
- result = inCipher.doFinal(incoming, offset, payloadLength);
- }
+ result = inCipher.doFinal(incoming, offset, payloadLength);
else
{
result = new byte[len - macBytesCount];
System.arraycopy(incoming, offset, result, 0, result.length);
}
}
- else
- { // no integrity protection; just confidentiality
- // if (inCipher != null) {
- result = inCipher.doFinal(incoming, offset, len);
- // } else {
- // result = new byte[len];
- // System.arraycopy(incoming, offset, result, 0, len);
- // }
- }
- // if (inCipher != null) {
- // result = inCipher.doFinal(result);
- // }
+ else // no integrity protection; just confidentiality
+ result = inCipher.doFinal(incoming, offset, len);
}
catch (IOException x)
{
if (x instanceof SaslException)
- {
- throw (SaslException) x;
- }
+ throw (SaslException) x;
throw new SaslException("engineUnwrap()", x);
}
-
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== engineUnwrap()");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineUnwrap");
return result;
}
protected byte[] engineWrap(final byte[] outgoing, final int offset,
final int len) throws SaslException
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> engineWrap()");
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineWrap");
if (outMac == null && outCipher == null)
- {
- throw new IllegalStateException("connection is not protected");
- }
-
+ throw new IllegalStateException("connection is not protected");
// at this point one, or both, of confidentiality and integrity protection
// services are active.
-
- // byte[] data = new byte[len];
- // System.arraycopy(outgoing, offset, data, 0, len);
byte[] result;
try
{
- // OutputBuffer frameOut = new OutputBuffer();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
// Process the data
if (outCipher != null)
{
- // data = outCipher.doFinal(data);
result = outCipher.doFinal(outgoing, offset, len);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding c (encrypted plaintext): "
- + Util.dumpString(result));
-
- // frameOut.setEOS(data);
+ if (Configuration.DEBUG)
+ log.fine("Encoding c (encrypted plaintext): "
+ + Util.dumpString(result));
out.write(result);
-
if (outMac != null)
{
outMac.update(result);
if (replayDetection)
{
outCounter++;
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "outCounter=" + String.valueOf(outCounter));
- outMac.update(new byte[] { (byte) (outCounter >>> 24),
- (byte) (outCounter >>> 16),
- (byte) (outCounter >>> 8),
- (byte) outCounter });
+ if (Configuration.DEBUG)
+ log.fine("outCounter=" + outCounter);
+ outMac.update(new byte[] { (byte)(outCounter >>> 24),
+ (byte)(outCounter >>> 16),
+ (byte)(outCounter >>> 8),
+ (byte) outCounter });
}
final byte[] C = outMac.doFinal();
- // frameOut.setOS(C);
out.write(C);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding C (integrity checksum): "
- + Util.dumpString(C));
- } // else confidentiality only; do nothing
+ if (Configuration.DEBUG)
+ log.fine("Encoding C (integrity checksum): " + Util.dumpString(C));
+ }
+ // else confidentiality only; do nothing
}
- else
- { // no confidentiality; just integrity [+ replay detection]
- // if (DEBUG && debuglevel > 6) debug(TRACE, "Encoding p (plaintext): "+Util.dumpString(data));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding p (plaintext): "
- + Util.dumpString(outgoing, offset, len));
-
- // frameOut.setEOS(data);
+ else // no confidentiality; just integrity [+ replay detection]
+ {
+ if (Configuration.DEBUG)
+ log.fine("Encoding p (plaintext): "
+ + Util.dumpString(outgoing, offset, len));
out.write(outgoing, offset, len);
-
- // if (outMac != null) {
- // outMac.update(data);
outMac.update(outgoing, offset, len);
if (replayDetection)
{
outCounter++;
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "outCounter=" + String.valueOf(outCounter));
- outMac.update(new byte[] { (byte) (outCounter >>> 24),
- (byte) (outCounter >>> 16),
- (byte) (outCounter >>> 8),
- (byte) outCounter });
+ if (Configuration.DEBUG)
+ log.fine("outCounter=" + outCounter);
+ outMac.update(new byte[] { (byte)(outCounter >>> 24),
+ (byte)(outCounter >>> 16),
+ (byte)(outCounter >>> 8),
+ (byte) outCounter });
}
final byte[] C = outMac.doFinal();
- // frameOut.setOS(C);
out.write(C);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding C (integrity checksum): "
- + Util.dumpString(C));
- // }
+ if (Configuration.DEBUG)
+ log.fine("Encoding C (integrity checksum): " + Util.dumpString(C));
}
-
- // frameOut.setEOS(data);
- //
- // if (outMac != null) {
- // outMac.update(data);
- // if (replayDetection) {
- // outCounter++;
- // if (DEBUG && debuglevel > 6) debug(TRACE, "outCounter="+String.valueOf(outCounter));
- // outMac.update(new byte[] {
- // (byte)(outCounter >>> 24),
- // (byte)(outCounter >>> 16),
- // (byte)(outCounter >>> 8),
- // (byte) outCounter });
- // }
- // byte[] C = outMac.doFinal();
- // frameOut.setOS(C);
- // if (DEBUG && debuglevel > 6) debug(TRACE, "Encoding C (integrity checksum): "+Util.dumpString(C));
- // }
-
- // result = frameOut.wrap();
result = out.toByteArray();
-
}
catch (IOException x)
{
if (x instanceof SaslException)
- {
- throw (SaslException) x;
- }
+ throw (SaslException) x;
throw new SaslException("engineWrap()", x);
}
-
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== engineWrap()");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineWrap");
return result;
}
@@ -509,13 +370,9 @@ public class SRPClient extends ClientMechanism implements SaslClient
if (inMac != null)
{
if (inCipher != null)
- {
- return Registry.QOP_AUTH_CONF;
- }
- else
- {
- return Registry.QOP_AUTH_INT;
- }
+ return Registry.QOP_AUTH_CONF;
+
+ return Registry.QOP_AUTH_INT;
}
return Registry.QOP_AUTH;
}
@@ -525,13 +382,9 @@ public class SRPClient extends ClientMechanism implements SaslClient
if (inMac != null)
{
if (inCipher != null)
- {
- return Registry.STRENGTH_HIGH;
- }
- else
- {
- return Registry.STRENGTH_MEDIUM;
- }
+ return Registry.STRENGTH_HIGH;
+
+ return Registry.STRENGTH_MEDIUM;
}
return Registry.STRENGTH_LOW;
}
@@ -550,19 +403,16 @@ public class SRPClient extends ClientMechanism implements SaslClient
private byte[] sendIdentities() throws SaslException
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> sendIdentities()");
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "sendIdentities");
// If necessary, prompt the client for the username and password
getUsernameAndPassword();
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Password: \"" + new String(password.getPassword()) + "\"");
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding U (username): \"" + U + "\"");
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding I (userid): \"" + authorizationID + "\"");
-
+ if (Configuration.DEBUG)
+ {
+ log.fine("Password: \"" + new String(password.getPassword()) + "\"");
+ log.fine("Encoding U (username): \"" + U + "\"");
+ log.fine("Encoding I (userid): \"" + authorizationID + "\"");
+ }
// if session re-use generate new 16-byte nonce
if (sid.length != 0)
{
@@ -570,9 +420,7 @@ public class SRPClient extends ClientMechanism implements SaslClient
getDefaultPRNG().nextBytes(cn);
}
else
- {
- cn = new byte[0];
- }
+ cn = new byte[0];
final OutputBuffer frameOut = new OutputBuffer();
try
@@ -586,36 +434,30 @@ public class SRPClient extends ClientMechanism implements SaslClient
catch (IOException x)
{
if (x instanceof SaslException)
- {
- throw (SaslException) x;
- }
+ throw (SaslException) x;
throw new AuthenticationException("sendIdentities()", x);
}
final byte[] result = frameOut.encode();
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== sendIdentities()");
- if (DEBUG && debuglevel > 2)
- debug(INFO, "C: " + Util.dumpString(result));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " U = " + U);
- if (DEBUG && debuglevel > 2)
- debug(INFO, " I = " + authorizationID);
- if (DEBUG && debuglevel > 2)
- debug(INFO, "sid = " + new String(sid));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " cn = " + Util.dumpString(cn));
- if (DEBUG && debuglevel > 2)
- debug(INFO, "cCB = " + Util.dumpString(channelBinding));
+ if (Configuration.DEBUG)
+ {
+ log.fine("C: " + Util.dumpString(result));
+ log.fine(" U = " + U);
+ log.fine(" I = " + authorizationID);
+ log.fine("sid = " + new String(sid));
+ log.fine(" cn = " + Util.dumpString(cn));
+ log.fine("cCB = " + Util.dumpString(channelBinding));
+ log.exiting(this.getClass().getName(), "sendIdentities");
+ }
return result;
}
private byte[] sendPublicKey(final byte[] input) throws SaslException
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> sendPublicKey()");
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "S: " + Util.dumpString(input));
-
+ if (Configuration.DEBUG)
+ {
+ log.entering(this.getClass().getName(), "sendPublicKey");
+ log.fine("S: " + Util.dumpString(input));
+ }
// Server sends [00], N, g, s, B, L
// or [FF], sn, sCB
final InputBuffer frameIn = new InputBuffer(input);
@@ -626,57 +468,47 @@ public class SRPClient extends ClientMechanism implements SaslClient
if (ack == 0x00)
{ // new session
N = frameIn.getMPI();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got N (modulus): " + Util.dump(N));
+ if (Configuration.DEBUG)
+ log.fine("Got N (modulus): " + Util.dump(N));
g = frameIn.getMPI();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got g (generator): " + Util.dump(g));
+ if (Configuration.DEBUG)
+ log.fine("Got g (generator): " + Util.dump(g));
s = frameIn.getOS();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got s (salt): " + Util.dumpString(s));
+ if (Configuration.DEBUG)
+ log.fine("Got s (salt): " + Util.dumpString(s));
B = frameIn.getMPI();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got B (server ephermeral public key): "
- + Util.dump(B));
+ if (Configuration.DEBUG)
+ log.fine("Got B (server ephermeral public key): " + Util.dump(B));
L = frameIn.getText();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got L (available options): \"" + L + "\"");
+ if (Configuration.DEBUG)
+ log.fine("Got L (available options): \"" + L + "\"");
}
else if (ack == 0xFF)
{ // session re-use
sn = frameIn.getOS();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got sn (server nonce): " + Util.dumpString(sn));
+ if (Configuration.DEBUG)
+ log.fine("Got sn (server nonce): " + Util.dumpString(sn));
sCB = frameIn.getEOS();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got sCB (server channel binding): "
- + Util.dumpString(sCB));
- }
- else
- { // unexpected scalar
- throw new SaslException("sendPublicKey(): Invalid scalar (" + ack
- + ") in server's request");
+ if (Configuration.DEBUG)
+ log.fine("Got sCB (server channel binding): " + Util.dumpString(sCB));
}
+ else // unexpected scalar
+ throw new SaslException("sendPublicKey(): Invalid scalar (" + ack
+ + ") in server's request");
}
catch (IOException x)
{
if (x instanceof SaslException)
- {
- throw (SaslException) x;
- }
+ throw (SaslException) x;
throw new SaslException("sendPublicKey()", x);
}
-
if (ack == 0x00)
{ // new session ---------------------------------------
o = createO(L.toLowerCase()); // do this first to initialise the SRP hash
-
final byte[] pBytes; // use ASCII encoding to inter-operate w/ non-java
pBytes = password.getBytes();
-
// ----------------------------------------------------------------------
final HashMap mapA = new HashMap();
- // mapA.put(SRP6KeyAgreement.HASH_FUNCTION, srp.newDigest());
mapA.put(SRP6KeyAgreement.HASH_FUNCTION, srp.getAlgorithm());
mapA.put(SRP6KeyAgreement.USER_IDENTITY, U);
mapA.put(SRP6KeyAgreement.USER_PASSWORD, pBytes);
@@ -689,9 +521,6 @@ public class SRPClient extends ClientMechanism implements SaslClient
{
throw new SaslException("sendPublicKey()", x);
}
-
- // ----------------------------------------------------------------------
-
// -------------------------------------------------------------------
try
{
@@ -702,7 +531,6 @@ public class SRPClient extends ClientMechanism implements SaslClient
out.writeMPI(B);
IncomingMessage in = new IncomingMessage(out.toByteArray());
out = clientHandler.processMessage(in);
-
in = new IncomingMessage(out.toByteArray());
A = in.readMPI();
K = clientHandler.getSharedSecret();
@@ -712,13 +540,11 @@ public class SRPClient extends ClientMechanism implements SaslClient
throw new SaslException("sendPublicKey()", x);
}
// -------------------------------------------------------------------
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "K: " + Util.dumpString(K));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding A (client ephemeral public key): "
- + Util.dump(A));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine("K: " + Util.dumpString(K));
+ log.fine("Encoding A (client ephemeral public key): " + Util.dump(A));
+ }
try
{
M1 = srp.generateM1(N, g, U, s, A, B, K, authorizationID, L, cn,
@@ -728,13 +554,11 @@ public class SRPClient extends ClientMechanism implements SaslClient
{
throw new AuthenticationException("sendPublicKey()", x);
}
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding o (client chosen options): \"" + o + "\"");
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding cIV (client IV): \"" + Util.dumpString(cIV)
- + "\"");
-
+ if (Configuration.DEBUG)
+ {
+ log.fine("Encoding o (client chosen options): \"" + o + "\"");
+ log.fine("Encoding cIV (client IV): \"" + Util.dumpString(cIV) + "\"");
+ }
final OutputBuffer frameOut = new OutputBuffer();
try
{
@@ -746,74 +570,65 @@ public class SRPClient extends ClientMechanism implements SaslClient
catch (IOException x)
{
if (x instanceof SaslException)
- {
- throw (SaslException) x;
- }
+ throw (SaslException) x;
throw new AuthenticationException("sendPublicKey()", x);
}
final byte[] result = frameOut.encode();
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== sendPublicKey()");
- if (DEBUG && debuglevel > 2)
- debug(INFO, "New session, or session re-use rejected...");
- if (DEBUG && debuglevel > 2)
- debug(INFO, "C: " + Util.dumpString(result));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " A = 0x" + A.toString(16));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " M1 = " + Util.dumpString(M1));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " o = " + o);
- if (DEBUG && debuglevel > 2)
- debug(INFO, "cIV = " + Util.dumpString(cIV));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine("New session, or session re-use rejected...");
+ log.fine("C: " + Util.dumpString(result));
+ log.fine(" A = 0x" + A.toString(16));
+ log.fine(" M1 = " + Util.dumpString(M1));
+ log.fine(" o = " + o);
+ log.fine("cIV = " + Util.dumpString(cIV));
+ log.exiting(this.getClass().getName(), "sendPublicKey");
+ }
return result;
}
- else
- { // session re-use accepted -------------------------------------
+ else // session re-use accepted -------------------------------------------
+ {
setupSecurityServices(true);
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== sendPublicKey()");
- if (DEBUG && debuglevel > 2)
- debug(INFO, "Session re-use accepted...");
+ if (Configuration.DEBUG)
+ {
+ log.fine("Session re-use accepted...");
+ log.exiting(this.getClass().getName(), "sendPublicKey");
+ }
return null;
}
}
private byte[] receiveEvidence(byte[] input) throws SaslException
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> receiveEvidence()");
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "S: " + Util.dumpString(input));
-
+ if (Configuration.DEBUG)
+ {
+ log.entering(this.getClass().getName(), "receiveEvidence");
+ log.fine("S: " + Util.dumpString(input));
+ }
// Server send M2, sIV, sCB, sid, ttl
final InputBuffer frameIn = new InputBuffer(input);
try
{
M2 = frameIn.getOS();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got M2 (server evidence): " + Util.dumpString(M2));
+ if (Configuration.DEBUG)
+ log.fine("Got M2 (server evidence): " + Util.dumpString(M2));
sIV = frameIn.getOS();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got sIV (server IV): " + Util.dumpString(sIV));
+ if (Configuration.DEBUG)
+ log.fine("Got sIV (server IV): " + Util.dumpString(sIV));
sid = frameIn.getEOS();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got sid (session ID): " + new String(sid));
+ if (Configuration.DEBUG)
+ log.fine("Got sid (session ID): " + new String(sid));
ttl = (int) frameIn.getScalar(4);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got ttl (session time-to-live): " + ttl + "sec.");
+ if (Configuration.DEBUG)
+ log.fine("Got ttl (session time-to-live): " + ttl + "sec.");
sCB = frameIn.getEOS();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got sCB (server channel binding): "
- + Util.dumpString(sCB));
+ if (Configuration.DEBUG)
+ log.fine("Got sCB (server channel binding): " + Util.dumpString(sCB));
}
catch (IOException x)
{
if (x instanceof SaslException)
- {
- throw (SaslException) x;
- }
+ throw (SaslException) x;
throw new AuthenticationException("receiveEvidence()", x);
}
@@ -827,18 +642,14 @@ public class SRPClient extends ClientMechanism implements SaslClient
{
throw new AuthenticationException("receiveEvidence()", x);
}
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Expected: " + Util.dumpString(expected));
+ if (Configuration.DEBUG)
+ log.fine("Expected: " + Util.dumpString(expected));
if (!Arrays.equals(M2, expected))
- {
- throw new AuthenticationException("M2 mismatch");
- }
+ throw new AuthenticationException("M2 mismatch");
setupSecurityServices(false);
-
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== receiveEvidence()");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "receiveEvidence");
return null;
}
@@ -846,19 +657,15 @@ public class SRPClient extends ClientMechanism implements SaslClient
{
try
{
- if ((!properties.containsKey(Registry.SASL_USERNAME))
- && (!properties.containsKey(Registry.SASL_PASSWORD)))
+ if ((! properties.containsKey(Registry.SASL_USERNAME))
+ && (! properties.containsKey(Registry.SASL_PASSWORD)))
{
final NameCallback nameCB;
final String defaultName = System.getProperty("user.name");
if (defaultName == null)
- {
- nameCB = new NameCallback("username: ");
- }
+ nameCB = new NameCallback("username: ");
else
- {
- nameCB = new NameCallback("username: ", defaultName);
- }
+ nameCB = new NameCallback("username: ", defaultName);
final PasswordCallback pwdCB = new PasswordCallback("password: ",
false);
handler.handle(new Callback[] { nameCB, pwdCB });
@@ -868,21 +675,15 @@ public class SRPClient extends ClientMechanism implements SaslClient
else
{
if (properties.containsKey(Registry.SASL_USERNAME))
- {
- this.U = (String) properties.get(Registry.SASL_USERNAME);
- }
+ this.U = (String) properties.get(Registry.SASL_USERNAME);
else
{
final NameCallback nameCB;
final String defaultName = System.getProperty("user.name");
if (defaultName == null)
- {
- nameCB = new NameCallback("username: ");
- }
+ nameCB = new NameCallback("username: ");
else
- {
- nameCB = new NameCallback("username: ", defaultName);
- }
+ nameCB = new NameCallback("username: ", defaultName);
this.handler.handle(new Callback[] { nameCB });
this.U = nameCB.getName();
}
@@ -897,14 +698,12 @@ public class SRPClient extends ClientMechanism implements SaslClient
else if (pw instanceof String)
password = new Password(((String) pw).toCharArray());
else
- throw new IllegalArgumentException(
- pw.getClass().getName()
- + "is not a valid password class");
+ throw new IllegalArgumentException(pw.getClass().getName()
+ + "is not a valid password class");
}
else
{
- final PasswordCallback pwdCB = new PasswordCallback(
- "password: ",
+ final PasswordCallback pwdCB = new PasswordCallback("password: ",
false);
this.handler.handle(new Callback[] { pwdCB });
password = new Password(pwdCB.getPassword());
@@ -912,13 +711,9 @@ public class SRPClient extends ClientMechanism implements SaslClient
}
if (U == null)
- {
- throw new AuthenticationException("null username supplied");
- }
+ throw new AuthenticationException("null username supplied");
if (password == null)
- {
- throw new AuthenticationException("null password supplied");
- }
+ throw new AuthenticationException("null password supplied");
}
catch (UnsupportedCallbackException x)
{
@@ -935,9 +730,8 @@ public class SRPClient extends ClientMechanism implements SaslClient
// to us by the client.
private String createO(final String aol) throws AuthenticationException
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> createO(\"" + aol + "\")");
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "createO", aol);
boolean replaydetectionAvailable = false;
boolean integrityAvailable = false;
boolean confidentialityAvailable = false;
@@ -945,7 +739,6 @@ public class SRPClient extends ClientMechanism implements SaslClient
int i;
String mdName = SRPRegistry.SRP_DEFAULT_DIGEST_NAME;
-
final StringTokenizer st = new StringTokenizer(aol, ",");
while (st.hasMoreTokens())
{
@@ -953,8 +746,8 @@ public class SRPClient extends ClientMechanism implements SaslClient
if (option.startsWith(SRPRegistry.OPTION_SRP_DIGEST + "="))
{
option = option.substring(option.indexOf('=') + 1);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "mda: <" + option + ">");
+ if (Configuration.DEBUG)
+ log.fine("mda: <" + option + ">");
for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++)
{
if (SRPRegistry.SRP_ALGORITHMS[i].equals(option))
@@ -965,14 +758,12 @@ public class SRPClient extends ClientMechanism implements SaslClient
}
}
else if (option.equals(SRPRegistry.OPTION_REPLAY_DETECTION))
- {
- replaydetectionAvailable = true;
- }
+ replaydetectionAvailable = true;
else if (option.startsWith(SRPRegistry.OPTION_INTEGRITY + "="))
{
option = option.substring(option.indexOf('=') + 1);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "ialg: <" + option + ">");
+ if (Configuration.DEBUG)
+ log.fine("ialg: <" + option + ">");
for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++)
{
if (SRPRegistry.INTEGRITY_ALGORITHMS[i].equals(option))
@@ -986,8 +777,8 @@ public class SRPClient extends ClientMechanism implements SaslClient
else if (option.startsWith(SRPRegistry.OPTION_CONFIDENTIALITY + "="))
{
option = option.substring(option.indexOf('=') + 1);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "calg: <" + option + ">");
+ if (Configuration.DEBUG)
+ log.fine("calg: <" + option + ">");
for (i = 0; i < SRPRegistry.CONFIDENTIALITY_ALGORITHMS.length; i++)
{
if (SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i].equals(option))
@@ -999,9 +790,7 @@ public class SRPClient extends ClientMechanism implements SaslClient
}
}
else if (option.startsWith(SRPRegistry.OPTION_MANDATORY + "="))
- {
- mandatory = option.substring(option.indexOf('=') + 1);
- }
+ mandatory = option.substring(option.indexOf('=') + 1);
else if (option.startsWith(SRPRegistry.OPTION_MAX_BUFFER_SIZE + "="))
{
final String maxBufferSize = option.substring(option.indexOf('=') + 1);
@@ -1010,32 +799,22 @@ public class SRPClient extends ClientMechanism implements SaslClient
rawSendSize = Integer.parseInt(maxBufferSize);
if (rawSendSize > Registry.SASL_BUFFER_MAX_LIMIT
|| rawSendSize < 1)
- {
- throw new AuthenticationException(
- "Illegal value for 'maxbuffersize' option");
- }
+ throw new AuthenticationException("Illegal value for 'maxbuffersize' option");
}
catch (NumberFormatException x)
{
- throw new AuthenticationException(
- SRPRegistry.OPTION_MAX_BUFFER_SIZE
- + "="
- + String.valueOf(maxBufferSize),
+ throw new AuthenticationException(SRPRegistry.OPTION_MAX_BUFFER_SIZE
+ + "=" + maxBufferSize,
x);
}
}
}
-
replayDetection = replaydetectionAvailable
- && Boolean.valueOf(
- (String) properties.get(SRPRegistry.SRP_REPLAY_DETECTION)).booleanValue();
+ && Boolean.valueOf((String) properties.get(SRPRegistry.SRP_REPLAY_DETECTION)).booleanValue();
boolean integrity = integrityAvailable
- && Boolean.valueOf(
- (String) properties.get(SRPRegistry.SRP_INTEGRITY_PROTECTION)).booleanValue();
+ && Boolean.valueOf((String) properties.get(SRPRegistry.SRP_INTEGRITY_PROTECTION)).booleanValue();
boolean confidentiality = confidentialityAvailable
- && Boolean.valueOf(
- (String) properties.get(SRPRegistry.SRP_CONFIDENTIALITY)).booleanValue();
-
+ && Boolean.valueOf((String) properties.get(SRPRegistry.SRP_CONFIDENTIALITY)).booleanValue();
// make sure we do the right thing
if (SRPRegistry.OPTION_REPLAY_DETECTION.equals(mandatory))
{
@@ -1043,95 +822,67 @@ public class SRPClient extends ClientMechanism implements SaslClient
integrity = true;
}
else if (SRPRegistry.OPTION_INTEGRITY.equals(mandatory))
- {
- integrity = true;
- }
+ integrity = true;
else if (SRPRegistry.OPTION_CONFIDENTIALITY.equals(mandatory))
- {
- confidentiality = true;
- }
+ confidentiality = true;
+
if (replayDetection)
{
if (chosenIntegrityAlgorithm == null)
- {
- throw new AuthenticationException(
- "Replay detection is required but no "
- + "integrity protection algorithm was chosen");
- }
+ throw new AuthenticationException(
+ "Replay detection is required but no integrity protection algorithm was chosen");
}
if (integrity)
{
if (chosenIntegrityAlgorithm == null)
- {
- throw new AuthenticationException(
- "Integrity protection is required but no "
- + "algorithm was chosen");
- }
+ throw new AuthenticationException(
+ "Integrity protection is required but no algorithm was chosen");
}
if (confidentiality)
{
if (chosenConfidentialityAlgorithm == null)
- {
- throw new AuthenticationException(
- "Confidentiality protection is required "
- + "but no algorithm was chosen");
- }
+ throw new AuthenticationException(
+ "Confidentiality protection is required but no algorithm was chosen");
}
-
// 1. check if we'll be using confidentiality; if not set IV to 0-byte
if (chosenConfidentialityAlgorithm == null)
- {
- cIV = new byte[0];
- }
+ cIV = new byte[0];
else
{
// 2. get the block size of the cipher
final IBlockCipher cipher = CipherFactory.getInstance(chosenConfidentialityAlgorithm);
if (cipher == null)
- {
- throw new AuthenticationException("createO()",
- new NoSuchAlgorithmException());
- }
+ throw new AuthenticationException("createO()",
+ new NoSuchAlgorithmException());
final int blockSize = cipher.defaultBlockSize();
// 3. generate random iv
cIV = new byte[blockSize];
getDefaultPRNG().nextBytes(cIV);
}
-
srp = SRP.instance(mdName);
-
// Now create the options list specifying which of the available options
// we have chosen.
// For now we just select the defaults. Later we need to add support for
// properties (perhaps in a file) where a user can specify the list of
// algorithms they would prefer to use.
-
final StringBuffer sb = new StringBuffer();
- sb.append(SRPRegistry.OPTION_SRP_DIGEST).append("=").append(mdName).append(
- ",");
+ sb.append(SRPRegistry.OPTION_SRP_DIGEST)
+ .append("=").append(mdName).append(",");
if (replayDetection)
- {
- sb.append(SRPRegistry.OPTION_REPLAY_DETECTION).append(",");
- }
+ sb.append(SRPRegistry.OPTION_REPLAY_DETECTION).append(",");
if (integrity)
- {
- sb.append(SRPRegistry.OPTION_INTEGRITY).append("=").append(
- chosenIntegrityAlgorithm).append(
- ",");
- }
+ sb.append(SRPRegistry.OPTION_INTEGRITY)
+ .append("=").append(chosenIntegrityAlgorithm).append(",");
if (confidentiality)
- {
- sb.append(SRPRegistry.OPTION_CONFIDENTIALITY).append("=").append(
- chosenConfidentialityAlgorithm).append(
- ",");
- }
- final String result = sb.append(SRPRegistry.OPTION_MAX_BUFFER_SIZE).append(
- "=").append(
- Registry.SASL_BUFFER_MAX_LIMIT).toString();
-
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== createO() --> " + result);
+ sb.append(SRPRegistry.OPTION_CONFIDENTIALITY)
+ .append("=").append(chosenConfidentialityAlgorithm).append(",");
+
+ final String result = sb.append(SRPRegistry.OPTION_MAX_BUFFER_SIZE)
+ .append("=").append(Registry.SASL_BUFFER_MAX_LIMIT)
+ .toString();
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "createO", result);
return result;
}
@@ -1139,33 +890,30 @@ public class SRPClient extends ClientMechanism implements SaslClient
throws SaslException
{
complete = true; // signal end of authentication phase
- if (!sessionReUse)
+ if (! sessionReUse)
{
outCounter = inCounter = 0;
// instantiate cipher if confidentiality protection filter is active
if (chosenConfidentialityAlgorithm != null)
{
- if (DEBUG && debuglevel > 2)
- debug(INFO, "Activating confidentiality protection filter");
+ if (Configuration.DEBUG)
+ log.fine("Activating confidentiality protection filter");
inCipher = CALG.getInstance(chosenConfidentialityAlgorithm);
outCipher = CALG.getInstance(chosenConfidentialityAlgorithm);
}
// instantiate hmacs if integrity protection filter is active
if (chosenIntegrityAlgorithm != null)
{
- if (DEBUG && debuglevel > 2)
- debug(INFO, "Activating integrity protection filter");
+ if (Configuration.DEBUG)
+ log.fine("Activating integrity protection filter");
inMac = IALG.getInstance(chosenIntegrityAlgorithm);
outMac = IALG.getInstance(chosenIntegrityAlgorithm);
}
}
- else
- { // same session new Keys
- K = srp.generateKn(K, cn, sn);
- }
+ else // same session new Keys
+ K = srp.generateKn(K, cn, sn);
final KDF kdf = KDF.getInstance(K);
-
// initialise in/out ciphers if confidentiality protection is used
if (inCipher != null)
{
@@ -1178,16 +926,13 @@ public class SRPClient extends ClientMechanism implements SaslClient
inMac.init(kdf);
outMac.init(kdf);
}
-
if (sid != null && sid.length != 0)
{ // update the security context and save in map
- if (DEBUG && debuglevel > 2)
- debug(INFO, "Updating security context for UID = " + uid);
- ClientStore.instance().cacheSession(
- uid,
+ if (Configuration.DEBUG)
+ log.fine("Updating security context for UID = " + uid);
+ ClientStore.instance().cacheSession(uid,
ttl,
- new SecurityContext(
- srp.getAlgorithm(),
+ new SecurityContext(srp.getAlgorithm(),
sid,
K,
cIV,
diff --git a/gnu/javax/crypto/sasl/srp/SRPRegistry.java b/gnu/javax/crypto/sasl/srp/SRPRegistry.java
index 262cbcba3..9f7bba8e9 100644
--- a/gnu/javax/crypto/sasl/srp/SRPRegistry.java
+++ b/gnu/javax/crypto/sasl/srp/SRPRegistry.java
@@ -140,7 +140,7 @@ public interface SRPRegistry
/**
* Name of the SRP password database property --a reference to
- * {@link gnu.crypto.sasl.srp.PasswordFile} object.
+ * {@link PasswordFile} object.
*/
String PASSWORD_DB = "gnu.crypto.sasl.srp.password.db";
diff --git a/gnu/javax/crypto/sasl/srp/SRPServer.java b/gnu/javax/crypto/sasl/srp/SRPServer.java
index 672660b26..18452555c 100644
--- a/gnu/javax/crypto/sasl/srp/SRPServer.java
+++ b/gnu/javax/crypto/sasl/srp/SRPServer.java
@@ -38,18 +38,18 @@ exception statement from your version. */
package gnu.javax.crypto.sasl.srp;
+import gnu.classpath.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.util.PRNG;
import gnu.java.security.util.Util;
-
import gnu.javax.crypto.assembly.Direction;
import gnu.javax.crypto.cipher.CipherFactory;
import gnu.javax.crypto.cipher.IBlockCipher;
import gnu.javax.crypto.key.IKeyAgreementParty;
-import gnu.javax.crypto.key.KeyAgreementFactory;
+import gnu.javax.crypto.key.IncomingMessage;
import gnu.javax.crypto.key.KeyAgreementException;
+import gnu.javax.crypto.key.KeyAgreementFactory;
import gnu.javax.crypto.key.OutgoingMessage;
-import gnu.javax.crypto.key.IncomingMessage;
import gnu.javax.crypto.key.srp6.SRP6KeyAgreement;
import gnu.javax.crypto.sasl.IllegalMechanismStateException;
import gnu.javax.crypto.sasl.InputBuffer;
@@ -57,114 +57,55 @@ import gnu.javax.crypto.sasl.IntegrityException;
import gnu.javax.crypto.sasl.OutputBuffer;
import gnu.javax.crypto.sasl.ServerMechanism;
-import java.io.IOException;
-import java.io.PrintWriter;
import java.io.ByteArrayOutputStream;
+import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
+import java.util.logging.Logger;
import javax.security.sasl.AuthenticationException;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
/**
- * <p>The SASL-SRP server-side mechanism.</p>
+ * The SASL-SRP server-side mechanism.
*/
public class SRPServer extends ServerMechanism implements SaslServer
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "SRPServer";
-
- // private static final String ERROR = "ERROR";
- private static final String WARN = " WARN";
-
- private static final String INFO = " INFO";
-
- private static final String TRACE = "DEBUG";
-
- private static final boolean DEBUG = true;
-
- private static final int debuglevel = 3;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(final String level, final Object obj)
- {
- err.println("[" + level + "] " + NAME + ": " + String.valueOf(obj));
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(SRPServer.class.getName());
private String U = null; // client's username
-
private BigInteger N, g, A, B;
-
private byte[] s; // salt
-
private byte[] cIV, sIV; // client+server IVs, when confidentiality is on
-
private byte[] cn, sn; // client's and server's nonce
-
private SRP srp; // SRP algorithm instance used by this server
-
private byte[] sid; // session ID when re-used
-
private int ttl = 360; // session time-to-live in seconds
-
private byte[] cCB; // peer's channel binding'
-
private String mandatory; // List of available options
-
private String L = null;
-
private String o;
-
private String chosenIntegrityAlgorithm;
-
private String chosenConfidentialityAlgorithm;
-
private int rawSendSize = Registry.SASL_BUFFER_MAX_LIMIT;
-
private byte[] K; // shared session key
-
private boolean replayDetection = true; // whether Replay Detection is on
-
private int inCounter = 0; // messages sequence numbers
-
private int outCounter = 0;
-
private IALG inMac, outMac; // if !null, use for integrity
-
private CALG inCipher, outCipher; // if !null, use for confidentiality
-
private IKeyAgreementParty serverHandler = KeyAgreementFactory.getPartyBInstance(Registry.SRP_SASL_KA);
-
/** Our default source of randomness. */
private PRNG prng = null;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public SRPServer()
{
super(Registry.SASL_SRP_MECHANISM);
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // abstract methods implementation -----------------------------------------
-
protected void initMechanism() throws SaslException
{
// TODO:
@@ -187,21 +128,18 @@ public class SRPServer extends ServerMechanism implements SaslServer
sid = null;
}
- // javax.security.sasl.SaslServer interface implementation -----------------
-
public byte[] evaluateResponse(final byte[] response) throws SaslException
{
switch (state)
{
case 0:
if (response == null)
- {
- return null;
- }
+ return null;
+
state++;
return sendProtocolElements(response);
case 1:
- if (!complete)
+ if (! complete)
{
state++;
return sendEvidence(response);
@@ -215,65 +153,15 @@ public class SRPServer extends ServerMechanism implements SaslServer
protected byte[] engineUnwrap(final byte[] incoming, final int offset,
final int len) throws SaslException
{
- // if (DEBUG && debuglevel > 8) debug(TRACE, "==> engineUnwrap()");
- //
- // if (inMac == null && inCipher == null) {
- // throw new IllegalStateException("connection is not protected");
- // }
- //
- // if (DEBUG && debuglevel > 6) debug(TRACE, "Incoming buffer (before security): "+Util.dumpString(incoming, offset, len));
- //
- // byte[] data = null;
- // try {
- // InputBuffer frameIn = InputBuffer.getInstance(incoming, offset, len);
- // data = frameIn.getEOS();
- // if (inMac != null) {
- // byte[] received_mac = frameIn.getOS();
- // if (DEBUG && debuglevel > 6) debug(TRACE, "Got C (received MAC): "+Util.dumpString(received_mac));
- // inMac.update(data);
- // if (replayDetection) {
- // inCounter++;
- // if (DEBUG && debuglevel > 6) debug(TRACE, "inCounter="+String.valueOf(inCounter));
- // inMac.update(new byte[] {
- // (byte)(inCounter >>> 24),
- // (byte)(inCounter >>> 16),
- // (byte)(inCounter >>> 8),
- // (byte) inCounter });
- // }
- // final byte[] computed_mac = inMac.doFinal();
- // if (DEBUG && debuglevel > 6) debug(TRACE, "Computed MAC: "+Util.dumpString(computed_mac));
- // if (!Arrays.equals(received_mac, computed_mac))
- // throw new IntegrityException("engineUnwrap()");
- // }
- // if (inCipher != null) {
- // data = inCipher.doFinal(data);
- // }
- // } catch (IOException x) {
- // if (x instanceof SaslException) {
- // throw (SaslException) x;
- // }
- // throw new SaslException("engineUnwrap()", x);
- // }
- //
- // if (DEBUG && debuglevel > 6) debug(TRACE, "Incoming buffer (after security): "+Util.dumpString(data));
- // if (DEBUG && debuglevel > 8) debug(TRACE, "<== engineUnwrap()");
- // return data;
-
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> engineUnwrap()");
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineUnwrap");
if (inMac == null && inCipher == null)
- {
- throw new IllegalStateException("connection is not protected");
- }
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Incoming buffer (before security): "
- + Util.dumpString(incoming, offset, len));
-
+ throw new IllegalStateException("connection is not protected");
+ if (Configuration.DEBUG)
+ log.fine("Incoming buffer (before security): "
+ + Util.dumpString(incoming, offset, len));
// at this point one, or both, of confidentiality and integrity protection
// services are active.
-
final byte[] result;
try
{
@@ -284,137 +172,67 @@ public class SRPServer extends ServerMechanism implements SaslServer
final byte[] received_mac = new byte[macBytesCount];
System.arraycopy(incoming, offset + payloadLength, received_mac, 0,
macBytesCount);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got C (received MAC): "
- + Util.dumpString(received_mac));
+ if (Configuration.DEBUG)
+ log.fine("Got C (received MAC): " + Util.dumpString(received_mac));
inMac.update(incoming, offset, payloadLength);
if (replayDetection)
{
inCounter++;
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "inCounter=" + String.valueOf(inCounter));
- inMac.update(new byte[] { (byte) (inCounter >>> 24),
- (byte) (inCounter >>> 16),
- (byte) (inCounter >>> 8),
- (byte) inCounter });
+ if (Configuration.DEBUG)
+ log.fine("inCounter=" + String.valueOf(inCounter));
+ inMac.update(new byte[] { (byte)(inCounter >>> 24),
+ (byte)(inCounter >>> 16),
+ (byte)(inCounter >>> 8),
+ (byte) inCounter });
}
-
final byte[] computed_mac = inMac.doFinal();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Computed MAC: " + Util.dumpString(computed_mac));
+ if (Configuration.DEBUG)
+ log.fine("Computed MAC: " + Util.dumpString(computed_mac));
if (!Arrays.equals(received_mac, computed_mac))
- {
- throw new IntegrityException("engineUnwrap()");
- }
+ throw new IntegrityException("engineUnwrap()");
// deal with the payload, which can be either plain or encrypted
if (inCipher != null)
- {
- result = inCipher.doFinal(incoming, offset, payloadLength);
- }
+ result = inCipher.doFinal(incoming, offset, payloadLength);
else
{
result = new byte[payloadLength];
System.arraycopy(incoming, offset, result, 0, result.length);
}
}
- else
- { // no integrity protection; just confidentiality
- // if (inCipher != null) {
- result = inCipher.doFinal(incoming, offset, len);
- // } else {
- // result = new byte[len];
- // System.arraycopy(incoming, offset, result, 0, len);
- // }
- }
+ else // no integrity protection; just confidentiality
+ result = inCipher.doFinal(incoming, offset, len);
}
catch (IOException x)
{
if (x instanceof SaslException)
- {
- throw (SaslException) x;
- }
+ throw (SaslException) x;
throw new SaslException("engineUnwrap()", x);
}
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Incoming buffer (after security): "
- + Util.dumpString(result));
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== engineUnwrap()");
+ if (Configuration.DEBUG)
+ {
+ log.fine("Incoming buffer (after security): " + Util.dumpString(result));
+ log.exiting(this.getClass().getName(), "engineUnwrap");
+ }
return result;
}
protected byte[] engineWrap(final byte[] outgoing, final int offset,
final int len) throws SaslException
{
- // if (DEBUG && debuglevel > 8) debug(TRACE, "==> engineWrap()");
- //
- // if (outMac == null && outCipher == null) {
- // throw new IllegalStateException("connection is not protected");
- // }
- //
- // byte[] data = new byte[len];
- // System.arraycopy(outgoing, offset, data, 0, len);
- //
- // if (DEBUG && debuglevel > 6) debug(TRACE, "Outgoing buffer (before security) (hex): "+Util.dumpString(data));
- // if (DEBUG && debuglevel > 6) debug(TRACE, "Outgoing buffer (before security) (str): \""+new String(data)+"\"");
- //
- // final byte[] result;
- // try {
- // OutputBuffer frameOut = new OutputBuffer();
- // // Process the data
- // if (outCipher != null) {
- // data = outCipher.doFinal(data);
- // if (DEBUG && debuglevel > 6) debug(TRACE, "Encoding c (encrypted plaintext): "+Util.dumpString(data));
- // } else {
- // if (DEBUG && debuglevel > 6) debug(TRACE, "Encoding p (plaintext): "+Util.dumpString(data));
- // }
- // frameOut.setEOS(data);
- // if (outMac != null) {
- // outMac.update(data);
- // if (replayDetection) {
- // outCounter++;
- // if (DEBUG && debuglevel > 6) debug(TRACE, "outCounter="+String.valueOf(outCounter));
- // outMac.update(new byte[] {
- // (byte)(outCounter >>> 24),
- // (byte)(outCounter >>> 16),
- // (byte)(outCounter >>> 8),
- // (byte) outCounter});
- // }
- // byte[] C = outMac.doFinal();
- // frameOut.setOS(C);
- // if (DEBUG && debuglevel > 6) debug(TRACE, "Encoding C (integrity checksum): "+Util.dumpString(C));
- // }
- // result = frameOut.wrap();
- //
- // } catch (IOException x) {
- // if (x instanceof SaslException) {
- // throw (SaslException) x;
- // }
- // throw new SaslException("engineWrap()", x);
- // }
- //
- // if (DEBUG && debuglevel > 8) debug(TRACE, "<== engineWrap()");
- // return result;
-
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> engineWrap()");
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineWrap");
if (outMac == null && outCipher == null)
+ throw new IllegalStateException("connection is not protected");
+ if (Configuration.DEBUG)
{
- throw new IllegalStateException("connection is not protected");
+ log.fine("Outgoing buffer (before security) (hex): "
+ + Util.dumpString(outgoing, offset, len));
+ log.fine("Outgoing buffer (before security) (str): \""
+ + new String(outgoing, offset, len) + "\"");
}
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Outgoing buffer (before security) (hex): "
- + Util.dumpString(outgoing, offset, len));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Outgoing buffer (before security) (str): \""
- + new String(outgoing, offset, len) + "\"");
-
// at this point one, or both, of confidentiality and integrity protection
// services are active.
-
byte[] result;
try
{
@@ -422,74 +240,62 @@ public class SRPServer extends ServerMechanism implements SaslServer
if (outCipher != null)
{
result = outCipher.doFinal(outgoing, offset, len);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding c (encrypted plaintext): "
- + Util.dumpString(result));
-
+ if (Configuration.DEBUG)
+ log.fine("Encoding c (encrypted plaintext): "
+ + Util.dumpString(result));
out.write(result);
-
if (outMac != null)
{
outMac.update(result);
if (replayDetection)
{
outCounter++;
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "outCounter=" + String.valueOf(outCounter));
- outMac.update(new byte[] { (byte) (outCounter >>> 24),
- (byte) (outCounter >>> 16),
- (byte) (outCounter >>> 8),
- (byte) outCounter });
+ if (Configuration.DEBUG)
+ log.fine("outCounter=" + outCounter);
+ outMac.update(new byte[] { (byte)(outCounter >>> 24),
+ (byte)(outCounter >>> 16),
+ (byte)(outCounter >>> 8),
+ (byte) outCounter });
}
final byte[] C = outMac.doFinal();
out.write(C);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding C (integrity checksum): "
- + Util.dumpString(C));
- } // else ciphertext only; do nothing
+ if (Configuration.DEBUG)
+ log.fine("Encoding C (integrity checksum): " + Util.dumpString(C));
+ }
+ // else ciphertext only; do nothing
}
- else
- { // no confidentiality; just integrity [+ replay detection]
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding p (plaintext): "
- + Util.dumpString(outgoing, offset, len));
-
+ else // no confidentiality; just integrity [+ replay detection]
+ {
+ if (Configuration.DEBUG)
+ log.fine("Encoding p (plaintext): "
+ + Util.dumpString(outgoing, offset, len));
out.write(outgoing, offset, len);
-
- // if (outMac != null) {
outMac.update(outgoing, offset, len);
if (replayDetection)
{
outCounter++;
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "outCounter=" + String.valueOf(outCounter));
- outMac.update(new byte[] { (byte) (outCounter >>> 24),
- (byte) (outCounter >>> 16),
- (byte) (outCounter >>> 8),
- (byte) outCounter });
+ if (Configuration.DEBUG)
+ log.fine("outCounter=" + outCounter);
+ outMac.update(new byte[] { (byte)(outCounter >>> 24),
+ (byte)(outCounter >>> 16),
+ (byte)(outCounter >>> 8),
+ (byte) outCounter });
}
final byte[] C = outMac.doFinal();
out.write(C);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding C (integrity checksum): "
- + Util.dumpString(C));
- // } // else plaintext only; do nothing
+ if (Configuration.DEBUG)
+ log.fine("Encoding C (integrity checksum): " + Util.dumpString(C));
}
-
result = out.toByteArray();
-
}
catch (IOException x)
{
if (x instanceof SaslException)
- {
- throw (SaslException) x;
- }
+ throw (SaslException) x;
throw new SaslException("engineWrap()", x);
}
-
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== engineWrap()");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineWrap");
return result;
}
@@ -498,13 +304,9 @@ public class SRPServer extends ServerMechanism implements SaslServer
if (inMac != null)
{
if (inCipher != null)
- {
- return Registry.QOP_AUTH_CONF;
- }
- else
- {
- return Registry.QOP_AUTH_INT;
- }
+ return Registry.QOP_AUTH_CONF;
+
+ return Registry.QOP_AUTH_INT;
}
return Registry.QOP_AUTH;
}
@@ -514,13 +316,9 @@ public class SRPServer extends ServerMechanism implements SaslServer
if (inMac != null)
{
if (inCipher != null)
- {
- return Registry.STRENGTH_HIGH;
- }
- else
- {
- return Registry.STRENGTH_MEDIUM;
- }
+ return Registry.STRENGTH_HIGH;
+
+ return Registry.STRENGTH_MEDIUM;
}
return Registry.STRENGTH_LOW;
}
@@ -535,45 +333,39 @@ public class SRPServer extends ServerMechanism implements SaslServer
return Registry.REUSE_TRUE;
}
- // other methods -----------------------------------------------------------
-
private byte[] sendProtocolElements(final byte[] input) throws SaslException
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> sendProtocolElements()");
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "C: " + Util.dumpString(input));
-
+ if (Configuration.DEBUG)
+ {
+ log.entering(this.getClass().getName(), "sendProtocolElements");
+ log.fine("C: " + Util.dumpString(input));
+ }
// Client send U, I, sid, cn
final InputBuffer frameIn = new InputBuffer(input);
try
{
U = frameIn.getText(); // Extract username
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got U (username): \"" + U + "\"");
+ if (Configuration.DEBUG)
+ log.fine("Got U (username): \"" + U + "\"");
authorizationID = frameIn.getText(); // Extract authorisation ID
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got I (userid): \"" + authorizationID + "\"");
+ if (Configuration.DEBUG)
+ log.fine("Got I (userid): \"" + authorizationID + "\"");
sid = frameIn.getEOS();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got sid (session ID): " + new String(sid));
+ if (Configuration.DEBUG)
+ log.fine("Got sid (session ID): " + new String(sid));
cn = frameIn.getOS();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got cn (client nonce): " + Util.dumpString(cn));
+ if (Configuration.DEBUG)
+ log.fine("Got cn (client nonce): " + Util.dumpString(cn));
cCB = frameIn.getEOS();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got cCB (client channel binding): "
- + Util.dumpString(cCB));
+ if (Configuration.DEBUG)
+ log.fine("Got cCB (client channel binding): " + Util.dumpString(cCB));
}
catch (IOException x)
{
if (x instanceof SaslException)
- {
- throw (SaslException) x;
- }
+ throw (SaslException) x;
throw new AuthenticationException("sendProtocolElements()", x);
}
-
// do/can we re-use?
if (ServerStore.instance().isAlive(sid))
{
@@ -589,15 +381,11 @@ public class SRPServer extends ServerMechanism implements SaslServer
outMac = ctx.getOutMac();
inCipher = ctx.getInCipher();
outCipher = ctx.getOutCipher();
-
if (sn == null || sn.length != 16)
- {
- sn = new byte[16];
- }
- getDefaultPRNG().nextBytes(sn);
+ sn = new byte[16];
+ getDefaultPRNG().nextBytes(sn);
setupSecurityServices(false);
-
final OutputBuffer frameOut = new OutputBuffer();
try
{
@@ -608,34 +396,27 @@ public class SRPServer extends ServerMechanism implements SaslServer
catch (IOException x)
{
if (x instanceof SaslException)
- {
- throw (SaslException) x;
- }
+ throw (SaslException) x;
throw new AuthenticationException("sendProtocolElements()", x);
}
final byte[] result = frameOut.encode();
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== sendProtocolElements()");
- if (DEBUG && debuglevel > 2)
- debug(INFO, "Old session...");
- if (DEBUG && debuglevel > 2)
- debug(INFO, "S: " + Util.dumpString(result));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " sn = " + Util.dumpString(sn));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " sCB = " + Util.dumpString(channelBinding));
+ if (Configuration.DEBUG)
+ {
+ log.fine("Old session...");
+ log.fine("S: " + Util.dumpString(result));
+ log.fine(" sn = " + Util.dumpString(sn));
+ log.fine(" sCB = " + Util.dumpString(channelBinding));
+ log.exiting(this.getClass().getName(), "sendProtocolElements");
+ }
return result;
}
else
{ // new session
authenticator.activate(properties);
-
// -------------------------------------------------------------------
final HashMap mapB = new HashMap();
- // mapB.put(SRP6KeyAgreement.HASH_FUNCTION, srp.newDigest());
mapB.put(SRP6KeyAgreement.HASH_FUNCTION, srp.getAlgorithm());
mapB.put(SRP6KeyAgreement.HOST_PASSWORD_DB, authenticator);
-
try
{
serverHandler.init(mapB);
@@ -643,7 +424,6 @@ public class SRPServer extends ServerMechanism implements SaslServer
out.writeString(U);
IncomingMessage in = new IncomingMessage(out.toByteArray());
out = serverHandler.processMessage(in);
-
in = new IncomingMessage(out.toByteArray());
N = in.readMPI();
g = in.readMPI();
@@ -655,26 +435,22 @@ public class SRPServer extends ServerMechanism implements SaslServer
throw new SaslException("sendProtocolElements()", x);
}
// -------------------------------------------------------------------
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding N (modulus): " + Util.dump(N));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding g (generator): " + Util.dump(g));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding s (client's salt): " + Util.dumpString(s));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding B (server ephemeral public key): "
- + Util.dump(B));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine("Encoding N (modulus): " + Util.dump(N));
+ log.fine("Encoding g (generator): " + Util.dump(g));
+ log.fine("Encoding s (client's salt): " + Util.dumpString(s));
+ log.fine("Encoding B (server ephemeral public key): " + Util.dump(B));
+ }
// The server creates an options list (L), which consists of a
// comma-separated list of option strings that specify the security
// service options the server supports.
L = createL();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding L (available options): \"" + L + "\"");
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Encoding sIV (server IV): " + Util.dumpString(sIV));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine("Encoding L (available options): \"" + L + "\"");
+ log.fine("Encoding sIV (server IV): " + Util.dumpString(sIV));
+ }
final OutputBuffer frameOut = new OutputBuffer();
try
{
@@ -688,69 +464,58 @@ public class SRPServer extends ServerMechanism implements SaslServer
catch (IOException x)
{
if (x instanceof SaslException)
- {
- throw (SaslException) x;
- }
+ throw (SaslException) x;
throw new AuthenticationException("sendProtocolElements()", x);
}
final byte[] result = frameOut.encode();
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== sendProtocolElements()");
- if (DEBUG && debuglevel > 2)
- debug(INFO, "New session...");
- if (DEBUG && debuglevel > 2)
- debug(INFO, "S: " + Util.dumpString(result));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " N = 0x" + N.toString(16));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " g = 0x" + g.toString(16));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " s = " + Util.dumpString(s));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " B = 0x" + B.toString(16));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " L = " + L);
+ if (Configuration.DEBUG)
+ {
+ log.fine("New session...");
+ log.fine("S: " + Util.dumpString(result));
+ log.fine(" N = 0x" + N.toString(16));
+ log.fine(" g = 0x" + g.toString(16));
+ log.fine(" s = " + Util.dumpString(s));
+ log.fine(" B = 0x" + B.toString(16));
+ log.fine(" L = " + L);
+ log.exiting(this.getClass().getName(), "sendProtocolElements");
+ }
return result;
}
}
private byte[] sendEvidence(final byte[] input) throws SaslException
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> sendEvidence()");
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "C: " + Util.dumpString(input));
-
+ if (Configuration.DEBUG)
+ {
+ log.entering(this.getClass().getName(), "sendEvidence");
+ log.fine("C: " + Util.dumpString(input));
+ }
// Client send A, M1, o, cIV
final InputBuffer frameIn = new InputBuffer(input);
final byte[] M1;
try
{
A = frameIn.getMPI(); // Extract client's ephemeral public key
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got A (client ephemeral public key): " + Util.dump(A));
+ if (Configuration.DEBUG)
+ log.fine("Got A (client ephemeral public key): " + Util.dump(A));
M1 = frameIn.getOS(); // Extract evidence
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got M1 (client evidence): " + Util.dumpString(M1));
+ if (Configuration.DEBUG)
+ log.fine("Got M1 (client evidence): " + Util.dumpString(M1));
o = frameIn.getText(); // Extract client's options list
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got o (client chosen options): \"" + o + "\"");
+ if (Configuration.DEBUG)
+ log.fine("Got o (client chosen options): \"" + o + "\"");
cIV = frameIn.getOS(); // Extract client's IV
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Got cIV (client IV): " + Util.dumpString(cIV));
+ if (Configuration.DEBUG)
+ log.fine("Got cIV (client IV): " + Util.dumpString(cIV));
}
catch (IOException x)
{
if (x instanceof SaslException)
- {
- throw (SaslException) x;
- }
+ throw (SaslException) x;
throw new AuthenticationException("sendEvidence()", x);
}
-
// Parse client's options and set security layer variables
parseO(o);
-
// ----------------------------------------------------------------------
try
{
@@ -765,10 +530,8 @@ public class SRPServer extends ServerMechanism implements SaslServer
throw new SaslException("sendEvidence()", x);
}
// ----------------------------------------------------------------------
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "K: " + Util.dumpString(K));
-
+ if (Configuration.DEBUG)
+ log.fine("K: " + Util.dumpString(K));
final byte[] expected;
try
{
@@ -779,15 +542,11 @@ public class SRPServer extends ServerMechanism implements SaslServer
{
throw new AuthenticationException("sendEvidence()", x);
}
-
// Verify client evidence
if (!Arrays.equals(M1, expected))
- {
- throw new AuthenticationException("M1 mismatch");
- }
+ throw new AuthenticationException("M1 mismatch");
setupSecurityServices(true);
-
final byte[] M2;
try
{
@@ -798,7 +557,6 @@ public class SRPServer extends ServerMechanism implements SaslServer
{
throw new AuthenticationException("sendEvidence()", x);
}
-
final OutputBuffer frameOut = new OutputBuffer();
try
{
@@ -811,93 +569,71 @@ public class SRPServer extends ServerMechanism implements SaslServer
catch (IOException x)
{
if (x instanceof SaslException)
- {
- throw (SaslException) x;
- }
+ throw (SaslException) x;
throw new AuthenticationException("sendEvidence()", x);
}
final byte[] result = frameOut.encode();
- if (DEBUG && debuglevel > 2)
- debug(INFO, "S: " + Util.dumpString(result));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " M2 = " + Util.dumpString(M2));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " sIV = " + Util.dumpString(sIV));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " sid = " + new String(sid));
- if (DEBUG && debuglevel > 2)
- debug(INFO, " ttl = " + ttl);
- if (DEBUG && debuglevel > 2)
- debug(INFO, " sCB = " + Util.dumpString(channelBinding));
-
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== sendEvidence()");
+ if (Configuration.DEBUG)
+ {
+ log.fine("S: " + Util.dumpString(result));
+ log.fine(" M2 = " + Util.dumpString(M2));
+ log.fine(" sIV = " + Util.dumpString(sIV));
+ log.fine(" sid = " + new String(sid));
+ log.fine(" ttl = " + ttl);
+ log.fine(" sCB = " + Util.dumpString(channelBinding));
+ log.exiting(this.getClass().getName(), "sendEvidence");
+ }
return result;
}
private String createL()
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> createL()");
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "createL()");
String s = (String) properties.get(SRPRegistry.SRP_MANDATORY);
if (s == null)
+ s = SRPRegistry.DEFAULT_MANDATORY;
+
+ if (! SRPRegistry.MANDATORY_NONE.equals(s)
+ && ! SRPRegistry.OPTION_REPLAY_DETECTION.equals(s)
+ && ! SRPRegistry.OPTION_INTEGRITY.equals(s)
+ && ! SRPRegistry.OPTION_CONFIDENTIALITY.equals(s))
{
+ if (Configuration.DEBUG)
+ log.fine("Unrecognised mandatory option (" + s + "). Using default...");
s = SRPRegistry.DEFAULT_MANDATORY;
}
- if (!SRPRegistry.MANDATORY_NONE.equals(s)
- && !SRPRegistry.OPTION_REPLAY_DETECTION.equals(s)
- && !SRPRegistry.OPTION_INTEGRITY.equals(s)
- && !SRPRegistry.OPTION_CONFIDENTIALITY.equals(s))
- {
- if (DEBUG && debuglevel > 4)
- debug(WARN, "Unrecognised mandatory option (" + s
- + "). Using default...");
- s = SRPRegistry.DEFAULT_MANDATORY;
- }
-
mandatory = s;
-
s = (String) properties.get(SRPRegistry.SRP_CONFIDENTIALITY);
final boolean confidentiality = (s == null ? SRPRegistry.DEFAULT_CONFIDENTIALITY
- : Boolean.valueOf(s).booleanValue());
-
+ : Boolean.valueOf(s).booleanValue());
s = (String) properties.get(SRPRegistry.SRP_INTEGRITY_PROTECTION);
boolean integrity = (s == null ? SRPRegistry.DEFAULT_INTEGRITY
- : Boolean.valueOf(s).booleanValue());
-
+ : Boolean.valueOf(s).booleanValue());
s = (String) properties.get(SRPRegistry.SRP_REPLAY_DETECTION);
final boolean replayDetection = (s == null ? SRPRegistry.DEFAULT_REPLAY_DETECTION
- : Boolean.valueOf(s).booleanValue());
-
+ : Boolean.valueOf(s).booleanValue());
final StringBuffer sb = new StringBuffer();
- sb.append(SRPRegistry.OPTION_SRP_DIGEST).append("=").append(
- srp.getAlgorithm()).append(
- ",");
+ sb.append(SRPRegistry.OPTION_SRP_DIGEST).append("=")
+ .append(srp.getAlgorithm()).append(",");
+
+ if (! SRPRegistry.MANDATORY_NONE.equals(mandatory))
+ sb.append(SRPRegistry.OPTION_MANDATORY)
+ .append("=").append(mandatory).append(",");
- if (!SRPRegistry.MANDATORY_NONE.equals(mandatory))
- {
- sb.append(SRPRegistry.OPTION_MANDATORY).append("=").append(mandatory).append(
- ",");
- }
if (replayDetection)
{
sb.append(SRPRegistry.OPTION_REPLAY_DETECTION).append(",");
// if replay detection is on then force integrity protection
integrity = true;
}
-
int i;
if (integrity)
{
for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++)
- {
- sb.append(SRPRegistry.OPTION_INTEGRITY).append("=").append(
- SRPRegistry.INTEGRITY_ALGORITHMS[i]).append(
- ",");
- }
+ sb.append(SRPRegistry.OPTION_INTEGRITY).append("=")
+ .append(SRPRegistry.INTEGRITY_ALGORITHMS[i]).append(",");
}
-
if (confidentiality)
{
IBlockCipher cipher;
@@ -905,19 +641,15 @@ public class SRPServer extends ServerMechanism implements SaslServer
{
cipher = CipherFactory.getInstance(SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i]);
if (cipher != null)
- {
- sb.append(SRPRegistry.OPTION_CONFIDENTIALITY).append("=").append(
- SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i]).append(
- ",");
- }
+ sb.append(SRPRegistry.OPTION_CONFIDENTIALITY).append("=")
+ .append(SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i]).append(",");
}
}
-
- final String result = sb.append(SRPRegistry.OPTION_MAX_BUFFER_SIZE).append(
- "=").append(
- Registry.SASL_BUFFER_MAX_LIMIT).toString();
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== createL()");
+ final String result = sb.append(SRPRegistry.OPTION_MAX_BUFFER_SIZE)
+ .append("=").append(Registry.SASL_BUFFER_MAX_LIMIT)
+ .toString();
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "createL");
return result;
}
@@ -934,69 +666,51 @@ public class SRPServer extends ServerMechanism implements SaslServer
while (st.hasMoreTokens())
{
option = st.nextToken();
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "option: <" + option + ">");
+ if (Configuration.DEBUG)
+ log.fine("option: <" + option + ">");
if (option.equals(SRPRegistry.OPTION_REPLAY_DETECTION))
- {
- replayDetection = true;
- }
+ replayDetection = true;
else if (option.startsWith(SRPRegistry.OPTION_INTEGRITY + "="))
{
if (integrity)
+ throw new AuthenticationException("Only one integrity algorithm may be chosen");
+
+ option = option.substring(option.indexOf('=') + 1);
+ if (Configuration.DEBUG)
+ log.fine("algorithm: <" + option + ">");
+ for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++)
{
- throw new AuthenticationException(
- "Only one integrity algorithm may be chosen");
- }
- else
- {
- option = option.substring(option.indexOf('=') + 1);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "algorithm: <" + option + ">");
- for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++)
+ if (SRPRegistry.INTEGRITY_ALGORITHMS[i].equals(option))
{
- if (SRPRegistry.INTEGRITY_ALGORITHMS[i].equals(option))
- {
- chosenIntegrityAlgorithm = option;
- integrity = true;
- break;
- }
- }
- if (!integrity)
- {
- throw new AuthenticationException(
- "Unknown integrity algorithm: "
- + option);
+ chosenIntegrityAlgorithm = option;
+ integrity = true;
+ break;
}
}
+ if (! integrity)
+ throw new AuthenticationException("Unknown integrity algorithm: "
+ + option);
}
else if (option.startsWith(SRPRegistry.OPTION_CONFIDENTIALITY + "="))
{
if (confidentiality)
+ throw new AuthenticationException("Only one confidentiality algorithm may be chosen");
+
+ option = option.substring(option.indexOf('=') + 1);
+ if (Configuration.DEBUG)
+ log.fine("algorithm: <" + option + ">");
+ for (i = 0; i < SRPRegistry.CONFIDENTIALITY_ALGORITHMS.length; i++)
{
- throw new AuthenticationException(
- "Only one confidentiality algorithm may be chosen");
- }
- else
- {
- option = option.substring(option.indexOf('=') + 1);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "algorithm: <" + option + ">");
- for (i = 0; i < SRPRegistry.CONFIDENTIALITY_ALGORITHMS.length; i++)
+ if (SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i].equals(option))
{
- if (SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i].equals(option))
- {
- chosenConfidentialityAlgorithm = option;
- confidentiality = true;
- break;
- }
- }
- if (!confidentiality)
- {
- throw new AuthenticationException(
- "Unknown confidentiality algorithm: "
- + option);
+ chosenConfidentialityAlgorithm = option;
+ confidentiality = true;
+ break;
}
}
+ if (! confidentiality)
+ throw new AuthenticationException("Unknown confidentiality algorithm: "
+ + option);
}
else if (option.startsWith(SRPRegistry.OPTION_MAX_BUFFER_SIZE + "="))
{
@@ -1006,71 +720,49 @@ public class SRPServer extends ServerMechanism implements SaslServer
rawSendSize = Integer.parseInt(maxBufferSize);
if (rawSendSize > Registry.SASL_BUFFER_MAX_LIMIT
|| rawSendSize < 1)
- throw new AuthenticationException(
- "Illegal value for 'maxbuffersize' option");
+ throw new AuthenticationException("Illegal value for 'maxbuffersize' option");
}
catch (NumberFormatException x)
{
- throw new AuthenticationException(
- SRPRegistry.OPTION_MAX_BUFFER_SIZE
- + "="
- + String.valueOf(maxBufferSize),
+ throw new AuthenticationException(SRPRegistry.OPTION_MAX_BUFFER_SIZE
+ + "=" + maxBufferSize,
x);
}
}
}
-
// check if client did the right thing
if (replayDetection)
{
- if (!integrity)
- {
- throw new AuthenticationException(
- "Missing integrity protection algorithm "
- + "but replay detection is chosen");
- }
+ if (! integrity)
+ throw new AuthenticationException("Missing integrity protection algorithm "
+ + "but replay detection is chosen");
}
if (mandatory.equals(SRPRegistry.OPTION_REPLAY_DETECTION))
{
- if (!replayDetection)
- {
- throw new AuthenticationException(
- "Replay detection is mandatory but was not chosen");
- }
+ if (! replayDetection)
+ throw new AuthenticationException("Replay detection is mandatory but was not chosen");
}
if (mandatory.equals(SRPRegistry.OPTION_INTEGRITY))
{
- if (!integrity)
- {
- throw new AuthenticationException(
- "Integrity protection is mandatory but was not chosen");
- }
+ if (! integrity)
+ throw new AuthenticationException("Integrity protection is mandatory but was not chosen");
}
if (mandatory.equals(SRPRegistry.OPTION_CONFIDENTIALITY))
{
- if (!confidentiality)
- {
- throw new AuthenticationException(
- "Confidentiality is mandatory but was not chosen");
- }
+ if (! confidentiality)
+ throw new AuthenticationException("Confidentiality is mandatory but was not chosen");
}
-
int blockSize = 0;
if (chosenConfidentialityAlgorithm != null)
{
final IBlockCipher cipher = CipherFactory.getInstance(chosenConfidentialityAlgorithm);
if (cipher != null)
- {
- blockSize = cipher.defaultBlockSize();
- }
- else
- { // should not happen
- throw new AuthenticationException("Confidentiality algorithm ("
- + chosenConfidentialityAlgorithm
- + ") not available");
- }
+ blockSize = cipher.defaultBlockSize();
+ else // should not happen
+ throw new AuthenticationException("Confidentiality algorithm ("
+ + chosenConfidentialityAlgorithm
+ + ") not available");
}
-
sIV = new byte[blockSize];
if (blockSize > 0)
getDefaultPRNG().nextBytes(sIV);
@@ -1086,30 +778,26 @@ public class SRPServer extends ServerMechanism implements SaslServer
// instantiate cipher if confidentiality protection filter is active
if (chosenConfidentialityAlgorithm != null)
{
- if (DEBUG && debuglevel > 2)
- debug(INFO, "Activating confidentiality protection filter");
+ if (Configuration.DEBUG)
+ log.fine("Activating confidentiality protection filter");
inCipher = CALG.getInstance(chosenConfidentialityAlgorithm);
outCipher = CALG.getInstance(chosenConfidentialityAlgorithm);
}
// instantiate hmacs if integrity protection filter is active
if (chosenIntegrityAlgorithm != null)
{
- if (DEBUG && debuglevel > 2)
- debug(INFO, "Activating integrity protection filter");
+ if (Configuration.DEBUG)
+ log.fine("Activating integrity protection filter");
inMac = IALG.getInstance(chosenIntegrityAlgorithm);
outMac = IALG.getInstance(chosenIntegrityAlgorithm);
}
-
// generate a new sid if at least integrity is used
sid = (inMac != null ? ServerStore.getNewSessionID() : new byte[0]);
}
- else
- { // same session new keys
- K = srp.generateKn(K, cn, sn);
- }
+ else // same session new keys
+ K = srp.generateKn(K, cn, sn);
final KDF kdf = KDF.getInstance(K);
-
// initialise in/out ciphers if confidentaility protection is used
if (inCipher != null)
{
@@ -1122,15 +810,12 @@ public class SRPServer extends ServerMechanism implements SaslServer
outMac.init(kdf);
inMac.init(kdf);
}
-
if (sid != null && sid.length != 0)
{ // update the security context and save in map
- if (DEBUG && debuglevel > 2)
- debug(INFO, "Updating security context for sid = " + new String(sid));
- ServerStore.instance().cacheSession(
- ttl,
- new SecurityContext(
- srp.getAlgorithm(),
+ if (Configuration.DEBUG)
+ log.fine("Updating security context for sid = " + new String(sid));
+ ServerStore.instance().cacheSession(ttl,
+ new SecurityContext(srp.getAlgorithm(),
sid,
K,
cIV,
diff --git a/gnu/javax/security/auth/login/ConfigFileParser.java b/gnu/javax/security/auth/login/ConfigFileParser.java
index f6c39bb3d..8efadca77 100644
--- a/gnu/javax/security/auth/login/ConfigFileParser.java
+++ b/gnu/javax/security/auth/login/ConfigFileParser.java
@@ -38,12 +38,15 @@ exception statement from your version. */
package gnu.javax.security.auth.login;
+import gnu.classpath.Configuration;
+
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.logging.Logger;
import javax.security.auth.login.AppConfigurationEntry;
@@ -88,26 +91,12 @@ import javax.security.auth.login.AppConfigurationEntry;
*/
public final class ConfigFileParser
{
- // Constants and fields
- // --------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
- private static final void debug(String m) {if (DEBUG) System.err.println(m);};
-
+ private static final Logger log = Logger.getLogger(ConfigFileParser.class.getName());
private ConfigFileTokenizer cft;
private Map map = new HashMap();
- // Constructor(s)
- // --------------------------------------------------------------------------
-
// default 0-arguments constructor
- // Class methods
- // --------------------------------------------------------------------------
-
- // Instance methods
- // --------------------------------------------------------------------------
-
/**
* Returns the parse result as a {@link Map} where the keys are application
* names, and the entries are {@link List}s of {@link AppConfigurationEntry}
@@ -161,7 +150,8 @@ public final class ConfigFileParser
}
String appName = cft.sval;
- debug("DEBUG: APP_NAME_OR_OTHER = " + appName);
+ if (Configuration.DEBUG)
+ log.fine("APP_NAME_OR_OTHER = " + appName);
if (cft.nextToken() != '{')
abort("Missing '{' after APP_NAME_OR_OTHER");
@@ -202,13 +192,15 @@ public final class ConfigFileParser
}
String clazz = validateClassName(cft.sval);
- debug("DEBUG: MODULE_CLASS = " + clazz);
+ if (Configuration.DEBUG)
+ log.fine("MODULE_CLASS = " + clazz);
if (cft.nextToken() != ConfigFileTokenizer.TT_WORD)
abort("Was expecting FLAG but found none");
String flag = cft.sval;
- debug("DEBUG: FLAG = " + flag);
+ if (Configuration.DEBUG)
+ log.fine("DEBUG: FLAG = " + flag);
AppConfigurationEntry.LoginModuleControlFlag f = null;
if (flag.equalsIgnoreCase("required"))
f = AppConfigurationEntry.LoginModuleControlFlag.REQUIRED;
@@ -230,32 +222,39 @@ public final class ConfigFileParser
abort("Was expecting PARAM_NAME but got '" + ((char) c) + "'");
paramName = cft.sval;
- debug("DEBUG: PARAM_NAME = " + paramName);
+ if (Configuration.DEBUG)
+ log.fine("PARAM_NAME = " + paramName);
if (cft.nextToken() != '=')
abort("Missing '=' after PARAM_NAME");
c = cft.nextToken();
if (c != '"' && c != '\'')
- debug(" WARN: Was expecting a quoted string but got no quote " +
- "character. Assume unquoted string");
-
+ {
+ if (Configuration.DEBUG)
+ log.fine("Was expecting a quoted string but got no quote character."
+ + " Assume unquoted string");
+ }
paramValue = expandParamValue(cft.sval);
- debug("DEBUG: PARAM_VALUE = " + paramValue);
+ if (Configuration.DEBUG)
+ log.fine("PARAM_VALUE = " + paramValue);
options.put(paramName, paramValue);
c = cft.nextToken();
}
-
AppConfigurationEntry ace = new AppConfigurationEntry(clazz, f, options);
- debug("DEBUG: LOGIN_MODULE_ENTRY = " + ace);
+ if (Configuration.DEBUG)
+ log.fine("LOGIN_MODULE_ENTRY = " + ace);
listOfACEs.add(ace);
return true;
}
private void abort(String m) throws IOException
{
- debug("ERROR: " + m);
- debug("DEBUG: Map (so far) = " + String.valueOf(map));
+ if (Configuration.DEBUG)
+ {
+ log.fine(m);
+ log.fine("Map (so far) = " + String.valueOf(map));
+ }
throw new IOException(m);
}
@@ -264,12 +263,13 @@ public final class ConfigFileParser
if (cn.startsWith(".") || cn.endsWith("."))
abort("MODULE_CLASS MUST NOT start or end with a '.'");
- String[] tokens = cn.split(".");
+ String[] tokens = cn.split("\\.");
for (int i = 0; i < tokens.length; i++)
{
String t = tokens[i];
- if (Character.isJavaIdentifierStart(cn.toCharArray()[0]))
- abort("");
+ if (! Character.isJavaIdentifierStart(t.toCharArray()[0]))
+ abort("Class name [" + cn
+ + "] contains an invalid sub-package identifier: " + t);
// we dont check the rest of the characters for isJavaIdentifierPart()
// because that's what the tokenizer does.
@@ -311,14 +311,17 @@ public final class ConfigFileParser
int j = s.indexOf("}", i + 2);
if (j == -1)
{
- debug(" WARN: Found a ${ prefix with no } suffix. Ignore");
+ if (Configuration.DEBUG)
+ log.fine("Found a ${ prefix with no } suffix. Ignore");
break;
}
String sysPropName = s.substring(i + 2, j);
- debug("DEBUG: Found a reference to System property " + sysPropName);
+ if (Configuration.DEBUG)
+ log.fine("Found a reference to System property " + sysPropName);
String sysPropValue = System.getProperty(sysPropName);
- debug("DEBUG: Resolved " + sysPropName + " to '" + sysPropValue + "'");
+ if (Configuration.DEBUG)
+ log.fine("Resolved " + sysPropName + " to '" + sysPropValue + "'");
if (sysPropValue != null)
{
result = s.substring(0, i) + sysPropValue + s.substring(j + 1);
@@ -330,7 +333,8 @@ public final class ConfigFileParser
}
catch (Exception x)
{
- debug(" WARN: Exception while expanding " + s + ". Ignore: " + x);
+ if (Configuration.DEBUG)
+ log.fine("Exception (ignored) while expanding " + s + ": " + x);
}
return result;
diff --git a/gnu/javax/security/auth/login/GnuConfiguration.java b/gnu/javax/security/auth/login/GnuConfiguration.java
index f0b8594a0..85b6bc3a0 100644
--- a/gnu/javax/security/auth/login/GnuConfiguration.java
+++ b/gnu/javax/security/auth/login/GnuConfiguration.java
@@ -50,6 +50,7 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.logging.Logger;
import javax.security.auth.AuthPermission;
import javax.security.auth.login.AppConfigurationEntry;
@@ -127,12 +128,7 @@ import javax.security.auth.login.Configuration;
*/
public final class GnuConfiguration extends Configuration
{
- // Constants and fields
- // --------------------------------------------------------------------------
-
- private static final boolean DEBUG = true;
- private static final void debug(String m) {if (DEBUG) System.err.println(m);};
-
+ private static final Logger log = Logger.getLogger(GnuConfiguration.class.getName());
/**
* The internal map of login modules keyed by application name. Each entry in
* this map is a {@link List} of {@link AppConfigurationEntry}s for that
@@ -179,7 +175,8 @@ public final class GnuConfiguration extends Configuration
if (loginModules == null || loginModules.size() == 0)
return null;
- debug("DEBUG: " + appName + " -> " + loginModules.size() + " entry(ies)");
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine(appName + " -> " + loginModules.size() + " entry(ies)");
return (AppConfigurationEntry[]) loginModules.toArray(new AppConfigurationEntry[0]);
}
@@ -193,7 +190,7 @@ public final class GnuConfiguration extends Configuration
* @throws SecurityException if the caller does not have an
* {@link AuthPermission} for the action named
* <code>refreshLoginConfiguration</code>.
- * @see {@link AuthPermission}
+ * @see AuthPermission
*/
public void refresh()
{
@@ -215,13 +212,25 @@ public final class GnuConfiguration extends Configuration
private void init()
{
if (processSecurityProperties())
- debug(" INFO: Using login configuration defined by Security property(ies)");
+ {
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("Using login configuration defined by Security property(ies)");
+ }
else if (processSystemProperty())
- debug(" INFO: Using login configuration defined by System property");
+ {
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("Using login configuration defined by System property");
+ }
else if (processUserHome())
- debug(" INFO: Using login configuration defined in ${user.home}");
+ {
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("Using login configuration defined in ${user.home}");
+ }
else
- debug(" WARN: No login configuration file found");
+ {
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("No login configuration file found");
+ }
}
/**
@@ -249,16 +258,18 @@ public final class GnuConfiguration extends Configuration
s = s.trim();
if (s.length() != 0)
{
- debug("DEBUG: java.security.auth.login.config.url." + counter
- + " = " + s);
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("java.security.auth.login.config.url." + counter
+ + " = " + s);
parseConfig(getInputStreamFromURL(s));
result = true;
}
}
catch (Throwable t)
{
- debug(" WARN: Exception while handling Security property at #"
- + counter + ". Continue: " + t);
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("Exception while handling Security property at #"
+ + counter + ". Continue: " + t);
}
return result;
}
@@ -287,7 +298,8 @@ public final class GnuConfiguration extends Configuration
}
catch (MalformedURLException x)
{
- debug(" WARN: Failed opening as URL: " + s + ". Will try as File");
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("Failed opening as URL: " + s + ". Will try as File");
result = new FileInputStream(s);
}
return result;
@@ -311,7 +323,8 @@ public final class GnuConfiguration extends Configuration
s = s.trim();
if (s.length() != 0)
{
- debug("DEBUG: java.security.auth.login.config = " + s);
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("java.security.auth.login.config = " + s);
parseConfig(getInputStreamFromURL(s));
result = true;
}
@@ -319,7 +332,8 @@ public final class GnuConfiguration extends Configuration
}
catch (Throwable t)
{
- debug(" WARN: Exception while handling System property. Continue: " + t);
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("Exception while handling System property. Continue: " + t);
}
return result;
}
@@ -349,8 +363,9 @@ public final class GnuConfiguration extends Configuration
if (jaasFile == null)
{
- debug(" WARN: Login Configuration file, in " + userHome
- + ", does not exist or is inaccessible");
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("Login Configuration file, in " + userHome
+ + ", does not exist or is inaccessible");
return result;
}
@@ -360,7 +375,8 @@ public final class GnuConfiguration extends Configuration
}
catch (Throwable t)
{
- debug(" WARN: Exception while handling ${user.home}: " + t);
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("Exception (ignored) while handling ${user.home}: " + t);
}
return result;
}
@@ -397,54 +413,54 @@ public final class GnuConfiguration extends Configuration
String uh = System.getProperty("user.home");
if (uh == null || uh.trim().length() == 0)
{
- debug(" WARN: User home path is not set or is empty");
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("User home path is not set or is empty");
return null;
}
-
uh = uh.trim();
File result = new File(uh);
- if (!result.exists())
+ if (! result.exists())
{
- debug(" WARN: User home '" + uh + "' does not exist");
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("User home '" + uh + "' does not exist");
return null;
}
-
- if (!result.isDirectory())
+ if (! result.isDirectory())
{
- debug(" WARN: User home '" + uh + "' is not a directory");
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("User home '" + uh + "' is not a directory");
return null;
}
-
- if (!result.canRead())
+ if (! result.canRead())
{
- debug(" WARN: User home '" + uh + "' is not readable");
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("User home '" + uh + "' is not readable");
return null;
}
-
return result;
}
private File getConfigFromUserHome(File userHome, String fileName)
{
File result = new File(userHome, fileName);
- if (!result.exists())
+ if (! result.exists())
{
- debug(" WARN: File '" + fileName + "' does not exist in user's home");
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("File '" + fileName + "' does not exist in user's home");
return null;
}
-
- if (!result.isFile())
+ if (! result.isFile())
{
- debug(" WARN: File '" + fileName + "' in user's home is not a file");
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("File '" + fileName + "' in user's home is not a file");
return null;
}
-
- if (!result.canRead())
+ if (! result.canRead())
{
- debug(" WARN: File '" + fileName + "' in user's home is not readable");
+ if (gnu.classpath.Configuration.DEBUG)
+ log.fine("File '" + fileName + "' in user's home is not readable");
return null;
}
-
return result;
}
}
diff --git a/gnu/javax/swing/text/html/CharacterAttributeTranslator.java b/gnu/javax/swing/text/html/CharacterAttributeTranslator.java
index 9718189da..5f7309583 100644
--- a/gnu/javax/swing/text/html/CharacterAttributeTranslator.java
+++ b/gnu/javax/swing/text/html/CharacterAttributeTranslator.java
@@ -39,16 +39,11 @@ package gnu.javax.swing.text.html;
import java.awt.Color;
import java.util.HashMap;
-import javax.swing.text.AbstractDocument;
-import javax.swing.text.AttributeSet;
-import javax.swing.text.BadLocationException;
-import javax.swing.text.DefaultStyledDocument;
-import javax.swing.text.Element;
-import javax.swing.text.ElementIterator;
-import javax.swing.text.GapContent;
+import java.util.StringTokenizer;
+
import javax.swing.text.MutableAttributeSet;
-import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
+import javax.swing.text.html.HTML.Attribute;
import javax.swing.text.html.HTML.Tag;
/**
@@ -57,6 +52,9 @@ import javax.swing.text.html.HTML.Tag;
*/
public class CharacterAttributeTranslator
{
+ /**
+ * Maps color name to its hex encoding.
+ */
private static final HashMap colorMap = new HashMap();
static
{
@@ -77,37 +75,75 @@ public class CharacterAttributeTranslator
colorMap.put("white" , "#FFFFFF");
colorMap.put("yellow" , "#FFFF00");
};
-
- private static Color getColor(String s)
+
+ /**
+ * Convert the color string represenation into java.awt.Color. The valid
+ * values are like "aqua" , "#00FFFF" or "rgb(1,6,44)".
+ *
+ * @param colorName the color to convert.
+ * @return the matching java.awt.color
+ */
+ private static Color getColor(String colorName)
{
- String s2 = (String)colorMap.get(s.toLowerCase());
- if( s2 == null )
- s2 = s;
+ colorName = colorName.toLowerCase();
try
{
- return Color.decode(s2);
+ if (colorName.startsWith("rgb"))
+ {
+ // rgb(red, green, blue) notation.
+ StringTokenizer st = new StringTokenizer(colorName, " ,()");
+ String representation = st.nextToken();
+
+ // Return null if the representation is not supported.
+ if (! representation.equals("rgb"))
+ return null;
+ int red = Integer.parseInt(st.nextToken());
+ int green = Integer.parseInt(st.nextToken());
+ int blue = Integer.parseInt(st.nextToken());
+
+ return new Color(red, green, blue);
+ }
+ else
+ {
+ String s2 = (String) colorMap.get(colorName);
+ if (s2 == null)
+ s2 = colorName;
+ return Color.decode(s2);
+ }
}
- catch(NumberFormatException nfe)
+ catch (Exception nex)
{
- return null;
+ // Can be either number format exception or illegal argument
+ // exception.
+ return null;
}
}
+ /**
+ * Translate the HTML character attribute to the Swing style constant.
+ *
+ * @param charAttr the character attributes of the html tag
+ * @param t the html tag itself
+ * @param a the attribute set where the translated attributes will be stored
+ *
+ * @return true if some attributes were translated, false otherwise.
+ */
public static boolean translateTag(MutableAttributeSet charAttr,
Tag t, MutableAttributeSet a)
{
if(t == Tag.FONT)
{
- if(a.getAttribute("color") != null)
+ Object color = a.getAttribute(Attribute.COLOR);
+ if(color != null)
{
- Color c = getColor(""+a.getAttribute("color"));
+ Color c = getColor(color.toString());
if( c == null )
return false;
charAttr.addAttribute(StyleConstants.Foreground, c);
return true;
}
- if(a.getAttribute("size") != null)
+ if(a.getAttribute(Attribute.SIZE) != null)
{
// FIXME
// charAttr.addAttribute(StyleConstants.FontSize,
@@ -118,37 +154,37 @@ public class CharacterAttributeTranslator
if( t == Tag.B )
{
- charAttr.addAttribute(StyleConstants.Bold, new Boolean(true));
+ charAttr.addAttribute(StyleConstants.Bold, Boolean.TRUE);
return true;
}
if( t == Tag.I )
{
- charAttr.addAttribute(StyleConstants.Italic, new Boolean(true));
+ charAttr.addAttribute(StyleConstants.Italic, Boolean.TRUE);
return true;
}
if( t == Tag.U )
{
- charAttr.addAttribute(StyleConstants.Underline, new Boolean(true));
+ charAttr.addAttribute(StyleConstants.Underline, Boolean.TRUE);
return true;
}
if( t == Tag.STRIKE )
{
- charAttr.addAttribute(StyleConstants.StrikeThrough, new Boolean(true));
+ charAttr.addAttribute(StyleConstants.StrikeThrough, Boolean.TRUE);
return true;
}
if( t == Tag.SUP )
{
- charAttr.addAttribute(StyleConstants.Superscript, new Boolean(true));
+ charAttr.addAttribute(StyleConstants.Superscript, Boolean.TRUE);
return true;
}
if( t == Tag.SUB )
{
- charAttr.addAttribute(StyleConstants.Subscript, new Boolean(true));
+ charAttr.addAttribute(StyleConstants.Subscript, Boolean.TRUE);
return true;
}
return false;
diff --git a/gnu/javax/swing/text/html/CombinedAttributes.java b/gnu/javax/swing/text/html/CombinedAttributes.java
new file mode 100644
index 000000000..b1e3de604
--- /dev/null
+++ b/gnu/javax/swing/text/html/CombinedAttributes.java
@@ -0,0 +1,213 @@
+/* CombinedAttributes.java -- A two combined sets of attributes
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.swing.text.html;
+
+import java.io.Serializable;
+import java.util.Enumeration;
+
+import javax.swing.text.AttributeSet;
+import javax.swing.text.SimpleAttributeSet;
+
+/**
+ * Contains the two combined attribute sets what are searched subsequently.
+ * This is used to combine style sheet attributes with the HTML view attributes.
+ * The parent cannot be used as the view may have its own attribute hierarchy.
+ *
+ * @author Audrius Meskauskas (AudriusA@Bioinformatics.org)
+ */
+public class CombinedAttributes implements AttributeSet, Serializable
+{
+ /**
+ * Returns the elements from both enumerations.
+ */
+ class CombinedEnumeration implements Enumeration
+ {
+ /**
+ * Create a combined enumeration that enumerates over two enumerations.
+ *
+ * @param first the first enumeration to enumerate
+ * @param second the second enumeration to enumerate
+ */
+ CombinedEnumeration(Enumeration first, Enumeration second)
+ {
+ a = first;
+ b = second;
+ }
+
+ /**
+ * The first enumeration (elements returned first)
+ */
+ final Enumeration a;
+
+ /**
+ * The second enumeration (elements returned later)
+ */
+ final Enumeration b;
+
+ /** @inheritDoc */
+ public boolean hasMoreElements()
+ {
+ return a.hasMoreElements() || b.hasMoreElements();
+ }
+
+ /** @inheritDoc */
+ public Object nextElement()
+ {
+ return a.hasMoreElements() ? a.nextElement():b.nextElement();
+ }
+ }
+
+
+ /**
+ * The first attribute set.
+ */
+ final AttributeSet a;
+
+ /**
+ * The second attribute set.
+ */
+ final AttributeSet b;
+
+ /**
+ * Create the CombinedAttributes what search in the two sets. If any of the
+ * two passed sets is null, another set is returned. Otherwise, the combined
+ * attribute set is returned.
+ *
+ * @param primary the first set (searched first)
+ * @param secondary the second set (searched later).
+ */
+ public static AttributeSet combine(AttributeSet primary,
+ AttributeSet secondary)
+ {
+ if (primary == null)
+ return secondary;
+ else if (secondary == null)
+ return primary;
+ else
+ return new CombinedAttributes(primary, secondary);
+ }
+
+ /**
+ * Create the CombinedAttributes what search in the two sets.
+ *
+ * @param primary the first set (searched first)
+ * @param secondary the second set (searched later).
+ */
+ private CombinedAttributes(AttributeSet primary, AttributeSet secondary)
+ {
+ a = primary;
+ b = secondary;
+ }
+
+ /** @inheritDoc */
+ public boolean containsAttribute(Object name, Object value)
+ {
+ return a.containsAttribute(name, value) || b.containsAttribute(name, value);
+ }
+
+ /** @inheritDoc */
+ public boolean containsAttributes(AttributeSet attributes)
+ {
+ Enumeration names = attributes.getAttributeNames();
+ Object name;
+ while (names.hasMoreElements())
+ {
+ name = names.nextElement();
+ if (!containsAttribute(name, attributes.getAttribute(name)))
+ return false;
+ }
+ return true;
+ }
+
+ /** @inheritDoc */
+ public AttributeSet copyAttributes()
+ {
+ SimpleAttributeSet copy = new SimpleAttributeSet();
+ copy.addAttributes(a);
+ copy.addAttributes(b);
+ return copy;
+ }
+
+ /** @inheritDoc */
+ public Object getAttribute(Object key)
+ {
+ Object value = a.getAttribute(key);
+ if (value == null)
+ value = b.getAttribute(key);
+
+ return value;
+ }
+
+ /** @inheritDoc */
+ public int getAttributeCount()
+ {
+ return a.getAttributeCount()+b.getAttributeCount();
+ }
+
+ /** @inheritDoc */
+ public Enumeration getAttributeNames()
+ {
+ return new CombinedEnumeration(a.getAttributeNames(), b.getAttributeNames());
+ }
+
+ /**
+ * There is no one.
+ *
+ * @return null, always.
+ */
+ public AttributeSet getResolveParent()
+ {
+ return null;
+ }
+
+ /** @inheritDoc */
+ public boolean isDefined(Object attrName)
+ {
+ return a.isDefined(attrName) || b.isDefined(attrName);
+ }
+
+ /** @inheritDoc */
+ public boolean isEqual(AttributeSet attr)
+ {
+ if (attr.getAttributeCount() == getAttributeCount())
+ return containsAttributes(attr);
+ else
+ return false;
+ }
+}
diff --git a/gnu/javax/swing/text/html/ImageViewIconFactory.java b/gnu/javax/swing/text/html/ImageViewIconFactory.java
new file mode 100644
index 000000000..862e690c9
--- /dev/null
+++ b/gnu/javax/swing/text/html/ImageViewIconFactory.java
@@ -0,0 +1,282 @@
+package gnu.javax.swing.text.html;
+
+
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Graphics;
+import java.io.Serializable;
+
+import javax.swing.Icon;
+import javax.swing.plaf.metal.MetalLookAndFeel;
+
+/**
+ * Creates icons for ImageView. The icons reflect the basic ideas of the Sun's
+ * icons as they would be described in the text (sheet of paper with image and
+ * broken sheet of paper with image). They are not pixel to pixel identical and
+ * contain elements from the metal icon factory.
+ *
+ * @author Audrius Meskauskas (audriusa@bioinformatics.org)
+ */
+public class ImageViewIconFactory
+{
+ private static Icon noImageIcon;
+
+ private static Icon loadingImageIcon;
+
+ /**
+ * This icon reflects the general concept (broken sheet of paper with
+ * image), but is currently not pixel to pixel identical with the Sun's
+ * implementation.
+ */
+ public static class NoImageIcon implements Icon, Serializable
+ {
+ /**
+ * Creates a new icon.
+ */
+ public NoImageIcon()
+ {
+ // Nothing to do here.
+ }
+
+ /**
+ * Returns the width of the icon, in pixels.
+ *
+ * @return The width of the icon.
+ */
+ public int getIconWidth()
+ {
+ return 38;
+ }
+
+ /**
+ * Returns the height of the icon, in pixels.
+ *
+ * @return The height of the icon.
+ */
+ public int getIconHeight()
+ {
+ return 38;
+ }
+
+ /**
+ * Paints the icon using colors from the {@link MetalLookAndFeel}.
+ *
+ * @param c
+ * the component (ignored).
+ * @param g
+ * the graphics device.
+ * @param x
+ * the x-coordinate for the top-left of the icon.
+ * @param y
+ * the y-coordinate for the top-left of the icon.
+ */
+ public void paintIcon(Component c, Graphics g, int x, int y)
+ {
+ // frame
+ Color savedColor = g.getColor();
+
+ g.setColor(MetalLookAndFeel.getBlack());
+
+ g.drawLine(x, y, x + 19, y);
+
+ g.drawLine(x, y + 1, x, y + 5);
+ g.drawLine(x, y + 13, x, y + 25);
+
+ g.drawLine(x, y + 25, x + 22, y + 25);
+
+ g.drawLine(x + 22, y + 25, x + 22, y + 21);
+ g.drawLine(x + 22, y + 13, x + 22, y + 6);
+
+ g.drawLine(x + 22, y + 6, x + 19, y);
+
+ g.drawLine(x + 17, y + 2, x + 21, y + 6);
+
+ g.drawLine(x + 18, y + 1, x + 19, y + 1);
+
+ g.setColor(MetalLookAndFeel.getControlShadow());
+
+ g.drawLine(x + 1, y + 1, x + 17, y + 1);
+
+ g.drawLine(x + 1, y + 1, x + 1, y + 5);
+ g.drawLine(x + 1, y + 13, x + 1, y + 24);
+
+ g.drawLine(x + 1, y + 24, x + 21, y + 24);
+
+ g.drawLine(x + 21, y + 24, x + 21, y + 21);
+ g.drawLine(x + 21, y + 13, x + 21, y + 7);
+
+ g.drawLine(x + 18, y + 2, x + 20, y + 4);
+
+ // Breaking line
+
+ // Shadow
+ g.drawLine(x + 1, y + 6, x + 20, y + 13);
+ g.drawLine(x + 1, y + 13, x + 20, y + 20);
+
+ // Edge
+ g.setColor(MetalLookAndFeel.getBlack());
+ g.drawLine(x, y + 6, x + 21, y + 14);
+ g.drawLine(x, y + 12, x + 21, y + 20);
+
+ // Picture
+
+ y += 1;
+ x += 3;
+
+ g.setColor(MetalLookAndFeel.getBlack());
+
+ // roof
+ g.drawLine(x + 4, y + 5, x + 8, y + 1);
+ g.drawLine(x + 8, y + 1, x + 15, y + 8);
+
+ // chimney
+ g.drawLine(x + 11, y + 2, x + 11, y + 4);
+ g.drawLine(x + 12, y + 2, x + 12, y + 5);
+
+ g.setColor(MetalLookAndFeel.getControlDarkShadow());
+
+ // roof paint
+ int xx = x + 8;
+ for (int i = 0; i < 4; i++)
+ g.drawLine(xx - i, y + 2 + i, xx + i, y + 2 + i);
+ g.fillRect(x + 4, y + 6, 9, 2);
+
+ // base of house
+ g.drawLine(x + 3, y + 14, x + 3, y + 18);
+ g.drawLine(x + 3, y + 18, x + 13, y + 18);
+
+ g.setColor(savedColor);
+ }
+ }
+
+ /**
+ * This icon reflects the general concept (sheet of paper with image), but is
+ * currently not pixel to pixel identical with the Sun's implementation.
+ */
+ public static class LoadingImageIcon implements Icon, Serializable
+ {
+
+ /**
+ * Creates a new icon.
+ */
+ public LoadingImageIcon()
+ {
+ // Nothing to do here.
+ }
+
+ /**
+ * Returns the width of the icon, in pixels.
+ *
+ * @return The width of the icon.
+ */
+ public int getIconWidth()
+ {
+ return 38;
+ }
+
+ /**
+ * Returns the height of the icon, in pixels.
+ *
+ * @return The height of the icon.
+ */
+ public int getIconHeight()
+ {
+ return 38;
+ }
+
+ /**
+ * Paints the icon using colors from the {@link MetalLookAndFeel}.
+ *
+ * @param c
+ * the component (ignored).
+ * @param g
+ * the graphics device.
+ * @param x
+ * the x-coordinate for the top-left of the icon.
+ * @param y
+ * the y-coordinate for the top-left of the icon.
+ */
+ public void paintIcon(Component c, Graphics g, int x, int y)
+ {
+ // frame
+ Color savedColor = g.getColor();
+
+ g.setColor(Color.black);
+ g.drawLine(x, y, x + 19, y);
+ g.drawLine(x, y + 1, x, y + 25);
+ g.drawLine(x, y + 25, x + 22, y + 25);
+ g.drawLine(x + 22, y + 25, x + 22, y + 6);
+ g.drawLine(x + 22, y + 6, x + 19, y);
+
+ g.drawLine(x + 17, y + 2, x + 21, y + 6);
+ g.drawLine(x + 18, y + 1, x + 19, y + 1);
+
+ g.setColor(new Color(204, 204, 255));
+
+ g.drawLine(x + 1, y + 1, x + 17, y + 1);
+ g.drawLine(x + 1, y + 1, x + 1, y + 24);
+ g.drawLine(x + 1, y + 24, x + 21, y + 24);
+ g.drawLine(x + 21, y + 24, x + 21, y + 7);
+ g.drawLine(x + 18, y + 2, x + 20, y + 4);
+
+ // Picture (house)
+
+ y += 3;
+ x += 3;
+
+ g.setColor(MetalLookAndFeel.getBlack());
+
+ // roof
+ g.drawLine(x + 1, y + 8, x + 8, y + 1);
+ g.drawLine(x + 8, y + 1, x + 15, y + 8);
+
+ // base of house
+ g.drawLine(x + 3, y + 6, x + 3, y + 15);
+ g.drawLine(x + 3, y + 15, x + 13, y + 15);
+ g.drawLine(x + 13, y + 6, x + 13, y + 15);
+
+ // door frame
+ g.drawLine(x + 6, y + 9, x + 6, y + 15);
+ g.drawLine(x + 6, y + 9, x + 10, y + 9);
+ g.drawLine(x + 10, y + 9, x + 10, y + 15);
+
+ // chimney
+ g.drawLine(x + 11, y + 2, x + 11, y + 4);
+ g.drawLine(x + 12, y + 2, x + 12, y + 5);
+
+ g.setColor(MetalLookAndFeel.getControlDarkShadow());
+
+ // roof paint
+ int xx = x + 8;
+ for (int i = 0; i < 4; i++)
+ g.drawLine(xx - i, y + 2 + i, xx + i, y + 2 + i);
+ g.fillRect(x + 4, y + 6, 9, 2);
+
+ // door knob
+ g.drawLine(x + 9, y + 12, x + 9, y + 12);
+
+ // house paint
+ g.setColor(MetalLookAndFeel.getPrimaryControl());
+ g.drawLine(x + 4, y + 8, x + 12, y + 8);
+ g.fillRect(x + 4, y + 9, 2, 6);
+ g.fillRect(x + 11, y + 9, 2, 6);
+
+ g.setColor(savedColor);
+ }
+ }
+
+ public static Icon getNoImageIcon()
+ {
+ if (noImageIcon == null)
+ noImageIcon = new NoImageIcon();
+ return noImageIcon;
+ }
+
+ public static Icon getLoadingImageIcon()
+ {
+ if (loadingImageIcon == null)
+ loadingImageIcon = new LoadingImageIcon();
+ return loadingImageIcon;
+ }
+
+}
diff --git a/gnu/javax/swing/text/html/parser/SmallHtmlAttributeSet.java b/gnu/javax/swing/text/html/parser/SmallHtmlAttributeSet.java
new file mode 100644
index 000000000..930a324f9
--- /dev/null
+++ b/gnu/javax/swing/text/html/parser/SmallHtmlAttributeSet.java
@@ -0,0 +1,261 @@
+/* SmallHtmlAttributeSet.java -- Small fixed HTML attribute set
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.swing.text.html.parser;
+
+import java.io.Serializable;
+import java.util.Enumeration;
+import java.util.NoSuchElementException;
+
+import javax.swing.text.AttributeSet;
+import javax.swing.text.html.HTML.Attribute;
+import javax.swing.text.html.HTML.Tag;
+
+/**
+ * Small fixed HTML attribute set. The most of the HTML elements contain only
+ * several attributes. With four attributes, the number of operations in more
+ * complex algorithms is not larger than using the naive algorithm.
+ *
+ * Same as HtmlAttributeSet, this set allows both strings and non-string as
+ * keys. The strings are case insensitive, the non strings are compared with
+ * .equals.
+ *
+ * @author Audrius Meskauskas (AudriusA@Bioinformatics.org)
+ */
+public class SmallHtmlAttributeSet
+ implements AttributeSet, Cloneable, Serializable
+{
+ private static final long serialVersionUID = 1;
+
+ /**
+ * The keys, stored in this attribute set.
+ */
+ final Object[] keys;
+
+ /**
+ * The values, stored in this attribute set.
+ */
+ final Object[] values;
+
+ /**
+ * The parent, used for resolving the values, not found in this set.
+ */
+ final AttributeSet parent;
+
+ /**
+ * Create a new small fixed attribute set that contains the unchangeable copy
+ * of the passed attribute set and inherits its parent.
+ *
+ * @param copyFrom the attribute set, containing the attribute values to copy.
+ */
+ public SmallHtmlAttributeSet(AttributeSet copyFrom)
+ {
+ int n = copyFrom.getAttributeCount();
+
+ keys = new Object[n];
+ values = new Object[n];
+ parent = copyFrom.getResolveParent();
+
+ Enumeration en = copyFrom.getAttributeNames();
+ Object key;
+ Object value;
+
+ for (int i = 0; i < n; i++)
+ {
+ key = en.nextElement();
+ keys[i] = key;
+ value = copyFrom.getAttribute(key);
+ values[i] = value;
+ }
+ }
+
+ public boolean containsAttribute(Object name, Object value)
+ {
+ Object contains = getAttribute(name);
+ if (value == null)
+ return value == contains;
+ else
+ return value.equals(contains);
+ }
+
+ public boolean containsAttributes(AttributeSet attributes)
+ {
+ if (attributes == this)
+ return true;
+ Object v;
+ for (int i = 0; i < keys.length; i++)
+ {
+ v = attributes.getAttribute(keys[i]);
+ if (v != values[i])
+ {
+ if (values[i] == null)
+ return false;
+ else if (! values[i].equals(v))
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * THIS can be safely returned as the set is not mutable.
+ */
+ public AttributeSet copyAttributes()
+ {
+ return this;
+ }
+
+ /**
+ * Get the attribute value, matching this key. If not found in this set, the
+ * call is delegated to parent.
+ *
+ * @return the value, matching key (or null if none).
+ */
+ public Object getAttribute(Object key)
+ {
+ // Null and HTML attributes or tags can be searched by direct comparison.
+ if (key == null || key instanceof Attribute || key instanceof Tag)
+ {
+ for (int i = 0; i < keys.length; i++)
+ {
+ if (keys[i] == key)
+ return values[i];
+ }
+ }
+
+ // Strings are case insensitive. Only string can be match the string.
+ else if (key instanceof String)
+ {
+ String ks = (String) key;
+ for (int i = 0; i < keys.length; i++)
+ {
+ if (keys[i] instanceof String)
+ if (ks.equalsIgnoreCase((String) keys[i]))
+ return values[i];
+ }
+ }
+
+ // Otherwise, defaults to .equals
+ else
+ {
+ for (int i = 0; i < keys.length; i++)
+ {
+ if (key.equals(keys[i]))
+ return values[i];
+ }
+ }
+
+ if (parent != null)
+ return parent.getAttribute(key);
+ else
+ return null;
+ }
+
+ /**
+ * Get the number of the stored attributes.
+ */
+ public int getAttributeCount()
+ {
+ return keys.length;
+ }
+
+ /**
+ * Get enumeration, containing the attribute names. No guard agains the
+ * concurent modification is required as the set is not mutable.
+ */
+ public Enumeration getAttributeNames()
+ {
+ return new Enumeration()
+ {
+ int p = 0;
+
+ public boolean hasMoreElements()
+ {
+ return p < keys.length;
+ }
+
+ public Object nextElement()
+ {
+ if (p < keys.length)
+ return keys[p++];
+ else
+ throw new NoSuchElementException();
+ }
+ };
+ }
+
+ /**
+ * Get the parent that this set uses to resolve the not found attributes.
+ */
+ public AttributeSet getResolveParent()
+ {
+ return parent;
+ }
+
+ /**
+ * Check if the given attribute is defined in this set (not in the parent).
+ */
+ public boolean isDefined(Object attrName)
+ {
+ if (attrName instanceof String)
+ attrName = ((String) attrName).toLowerCase();
+
+ for (int i = 0; i < keys.length; i++)
+ {
+ if (attrName.equals(keys[i]))
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Check this set and another set for equality by content.
+ */
+ public boolean isEqual(AttributeSet attr)
+ {
+ return keys.length == attr.getAttributeCount() && containsAttributes(attr);
+ }
+
+ /**
+ * It is safe to return THIS on cloning, if one happens.
+ */
+ protected Object clone()
+ {
+ return this;
+ }
+}
diff --git a/gnu/javax/swing/text/html/parser/htmlAttributeSet.java b/gnu/javax/swing/text/html/parser/htmlAttributeSet.java
index a4e6f73c5..b89eec619 100644
--- a/gnu/javax/swing/text/html/parser/htmlAttributeSet.java
+++ b/gnu/javax/swing/text/html/parser/htmlAttributeSet.java
@@ -46,6 +46,7 @@ import javax.swing.text.html.HTML;
/**
* A set, adapted to store HTML attributes.
+ *
* @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org)
*/
public class htmlAttributeSet
@@ -53,23 +54,34 @@ public class htmlAttributeSet
{
public static final htmlAttributeSet EMPTY_HTML_ATTRIBUTE_SET =
new htmlAttributeSet();
+
AttributeSet parent;
/**
- * Looks in this set and, if not found, later looks in the parent set.
- * Calls toString(), allowing to pass as HTML.Attribute, as String
- * to this method.
- * @param key A key to search for a value.
+ * Looks in this set and, if not found, later looks in the parent set. Calls
+ * toString(), allowing to pass as HTML.Attribute, as String to this method.
+ *
+ * @param _key A key to search for a value.
* @return The value, if one is defined.
*/
public Object getAttribute(Object _key)
{
+ Object v = super.getAttribute(_key);
+ if (v != null || _key == null)
+ return v;
+
Object key = _key.toString().toLowerCase();
- Object v = super.getAttribute(key);
+ v = super.getAttribute(key);
+ if (v != null)
+ return v;
+
+ key = HTML.getAttributeKey((String) key);
+ v = super.getAttribute(key);
if (v != null)
return v;
- else if (parent != null)
+
+ if (parent != null)
return parent.getAttribute(key);
else
return null;
@@ -85,26 +97,29 @@ public class htmlAttributeSet
final Enumeration enumeration = super.getAttributeNames();
return new Enumeration()
+ {
+ public boolean hasMoreElements()
+ {
+ return enumeration.hasMoreElements();
+ }
+
+ public Object nextElement()
{
- public boolean hasMoreElements()
- {
- return enumeration.hasMoreElements();
- }
-
- public Object nextElement()
- {
- Object key = enumeration.nextElement();
- HTML.Attribute hKey = HTML.getAttributeKey((String) key);
- if (hKey != null)
- return hKey;
- else
- return key;
- }
- };
+ Object key = enumeration.nextElement();
+ if (key instanceof String)
+ {
+ HTML.Attribute hKey = HTML.getAttributeKey((String) key);
+ if (hKey != null)
+ return hKey;
+ }
+ return key;
+ }
+ };
}
/**
* Set the parent set, containing the default values.
+ *
* @param a_parent
*/
public void setResolveParent(AttributeSet a_parent)
@@ -114,7 +129,8 @@ public class htmlAttributeSet
/**
* Get the parent set, containing the default values.
- * @return
+ *
+ * @return the parent, used to resolve the attributes.
*/
public AttributeSet getResolveParent()
{
@@ -123,11 +139,45 @@ public class htmlAttributeSet
/**
* Add the attribute to this attribute set.
- * @param key Attribute key (will be case insensitive)
+ *
+ * @param key Attribute key (if string, it will be case insensitive)
* @param value Attribute value
*/
public void addAttribute(Object key, Object value)
{
- super.addAttribute(key.toString().toLowerCase(), value);
+ if (key instanceof String)
+ super.addAttribute(((String) key).toLowerCase(), value);
+ else
+ super.addAttribute(key, value);
}
+
+ /**
+ * Copy attributes. The returned copy does not longer contains the extended
+ * features, needed to participate in the HTML parsing. The returned set may
+ * not be mutable.
+ */
+ public AttributeSet copyAttributes()
+ {
+ if (getAttributeCount() <= 8)
+ // For the small size, typical in HTML tags, the direct iteration is
+ // faster than more complex algorithms.
+ return new SmallHtmlAttributeSet(this);
+ else
+ return (AttributeSet) clone();
+ }
+
+ /**
+ * Returns a clone of the attribute set.
+ *
+ * @return A clone of the attribute set.
+ */
+ public Object clone()
+ {
+ htmlAttributeSet set = new htmlAttributeSet();
+ set.addAttributes(this);
+ AttributeSet parent = getResolveParent();
+ if (parent != null)
+ set.setResolveParent(parent);
+ return set;
+ }
}
diff --git a/gnu/xml/dom/DomIterator.java b/gnu/xml/dom/DomIterator.java
index 472c6e805..8a258926b 100644
--- a/gnu/xml/dom/DomIterator.java
+++ b/gnu/xml/dom/DomIterator.java
@@ -1,5 +1,5 @@
/* DomIterator.java --
- Copyright (C) 1999,2000,2001 Free Software Foundation, Inc.
+ Copyright (C) 1999, 2000, 2001, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -297,7 +297,9 @@ public final class DomIterator
{
next = next.getParentNode();
}
- if (next == root)
+
+ // If we have exceeded the root node then stop traversing.
+ if (next == root.getParentNode())
{
return null;
}
diff --git a/gnu/xml/stream/SAXParser.java b/gnu/xml/stream/SAXParser.java
index fd768a43d..e58d5fb52 100644
--- a/gnu/xml/stream/SAXParser.java
+++ b/gnu/xml/stream/SAXParser.java
@@ -976,10 +976,56 @@ public class SAXParser
public static void main(String[] args)
throws Exception
{
- SAXParser parser = new SAXParser();
- InputSource input = new InputSource(args[0]);
- parser.parse(input, new org.xml.sax.helpers.DefaultHandler());
-
+ boolean validating = false;
+ boolean namespaceAware = false;
+ boolean xIncludeAware = false;
+ boolean expectCallbackClass = false;
+ String callbackClass = null;
+ int pos = 0;
+ while (pos < args.length && (args[pos].startsWith("-") || expectCallbackClass))
+ {
+ if ("-x".equals(args[pos]))
+ xIncludeAware = true;
+ else if ("-v".equals(args[pos]))
+ validating = true;
+ else if ("-n".equals(args[pos]))
+ namespaceAware = true;
+ else if ("-c".equals(args[pos]))
+ expectCallbackClass = true;
+ else if (expectCallbackClass)
+ {
+ callbackClass = args[pos];
+ expectCallbackClass = false;
+ }
+ pos++;
+ }
+ if (pos >= args.length || expectCallbackClass)
+ {
+ System.out.println("Syntax: SAXParser [-n] [-v] [-x] [-c <class>] <file> [<file2> [...]]");
+ System.out.println("\t-n: use namespace aware mode");
+ System.out.println("\t-v: use validating parser");
+ System.out.println("\t-x: use XInclude aware mode");
+ System.out.println("\t-c <class>: use specified class as callback handler (must have a no-arg public constructor)");
+ System.exit(2);
+ }
+ while (pos < args.length)
+ {
+ ContentHandler handler = null;
+ if (callbackClass != null)
+ {
+ Class t = Class.forName(callbackClass);
+ handler = (ContentHandler) t.newInstance();
+ }
+ else
+ handler = new org.xml.sax.helpers.DefaultHandler();
+ SAXParser parser = new SAXParser(validating, namespaceAware,
+ xIncludeAware);
+ InputSource input = new InputSource(args[pos]);
+ XMLReader reader = parser.getXMLReader();
+ reader.setContentHandler(handler);
+ reader.parse(input);
+ pos++;
+ }
}
}
diff --git a/gnu/xml/stream/XMLParser.java b/gnu/xml/stream/XMLParser.java
index 87096eecf..ef3779944 100644
--- a/gnu/xml/stream/XMLParser.java
+++ b/gnu/xml/stream/XMLParser.java
@@ -56,6 +56,8 @@ package gnu.xml.stream;
import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
@@ -86,6 +88,8 @@ import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import gnu.java.net.CRLFInputStream;
+import gnu.classpath.debug.TeeInputStream;
+import gnu.classpath.debug.TeeReader;
/**
* An XML parser.
@@ -420,6 +424,21 @@ public class XMLParser
ids = new HashSet();
idrefs = new HashSet();
}
+ String debug = System.getProperty("gnu.xml.debug.input");
+ if (debug != null)
+ {
+ try
+ {
+ File file = File.createTempFile(debug, ".xml");
+ in = new TeeInputStream(in, new FileOutputStream(file));
+ }
+ catch (IOException e)
+ {
+ RuntimeException e2 = new RuntimeException();
+ e2.initCause(e);
+ throw e2;
+ }
+ }
pushInput(new Input(in, null, null, systemId, null, null, false, true));
}
@@ -479,6 +498,21 @@ public class XMLParser
ids = new HashSet();
idrefs = new HashSet();
}
+ String debug = System.getProperty("gnu.xml.debug.input");
+ if (debug != null)
+ {
+ try
+ {
+ File file = File.createTempFile(debug, ".xml");
+ reader = new TeeReader(reader, new FileWriter(file));
+ }
+ catch (IOException e)
+ {
+ RuntimeException e2 = new RuntimeException();
+ e2.initCause(e);
+ throw e2;
+ }
+ }
pushInput(new Input(null, reader, null, systemId, null, null, false, true));
}
@@ -1332,6 +1366,15 @@ public class XMLParser
return false;
}
count += l2;
+ // check the characters we received first before doing additional reads
+ for (int i = 0; i < count; i++)
+ {
+ if (chars[i] != tmpBuf[i])
+ {
+ reset();
+ return false;
+ }
+ }
while (count < len)
{
// force read
@@ -1341,15 +1384,14 @@ public class XMLParser
reset();
return false;
}
- tmpBuf[count++] = (char) c;
- }
- for (int i = 0; i < len; i++)
- {
- if (chars[i] != tmpBuf[i])
+ tmpBuf[count] = (char) c;
+ // check each character as it is read
+ if (chars[count] != tmpBuf[count])
{
reset();
return false;
}
+ count++;
}
return true;
}
@@ -4250,97 +4292,131 @@ public class XMLParser
public static void main(String[] args)
throws Exception
{
+ boolean validating = false;
+ boolean namespaceAware = false;
boolean xIncludeAware = false;
- if (args.length > 1 && "-x".equals(args[1]))
- xIncludeAware = true;
- XMLParser p = new XMLParser(new java.io.FileInputStream(args[0]),
- absolutize(null, args[0]),
- true, // validating
- true, // namespaceAware
- true, // coalescing,
- true, // replaceERefs
- true, // externalEntities
- true, // supportDTD
- true, // baseAware
- true, // stringInterning
- true, // extendedEventTypes
- null,
- null);
- XMLStreamReader reader = p;
- if (xIncludeAware)
- reader = new XIncludeFilter(p, args[0], true, true, true);
- try
+ int pos = 0;
+ while (pos < args.length && args[pos].startsWith("-"))
{
- int event;
- //do
- while (reader.hasNext())
+ if ("-x".equals(args[pos]))
+ xIncludeAware = true;
+ else if ("-v".equals(args[pos]))
+ validating = true;
+ else if ("-n".equals(args[pos]))
+ namespaceAware = true;
+ pos++;
+ }
+ if (pos >= args.length)
+ {
+ System.out.println("Syntax: XMLParser [-n] [-v] [-x] <file> [<file2> [...]]");
+ System.out.println("\t-n: use namespace aware mode");
+ System.out.println("\t-v: use validating parser");
+ System.out.println("\t-x: use XInclude aware mode");
+ System.exit(2);
+ }
+ while (pos < args.length)
+ {
+ XMLParser p = new XMLParser(new java.io.FileInputStream(args[pos]),
+ absolutize(null, args[pos]),
+ validating, // validating
+ namespaceAware, // namespaceAware
+ true, // coalescing,
+ true, // replaceERefs
+ true, // externalEntities
+ true, // supportDTD
+ true, // baseAware
+ true, // stringInterning
+ true, // extendedEventTypes
+ null,
+ null);
+ XMLStreamReader reader = p;
+ if (xIncludeAware)
+ reader = new XIncludeFilter(p, args[pos], true, true, true);
+ try
{
- event = reader.next();
- Location loc = reader.getLocation();
- System.out.print(loc.getLineNumber()+":"+loc.getColumnNumber()+" ");
- switch (event)
+ int event;
+ //do
+ while (reader.hasNext())
{
- case XMLStreamConstants.START_DOCUMENT:
- System.out.println("START_DOCUMENT version="+reader.getVersion()+
- " encoding="+reader.getEncoding());
- break;
- case XMLStreamConstants.END_DOCUMENT:
- System.out.println("END_DOCUMENT");
- break;
- case XMLStreamConstants.START_ELEMENT:
- System.out.println("START_ELEMENT "+reader.getName());
- int l = reader.getNamespaceCount();
- for (int i = 0; i < l; i++)
- System.out.println("\tnamespace "+reader.getNamespacePrefix(i)+
- "='"+reader.getNamespaceURI(i)+"'");
- l = reader.getAttributeCount();
- for (int i = 0; i < l; i++)
- System.out.println("\tattribute "+reader.getAttributeName(i)+
- "='"+reader.getAttributeValue(i)+"'");
- break;
- case XMLStreamConstants.END_ELEMENT:
- System.out.println("END_ELEMENT "+reader.getName());
- break;
- case XMLStreamConstants.CHARACTERS:
- System.out.println("CHARACTERS '"+encodeText(reader.getText())+"'");
- break;
- case XMLStreamConstants.CDATA:
- System.out.println("CDATA '"+encodeText(reader.getText())+"'");
- break;
- case XMLStreamConstants.SPACE:
- System.out.println("SPACE '"+encodeText(reader.getText())+"'");
- break;
- case XMLStreamConstants.DTD:
- System.out.println("DTD "+reader.getText());
- break;
- case XMLStreamConstants.ENTITY_REFERENCE:
- System.out.println("ENTITY_REFERENCE "+reader.getText());
- break;
- case XMLStreamConstants.COMMENT:
- System.out.println("COMMENT '"+encodeText(reader.getText())+"'");
- break;
- case XMLStreamConstants.PROCESSING_INSTRUCTION:
- System.out.println("PROCESSING_INSTRUCTION "+reader.getPITarget()+
- " "+reader.getPIData());
- break;
- case START_ENTITY:
- System.out.println("START_ENTITY "+reader.getText());
- break;
- case END_ENTITY:
- System.out.println("END_ENTITY "+reader.getText());
- break;
- default:
- System.out.println("Unknown event: "+event);
+ event = reader.next();
+ Location loc = reader.getLocation();
+ System.out.print(loc.getLineNumber() + ":" +
+ loc.getColumnNumber() + " ");
+ switch (event)
+ {
+ case XMLStreamConstants.START_DOCUMENT:
+ System.out.println("START_DOCUMENT version=" +
+ reader.getVersion() +
+ " encoding=" +
+ reader.getEncoding());
+ break;
+ case XMLStreamConstants.END_DOCUMENT:
+ System.out.println("END_DOCUMENT");
+ break;
+ case XMLStreamConstants.START_ELEMENT:
+ System.out.println("START_ELEMENT " +
+ reader.getName());
+ int l = reader.getNamespaceCount();
+ for (int i = 0; i < l; i++)
+ System.out.println("\tnamespace " +
+ reader.getNamespacePrefix(i) + "='" +
+ reader.getNamespaceURI(i)+"'");
+ l = reader.getAttributeCount();
+ for (int i = 0; i < l; i++)
+ System.out.println("\tattribute " +
+ reader.getAttributeName(i) + "='" +
+ reader.getAttributeValue(i) + "'");
+ break;
+ case XMLStreamConstants.END_ELEMENT:
+ System.out.println("END_ELEMENT " + reader.getName());
+ break;
+ case XMLStreamConstants.CHARACTERS:
+ System.out.println("CHARACTERS '" +
+ encodeText(reader.getText()) + "'");
+ break;
+ case XMLStreamConstants.CDATA:
+ System.out.println("CDATA '" +
+ encodeText(reader.getText()) + "'");
+ break;
+ case XMLStreamConstants.SPACE:
+ System.out.println("SPACE '" +
+ encodeText(reader.getText()) + "'");
+ break;
+ case XMLStreamConstants.DTD:
+ System.out.println("DTD " + reader.getText());
+ break;
+ case XMLStreamConstants.ENTITY_REFERENCE:
+ System.out.println("ENTITY_REFERENCE " + reader.getText());
+ break;
+ case XMLStreamConstants.COMMENT:
+ System.out.println("COMMENT '" +
+ encodeText(reader.getText()) + "'");
+ break;
+ case XMLStreamConstants.PROCESSING_INSTRUCTION:
+ System.out.println("PROCESSING_INSTRUCTION " +
+ reader.getPITarget() + " " +
+ reader.getPIData());
+ break;
+ case START_ENTITY:
+ System.out.println("START_ENTITY " + reader.getText());
+ break;
+ case END_ENTITY:
+ System.out.println("END_ENTITY " + reader.getText());
+ break;
+ default:
+ System.out.println("Unknown event: " + event);
+ }
}
}
- }
- catch (XMLStreamException e)
- {
- Location l = reader.getLocation();
- System.out.println("At line "+l.getLineNumber()+
- ", column "+l.getColumnNumber()+
- " of "+l.getSystemId());
- throw e;
+ catch (XMLStreamException e)
+ {
+ Location l = reader.getLocation();
+ System.out.println("At line "+l.getLineNumber()+
+ ", column "+l.getColumnNumber()+
+ " of "+l.getSystemId());
+ throw e;
+ }
+ pos++;
}
}
@@ -5039,7 +5115,6 @@ public class XMLParser
void mark(int len)
throws IOException
{
- //System.out.println(" mark:"+len);
markOffset = offset;
markLine = line;
markColumn = column;
@@ -5082,7 +5157,9 @@ public class XMLParser
{
int ret;
if (unicodeReader != null)
- ret = unicodeReader.read(b, off, len);
+ {
+ ret = unicodeReader.read(b, off, len);
+ }
else
{
byte[] b2 = new byte[len];
diff --git a/gnu/xml/transform/TransformerImpl.java b/gnu/xml/transform/TransformerImpl.java
index 6a0a5be16..732a911bd 100644
--- a/gnu/xml/transform/TransformerImpl.java
+++ b/gnu/xml/transform/TransformerImpl.java
@@ -238,7 +238,7 @@ class TransformerImpl
outputProperties.getProperty(OutputKeys.CDATA_SECTION_ELEMENTS);
boolean indent =
"yes".equals(outputProperties.getProperty(OutputKeys.INDENT));
- if (created)
+ if (created && parent instanceof DomDocument)
{
// Discover document element
DomDocument resultDoc = (DomDocument) parent;
@@ -320,7 +320,7 @@ class TransformerImpl
}
if (indent)
{
- if (created)
+ if (created && parent instanceof DomDocument)
{
DomDocument domDoc = (DomDocument) parent;
domDoc.setBuilding(true);
@@ -332,7 +332,7 @@ class TransformerImpl
(Document) parent :
parent.getOwnerDocument();
reindent(resultDoc, parent, 0);
- if (created)
+ if (created && parent instanceof DomDocument)
{
DomDocument domDoc = (DomDocument) parent;
domDoc.setBuilding(false);
@@ -576,6 +576,19 @@ class TransformerImpl
}
catch (IOException e)
{
+ if (errorListener != null)
+ {
+ try
+ {
+ errorListener.error(new TransformerException(e));
+ }
+ catch (TransformerException e2)
+ {
+ e2.printStackTrace(System.err);
+ }
+ }
+ else
+ e.printStackTrace(System.err);
}
}
}
diff --git a/include/Makefile.am b/include/Makefile.am
index 783ba18ee..5913f67ba 100644
--- a/include/Makefile.am
+++ b/include/Makefile.am
@@ -37,11 +37,16 @@ $(top_srcdir)/include/gnu_xml_libxmlj_transform_GnomeTransformer.h \
$(top_srcdir)/include/gnu_xml_libxmlj_transform_GnomeTransformerFactory.h
GTKPEER_H_FILES = \
+$(top_srcdir)/include/gnu_java_awt_peer_gtk_CairoSurface.h \
+$(top_srcdir)/include/gnu_java_awt_peer_gtk_CairoGraphics2D.h \
+$(top_srcdir)/include/gnu_java_awt_peer_gtk_ComponentGraphics.h \
+$(top_srcdir)/include/gnu_java_awt_peer_gtk_ComponentGraphicsCopy.h \
+$(top_srcdir)/include/gnu_java_awt_peer_gtk_FreetypeGlyphVector.h \
$(top_srcdir)/include/gnu_java_awt_peer_gtk_GdkFontPeer.h \
-$(top_srcdir)/include/gnu_java_awt_peer_gtk_GdkGraphics2D.h \
$(top_srcdir)/include/gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.h \
$(top_srcdir)/include/gnu_java_awt_peer_gtk_GdkPixbufDecoder.h \
$(top_srcdir)/include/gnu_java_awt_peer_gtk_GdkRobotPeer.h \
+$(top_srcdir)/include/gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.h \
$(top_srcdir)/include/gnu_java_awt_peer_gtk_GdkTextLayout.h \
$(top_srcdir)/include/gnu_java_awt_peer_gtk_GtkButtonPeer.h \
$(top_srcdir)/include/gnu_java_awt_peer_gtk_GtkCanvasPeer.h \
@@ -71,6 +76,7 @@ $(top_srcdir)/include/gnu_java_awt_peer_gtk_GtkTextAreaPeer.h \
$(top_srcdir)/include/gnu_java_awt_peer_gtk_GtkTextFieldPeer.h \
$(top_srcdir)/include/gnu_java_awt_peer_gtk_GtkToolkit.h \
$(top_srcdir)/include/gnu_java_awt_peer_gtk_GtkWindowPeer.h \
+$(top_srcdir)/include/gnu_java_awt_peer_gtk_GtkVolatileImage.h \
$(top_srcdir)/include/gnu_java_awt_peer_gtk_GThreadNativeMethodRunner.h
QTPEER_H_FILES = \
@@ -119,6 +125,7 @@ $(QTPEER_H_FILES) \
$(top_srcdir)/include/gnu_java_net_VMPlainDatagramSocketImpl.h \
$(top_srcdir)/include/gnu_java_net_VMPlainSocketImpl.h \
$(top_srcdir)/include/gnu_java_net_local_LocalSocketImpl.h \
+$(top_srcdir)/include/gnu_java_nio_VMChannel.h \
$(top_srcdir)/include/gnu_java_nio_VMPipe.h \
$(top_srcdir)/include/gnu_java_nio_VMSelector.h \
$(top_srcdir)/include/gnu_java_nio_channels_FileChannelImpl.h \
@@ -171,6 +178,8 @@ $(top_srcdir)/include/gnu_java_net_VMPlainSocketImpl.h: $(top_srcdir)/vm/referen
$(JAVAH) -o $@ gnu.java.net.VMPlainSocketImpl
$(top_srcdir)/include/gnu_java_net_local_LocalSocketImpl.h: $(top_srcdir)/gnu/java/net/local/LocalSocketImpl.java
$(JAVAH) -o $@ gnu.java.net.local.LocalSocketImpl
+$(top_srcdir)/include/gnu_java_nio_VMChannel.h: $(top_srcdir)/vm/reference/gnu/java/nio/VMChannel.java
+ $(JAVAH) -o $@ gnu.java.nio.VMChannel
$(top_srcdir)/include/gnu_java_nio_VMPipe.h: $(top_srcdir)/vm/reference/gnu/java/nio/VMPipe.java
$(JAVAH) -o $@ gnu.java.nio.VMPipe
$(top_srcdir)/include/gnu_java_nio_VMSelector.h: $(top_srcdir)/vm/reference/gnu/java/nio/VMSelector.java
diff --git a/include/gnu_java_awt_peer_gtk_CairoGraphics2D.h b/include/gnu_java_awt_peer_gtk_CairoGraphics2D.h
new file mode 100644
index 000000000..7a20949ed
--- /dev/null
+++ b/include/gnu_java_awt_peer_gtk_CairoGraphics2D.h
@@ -0,0 +1,45 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */
+
+#ifndef __gnu_java_awt_peer_gtk_CairoGraphics2D__
+#define __gnu_java_awt_peer_gtk_CairoGraphics2D__
+
+#include <jni.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+JNIEXPORT jlong JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_init (JNIEnv *env, jobject, jlong);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_disposeNative (JNIEnv *env, jobject, jlong);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_drawPixels (JNIEnv *env, jobject, jlong, jintArray, jint, jint, jint, jdoubleArray);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_setGradient (JNIEnv *env, jobject, jlong, jdouble, jdouble, jdouble, jdouble, jint, jint, jint, jint, jint, jint, jint, jint, jboolean);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_setTexturePixels (JNIEnv *env, jobject, jlong, jintArray, jint, jint, jint);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSetMatrix (JNIEnv *env, jobject, jlong, jdoubleArray);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSetOperator (JNIEnv *env, jobject, jlong, jint);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSetRGBAColor (JNIEnv *env, jobject, jlong, jdouble, jdouble, jdouble, jdouble);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSetFillRule (JNIEnv *env, jobject, jlong, jint);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSetLine (JNIEnv *env, jobject, jlong, jdouble, jint, jint, jdouble);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSetDash (JNIEnv *env, jobject, jlong, jdoubleArray, jint, jdouble);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoDrawGlyphVector (JNIEnv *env, jobject, jlong, jobject, jfloat, jfloat, jint, jintArray, jfloatArray);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoRelCurveTo (JNIEnv *env, jobject, jlong, jdouble, jdouble, jdouble, jdouble, jdouble, jdouble);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoRectangle (JNIEnv *env, jobject, jlong, jdouble, jdouble, jdouble, jdouble);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoNewPath (JNIEnv *env, jobject, jlong);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoClosePath (JNIEnv *env, jobject, jlong);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoMoveTo (JNIEnv *env, jobject, jlong, jdouble, jdouble);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoRelMoveTo (JNIEnv *env, jobject, jlong, jdouble, jdouble);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoLineTo (JNIEnv *env, jobject, jlong, jdouble, jdouble);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoRelLineTo (JNIEnv *env, jobject, jlong, jdouble, jdouble);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoCurveTo (JNIEnv *env, jobject, jlong, jdouble, jdouble, jdouble, jdouble, jdouble, jdouble);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoStroke (JNIEnv *env, jobject, jlong);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoFill (JNIEnv *env, jobject, jlong);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoClip (JNIEnv *env, jobject, jlong);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoPreserveClip (JNIEnv *env, jobject, jlong);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoResetClip (JNIEnv *env, jobject, jlong);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSurfaceSetFilter (JNIEnv *env, jobject, jlong, jint);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __gnu_java_awt_peer_gtk_CairoGraphics2D__ */
diff --git a/include/gnu_java_awt_peer_gtk_CairoSurface.h b/include/gnu_java_awt_peer_gtk_CairoSurface.h
new file mode 100644
index 000000000..8899349e1
--- /dev/null
+++ b/include/gnu_java_awt_peer_gtk_CairoSurface.h
@@ -0,0 +1,28 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */
+
+#ifndef __gnu_java_awt_peer_gtk_CairoSurface__
+#define __gnu_java_awt_peer_gtk_CairoSurface__
+
+#include <jni.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoSurface_create (JNIEnv *env, jobject, jint, jint, jint);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoSurface_destroy (JNIEnv *env, jobject, jlong, jlong);
+JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_gtk_CairoSurface_nativeGetElem (JNIEnv *env, jobject, jlong, jint);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoSurface_nativeSetElem (JNIEnv *env, jobject, jlong, jint, jint);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoSurface_nativeDrawSurface (JNIEnv *env, jobject, jlong, jlong, jdoubleArray);
+JNIEXPORT jintArray JNICALL Java_gnu_java_awt_peer_gtk_CairoSurface_nativeGetPixels (JNIEnv *env, jobject, jlong, jint);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoSurface_nativeSetPixels (JNIEnv *env, jobject, jlong, jintArray);
+JNIEXPORT jlong JNICALL Java_gnu_java_awt_peer_gtk_CairoSurface_getFlippedBuffer (JNIEnv *env, jobject, jlong, jint);
+JNIEXPORT jlong JNICALL Java_gnu_java_awt_peer_gtk_CairoSurface_nativeNewCairoContext (JNIEnv *env, jobject, jlong);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_CairoSurface_copyAreaNative2 (JNIEnv *env, jobject, jlong, jint, jint, jint, jint, jint, jint, jint);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __gnu_java_awt_peer_gtk_CairoSurface__ */
diff --git a/include/gnu_java_awt_peer_gtk_ComponentGraphics.h b/include/gnu_java_awt_peer_gtk_ComponentGraphics.h
new file mode 100644
index 000000000..4fd597eff
--- /dev/null
+++ b/include/gnu_java_awt_peer_gtk_ComponentGraphics.h
@@ -0,0 +1,26 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */
+
+#ifndef __gnu_java_awt_peer_gtk_ComponentGraphics__
+#define __gnu_java_awt_peer_gtk_ComponentGraphics__
+
+#include <jni.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+JNIEXPORT jlong JNICALL Java_gnu_java_awt_peer_gtk_ComponentGraphics_initState (JNIEnv *env, jobject, jobject);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_ComponentGraphics_disposeSurface (JNIEnv *env, jobject, jlong);
+JNIEXPORT jlong JNICALL Java_gnu_java_awt_peer_gtk_ComponentGraphics_initFromVolatile (JNIEnv *env, jobject, jlong, jint, jint);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_ComponentGraphics_start_1gdk_1drawing (JNIEnv *env, jobject);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_ComponentGraphics_end_1gdk_1drawing (JNIEnv *env, jobject);
+JNIEXPORT jboolean JNICALL Java_gnu_java_awt_peer_gtk_ComponentGraphics_hasXRender (JNIEnv *env, jclass);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_ComponentGraphics_copyAreaNative (JNIEnv *env, jobject, jobject, jint, jint, jint, jint, jint, jint);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_ComponentGraphics_drawVolatile (JNIEnv *env, jobject, jobject, jlong, jint, jint, jint, jint);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __gnu_java_awt_peer_gtk_ComponentGraphics__ */
diff --git a/include/gnu_java_awt_peer_gtk_ComponentGraphicsCopy.h b/include/gnu_java_awt_peer_gtk_ComponentGraphicsCopy.h
new file mode 100644
index 000000000..8e4b2cdb3
--- /dev/null
+++ b/include/gnu_java_awt_peer_gtk_ComponentGraphicsCopy.h
@@ -0,0 +1,20 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */
+
+#ifndef __gnu_java_awt_peer_gtk_ComponentGraphicsCopy__
+#define __gnu_java_awt_peer_gtk_ComponentGraphicsCopy__
+
+#include <jni.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_ComponentGraphicsCopy_getPixbuf (JNIEnv *env, jobject, jobject, jobject);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_ComponentGraphicsCopy_copyPixbuf (JNIEnv *env, jobject, jobject, jobject, jint, jint, jint, jint);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __gnu_java_awt_peer_gtk_ComponentGraphicsCopy__ */
diff --git a/include/gnu_java_awt_peer_gtk_FreetypeGlyphVector.h b/include/gnu_java_awt_peer_gtk_FreetypeGlyphVector.h
new file mode 100644
index 000000000..10a4ea5e5
--- /dev/null
+++ b/include/gnu_java_awt_peer_gtk_FreetypeGlyphVector.h
@@ -0,0 +1,22 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */
+
+#ifndef __gnu_java_awt_peer_gtk_FreetypeGlyphVector__
+#define __gnu_java_awt_peer_gtk_FreetypeGlyphVector__
+
+#include <jni.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+JNIEXPORT jintArray JNICALL Java_gnu_java_awt_peer_gtk_FreetypeGlyphVector_getGlyphs (JNIEnv *env, jobject, jintArray);
+JNIEXPORT jobject JNICALL Java_gnu_java_awt_peer_gtk_FreetypeGlyphVector_getKerning (JNIEnv *env, jobject, jint, jint);
+JNIEXPORT jdoubleArray JNICALL Java_gnu_java_awt_peer_gtk_FreetypeGlyphVector_getMetricsNative (JNIEnv *env, jobject, jint);
+JNIEXPORT jobject JNICALL Java_gnu_java_awt_peer_gtk_FreetypeGlyphVector_getGlyphOutlineNative (JNIEnv *env, jobject, jint);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __gnu_java_awt_peer_gtk_FreetypeGlyphVector__ */
diff --git a/include/gnu_java_awt_peer_gtk_GdkFontPeer.h b/include/gnu_java_awt_peer_gtk_GdkFontPeer.h
index 745be47d6..3b9ddd443 100644
--- a/include/gnu_java_awt_peer_gtk_GdkFontPeer.h
+++ b/include/gnu_java_awt_peer_gtk_GdkFontPeer.h
@@ -16,8 +16,8 @@ JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkFontPeer_dispose (JNIEnv *e
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkFontPeer_setFont (JNIEnv *env, jobject, jstring, jint, jint);
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkFontPeer_getFontMetrics (JNIEnv *env, jobject, jdoubleArray);
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkFontPeer_getTextMetrics (JNIEnv *env, jobject, jstring, jdoubleArray);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkFontPeer_releasePeerGraphicsResource (JNIEnv *env, jobject);
JNIEXPORT jbyteArray JNICALL Java_gnu_java_awt_peer_gtk_GdkFontPeer_getTrueTypeTable (JNIEnv *env, jobject, jbyte, jbyte, jbyte, jbyte);
-JNIEXPORT jobject JNICALL Java_gnu_java_awt_peer_gtk_GdkFontPeer_getGlyphVector (JNIEnv *env, jobject, jstring, jobject, jobject);
#ifdef __cplusplus
}
diff --git a/include/gnu_java_awt_peer_gtk_GdkGraphics2D.h b/include/gnu_java_awt_peer_gtk_GdkGraphics2D.h
deleted file mode 100644
index 6bf66b7aa..000000000
--- a/include/gnu_java_awt_peer_gtk_GdkGraphics2D.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/* DO NOT EDIT THIS FILE - it is machine generated */
-
-#ifndef __gnu_java_awt_peer_gtk_GdkGraphics2D__
-#define __gnu_java_awt_peer_gtk_GdkGraphics2D__
-
-#include <jni.h>
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_initStaticState (JNIEnv *env, jclass);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_initState__Lgnu_java_awt_peer_gtk_GtkComponentPeer_2 (JNIEnv *env, jobject, jobject);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_initState__II (JNIEnv *env, jobject, jint, jint);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_initState___3III (JNIEnv *env, jobject, jintArray, jint, jint);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_copyState (JNIEnv *env, jobject, jobject);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_dispose (JNIEnv *env, jobject);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSurfaceSetFilter (JNIEnv *env, jobject, jint);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_gdkDrawDrawable (JNIEnv *env, jobject, jobject, jint, jint);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_drawPixels (JNIEnv *env, jobject, jintArray, jint, jint, jint, jdoubleArray);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_setTexturePixels (JNIEnv *env, jobject, jintArray, jint, jint, jint);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_setGradient (JNIEnv *env, jobject, jdouble, jdouble, jdouble, jdouble, jint, jint, jint, jint, jint, jint, jint, jint, jboolean);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSave (JNIEnv *env, jobject);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoRestore (JNIEnv *env, jobject);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetMatrix (JNIEnv *env, jobject, jdoubleArray);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetOperator (JNIEnv *env, jobject, jint);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetRGBAColor (JNIEnv *env, jobject, jdouble, jdouble, jdouble, jdouble);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetFillRule (JNIEnv *env, jobject, jint);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetLineWidth (JNIEnv *env, jobject, jdouble);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetLineCap (JNIEnv *env, jobject, jint);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetLineJoin (JNIEnv *env, jobject, jint);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetDash (JNIEnv *env, jobject, jdoubleArray, jint, jdouble);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetMiterLimit (JNIEnv *env, jobject, jdouble);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoNewPath (JNIEnv *env, jobject);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoMoveTo (JNIEnv *env, jobject, jdouble, jdouble);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoLineTo (JNIEnv *env, jobject, jdouble, jdouble);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoCurveTo (JNIEnv *env, jobject, jdouble, jdouble, jdouble, jdouble, jdouble, jdouble);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoRelMoveTo (JNIEnv *env, jobject, jdouble, jdouble);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoRelLineTo (JNIEnv *env, jobject, jdouble, jdouble);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoRelCurveTo (JNIEnv *env, jobject, jdouble, jdouble, jdouble, jdouble, jdouble, jdouble);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoRectangle (JNIEnv *env, jobject, jdouble, jdouble, jdouble, jdouble);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoClosePath (JNIEnv *env, jobject);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoStroke (JNIEnv *env, jobject);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoFill (JNIEnv *env, jobject);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoClip (JNIEnv *env, jobject);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoDrawGlyphVector (JNIEnv *env, jobject, jobject, jfloat, jfloat, jint, jintArray, jfloatArray);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoDrawGdkTextLayout (JNIEnv *env, jobject, jobject, jfloat, jfloat);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphics2D_releasePeerGraphicsResource (JNIEnv *env, jclass, jobject);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __gnu_java_awt_peer_gtk_GdkGraphics2D__ */
diff --git a/include/gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.h b/include/gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.h
index 60f7af423..2a619c609 100644
--- a/include/gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.h
+++ b/include/gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.h
@@ -10,6 +10,10 @@ extern "C"
{
#endif
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment_initStaticState (JNIEnv *env, jclass);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment_nativeInitState (JNIEnv *env, jobject);
+JNIEXPORT jobjectArray JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment_nativeGetScreenDevices (JNIEnv *env, jobject);
+JNIEXPORT jobject JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment_nativeGetDefaultScreenDevice (JNIEnv *env, jobject);
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment_nativeGetNumFontFamilies (JNIEnv *env, jobject);
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment_nativeGetFontFamilies (JNIEnv *env, jobject, jobjectArray);
diff --git a/include/gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.h b/include/gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.h
new file mode 100644
index 000000000..8037af082
--- /dev/null
+++ b/include/gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.h
@@ -0,0 +1,26 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */
+
+#ifndef __gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice__
+#define __gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice__
+
+#include <jni.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_initStaticState (JNIEnv *env, jclass);
+JNIEXPORT jobject JNICALL Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_nativeGetFixedDisplayMode (JNIEnv *env, jobject, jobject);
+JNIEXPORT jstring JNICALL Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_nativeGetIDString (JNIEnv *env, jobject);
+JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_nativeGetDisplayModeIndex (JNIEnv *env, jobject, jobject);
+JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_nativeGetDisplayModeRate (JNIEnv *env, jobject, jobject);
+JNIEXPORT jobjectArray JNICALL Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_nativeGetDisplayModes (JNIEnv *env, jobject, jobject);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_nativeSetDisplayMode (JNIEnv *env, jobject, jobject, jint, jshort);
+JNIEXPORT jobject JNICALL Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_nativeGetBounds (JNIEnv *env, jobject);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice__ */
diff --git a/include/gnu_java_awt_peer_gtk_GdkTextLayout.h b/include/gnu_java_awt_peer_gtk_GdkTextLayout.h
index c74a574e7..fae4d775b 100644
--- a/include/gnu_java_awt_peer_gtk_GdkTextLayout.h
+++ b/include/gnu_java_awt_peer_gtk_GdkTextLayout.h
@@ -11,10 +11,12 @@ extern "C"
#endif
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkTextLayout_setText (JNIEnv *env, jobject, jstring);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkTextLayout_setFont (JNIEnv *env, jobject, jobject);
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkTextLayout_getExtents (JNIEnv *env, jobject, jdoubleArray, jdoubleArray);
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkTextLayout_indexToPos (JNIEnv *env, jobject, jint, jdoubleArray);
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkTextLayout_initState (JNIEnv *env, jobject);
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkTextLayout_dispose (JNIEnv *env, jobject);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkTextLayout_cairoDrawGdkTextLayout (JNIEnv *env, jobject, jlong, jfloat, jfloat);
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkTextLayout_initStaticState (JNIEnv *env, jclass);
JNIEXPORT jobject JNICALL Java_gnu_java_awt_peer_gtk_GdkTextLayout_getOutline (JNIEnv *env, jobject, jobject);
diff --git a/include/gnu_java_awt_peer_gtk_GtkImage.h b/include/gnu_java_awt_peer_gtk_GtkImage.h
index 48940a1ca..0ea798bc2 100644
--- a/include/gnu_java_awt_peer_gtk_GtkImage.h
+++ b/include/gnu_java_awt_peer_gtk_GtkImage.h
@@ -10,15 +10,14 @@ extern "C"
{
#endif
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GtkImage_initFromBuffer (JNIEnv *env, jobject, jlong);
JNIEXPORT jintArray JNICALL Java_gnu_java_awt_peer_gtk_GtkImage_getPixels (JNIEnv *env, jobject);
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GtkImage_setPixels (JNIEnv *env, jobject, jintArray);
JNIEXPORT jboolean JNICALL Java_gnu_java_awt_peer_gtk_GtkImage_loadPixbuf (JNIEnv *env, jobject, jstring);
JNIEXPORT jboolean JNICALL Java_gnu_java_awt_peer_gtk_GtkImage_loadImageFromData (JNIEnv *env, jobject, jbyteArray);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GtkImage_createPixmap (JNIEnv *env, jobject);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GtkImage_freePixmap (JNIEnv *env, jobject);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GtkImage_createScaledPixmap (JNIEnv *env, jobject, jobject, jint);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GtkImage_drawPixelsScaled (JNIEnv *env, jobject, jobject, jint, jint, jint, jint, jint, jint, jint, jboolean);
-JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GtkImage_drawPixelsScaledFlipped (JNIEnv *env, jobject, jobject, jint, jint, jint, jboolean, jboolean, jint, jint, jint, jint, jint, jint, jint, jint, jboolean);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GtkImage_createPixbuf (JNIEnv *env, jobject);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GtkImage_freePixbuf (JNIEnv *env, jobject);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GtkImage_createScaledPixbuf (JNIEnv *env, jobject, jobject, jint);
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GtkImage_createFromPixbuf (JNIEnv *env, jobject);
#ifdef __cplusplus
diff --git a/include/gnu_java_awt_peer_gtk_GtkVolatileImage.h b/include/gnu_java_awt_peer_gtk_GtkVolatileImage.h
new file mode 100644
index 000000000..43b55e828
--- /dev/null
+++ b/include/gnu_java_awt_peer_gtk_GtkVolatileImage.h
@@ -0,0 +1,23 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */
+
+#ifndef __gnu_java_awt_peer_gtk_GtkVolatileImage__
+#define __gnu_java_awt_peer_gtk_GtkVolatileImage__
+
+#include <jni.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+JNIEXPORT jlong JNICALL Java_gnu_java_awt_peer_gtk_GtkVolatileImage_init (JNIEnv *env, jobject, jobject, jint, jint);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GtkVolatileImage_destroy (JNIEnv *env, jobject, jlong);
+JNIEXPORT jintArray JNICALL Java_gnu_java_awt_peer_gtk_GtkVolatileImage_nativeGetPixels (JNIEnv *env, jobject, jlong);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GtkVolatileImage_nativeCopyArea (JNIEnv *env, jobject, jlong, jint, jint, jint, jint, jint, jint);
+JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GtkVolatileImage_nativeDrawVolatile (JNIEnv *env, jobject, jlong, jlong, jint, jint, jint, jint);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __gnu_java_awt_peer_gtk_GtkVolatileImage__ */
diff --git a/include/java_io_VMFile.h b/include/java_io_VMFile.h
index 0ab188fb0..fa1079f12 100644
--- a/include/java_io_VMFile.h
+++ b/include/java_io_VMFile.h
@@ -24,6 +24,7 @@ JNIEXPORT jboolean JNICALL Java_java_io_VMFile_isFile (JNIEnv *env, jclass, jstr
JNIEXPORT jboolean JNICALL Java_java_io_VMFile_canWrite (JNIEnv *env, jclass, jstring);
JNIEXPORT jboolean JNICALL Java_java_io_VMFile_canRead (JNIEnv *env, jclass, jstring);
JNIEXPORT jboolean JNICALL Java_java_io_VMFile_isDirectory (JNIEnv *env, jclass, jstring);
+JNIEXPORT jstring JNICALL Java_java_io_VMFile_toCanonicalForm (JNIEnv *env, jclass, jstring);
#undef java_io_VMFile_IS_CASE_SENSITIVE
#define java_io_VMFile_IS_CASE_SENSITIVE 1L
#undef java_io_VMFile_IS_DOS_8_3
diff --git a/include/jni.h b/include/jni.h
index 8ebf3f7f7..3a0d9c31e 100644
--- a/include/jni.h
+++ b/include/jni.h
@@ -1,5 +1,5 @@
/* jni.h
- Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005 Free Software Foundation
+ Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006 Free Software Foundation
This file is part of GNU Classpath.
@@ -1584,6 +1584,45 @@ typedef struct JavaVMInitArgs
jboolean ignoreUnrecognized;
} JavaVMInitArgs;
+typedef struct JDK1_1InitArgs
+{
+ /* VM version. Should be JNI_VERSION_1_1. Note that before JDK
+ 1.1.2, this field was named 'reserved0'. (I don't know what the
+ current 'reserved0' field was named then.) */
+ jint version;
+
+ /* A null-terminated array of environment strings, each of the form
+ "KEY=VALUE". This is used to set system properties. Note that
+ before JDK 1.1.2, this field was named 'reserved1'. */
+ char **properties;
+
+ jint checkSource;
+ jint nativeStackSize;
+ jint javaStackSize;
+ jint minHeapSize;
+ jint maxHeapSize;
+ jint verifyMode;
+ const char *classpath;
+
+ jint (JNICALL *vfprintf) (FILE *file, const char *fmt, va_list args);
+ void (JNICALL *exit) (jint value);
+ void (JNICALL *abort) (void);
+
+ jint enableClassGC;
+ jint enableVerboseGC;
+ jint disableAsyncGC;
+
+ jint reserved0;
+ jint reserved1;
+ jint reserved2;
+} JDK1_1InitArgs;
+
+typedef struct JDK1_1AttachArgs
+{
+ /* Dummy field since C cannot have empty structs. The name and type
+ are chosen to comply with the spec. */
+ void *__padding;
+} JDK1_1AttachArgs;
/* Keep c-font-lock-extra-types in alphabetical order. */
diff --git a/java/awt/Component.java b/java/awt/Component.java
index dcebc7403..65ac80373 100644
--- a/java/awt/Component.java
+++ b/java/awt/Component.java
@@ -2067,11 +2067,9 @@ public abstract class Component
*/
public VolatileImage createVolatileImage(int width, int height)
{
- if (GraphicsEnvironment.isHeadless())
- return null;
- GraphicsConfiguration config = getGraphicsConfiguration();
- return config == null ? null
- : config.createCompatibleVolatileImage(width, height);
+ if (peer != null)
+ return peer.createVolatileImage(width, height);
+ return null;
}
/**
@@ -2090,11 +2088,9 @@ public abstract class Component
ImageCapabilities caps)
throws AWTException
{
- if (GraphicsEnvironment.isHeadless())
- return null;
- GraphicsConfiguration config = getGraphicsConfiguration();
- return config == null ? null
- : config.createCompatibleVolatileImage(width, height, caps);
+ if (peer != null)
+ return peer.createVolatileImage(width, height);
+ return null;
}
/**
@@ -4811,8 +4807,38 @@ p * <li>the set of backward traversal keys
{
Object target = e.getSource ();
Event translated = null;
+
+ if (e instanceof WindowEvent)
+ {
+ WindowEvent we = (WindowEvent) e;
+ int id = we.id;
+ int newId = 0;
+
+ switch (id)
+ {
+ case WindowEvent.WINDOW_DEICONIFIED:
+ newId = Event.WINDOW_DEICONIFY;
+ break;
+ case WindowEvent.WINDOW_CLOSED:
+ case WindowEvent.WINDOW_CLOSING:
+ newId = Event.WINDOW_DESTROY;
+ break;
+ case WindowEvent.WINDOW_ICONIFIED:
+ newId = Event.WINDOW_ICONIFY;
+ break;
+ case WindowEvent.WINDOW_GAINED_FOCUS:
+ newId = Event.GOT_FOCUS;
+ break;
+ case WindowEvent.WINDOW_LOST_FOCUS:
+ newId = Event.LOST_FOCUS;
+ break;
+ default:
+ return null;
+ }
- if (e instanceof InputEvent)
+ translated = new Event(target, 0, newId, 0, 0, 0, 0);
+ }
+ else if (e instanceof InputEvent)
{
InputEvent ie = (InputEvent) e;
long when = ie.getWhen ();
diff --git a/java/awt/Container.java b/java/awt/Container.java
index c2c0d7f1d..f145d5696 100644
--- a/java/awt/Container.java
+++ b/java/awt/Container.java
@@ -458,8 +458,44 @@ public class Container extends Component
{
synchronized (getTreeLock ())
{
- while (ncomponents > 0)
- remove(0);
+ // In order to allow the same bad tricks to be used as in RI
+ // this code has to stay exactly that way: In a real-life app
+ // a Container subclass implemented its own vector for
+ // subcomponents, supplied additional addXYZ() methods
+ // and overrode remove(int) and removeAll (the latter calling
+ // super.removeAll() ).
+ // By doing it this way, user code cannot prevent the correct
+ // removal of components.
+ for ( int index = 0; index < ncomponents; index++)
+ {
+ Component r = component[index];
+
+ ComponentListener[] list = r.getComponentListeners();
+ for (int j = 0; j < list.length; j++)
+ r.removeComponentListener(list[j]);
+
+ r.removeNotify();
+
+ if (layoutMgr != null)
+ layoutMgr.removeLayoutComponent(r);
+
+ r.parent = null;
+
+ if (isShowing ())
+ {
+ // Post event to notify of removing the component.
+ ContainerEvent ce
+ = new ContainerEvent(this,
+ ContainerEvent.COMPONENT_REMOVED,
+ r);
+
+ getToolkit().getSystemEventQueue().postEvent(ce);
+ }
+ }
+
+ invalidate();
+
+ ncomponents = 0;
}
}
diff --git a/java/awt/DefaultKeyboardFocusManager.java b/java/awt/DefaultKeyboardFocusManager.java
index a60cefd9c..037cb834c 100644
--- a/java/awt/DefaultKeyboardFocusManager.java
+++ b/java/awt/DefaultKeyboardFocusManager.java
@@ -274,10 +274,12 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager
public boolean dispatchKeyEvent (KeyEvent e)
{
- Component focusOwner = getGlobalPermanentFocusOwner ();
-
+ Component focusOwner = getFocusOwner();
+ if (focusOwner == null)
+ focusOwner = getFocusedWindow();
+
if (focusOwner != null)
- redispatchEvent(focusOwner, e);
+ redispatchEvent(focusOwner, e);
// Loop through all registered KeyEventPostProcessors, giving
// each a chance to process this event.
@@ -294,7 +296,7 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager
// MenuShortcut.
if (postProcessKeyEvent (e))
return true;
-
+
// Always return true.
return true;
}
diff --git a/java/awt/LightweightDispatcher.java b/java/awt/LightweightDispatcher.java
index 3be18910b..7e33bd4e9 100644
--- a/java/awt/LightweightDispatcher.java
+++ b/java/awt/LightweightDispatcher.java
@@ -38,8 +38,6 @@ exception statement from your version. */
package java.awt;
-import gnu.java.awt.AWTUtilities;
-
import java.awt.event.MouseEvent;
import java.util.WeakHashMap;
@@ -147,11 +145,11 @@ class LightweightDispatcher
return false;
Container parent = deepest.getParent();
Point loc = ev.getPoint();
- loc = AWTUtilities.convertPoint(window, loc.x, loc.y, parent);
+ loc = convertPointToChild(window, loc, parent);
Component target = null;
if (parent != null)
{
- target = findTarget(deepest.getParent(), loc);
+ target = findTarget(parent, loc);
while (target == null && parent != null)
{
if (parent.getMouseListeners().length > 0
@@ -171,8 +169,8 @@ class LightweightDispatcher
{
if (lastTarget != null)
{
- Point p1 = AWTUtilities.convertPoint(window, ev.getX(),
- ev.getY(), lastTarget);
+ Point p1 = convertPointToChild(window, ev.getPoint(),
+ lastTarget);
MouseEvent mouseExited =
new MouseEvent(lastTarget, MouseEvent.MOUSE_EXITED,
ev.getWhen(), ev.getModifiers(), p1.x, p1.y,
@@ -190,8 +188,7 @@ class LightweightDispatcher
// button.
if (target != null && (dragTarget == null || dragTarget == target))
{
- Point p = AWTUtilities.convertPoint(window, ev.getX(), ev.getY(),
- target);
+ Point p = convertPointToChild(window, ev.getPoint(), target);
MouseEvent mouseEntered =
new MouseEvent(target, MouseEvent.MOUSE_ENTERED, ev.getWhen(),
ev.getModifiers(), p.x, p.y, ev.getClickCount(),
@@ -254,8 +251,9 @@ class LightweightDispatcher
if (target != null)
{
- Point targetCoordinates =
- AWTUtilities.convertPoint(window, ev.getX(), ev.getY(), target);
+ Point targetCoordinates = convertPointToChild(window,
+ ev.getPoint(),
+ target);
int dx = targetCoordinates.x - ev.getX();
int dy = targetCoordinates.y - ev.getY();
ev.translatePoint(dx, dy);
@@ -293,20 +291,49 @@ class LightweightDispatcher
Component target = null;
if (c != null)
{
- Point childLoc;
for (int i = 0; i < children.length; i++)
{
Component child = children[i];
- childLoc = AWTUtilities.convertPoint(c, loc.x, loc.y, child);
- if (child.isShowing() && child.contains(childLoc)
- && (child.getMouseListeners().length > 0
- || child.getMouseMotionListeners().length > 0))
+ if (child.isShowing())
{
- target = child;
- break;
+ if (child.contains(loc.x - child.getX(), loc.y - child.getY())
+ && (child.getMouseListeners().length > 0
+ || child.getMouseMotionListeners().length > 0))
+ {
+ target = child;
+ break;
+ }
}
}
}
return target;
}
+
+ /**
+ * Converts a point in the parent's coordinate system to a child coordinate
+ * system. The resulting point is stored in the same Point object and
+ * returned.
+ *
+ * @param parent the parent component
+ * @param p the point
+ * @param child the child component
+ *
+ * @return the translated point
+ */
+ private Point convertPointToChild(Component parent, Point p,
+ Component child)
+ {
+ int offX = 0;
+ int offY = 0;
+ Component comp = child;
+ while (comp != null && comp != parent)
+ {
+ offX += comp.getX();
+ offY += comp.getY();
+ comp = comp.getParent();
+ }
+ p.x -= offX;
+ p.y -= offY;
+ return p;
+ }
}
diff --git a/java/awt/TexturePaint.java b/java/awt/TexturePaint.java
index 39cc892a6..387ccb0fd 100644
--- a/java/awt/TexturePaint.java
+++ b/java/awt/TexturePaint.java
@@ -38,7 +38,7 @@ exception statement from your version. */
package java.awt;
-import gnu.classpath.NotImplementedException;
+import gnu.java.awt.java2d.TexturePaintContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
@@ -100,10 +100,10 @@ public class TexturePaint implements Paint
public PaintContext createContext(ColorModel cm, Rectangle deviceBounds,
Rectangle2D userBounds,
AffineTransform xform, RenderingHints hints)
- throws NotImplementedException
{
- // FIXME: Not implemented.
- return null;
+ // TODO: Maybe add some hook for providing alternative/accelerated
+ // implementations of this.
+ return new TexturePaintContext(this, deviceBounds, userBounds, xform);
}
/**
diff --git a/java/awt/Window.java b/java/awt/Window.java
index 4861dd0a4..b9661f1de 100644
--- a/java/awt/Window.java
+++ b/java/awt/Window.java
@@ -38,11 +38,8 @@ exception statement from your version. */
package java.awt;
-import gnu.classpath.NotImplementedException;
-
import java.awt.event.ComponentEvent;
import java.awt.event.FocusEvent;
-import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
diff --git a/java/awt/datatransfer/DataFlavor.java b/java/awt/datatransfer/DataFlavor.java
index e8632cf61..33b98379c 100644
--- a/java/awt/datatransfer/DataFlavor.java
+++ b/java/awt/datatransfer/DataFlavor.java
@@ -38,6 +38,8 @@ exception statement from your version. */
package java.awt.datatransfer;
+import gnu.classpath.NotImplementedException;
+
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -785,7 +787,8 @@ public class DataFlavor implements java.io.Externalizable, Cloneable
*
* @exception IOException If an error occurs.
*/
- public void writeExternal(ObjectOutput stream) throws IOException
+ public void writeExternal(ObjectOutput stream)
+ throws IOException, NotImplementedException
{
// FIXME: Implement me
}
@@ -801,7 +804,7 @@ public class DataFlavor implements java.io.Externalizable, Cloneable
* cannot be found.
*/
public void readExternal(ObjectInput stream)
- throws IOException, ClassNotFoundException
+ throws IOException, ClassNotFoundException, NotImplementedException
{
// FIXME: Implement me
}
diff --git a/java/awt/dnd/DropTargetContext.java b/java/awt/dnd/DropTargetContext.java
index 37cbb3fe0..aade755da 100644
--- a/java/awt/dnd/DropTargetContext.java
+++ b/java/awt/dnd/DropTargetContext.java
@@ -1,5 +1,5 @@
/* DropTargetContext.java --
- Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation
+ Copyright (C) 2002, 2003, 2004, 2005, 2006 Free Software Foundation
This file is part of GNU Classpath.
@@ -37,6 +37,8 @@ exception statement from your version. */
package java.awt.dnd;
+import gnu.classpath.NotImplementedException;
+
import java.awt.Component;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
@@ -60,23 +62,23 @@ public class DropTargetContext implements Serializable
protected boolean isLocal;
protected Transferable transferable;
- TransferableProxy (Transferable t, boolean local)
+ TransferableProxy(Transferable t, boolean local)
{
this.transferable = t;
this.isLocal = local;
}
- public DataFlavor[] getTransferDataFlavors ()
+ public DataFlavor[] getTransferDataFlavors()
{
- return transferable.getTransferDataFlavors ();
+ return transferable.getTransferDataFlavors();
}
- public boolean isDataFlavorSupported (DataFlavor flavor)
+ public boolean isDataFlavorSupported(DataFlavor flavor)
{
- return transferable.isDataFlavorSupported (flavor);
+ return transferable.isDataFlavorSupported(flavor);
}
- public Object getTransferData (DataFlavor flavor)
+ public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException
{
return transferable.getTransferData (flavor);
@@ -88,32 +90,32 @@ public class DropTargetContext implements Serializable
private java.awt.dnd.peer.DropTargetContextPeer dtcp;
// package private
- DropTargetContext (DropTarget dropTarget)
+ DropTargetContext(DropTarget dropTarget)
{
this.dropTarget = dropTarget;
}
- public DropTarget getDropTarget ()
+ public DropTarget getDropTarget()
{
return dropTarget;
}
- public Component getComponent ()
+ public Component getComponent()
{
- return dropTarget.getComponent ();
+ return dropTarget.getComponent();
}
- public void addNotify (java.awt.dnd.peer.DropTargetContextPeer dtcp)
+ public void addNotify(java.awt.dnd.peer.DropTargetContextPeer dtcp)
{
this.dtcp = dtcp;
}
- public void removeNotify ()
+ public void removeNotify()
{
this.dtcp = null;
}
- protected void setTargetActions (int actions)
+ protected void setTargetActions(int actions)
{
targetActions = actions;
}
@@ -129,31 +131,37 @@ public class DropTargetContext implements Serializable
* @exception InvalidDnDOperationException If a drop is not outstanding.
*/
public void dropComplete (boolean success)
+ throws NotImplementedException
{
// FIXME: implement this
}
protected void acceptDrag (int dragOperation)
+ throws NotImplementedException
{
// FIXME: implement this
}
protected void rejectDrag ()
+ throws NotImplementedException
{
// FIXME: implement this
}
protected void acceptDrop (int dropOperation)
+ throws NotImplementedException
{
// FIXME: implement this
}
protected void rejectDrop ()
+ throws NotImplementedException
{
// FIXME: implement this
}
protected DataFlavor[] getCurrentDataFlavors ()
+ throws NotImplementedException
{
// FIXME: implement this
return null;
@@ -161,12 +169,12 @@ public class DropTargetContext implements Serializable
protected List<DataFlavor> getCurrentDataFlavorsAsList ()
{
- return Arrays.asList (getCurrentDataFlavors ());
+ return Arrays.asList(getCurrentDataFlavors ());
}
protected boolean isDataFlavorSupported (DataFlavor flavor)
{
- return getCurrentDataFlavorsAsList ().contains (flavor);
+ return getCurrentDataFlavorsAsList().contains (flavor);
}
/**
@@ -174,7 +182,8 @@ public class DropTargetContext implements Serializable
*
* @exception InvalidDnDOperationException If a drag is not outstanding.
*/
- protected Transferable getTransferable() throws InvalidDnDOperationException
+ protected Transferable getTransferable()
+ throws InvalidDnDOperationException, NotImplementedException
{
// FIXME: implement this
return null;
@@ -182,6 +191,6 @@ public class DropTargetContext implements Serializable
protected Transferable createTransferableProxy(Transferable t, boolean local)
{
- return new TransferableProxy (t, local);
+ return new TransferableProxy(t, local);
}
} // class DropTargetContext
diff --git a/java/awt/dnd/DropTargetDropEvent.java b/java/awt/dnd/DropTargetDropEvent.java
index 399a01c4f..abdc55fe5 100644
--- a/java/awt/dnd/DropTargetDropEvent.java
+++ b/java/awt/dnd/DropTargetDropEvent.java
@@ -1,5 +1,5 @@
/* DropTargetDropEvent.java --
- Copyright (C) 2002 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -37,6 +37,8 @@ exception statement from your version. */
package java.awt.dnd;
+import gnu.classpath.NotImplementedException;
+
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
@@ -65,10 +67,10 @@ public class DropTargetDropEvent extends DropTargetEvent
* actions is not a bitwise mask of DnDConstants, or dtc is null.
* @exception NullPointerException If location is null.
*/
- public DropTargetDropEvent (DropTargetContext dtc, Point location,
- int dropAction, int actions)
+ public DropTargetDropEvent(DropTargetContext dtc, Point location,
+ int dropAction, int actions)
{
- this (dtc, location, dropAction, actions, false);
+ this(dtc, location, dropAction, actions, false);
}
/**
@@ -78,16 +80,16 @@ public class DropTargetDropEvent extends DropTargetEvent
* actions is not a bitwise mask of DnDConstants, or dtc is null.
* @exception NullPointerException If location is null.
*/
- public DropTargetDropEvent (DropTargetContext dtc, Point location,
- int dropAction, int actions, boolean isLocalTx)
+ public DropTargetDropEvent(DropTargetContext dtc, Point location,
+ int dropAction, int actions, boolean isLocalTx)
{
- super (dtc);
+ super(dtc);
if (location == null)
- throw new NullPointerException ();
+ throw new NullPointerException();
if (dtc == null)
- throw new IllegalArgumentException ();
+ throw new IllegalArgumentException();
if (dropAction != DnDConstants.ACTION_NONE
&& dropAction != DnDConstants.ACTION_COPY
@@ -95,7 +97,7 @@ public class DropTargetDropEvent extends DropTargetEvent
&& dropAction != DnDConstants.ACTION_COPY_OR_MOVE
&& dropAction != DnDConstants.ACTION_LINK
&& dropAction != DnDConstants.ACTION_REFERENCE)
- throw new IllegalArgumentException ();
+ throw new IllegalArgumentException();
int actionsMask = DnDConstants.ACTION_NONE
| DnDConstants.ACTION_COPY
@@ -105,7 +107,7 @@ public class DropTargetDropEvent extends DropTargetEvent
| DnDConstants.ACTION_REFERENCE;
if (~(actions ^ actionsMask) != 0)
- throw new IllegalArgumentException ();
+ throw new IllegalArgumentException();
this.dropAction = dropAction;
this.actions = actions;
@@ -113,52 +115,53 @@ public class DropTargetDropEvent extends DropTargetEvent
this.isLocalTx = isLocalTx;
}
- public Point getLocation ()
+ public Point getLocation()
{
return location;
}
- public DataFlavor[] getCurrentDataFlavors ()
+ public DataFlavor[] getCurrentDataFlavors()
{
- return context.getCurrentDataFlavors ();
+ return context.getCurrentDataFlavors();
}
- public List<DataFlavor> getCurrentDataFlavorsAsList ()
+ public List<DataFlavor> getCurrentDataFlavorsAsList()
{
- return context.getCurrentDataFlavorsAsList ();
+ return context.getCurrentDataFlavorsAsList();
}
- public boolean isDataFlavorSupported (DataFlavor flavor)
+ public boolean isDataFlavorSupported(DataFlavor flavor)
{
- return context.isDataFlavorSupported (flavor);
+ return context.isDataFlavorSupported(flavor);
}
- public int getSourceActions ()
+ public int getSourceActions()
{
return actions;
}
- public int getDropAction ()
+ public int getDropAction()
{
return dropAction;
}
- public Transferable getTransferable ()
+ public Transferable getTransferable()
{
return context.getTransferable ();
}
- public void acceptDrop (int dropAction)
+ public void acceptDrop(int dropAction)
{
- context.acceptDrop (dropAction);
+ context.acceptDrop(dropAction);
}
- public void rejectDrop ()
+ public void rejectDrop()
{
- context.rejectDrop ();
+ context.rejectDrop();
}
- public void dropComplete (boolean success)
+ public void dropComplete(boolean success)
+ throws NotImplementedException
{
// FIXME: implement this
}
diff --git a/java/awt/font/TextLayout.java b/java/awt/font/TextLayout.java
index b7b1030f2..6bae3facd 100644
--- a/java/awt/font/TextLayout.java
+++ b/java/awt/font/TextLayout.java
@@ -1,5 +1,5 @@
/* TextLayout.java --
- Copyright (C) 2003, 2004 Free Software Foundation, Inc.
+ Copyright (C) 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,8 +38,7 @@ exception statement from your version. */
package java.awt.font;
-import gnu.java.awt.ClasspathToolkit;
-import gnu.java.awt.peer.ClasspathTextLayoutPeer;
+import gnu.classpath.NotImplementedException;
import java.awt.Font;
import java.awt.Graphics2D;
@@ -47,116 +46,271 @@ import java.awt.Shape;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.Point2D;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
+import java.text.Bidi;
import java.util.Map;
/**
- * @author Michael Koch
+ * @author Sven de Marothy
*/
public final class TextLayout implements Cloneable
{
- public static final CaretPolicy DEFAULT_CARET_POLICY = new CaretPolicy ();
- ClasspathTextLayoutPeer peer;
-
- public static class CaretPolicy
+ private GlyphVector[] runs;
+ private Font font;
+ private FontRenderContext frc;
+ private String string;
+ private Rectangle2D boundsCache;
+ private LineMetrics lm;
+
+ /**
+ * Start and end character indices of the runs.
+ * First index is the run number, second is 0 or 1 for the starting
+ * and ending character index of the run, respectively.
+ */
+ private int[][] runIndices;
+
+ /**
+ * Base directionality, determined from the first char.
+ */
+ private boolean leftToRight;
+
+ /**
+ * Whether this layout contains whitespace or not.
+ */
+ private boolean hasWhitespace = false;
+
+ /**
+ * The default caret policy.
+ */
+ static TextLayout.CaretPolicy DEFAULT_CARET_POLICY = new CaretPolicy();
+
+ /**
+ * Constructs a TextLayout.
+ */
+ public TextLayout (String string, Font font, FontRenderContext frc)
{
- public CaretPolicy ()
- {
- // Do nothing here.
- }
+ this.font = font;
+ this.frc = frc;
+ this.string = string;
+ lm = font.getLineMetrics(string, frc);
- public TextHitInfo getStrongCaret (TextHitInfo hit1, TextHitInfo hit2,
- TextLayout layout)
- {
- return layout.peer.getStrongCaret(hit1, hit2);
- }
- }
+ // Get base direction and whitespace info
+ getStringProperties();
- public TextLayout (AttributedCharacterIterator text, FontRenderContext frc)
- {
- AttributedString as = new AttributedString (text);
- ClasspathToolkit tk = (ClasspathToolkit)(Toolkit.getDefaultToolkit ());
- peer = tk.getClasspathTextLayoutPeer(as, frc);
+ if( Bidi.requiresBidi( string.toCharArray(), 0, string.length() ) )
+ {
+ Bidi bidi = new Bidi( string, leftToRight ?
+ Bidi.DIRECTION_LEFT_TO_RIGHT :
+ Bidi.DIRECTION_RIGHT_TO_LEFT );
+ int rc = bidi.getRunCount();
+ byte[] table = new byte[ rc ];
+ for(int i = 0; i < table.length; i++)
+ table[i] = (byte)bidi.getRunLevel(i);
+
+ runs = new GlyphVector[ rc ];
+ runIndices = new int[rc][2];
+ for(int i = 0; i < runs.length; i++)
+ {
+ runIndices[i][0] = bidi.getRunStart( i );
+ runIndices[i][1] = bidi.getRunLimit( i );
+ if( runIndices[i][0] != runIndices[i][1] ) // no empty runs.
+ {
+ runs[i] = font.layoutGlyphVector
+ ( frc, string.toCharArray(),
+ runIndices[i][0], runIndices[i][1],
+ ((table[i] & 1) == 0) ? Font.LAYOUT_LEFT_TO_RIGHT :
+ Font.LAYOUT_RIGHT_TO_LEFT );
+ }
+ }
+ Bidi.reorderVisually( table, 0, runs, 0, runs.length );
+ }
+ else
+ {
+ runs = new GlyphVector[ 1 ];
+ runIndices = new int[1][2];
+ runIndices[0][0] = 0;
+ runIndices[0][1] = string.length();
+ runs[ 0 ] = font.layoutGlyphVector( frc, string.toCharArray(),
+ 0, string.length(),
+ leftToRight ?
+ Font.LAYOUT_LEFT_TO_RIGHT :
+ Font.LAYOUT_RIGHT_TO_LEFT );
+ }
}
- public TextLayout (String string, Font font, FontRenderContext frc)
+ public TextLayout (String string,
+ Map<? extends AttributedCharacterIterator.Attribute, ?> attributes,
+ FontRenderContext frc)
{
- AttributedString as = new AttributedString (string);
- as.addAttribute (TextAttribute.FONT, font);
- ClasspathToolkit tk = (ClasspathToolkit)(Toolkit.getDefaultToolkit ());
- peer = tk.getClasspathTextLayoutPeer(as, frc);
+ this( string, new Font( attributes ), frc );
}
- public TextLayout (String string, Map<? extends AttributedCharacterIterator.Attribute,?> attributes, FontRenderContext frc)
- {
- AttributedString as = new AttributedString (string, attributes);
- ClasspathToolkit tk = (ClasspathToolkit)(Toolkit.getDefaultToolkit ());
- peer = tk.getClasspathTextLayoutPeer(as, frc);
+ public TextLayout (AttributedCharacterIterator text, FontRenderContext frc)
+ throws NotImplementedException
+ {
+ throw new Error ("not implemented");
+ }
+
+ /**
+ * Scan the character run for the first strongly directional character,
+ * which in turn defines the base directionality of the whole layout.
+ */
+ private void getStringProperties()
+ {
+ boolean gotDirection = false;
+ int i = 0;
+
+ leftToRight = true;
+ while( i < string.length() && !gotDirection )
+ switch( Character.getDirectionality( string.charAt( i++ ) ) )
+ {
+ case Character.DIRECTIONALITY_LEFT_TO_RIGHT:
+ case Character.DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING:
+ case Character.DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE:
+ gotDirection = true;
+ break;
+
+ case Character.DIRECTIONALITY_RIGHT_TO_LEFT:
+ case Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC:
+ case Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING:
+ case Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE:
+ leftToRight = false;
+ gotDirection = true;
+ break;
+ }
+
+ // Determine if there's whitespace in the thing.
+ // Ignore trailing chars.
+ i = string.length() - 1;
+ hasWhitespace = false;
+ while( i >= 0 && Character.isWhitespace( string.charAt(i) ) )
+ i--;
+ // Check the remaining chars
+ while( i >= 0 )
+ if( Character.isWhitespace( string.charAt(i--) ) )
+ hasWhitespace = true;
}
protected Object clone ()
{
- try
- {
- TextLayout tl = (TextLayout) super.clone ();
- tl.peer = (ClasspathTextLayoutPeer) this.peer.clone();
- return tl;
- }
- catch (CloneNotSupportedException e)
- {
- // This should never occur
- throw new InternalError ();
- }
+ return new TextLayout( string, font, frc );
}
-
public void draw (Graphics2D g2, float x, float y)
- {
- peer.draw(g2, x, y);
+ {
+ for(int i = 0; i < runs.length; i++)
+ {
+ g2.drawGlyphVector(runs[i], x, y);
+ Rectangle2D r = runs[i].getLogicalBounds();
+ x += r.getWidth();
+ }
}
public boolean equals (Object obj)
{
- if (! (obj instanceof TextLayout))
+ if( !( obj instanceof TextLayout) )
return false;
- return equals ((TextLayout) obj);
+ return equals( (TextLayout) obj );
}
public boolean equals (TextLayout tl)
{
- return this.peer.equals(tl.peer);
+ if( runs.length != tl.runs.length )
+ return false;
+ // Compare all glyph vectors.
+ for( int i = 0; i < runs.length; i++ )
+ if( !runs[i].equals( tl.runs[i] ) )
+ return false;
+ return true;
}
public float getAdvance ()
{
- return peer.getAdvance();
+ float totalAdvance = 0f;
+ for(int i = 0; i < runs.length; i++)
+ totalAdvance += runs[i].getLogicalBounds().getWidth();
+ return totalAdvance;
}
public float getAscent ()
{
- return peer.getAscent();
+ return lm.getAscent();
}
public byte getBaseline ()
{
- return peer.getBaseline();
+ return (byte)lm.getBaselineIndex();
}
public float[] getBaselineOffsets ()
{
- return peer.getBaselineOffsets();
+ return lm.getBaselineOffsets();
}
public Shape getBlackBoxBounds (int firstEndpoint, int secondEndpoint)
{
- return peer.getBlackBoxBounds(firstEndpoint, secondEndpoint);
+ if( firstEndpoint < 0 || secondEndpoint > getCharacterCount() )
+ return new Rectangle2D.Float();
+
+ GeneralPath gp = new GeneralPath();
+ int i = 0; // run index
+ double advance = 0;
+
+ // go to first run
+ while( runIndices[i + 1][1] < firstEndpoint )
+ {
+ advance += runs[i].getLogicalBounds().getWidth();
+ i++;
+ }
+
+ int j = 0; // index into the run.
+ if( runIndices[i][1] - runIndices[i][0] > 1 )
+ {
+ while( runs[i].getGlyphCharIndex( j + 1 ) <
+ (firstEndpoint - runIndices[i][0] ) )j++;
+ }
+
+ gp.append(runs[i].getGlyphVisualBounds( j ), false);
+ boolean keepGoing = true;;
+
+ do
+ {
+ while( j < runs[i].getNumGlyphs() &&
+ runs[i].getGlyphCharIndex( j ) + runIndices[i][0] <
+ secondEndpoint )
+ {
+ Rectangle2D r2 = (runs[i].getGlyphVisualBounds( j )).
+ getBounds2D();
+ Point2D p = runs[i].getGlyphPosition( j );
+ r2.setRect( advance + p.getX(), r2.getY(),
+ r2.getWidth(), r2.getHeight() );
+ gp.append(r2, false);
+ j++;
+ }
+
+ if( j >= runs[i].getNumGlyphs() )
+ {
+ advance += runs[i].getLogicalBounds().getWidth();
+ i++;
+ j = 0;
+ }
+ else
+ keepGoing = false;
+ }
+ while( keepGoing );
+
+ return gp;
}
public Rectangle2D getBounds()
{
- return peer.getBounds();
+ if( boundsCache == null )
+ boundsCache = getOutline(new AffineTransform()).getBounds();
+ return boundsCache;
}
public float[] getCaretInfo (TextHitInfo hit)
@@ -165,144 +319,274 @@ public final class TextLayout implements Cloneable
}
public float[] getCaretInfo (TextHitInfo hit, Rectangle2D bounds)
+ throws NotImplementedException
{
- return peer.getCaretInfo(hit, bounds);
+ throw new Error ("not implemented");
}
public Shape getCaretShape (TextHitInfo hit)
{
- return getCaretShape(hit, getBounds());
+ return getCaretShape( hit, getBounds() );
}
public Shape getCaretShape (TextHitInfo hit, Rectangle2D bounds)
+ throws NotImplementedException
{
- return peer.getCaretShape(hit, bounds);
+ throw new Error ("not implemented");
}
public Shape[] getCaretShapes (int offset)
{
- return getCaretShapes(offset, getBounds());
+ return getCaretShapes( offset, getBounds() );
}
public Shape[] getCaretShapes (int offset, Rectangle2D bounds)
+ throws NotImplementedException
{
- return getCaretShapes(offset, getBounds(), DEFAULT_CARET_POLICY);
- }
-
- public Shape[] getCaretShapes (int offset, Rectangle2D bounds,
- TextLayout.CaretPolicy policy)
- {
- return peer.getCaretShapes(offset, bounds, policy);
+ throw new Error ("not implemented");
}
public int getCharacterCount ()
{
- return peer.getCharacterCount();
+ return string.length();
}
public byte getCharacterLevel (int index)
+ throws NotImplementedException
{
- return peer.getCharacterLevel(index);
+ throw new Error ("not implemented");
}
public float getDescent ()
{
- return peer.getDescent();
+ return lm.getDescent();
}
public TextLayout getJustifiedLayout (float justificationWidth)
{
- return peer.getJustifiedLayout(justificationWidth);
+ TextLayout newLayout = (TextLayout)clone();
+
+ if( hasWhitespace )
+ newLayout.handleJustify( justificationWidth );
+
+ return newLayout;
}
public float getLeading ()
{
- return peer.getLeading();
+ return lm.getLeading();
}
public Shape getLogicalHighlightShape (int firstEndpoint, int secondEndpoint)
{
- return getLogicalHighlightShape (firstEndpoint, secondEndpoint, getBounds());
+ return getLogicalHighlightShape( firstEndpoint, secondEndpoint,
+ getBounds() );
}
public Shape getLogicalHighlightShape (int firstEndpoint, int secondEndpoint,
Rectangle2D bounds)
{
- return peer.getLogicalHighlightShape(firstEndpoint, secondEndpoint, bounds);
+ if( firstEndpoint < 0 || secondEndpoint > getCharacterCount() )
+ return new Rectangle2D.Float();
+
+ int i = 0; // run index
+ double advance = 0;
+
+ // go to first run
+ if( i > 0 )
+ while( runIndices[i + 1][1] < firstEndpoint )
+ {
+ advance += runs[i].getLogicalBounds().getWidth();
+ i++;
+ }
+
+ int j = 0; // index into the run.
+ if( runIndices[i][1] - runIndices[i][0] > 1 )
+ {
+ while( runs[i].getGlyphCharIndex( j + 1 ) <
+ (firstEndpoint - runIndices[i][0] ) )j++;
+ }
+
+ Rectangle2D r = (runs[i].getGlyphLogicalBounds( j )).getBounds2D();
+ boolean keepGoing = true;;
+
+ do
+ {
+ while( j < runs[i].getNumGlyphs() &&
+ runs[i].getGlyphCharIndex( j ) + runIndices[i][0] <
+ secondEndpoint )
+ {
+ Rectangle2D r2 = (runs[i].getGlyphLogicalBounds( j )).
+ getBounds2D();
+ Point2D p = runs[i].getGlyphPosition( j );
+ r2.setRect( advance + p.getX(), r2.getY(),
+ r2.getWidth(), r2.getHeight() );
+ r = r.createUnion( r2 );
+ j++;
+ }
+
+ if( j >= runs[i].getNumGlyphs() )
+ {
+ advance += runs[i].getLogicalBounds().getWidth();
+ i++;
+ j = 0;
+ }
+ else
+ keepGoing = false;
+ }
+ while( keepGoing );
+
+ return r;
}
public int[] getLogicalRangesForVisualSelection (TextHitInfo firstEndpoint,
TextHitInfo secondEndpoint)
+ throws NotImplementedException
{
- return peer.getLogicalRangesForVisualSelection(firstEndpoint, secondEndpoint);
+ throw new Error ("not implemented");
}
public TextHitInfo getNextLeftHit (int offset)
+ throws NotImplementedException
{
- return getNextLeftHit(offset, DEFAULT_CARET_POLICY);
- }
-
- public TextHitInfo getNextLeftHit (int offset, TextLayout.CaretPolicy policy)
- {
- return peer.getNextLeftHit(offset, policy);
+ throw new Error ("not implemented");
}
public TextHitInfo getNextLeftHit (TextHitInfo hit)
+ throws NotImplementedException
{
- return getNextLeftHit(hit.getCharIndex());
+ throw new Error ("not implemented");
}
public TextHitInfo getNextRightHit (int offset)
+ throws NotImplementedException
{
- return getNextRightHit(offset, DEFAULT_CARET_POLICY);
- }
-
- public TextHitInfo getNextRightHit (int offset, TextLayout.CaretPolicy policy)
- {
- return peer.getNextRightHit(offset, policy);
+ throw new Error ("not implemented");
}
public TextHitInfo getNextRightHit (TextHitInfo hit)
+ throws NotImplementedException
{
- return getNextRightHit(hit.getCharIndex());
+ throw new Error ("not implemented");
}
public Shape getOutline (AffineTransform tx)
{
- return peer.getOutline(tx);
+ float x = 0f;
+ GeneralPath gp = new GeneralPath();
+ for(int i = 0; i < runs.length; i++)
+ {
+ gp.append( runs[i].getOutline( x, 0f ), false );
+ Rectangle2D r = runs[i].getLogicalBounds();
+ x += r.getWidth();
+ }
+ if( tx != null )
+ gp.transform( tx );
+ return gp;
}
public float getVisibleAdvance ()
{
- return peer.getVisibleAdvance();
+ float totalAdvance = 0f;
+
+ if( runs.length <= 0 )
+ return 0f;
+
+ // No trailing whitespace
+ if( !Character.isWhitespace( string.charAt( string.length() -1 ) ) )
+ return getAdvance();
+
+ // Get length of all runs up to the last
+ for(int i = 0; i < runs.length - 1; i++)
+ totalAdvance += runs[i].getLogicalBounds().getWidth();
+
+ int lastRun = runIndices[ runs.length - 1 ][0];
+ int j = string.length() - 1;
+ while( j >= lastRun && Character.isWhitespace( string.charAt( j ) ) ) j--;
+
+ if( j < lastRun )
+ return totalAdvance; // entire last run is whitespace
+
+ int lastNonWSChar = j - lastRun;
+ j = 0;
+ while( runs[ runs.length - 1 ].getGlyphCharIndex( j )
+ <= lastNonWSChar )
+ {
+ totalAdvance += runs[ runs.length - 1 ].getGlyphLogicalBounds( j ).
+ getBounds2D().getWidth();
+ j ++;
+ }
+
+ return totalAdvance;
}
public Shape getVisualHighlightShape (TextHitInfo firstEndpoint,
TextHitInfo secondEndpoint)
{
- return getVisualHighlightShape(firstEndpoint, secondEndpoint, getBounds());
+ return getVisualHighlightShape( firstEndpoint, secondEndpoint,
+ getBounds() );
}
public Shape getVisualHighlightShape (TextHitInfo firstEndpoint,
TextHitInfo secondEndpoint,
Rectangle2D bounds)
+ throws NotImplementedException
{
- return peer.getVisualHighlightShape(firstEndpoint, secondEndpoint, bounds);
+ throw new Error ("not implemented");
}
public TextHitInfo getVisualOtherHit (TextHitInfo hit)
+ throws NotImplementedException
{
- return peer.getVisualOtherHit(hit);
+ throw new Error ("not implemented");
}
+ /**
+ * This is a protected method of a <code>final</code> class, meaning
+ * it exists only to taunt you.
+ */
protected void handleJustify (float justificationWidth)
{
- peer.handleJustify(justificationWidth);
- }
-
- public int hashCode ()
- {
- return peer.hashCode();
+ // We assume that the text has non-trailing whitespace.
+ // First get the change in width to insert into the whitespaces.
+ double deltaW = justificationWidth - getVisibleAdvance();
+ int nglyphs = 0; // # of whitespace chars
+
+ // determine last non-whitespace char.
+ int lastNWS = string.length() - 1;
+ while( Character.isWhitespace( string.charAt( lastNWS ) ) ) lastNWS--;
+
+ // locations of the glyphs.
+ int[] wsglyphs = new int[string.length() * 10];
+ for(int run = 0; run < runs.length; run++ )
+ for(int i = 0; i < runs[run].getNumGlyphs(); i++ )
+ {
+ int cindex = runIndices[run][0] + runs[run].getGlyphCharIndex( i );
+ if( Character.isWhitespace( string.charAt( cindex ) ) )
+ // && cindex < lastNWS )
+ {
+ wsglyphs[ nglyphs * 2 ] = run;
+ wsglyphs[ nglyphs * 2 + 1] = i;
+ nglyphs++;
+ }
+ }
+
+ deltaW = deltaW / nglyphs; // Change in width per whitespace glyph
+ double w = 0;
+ int cws = 0;
+ // Shift all characters
+ for(int run = 0; run < runs.length; run++ )
+ for(int i = 0; i < runs[ run ].getNumGlyphs(); i++ )
+ {
+ if( wsglyphs[ cws * 2 ] == run && wsglyphs[ cws * 2 + 1 ] == i )
+ {
+ cws++; // update 'current whitespace'
+ w += deltaW; // increment the shift
+ }
+ Point2D p = runs[ run ].getGlyphPosition( i );
+ p.setLocation( p.getX() + w, p.getY() );
+ runs[ run ].setGlyphPosition( i, p );
+ }
}
public TextHitInfo hitTestChar (float x, float y)
@@ -312,21 +596,48 @@ public final class TextLayout implements Cloneable
public TextHitInfo hitTestChar (float x, float y, Rectangle2D bounds)
{
- return peer.hitTestChar(x, y, bounds);
+ return hitTestChar( x, y, getBounds() );
}
public boolean isLeftToRight ()
{
- return peer.isLeftToRight();
+ return leftToRight;
}
public boolean isVertical ()
{
- return peer.isVertical();
+ return false; // FIXME: How do you create a vertical layout?
+ }
+
+ public int hashCode ()
+ throws NotImplementedException
+ {
+ throw new Error ("not implemented");
}
public String toString ()
{
- return peer.toString();
+ return "TextLayout [string:"+string+", Font:"+font+" Rendercontext:"+
+ frc+"]";
+ }
+
+ /**
+ * Inner class describing a caret policy
+ */
+ public static class CaretPolicy
+ {
+ public CaretPolicy()
+ {
+ }
+
+ public TextHitInfo getStrongCaret(TextHitInfo hit1,
+ TextHitInfo hit2,
+ TextLayout layout)
+ throws NotImplementedException
+ {
+ throw new Error ("not implemented");
+ }
}
}
+
+
diff --git a/java/awt/geom/AffineTransform.java b/java/awt/geom/AffineTransform.java
index 4d1a4d6d5..55b688355 100644
--- a/java/awt/geom/AffineTransform.java
+++ b/java/awt/geom/AffineTransform.java
@@ -414,7 +414,9 @@ public class AffineTransform implements Cloneable, Serializable
public static AffineTransform getTranslateInstance(double tx, double ty)
{
AffineTransform t = new AffineTransform();
- t.setToTranslation(tx, ty);
+ t.m02 = tx;
+ t.m12 = ty;
+ t.type = (tx == 0 && ty == 0) ? TYPE_UNIFORM_SCALE : TYPE_TRANSLATION;
return t;
}
diff --git a/java/awt/image/BufferedImage.java b/java/awt/image/BufferedImage.java
index 1e2ebe296..e79a09a0f 100644
--- a/java/awt/image/BufferedImage.java
+++ b/java/awt/image/BufferedImage.java
@@ -1,5 +1,5 @@
/* BufferedImage.java --
- Copyright (C) 2000, 2002, 2003, 2004, 2005 Free Software Foundation
+ Copyright (C) 2000, 2002, 2003, 2004, 2005, 2006, Free Software Foundation
This file is part of GNU Classpath.
@@ -80,7 +80,7 @@ public class BufferedImage extends Image
TYPE_BYTE_INDEXED = 13;
static final int[] bits3 = { 8, 8, 8 };
- static final int[] bits4 = { 8, 8, 8 };
+ static final int[] bits4 = { 8, 8, 8, 8 };
static final int[] bits1byte = { 8 };
static final int[] bits1ushort = { 16 };
@@ -99,6 +99,13 @@ public class BufferedImage extends Image
Vector observers;
+ /**
+ * Creates a new buffered image.
+ *
+ * @param w the width.
+ * @param h the height.
+ * @param type the image type (see the constants defined by this class).
+ */
public BufferedImage(int w, int h, int type)
{
ColorModel cm = null;
@@ -363,11 +370,28 @@ public class BufferedImage extends Image
return 1;
}
+ /**
+ * Returns the value of the specified property, or
+ * {@link Image#UndefinedProperty} if the property is not defined.
+ *
+ * @param string the property key (<code>null</code> not permitted).
+ *
+ * @return The property value.
+ *
+ * @throws NullPointerException if <code>string</code> is <code>null</code>.
+ */
public Object getProperty(String string)
{
- if (properties == null)
- return null;
- return properties.get(string);
+ if (string == null)
+ throw new NullPointerException("The property name cannot be null.");
+ Object result = Image.UndefinedProperty;
+ if (properties != null)
+ {
+ Object v = properties.get(string);
+ if (v != null)
+ result = v;
+ }
+ return result;
}
public Object getProperty(String string, ImageObserver imageobserver)
@@ -375,10 +399,15 @@ public class BufferedImage extends Image
return getProperty(string);
}
-
+ /**
+ * Returns <code>null</code> always.
+ *
+ * @return <code>null</code> always.
+ */
public String[] getPropertyNames()
{
- // FIXME: implement
+ // This method should always return null, see:
+ // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4640609
return null;
}
diff --git a/java/io/File.java b/java/io/File.java
index 731fa5826..36cfa24ea 100644
--- a/java/io/File.java
+++ b/java/io/File.java
@@ -1,5 +1,5 @@
/* File.java -- Class representing a file on disk
- Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005
+ Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006
Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -82,7 +82,7 @@ public class File implements Serializable, Comparable<File>
/**
* This is the string that is used to separate the host name from the
- * path name in paths than include the host name. It is the value of
+ * path name in paths that include the host name. It is the value of
* the <code>path.separator</code> system property.
*/
public static final String pathSeparator
@@ -484,9 +484,9 @@ public class File implements Serializable, Comparable<File>
/**
* This method returns a canonical representation of the pathname of
* this file. The actual form of the canonical representation is
- * different. On the GNU system, the canonical form differs from the
- * absolute form in that all relative file references to "." and ".."
- * are resolved and removed.
+ * system-dependent. On the GNU system, conversion to canonical
+ * form involves the removal of redundant separators, references to
+ * "." and "..", and symbolic links.
* <p>
* Note that this method, unlike the other methods which return path
* names, can throw an IOException. This is because native method
diff --git a/java/lang/String.java b/java/lang/String.java
index 7a014d431..28b77c0aa 100644
--- a/java/lang/String.java
+++ b/java/lang/String.java
@@ -1822,7 +1822,7 @@ public final class String
*/
public synchronized int codePointCount(int start, int end)
{
- if (start < 0 || end >= count || start > end)
+ if (start < 0 || end > count || start > end)
throw new StringIndexOutOfBoundsException();
start += offset;
diff --git a/java/lang/management/RuntimeMXBean.java b/java/lang/management/RuntimeMXBean.java
new file mode 100644
index 000000000..c572394f8
--- /dev/null
+++ b/java/lang/management/RuntimeMXBean.java
@@ -0,0 +1,274 @@
+/* RuntimeMXBean.java - Interface for a runtime bean
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package java.lang.management;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Provides access to information about the underlying virtual
+ * machine. Instances of this bean are obtained by calling
+ * {@link ManagementFactory#getRuntimeMXBean()}.
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+public interface RuntimeMXBean
+{
+
+ /**
+ * <p>
+ * Returns the boot classpath used by the virtual machine. This
+ * value follows the standard path syntax used by the underlying
+ * operating system (e.g. directories separated by ':' on UNIX
+ * or ';' on Windows).
+ * </p>
+ * <p>
+ * Supplying this value is optional. Users should check the
+ * return value of {@link isBootClassPathSupported()} prior to
+ * calling this method.
+ * </p>
+ *
+ * @return the boot classpath of the virtual machine, if supported.
+ * @throws UnsupportedOperationException in cases where this
+ * functionality is not
+ * supported by the VM.
+ * @throws SecurityException if a security manager exists and
+ * denies ManagementPermission("monitor").
+ * @see #isBootClassPathSupported()
+ * @see java.lang.management.ManagementPermission
+ */
+ String getBootClassPath();
+
+ /**
+ * Returns the classpath used by the system classloader. This
+ * is equivalent to obtaining the <code>java.class.path</code>
+ * property via {@link System#getProperty(String)}. This value
+ * follows the standard path syntax used by the underlying operating
+ * system (e.g. directories separated by ':' on UNIX or ';' on
+ * Windows).
+ *
+ * @return the classpath used by the system class loader.
+ * @throws SecurityException if a security manager exists which
+ * prevents access to the classpath
+ * property.
+ * @see java.lang.System#getProperty(String)
+ * @see java.lang.SecurityManager#checkPropertyAccess(String)
+ */
+ String getClassPath();
+
+ /**
+ * Returns a list of the arguments given to the virtual machine,
+ * excluding those that apply to the <code>main()</code> method
+ * of the class file being executed. These may not just be those
+ * specified at the command line, but may also include arguments
+ * from environment variables, configuration files, etc. All
+ * command line arguments may not reach the virtual machine, so
+ * these are not included in this list.
+ *
+ * @return a list of arguments passed to the virtual machine.
+ * @throws SecurityException if a security manager exists and
+ * denies ManagementPermission("monitor").
+ * @see java.lang.management.ManagementPermission
+ */
+ List<String> getInputArguments();
+
+ /**
+ * Returns the library path. This is equivalent to obtaining the
+ * <code>java.library.path</code> property via
+ * {@link System#getProperty(String)}. This value follows the
+ * standard path syntax used by the underlying operating
+ * system (e.g. directories separated by ':' on UNIX or ';' on
+ * Windows).
+ *
+ * @return the library path.
+ * @throws SecurityException if a security manager exists which
+ * prevents access to the library path
+ * property.
+ * @see java.lang.System#getProperty(String)
+ * @see java.lang.SecurityManager#checkPropertyAccess(String)
+ */
+ String getLibraryPath();
+
+ /**
+ * Returns the version of the management specification
+ * implemented by the virtual machine.
+ *
+ * @return the version of the management specification
+ * implemented.
+ */
+ String getManagementSpecVersion();
+
+ /**
+ * Returns the name of this virtual machine. The content
+ * of this property is left up to the developer of the
+ * virtual machine. It may include a number of system
+ * attributes and may differ between instances of the
+ * same virtual machine (for example, it might include
+ * the process identifier).
+ *
+ * @return the name of this virtual machine.
+ */
+ String getName();
+
+ /**
+ * Returns the specification name of the virtual machine.
+ * This is equivalent to obtaining the
+ * <code>java.vm.specification.name</code> property via
+ * {@link System#getProperty(String)}.
+ *
+ * @return the specification name of the VM.
+ * @throws SecurityException if a security manager exists which
+ * prevents access to the VM
+ * specification name property.
+ * @see java.lang.System#getProperty(String)
+ * @see java.lang.SecurityManager#checkPropertyAccess(String)
+ */
+ String getSpecName();
+
+ /**
+ * Returns the specification vendor of the virtual machine.
+ * This is equivalent to obtaining the
+ * <code>java.vm.specification.vendor</code> property via
+ * {@link System#getProperty(String)}.
+ *
+ * @return the specification vendor of the VM.
+ * @throws SecurityException if a security manager exists which
+ * prevents access to the VM
+ * specification vendor property.
+ * @see java.lang.System#getProperty(String)
+ * @see java.lang.SecurityManager#checkPropertyAccess(String)
+ */
+ String getSpecVendor();
+
+ /**
+ * Returns the specification version of the virtual machine.
+ * This is equivalent to obtaining the
+ * <code>java.vm.specification.version</code> property via
+ * {@link System#getProperty(String)}.
+ *
+ * @return the specification version of the VM.
+ * @throws SecurityException if a security manager exists which
+ * prevents access to the VM
+ * specification version property.
+ * @see java.lang.System#getProperty(String)
+ * @see java.lang.SecurityManager#checkPropertyAccess(String)
+ */
+ String getSpecVersion();
+
+ /**
+ * Returns the approximate start time of the virtual machine
+ * in milliseconds.
+ *
+ * @return the start time of the virtual machine.
+ */
+ long getStartTime();
+
+ /**
+ * Returns a map containing the keys and values of the system
+ * properties. This gives largely the same result as calling
+ * {@link System#getProperties()}, but the resulting map
+ * is filtered so as to only provide keys and values that
+ * are <code>String</code>s.
+ *
+ * @return the map of system properties.
+ */
+ Map<String,String> getSystemProperties();
+
+ /**
+ * Returns the uptime of the virtual machine in milliseconds.
+ *
+ * @return the uptime of the virtual machine.
+ */
+ long getUptime();
+
+ /**
+ * Returns the implementation name of the virtual machine.
+ * This is equivalent to obtaining the
+ * <code>java.vm.name</code> property via
+ * {@link System#getProperty(String)}.
+ *
+ * @return the implementation name of the VM.
+ * @throws SecurityException if a security manager exists which
+ * prevents access to the VM name
+ * property.
+ * @see java.lang.System#getProperty(String)
+ * @see java.lang.SecurityManager#checkPropertyAccess(String)
+ */
+ String getVmName();
+
+ /**
+ * Returns the implementation vendor of the virtual machine.
+ * This is equivalent to obtaining the
+ * <code>java.vm.vendor</code> property via
+ * {@link System#getProperty(String)}.
+ *
+ * @return the implementation vendor of the VM.
+ * @throws SecurityException if a security manager exists which
+ * prevents access to the VM vendor
+ * property.
+ * @see java.lang.System#getProperty(String)
+ * @see java.lang.SecurityManager#checkPropertyAccess(String)
+ */
+ String getVmVendor();
+
+ /**
+ * Returns the implementation version of the virtual machine.
+ * This is equivalent to obtaining the
+ * <code>java.vm.version</code> property via
+ * {@link System#getProperty(String)}.
+ *
+ * @return the implementation version of the VM.
+ * @throws SecurityException if a security manager exists which
+ * prevents access to the VM version
+ * property.
+ * @see java.lang.System#getProperty(String)
+ * @see java.lang.SecurityManager#checkPropertyAccess(String)
+ */
+ String getVmVersion();
+
+ /**
+ * Returns true if the virtual machine supports the boot classpath
+ * mechanism.
+ *
+ * @return true if the boot classpath property is supported by the
+ * virtual machine.
+ */
+ boolean isBootClassPathSupported();
+
+}
diff --git a/java/net/InetSocketAddress.java b/java/net/InetSocketAddress.java
index 912545752..5267cc11a 100644
--- a/java/net/InetSocketAddress.java
+++ b/java/net/InetSocketAddress.java
@@ -86,7 +86,6 @@ public class InetSocketAddress extends SocketAddress
this.addr = addr;
this.port = port;
- this.hostname = addr.getHostName();
}
/**
@@ -186,7 +185,7 @@ public class InetSocketAddress extends SocketAddress
if (addr == null && sa.addr != null)
return false;
- else if (addr == null && sa.addr == null)
+ else if (addr == null && sa.addr == null) // we know hostname != null
return hostname.equals(sa.hostname) && sa.port == port;
else
return addr.equals(sa.addr) && sa.port == port;
@@ -213,6 +212,9 @@ public class InetSocketAddress extends SocketAddress
*/
public final String getHostName()
{
+ if (hostname == null) // we know addr != null
+ hostname = addr.getHostName();
+
return hostname;
}
@@ -249,10 +251,11 @@ public class InetSocketAddress extends SocketAddress
/**
* Returns the <code>InetSocketAddress</code> as string
*
- * @return A string represenation of this address.
+ * @return A string representation of this address.
*/
public String toString()
{
+ // Note: if addr is null, then hostname != null.
return (addr == null ? hostname : addr.toString()) + ":" + port;
}
}
diff --git a/java/security/UnresolvedPermission.java b/java/security/UnresolvedPermission.java
index d3f671a9c..449454aaf 100644
--- a/java/security/UnresolvedPermission.java
+++ b/java/security/UnresolvedPermission.java
@@ -201,6 +201,47 @@ public final class UnresolvedPermission extends Permission
{
return new UnresolvedPermissionCollection();
}
+
+ /**
+ * Return the name of the class of the unresolved permission.
+ * @since 1.5
+ */
+ public String getUnresolvedType()
+ {
+ return type;
+ }
+
+ /**
+ * Return the name of the unresolved permission.
+ * @since 1.5
+ */
+ public String getUnresolvedName()
+ {
+ return name;
+ }
+
+ /**
+ * Return the actions of the unresolved permission, or null
+ * if there are no actions.
+ * @since 1.5
+ */
+ public String getUnresolvedActions()
+ {
+ return actions;
+ }
+
+ /**
+ * Return the certificates of the unresolved permission.
+ * If there are no certificates, null is returned. Otherwise,
+ * a new array is returned.
+ * @since 1.5
+ */
+ public Certificate[] getUnresolvedCerts()
+ {
+ if (certs == null)
+ return null;
+ return (Certificate[]) certs.clone();
+ }
} // class UnresolvedPermission
/**
diff --git a/java/text/Bidi.java b/java/text/Bidi.java
index 437436045..05b10f52d 100644
--- a/java/text/Bidi.java
+++ b/java/text/Bidi.java
@@ -644,6 +644,7 @@ public final class Bidi
case Character.DIRECTIONALITY_OTHER_NEUTRALS:
case Character.DIRECTIONALITY_SEGMENT_SEPARATOR:
case Character.DIRECTIONALITY_PARAGRAPH_SEPARATOR:
+ case Character.DIRECTIONALITY_WHITESPACE:
if (neutralStart == -1)
neutralStart = i;
break;
@@ -657,7 +658,7 @@ public final class Bidi
? prevStrong
: embeddingDirection);
for (int j = neutralStart; j < i; ++j)
- types[i] = override;
+ types[j] = override;
}
prevStrong = newStrong;
neutralStart = -1;
diff --git a/java/util/Arrays.java b/java/util/Arrays.java
index cfe8f2e53..540765a8e 100644
--- a/java/util/Arrays.java
+++ b/java/util/Arrays.java
@@ -97,7 +97,7 @@ public class Arrays
int mid = 0;
while (low <= hi)
{
- mid = (low + hi) >> 1;
+ mid = (low + hi) >>> 1;
final byte d = a[mid];
if (d == key)
return mid;
@@ -131,7 +131,7 @@ public class Arrays
int mid = 0;
while (low <= hi)
{
- mid = (low + hi) >> 1;
+ mid = (low + hi) >>> 1;
final char d = a[mid];
if (d == key)
return mid;
@@ -165,7 +165,7 @@ public class Arrays
int mid = 0;
while (low <= hi)
{
- mid = (low + hi) >> 1;
+ mid = (low + hi) >>> 1;
final short d = a[mid];
if (d == key)
return mid;
@@ -199,7 +199,7 @@ public class Arrays
int mid = 0;
while (low <= hi)
{
- mid = (low + hi) >> 1;
+ mid = (low + hi) >>> 1;
final int d = a[mid];
if (d == key)
return mid;
@@ -233,7 +233,7 @@ public class Arrays
int mid = 0;
while (low <= hi)
{
- mid = (low + hi) >> 1;
+ mid = (low + hi) >>> 1;
final long d = a[mid];
if (d == key)
return mid;
@@ -268,7 +268,7 @@ public class Arrays
int mid = 0;
while (low <= hi)
{
- mid = (low + hi) >> 1;
+ mid = (low + hi) >>> 1;
final int r = Float.compare(a[mid], key);
if (r == 0)
return mid;
@@ -303,7 +303,7 @@ public class Arrays
int mid = 0;
while (low <= hi)
{
- mid = (low + hi) >> 1;
+ mid = (low + hi) >>> 1;
final int r = Double.compare(a[mid], key);
if (r == 0)
return mid;
@@ -369,7 +369,7 @@ public class Arrays
int mid = 0;
while (low <= hi)
{
- mid = (low + hi) >> 1;
+ mid = (low + hi) >>> 1;
final int d = Collections.compare(key, a[mid], c);
if (d == 0)
return mid;
diff --git a/java/util/Collections.java b/java/util/Collections.java
index 40268379a..bdc89a59a 100644
--- a/java/util/Collections.java
+++ b/java/util/Collections.java
@@ -701,7 +701,7 @@ public class Collections
boolean forward = true;
while (low <= hi)
{
- pos = (low + hi) >> 1;
+ pos = (low + hi) >>> 1;
if (i < pos)
{
if (!forward)
@@ -730,7 +730,7 @@ public class Collections
{
while (low <= hi)
{
- pos = (low + hi) >> 1;
+ pos = (low + hi) >>> 1;
final int d = compare(((List<T>) l).get(pos), key, c);
if (d == 0)
return pos;
diff --git a/java/util/logging/LogManager.java b/java/util/logging/LogManager.java
index 521145f6b..ae0f446a8 100644
--- a/java/util/logging/LogManager.java
+++ b/java/util/logging/LogManager.java
@@ -834,11 +834,11 @@ public class LogManager
}
catch (ClassNotFoundException e)
{
- warn(property, className, "class not found");
+ warn(property, className, "class not found", e);
}
catch (IllegalAccessException e)
{
- warn(property, className, "illegal access");
+ warn(property, className, "illegal access", e);
}
catch (InstantiationException e)
{
@@ -846,7 +846,7 @@ public class LogManager
}
catch (java.lang.LinkageError e)
{
- warn(property, className, "linkage error");
+ warn(property, className, "linkage error", e);
}
return null;
diff --git a/java/util/regex/Matcher.java b/java/util/regex/Matcher.java
index e86be25fc..25e73810e 100644
--- a/java/util/regex/Matcher.java
+++ b/java/util/regex/Matcher.java
@@ -38,9 +38,9 @@ exception statement from your version. */
package java.util.regex;
-import gnu.regexp.RE;
-import gnu.regexp.REMatch;
-import gnu.regexp.CharIndexed;
+import gnu.java.util.regex.CharIndexed;
+import gnu.java.util.regex.RE;
+import gnu.java.util.regex.REMatch;
/**
* Instance of a regular expression applied to a char sequence.
diff --git a/java/util/regex/Pattern.java b/java/util/regex/Pattern.java
index 8c1998343..89e67f9b4 100644
--- a/java/util/regex/Pattern.java
+++ b/java/util/regex/Pattern.java
@@ -37,9 +37,9 @@ exception statement from your version. */
package java.util.regex;
-import gnu.regexp.RE;
-import gnu.regexp.REException;
-import gnu.regexp.RESyntax;
+import gnu.java.util.regex.RE;
+import gnu.java.util.regex.REException;
+import gnu.java.util.regex.RESyntax;
import java.io.Serializable;
import java.util.ArrayList;
diff --git a/javax/swing/JComboBox.java b/javax/swing/JComboBox.java
index 38776f17f..140acf3a3 100644
--- a/javax/swing/JComboBox.java
+++ b/javax/swing/JComboBox.java
@@ -675,7 +675,7 @@ public class JComboBox extends JComponent implements ItemSelectable,
}
else
throw new RuntimeException("Unable to remove the items because the data "
- +"model it is not an instance of "
+ + "model it is not an instance of "
+ "MutableComboBoxModel.");
}
@@ -848,7 +848,7 @@ public class JComboBox extends JComponent implements ItemSelectable,
{
PopupMenuListener[] listeners = getPopupMenuListeners();
PopupMenuEvent e = new PopupMenuEvent(this);
- for(int i = 0; i < listeners.length; i++)
+ for (int i = 0; i < listeners.length; i++)
listeners[i].popupMenuCanceled(e);
}
@@ -862,7 +862,7 @@ public class JComboBox extends JComponent implements ItemSelectable,
{
PopupMenuListener[] listeners = getPopupMenuListeners();
PopupMenuEvent e = new PopupMenuEvent(this);
- for(int i = 0; i < listeners.length; i++)
+ for (int i = 0; i < listeners.length; i++)
listeners[i].popupMenuWillBecomeInvisible(e);
}
@@ -876,7 +876,7 @@ public class JComboBox extends JComponent implements ItemSelectable,
{
PopupMenuListener[] listeners = getPopupMenuListeners();
PopupMenuEvent e = new PopupMenuEvent(this);
- for(int i = 0; i < listeners.length; i++)
+ for (int i = 0; i < listeners.length; i++)
listeners[i].popupMenuWillBecomeVisible(e);
}
diff --git a/javax/swing/JComponent.java b/javax/swing/JComponent.java
index dbbad5c21..3b5311f5d 100644
--- a/javax/swing/JComponent.java
+++ b/javax/swing/JComponent.java
@@ -2039,19 +2039,10 @@ public abstract class JComponent extends Container implements Serializable
continue;
boolean translated = false;
- try
- {
- g.clipRect(bounds.x, bounds.y, bounds.width, bounds.height);
- g.translate(bounds.x, bounds.y);
- translated = true;
- children[i].paint(g);
- }
- finally
- {
- if (translated)
- g.translate(-bounds.x, -bounds.y);
- g.setClip(oldClip);
- }
+ Graphics g2 = g.create(bounds.x, bounds.y, bounds.width,
+ bounds.height);
+ children[i].paint(g2);
+ g2.dispose();
}
g.setClip(originalClip);
}
@@ -2183,8 +2174,13 @@ public abstract class JComponent extends Container implements Serializable
// Paint on the offscreen buffer.
Component root = getRoot(this);
- Image buffer = rm.getOffscreenBuffer(this, root.getWidth(),
- root.getHeight());
+ Image buffer = rm.getVolatileOffscreenBuffer(this, root.getWidth(),
+ root.getHeight());
+ // The volatile offscreen buffer may be null when that's not supported
+ // by the AWT backend. Fall back to normal backbuffer in this case.
+ if (buffer == null)
+ buffer = rm.getOffscreenBuffer(this, root.getWidth(), root.getHeight());
+
//Rectangle targetClip = SwingUtilities.convertRectangle(this, r, root);
Point translation = SwingUtilities.convertPoint(this, 0, 0, root);
Graphics g2 = buffer.getGraphics();
@@ -2361,6 +2357,19 @@ public abstract class JComponent extends Container implements Serializable
}
}
+ /**
+ * Returns the input map associated with this component for the given
+ * state/condition.
+ *
+ * @param condition the state (one of {@link #WHEN_FOCUSED},
+ * {@link #WHEN_ANCESTOR_OF_FOCUSED_COMPONENT} and
+ * {@link #WHEN_IN_FOCUSED_WINDOW}).
+ *
+ * @return The input map.
+ * @throws IllegalArgumentException if <code>condition</code> is not one of
+ * the specified values.
+ * @since 1.3
+ */
public final InputMap getInputMap(int condition)
{
enableEvents(AWTEvent.KEY_EVENT_MASK);
@@ -2383,10 +2392,20 @@ public abstract class JComponent extends Container implements Serializable
case UNDEFINED_CONDITION:
default:
- return null;
+ throw new IllegalArgumentException("Invalid 'condition' argument: "
+ + condition);
}
}
+ /**
+ * Returns the input map associated with this component for the
+ * {@link #WHEN_FOCUSED} state.
+ *
+ * @return The input map.
+ *
+ * @since 1.3
+ * @see #getInputMap(int)
+ */
public final InputMap getInputMap()
{
return getInputMap(WHEN_FOCUSED);
diff --git a/javax/swing/JEditorPane.java b/javax/swing/JEditorPane.java
index 73b775738..4ae3c5a1c 100644
--- a/javax/swing/JEditorPane.java
+++ b/javax/swing/JEditorPane.java
@@ -1,5 +1,5 @@
/* JEditorPane.java --
- Copyright (C) 2002, 2004, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2004, 2005, 2006, Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -538,8 +538,8 @@ public class JEditorPane extends JTextComponent
public JEditorPane(URL url) throws IOException
{
- init ();
- setEditorKit (createEditorKitForContentType("text/html"));;
+ init();
+ setEditorKit(createEditorKitForContentType("text/html"));;
setPage(url);
}
@@ -581,7 +581,7 @@ public class JEditorPane extends JTextComponent
// TODO: Have to handle the case where a ClassLoader was specified
// when the EditorKit was registered
EditorKit e = null;
- String className = (String)registerMap.get(type);
+ String className = (String) registerMap.get(type);
if (className != null)
{
try
diff --git a/javax/swing/JFormattedTextField.java b/javax/swing/JFormattedTextField.java
index 761955d6d..054752550 100644
--- a/javax/swing/JFormattedTextField.java
+++ b/javax/swing/JFormattedTextField.java
@@ -101,11 +101,11 @@ public class JFormattedTextField extends JTextField
* @throws CloneNotSupportedException if the Object's class doesn't support
* the {@link Cloneable} interface
*/
- protected Object clone ()
+ protected Object clone()
throws CloneNotSupportedException
{
// Clone this formatter.
- AbstractFormatter newFormatter = (AbstractFormatter)super.clone();
+ AbstractFormatter newFormatter = (AbstractFormatter) super.clone();
// And remove the association to the JFormattedTextField.
newFormatter.textField = null;
@@ -119,7 +119,7 @@ public class JFormattedTextField extends JTextField
* @return <code>null</code>. Should be subclassed by formatters that want
* to install custom Actions on the JFormattedTextField.
*/
- protected Action[] getActions ()
+ protected Action[] getActions()
{
return null;
}
@@ -132,7 +132,7 @@ public class JFormattedTextField extends JTextField
* @return <code>null</code>. Should be subclassed by formatters
* that want to restrict Document mutations.
*/
- protected DocumentFilter getDocumentFilter ()
+ protected DocumentFilter getDocumentFilter()
{
// Subclasses should override this if they want to install a
// DocumentFilter.
@@ -146,7 +146,7 @@ public class JFormattedTextField extends JTextField
* @return the JFormattedTextField on which this formatter is currently
* installed
*/
- protected JFormattedTextField getFormattedTextField ()
+ protected JFormattedTextField getFormattedTextField()
{
return textField;
}
@@ -159,7 +159,7 @@ public class JFormattedTextField extends JTextField
* @return <code>null</code>. Subclassed by formatters that want to restrict
* cursor location within the JFormattedTextField.
*/
- protected NavigationFilter getNavigationFilter ()
+ protected NavigationFilter getNavigationFilter()
{
// This should be subclassed if the formatter wants to install
// a NavigationFilter on the JFormattedTextField.
@@ -199,7 +199,7 @@ public class JFormattedTextField extends JTextField
// Set the DocumentFilter for the field's Document.
if (doc instanceof AbstractDocument)
- ((AbstractDocument)doc).setDocumentFilter(getDocumentFilter());
+ ((AbstractDocument) doc).setDocumentFilter(getDocumentFilter());
// Set the NavigationFilter.
textField.setNavigationFilter(getNavigationFilter());
@@ -221,12 +221,12 @@ public class JFormattedTextField extends JTextField
* This resets the DocumentFilter, NavigationFilter, and any additional
* Actions (returned by <code>getActions()</code>).
*/
- public void uninstall ()
+ public void uninstall()
{
// Set the DocumentFilter for the field's Document.
Document doc = textField.getDocument();
if (doc instanceof AbstractDocument)
- ((AbstractDocument)doc).setDocumentFilter(null);
+ ((AbstractDocument) doc).setDocumentFilter(null);
textField.setNavigationFilter(null);
// FIXME: Have to remove the Actions from getActions()
this.textField = null;
@@ -236,7 +236,7 @@ public class JFormattedTextField extends JTextField
* Invoke this method when invalid values are entered. This forwards the
* call to the JFormattedTextField.
*/
- protected void invalidEdit ()
+ protected void invalidEdit()
{
textField.invalidEdit();
}
@@ -247,7 +247,7 @@ public class JFormattedTextField extends JTextField
*
* @param valid the new state for the <code>editValid</code> property
*/
- protected void setEditValid (boolean valid)
+ protected void setEditValid(boolean valid)
{
textField.editValid = valid;
}
@@ -259,7 +259,7 @@ public class JFormattedTextField extends JTextField
* @return an Object that <code>text</code> represented
* @throws ParseException if there is an error in the conversion
*/
- public abstract Object stringToValue (String text)
+ public abstract Object stringToValue(String text)
throws ParseException;
/**
@@ -270,7 +270,7 @@ public class JFormattedTextField extends JTextField
* @return a String to be displayed
* @throws ParseException if there is an error in the conversion
*/
- public abstract String valueToString (Object value)
+ public abstract String valueToString(Object value)
throws ParseException;
}
@@ -280,12 +280,12 @@ public class JFormattedTextField extends JTextField
*/
public abstract static class AbstractFormatterFactory
{
- public AbstractFormatterFactory ()
+ public AbstractFormatterFactory()
{
// Do nothing here.
}
- public abstract AbstractFormatter getFormatter (JFormattedTextField tf);
+ public abstract AbstractFormatter getFormatter(JFormattedTextField tf);
}
/** The possible focusLostBehavior options **/
@@ -315,7 +315,7 @@ public class JFormattedTextField extends JTextField
* properly configure this text field to edit a particular type
* of value.
*/
- public JFormattedTextField ()
+ public JFormattedTextField()
{
this((AbstractFormatterFactory) null, null);
}
@@ -328,7 +328,7 @@ public class JFormattedTextField extends JTextField
* @param format the Format that this JFormattedTextField should be able
* to handle
*/
- public JFormattedTextField (Format format)
+ public JFormattedTextField(Format format)
{
this ();
setFormatterFactory(getAppropriateFormatterFactory(format));
@@ -341,9 +341,9 @@ public class JFormattedTextField extends JTextField
*
* @param formatter the formatter to use for this JFormattedTextField
*/
- public JFormattedTextField (AbstractFormatter formatter)
+ public JFormattedTextField(AbstractFormatter formatter)
{
- this(new DefaultFormatterFactory (formatter));
+ this(new DefaultFormatterFactory(formatter));
}
/**
@@ -351,7 +351,7 @@ public class JFormattedTextField extends JTextField
*
* @param factory the formatter factory to use for this JFormattedTextField
*/
- public JFormattedTextField (AbstractFormatterFactory factory)
+ public JFormattedTextField(AbstractFormatterFactory factory)
{
setFormatterFactory(factory);
}
@@ -363,7 +363,7 @@ public class JFormattedTextField extends JTextField
* @param factory the initial formatter factory for this JFormattedTextField
* @param value the initial value for the text field
*/
- public JFormattedTextField (AbstractFormatterFactory factory, Object value)
+ public JFormattedTextField(AbstractFormatterFactory factory, Object value)
{
setFormatterFactory(factory);
setValue(value);
@@ -375,7 +375,7 @@ public class JFormattedTextField extends JTextField
*
* @param value the initial value for this JFormattedTextField
*/
- public JFormattedTextField (Object value)
+ public JFormattedTextField(Object value)
{
setValue(value);
}
@@ -387,13 +387,13 @@ public class JFormattedTextField extends JTextField
* @return a DefaultFormatterFactory whose defaultFormatter is appropriate
* for the given Format.
*/
- private AbstractFormatterFactory getAppropriateFormatterFactory (Format format)
+ private AbstractFormatterFactory getAppropriateFormatterFactory(Format format)
{
AbstractFormatter newFormatter;
if (format instanceof DateFormat)
- newFormatter = new DateFormatter((DateFormat)format);
+ newFormatter = new DateFormatter((DateFormat) format);
else if (format instanceof NumberFormat)
- newFormatter = new NumberFormatter ((NumberFormat)format);
+ newFormatter = new NumberFormatter ((NumberFormat) format);
else
newFormatter = new InternationalFormatter(format);
@@ -406,7 +406,7 @@ public class JFormattedTextField extends JTextField
*
* @throws ParseException if the formatter cannot format the current value
*/
- public void commitEdit ()
+ public void commitEdit()
throws ParseException
{
if (formatter == null)
@@ -427,7 +427,7 @@ public class JFormattedTextField extends JTextField
*
* @return an array of Actions that this text field supports
*/
- public Action[] getActions ()
+ public Action[] getActions()
{
// FIXME: Add JFormattedTextField specific actions
// These are related to committing or cancelling edits.
@@ -449,7 +449,7 @@ public class JFormattedTextField extends JTextField
* Returns the current formatter used for this JFormattedTextField.
* @return the current formatter used for this JFormattedTextField
*/
- public AbstractFormatter getFormatter ()
+ public AbstractFormatter getFormatter()
{
return formatter;
}
@@ -459,12 +459,12 @@ public class JFormattedTextField extends JTextField
* JFormattedTextField.
* @return the factory currently used to generate formatters
*/
- public AbstractFormatterFactory getFormatterFactory ()
+ public AbstractFormatterFactory getFormatterFactory()
{
return formatterFactory;
}
- public String getUIClassID ()
+ public String getUIClassID()
{
return "FormattedTextFieldUI";
}
@@ -475,7 +475,7 @@ public class JFormattedTextField extends JTextField
* valid edits and allows invalid input to be temporarily displayed.
* @return the last committed valid value
*/
- public Object getValue ()
+ public Object getValue()
{
return value;
}
@@ -484,7 +484,7 @@ public class JFormattedTextField extends JTextField
* This method is used to provide feedback to the user when an invalid value
* is input during editing.
*/
- protected void invalidEdit ()
+ protected void invalidEdit()
{
UIManager.getLookAndFeel().provideErrorFeedback(this);
}
@@ -494,7 +494,7 @@ public class JFormattedTextField extends JTextField
* managed by the current formatted.
* @return true if the value being edited is valid.
*/
- public boolean isEditValid ()
+ public boolean isEditValid()
{
return editValid;
}
@@ -506,7 +506,7 @@ public class JFormattedTextField extends JTextField
*
* @param evt the FocusEvent
*/
- protected void processFocusEvent (FocusEvent evt)
+ protected void processFocusEvent(FocusEvent evt)
{
super.processFocusEvent(evt);
// Let the formatterFactory change the formatter for this text field
@@ -561,7 +561,7 @@ public class JFormattedTextField extends JTextField
* @param formatter the AbstractFormatter to use for formatting the value for
* this JFormattedTextField
*/
- protected void setFormatter (AbstractFormatter formatter)
+ protected void setFormatter(AbstractFormatter formatter)
{
AbstractFormatter oldFormatter = null;
@@ -585,7 +585,7 @@ public class JFormattedTextField extends JTextField
* @param factory the AbstractFormatterFactory that will be used to generate
* formatters for this JFormattedTextField
*/
- public void setFormatterFactory (AbstractFormatterFactory factory)
+ public void setFormatterFactory(AbstractFormatterFactory factory)
{
if (formatterFactory == factory)
return;
@@ -606,7 +606,7 @@ public class JFormattedTextField extends JTextField
*
* @param newValue the value to be formatted and displayed
*/
- public void setValue (Object newValue)
+ public void setValue(Object newValue)
{
if (value == newValue)
return;
diff --git a/javax/swing/JFrame.java b/javax/swing/JFrame.java
index 11b9c1fd3..1371525dd 100644
--- a/javax/swing/JFrame.java
+++ b/javax/swing/JFrame.java
@@ -157,7 +157,8 @@ public class JFrame extends Frame
protected void frameInit()
{
- super.setLayout(new BorderLayout(1, 1));
+ super.setLayout(new BorderLayout());
+ setBackground(UIManager.getDefaults().getColor("control"));
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
getRootPane(); // will do set/create
diff --git a/javax/swing/JLayeredPane.java b/javax/swing/JLayeredPane.java
index 0ad38b5e9..c097c655a 100644
--- a/javax/swing/JLayeredPane.java
+++ b/javax/swing/JLayeredPane.java
@@ -147,19 +147,19 @@ public class JLayeredPane extends JComponent implements Accessible
public static final String LAYER_PROPERTY = "layeredContainerLayer";
- public static final Integer FRAME_CONTENT_LAYER = new Integer (-30000);
+ public static final Integer FRAME_CONTENT_LAYER = new Integer(-30000);
- public static final Integer DEFAULT_LAYER = new Integer (0);
- public static final Integer PALETTE_LAYER = new Integer (100);
- public static final Integer MODAL_LAYER = new Integer (200);
- public static final Integer POPUP_LAYER = new Integer (300);
- public static final Integer DRAG_LAYER = new Integer (400);
+ public static final Integer DEFAULT_LAYER = new Integer(0);
+ public static final Integer PALETTE_LAYER = new Integer(100);
+ public static final Integer MODAL_LAYER = new Integer(200);
+ public static final Integer POPUP_LAYER = new Integer(300);
+ public static final Integer DRAG_LAYER = new Integer(400);
private Hashtable componentToLayer; // Component -> Layer Number (Integer)
public JLayeredPane()
{
- componentToLayer = new Hashtable ();
+ componentToLayer = new Hashtable();
setLayout(null);
}
diff --git a/javax/swing/JMenuBar.java b/javax/swing/JMenuBar.java
index 18e47dcd9..35f129377 100644
--- a/javax/swing/JMenuBar.java
+++ b/javax/swing/JMenuBar.java
@@ -370,10 +370,30 @@ public class JMenuBar extends JComponent implements Accessible, MenuElement
{
MenuElement[] subElements = new MenuElement[getComponentCount()];
+ int j = 0;
+ boolean doResize = false;
+ MenuElement menu;
for (int i = 0; i < getComponentCount(); i++)
- subElements[i] = (MenuElement) getMenu(i);
+ {
+ menu = getMenu(i);
+ if (menu != null)
+ {
+ subElements[j++] = (MenuElement) menu;
+ }
+ else
+ doResize = true;
+ }
- return subElements;
+ if (! doResize)
+ return subElements;
+ else
+ {
+ MenuElement[] subElements2 = new MenuElement[j];
+ for (int i = 0; i < j; i++)
+ subElements2[i] = subElements[i];
+
+ return subElements2;
+ }
}
/**
@@ -522,6 +542,9 @@ public class JMenuBar extends JComponent implements Accessible, MenuElement
KeyEvent e, int condition,
boolean pressed)
{
+ if (menuElement == null)
+ return false;
+
// First check the menuElement itself, if it's a JComponent
if (menuElement instanceof JComponent
&& ((JComponent) menuElement).processKeyBinding(ks, e, condition,
diff --git a/javax/swing/JMenuItem.java b/javax/swing/JMenuItem.java
index f04008bcd..90d54b1d3 100644
--- a/javax/swing/JMenuItem.java
+++ b/javax/swing/JMenuItem.java
@@ -38,8 +38,6 @@ exception statement from your version. */
package javax.swing;
-import gnu.classpath.NotImplementedException;
-
import java.awt.Component;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
@@ -51,6 +49,7 @@ import java.util.EventListener;
import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;
+import javax.accessibility.AccessibleState;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.MenuDragMouseEvent;
@@ -696,7 +695,11 @@ public class JMenuItem extends AbstractButton implements Accessible,
public AccessibleContext getAccessibleContext()
{
if (accessibleContext == null)
- accessibleContext = new AccessibleJMenuItem();
+ {
+ AccessibleJMenuItem ctx = new AccessibleJMenuItem();
+ addChangeListener(ctx);
+ accessibleContext = ctx;
+ }
return accessibleContext;
}
@@ -712,6 +715,11 @@ public class JMenuItem extends AbstractButton implements Accessible,
{
private static final long serialVersionUID = 6748924232082076534L;
+ private boolean armed;
+ private boolean focusOwner;
+ private boolean pressed;
+ private boolean selected;
+
/**
* Creates a new <code>AccessibleJMenuItem</code> instance.
*/
@@ -720,10 +728,99 @@ public class JMenuItem extends AbstractButton implements Accessible,
//super(component);
}
+ /**
+ * Receives notification when the menu item's state changes and fires
+ * appropriate property change events to registered listeners.
+ *
+ * @param event the change event
+ */
public void stateChanged(ChangeEvent event)
- throws NotImplementedException
{
- // TODO: What should be done here, if anything?
+ // This is fired in all cases.
+ firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
+ Boolean.FALSE, Boolean.TRUE);
+
+ ButtonModel model = getModel();
+
+ // Handle the armed property.
+ if (model.isArmed())
+ {
+ if (! armed)
+ {
+ armed = true;
+ firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
+ AccessibleState.ARMED, null);
+ }
+ }
+ else
+ {
+ if (armed)
+ {
+ armed = false;
+ firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
+ null, AccessibleState.ARMED);
+ }
+ }
+
+ // Handle the pressed property.
+ if (model.isPressed())
+ {
+ if (! pressed)
+ {
+ pressed = true;
+ firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
+ AccessibleState.PRESSED, null);
+ }
+ }
+ else
+ {
+ if (pressed)
+ {
+ pressed = false;
+ firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
+ null, AccessibleState.PRESSED);
+ }
+ }
+
+ // Handle the selected property.
+ if (model.isSelected())
+ {
+ if (! selected)
+ {
+ selected = true;
+ firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
+ AccessibleState.SELECTED, null);
+ }
+ }
+ else
+ {
+ if (selected)
+ {
+ selected = false;
+ firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
+ null, AccessibleState.SELECTED);
+ }
+ }
+
+ // Handle the focusOwner property.
+ if (isFocusOwner())
+ {
+ if (! focusOwner)
+ {
+ focusOwner = true;
+ firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
+ AccessibleState.FOCUSED, null);
+ }
+ }
+ else
+ {
+ if (focusOwner)
+ {
+ focusOwner = false;
+ firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
+ null, AccessibleState.FOCUSED);
+ }
+ }
}
/**
diff --git a/javax/swing/JScrollPane.java b/javax/swing/JScrollPane.java
index 09e37378b..45df1d919 100644
--- a/javax/swing/JScrollPane.java
+++ b/javax/swing/JScrollPane.java
@@ -170,7 +170,8 @@ public class JScrollPane extends JComponent
return columnHeader;
}
- public Component getCorner(String key) {
+ public Component getCorner(String key)
+ {
if (getComponentOrientation()
== ComponentOrientation.LEFT_TO_RIGHT)
{
@@ -247,7 +248,7 @@ public class JScrollPane extends JComponent
if (viewportBorder == null)
{
if (getViewport() == null)
- return new Rectangle(0,0,0,0);
+ return new Rectangle(0, 0, 0, 0);
else
return getViewport().getBounds();
}
@@ -255,8 +256,7 @@ public class JScrollPane extends JComponent
{
Insets i = viewportBorder.getBorderInsets(getViewport());
if (getViewport() == null)
- return new Rectangle(0,0,
- i.left+i.right, i.top+i.bottom);
+ return new Rectangle(0, 0, i.left + i.right, i.top + i.bottom);
else
{
Rectangle b = getViewport().getBounds();
diff --git a/javax/swing/JSlider.java b/javax/swing/JSlider.java
index ed94c4ecc..8a06d4f01 100644
--- a/javax/swing/JSlider.java
+++ b/javax/swing/JSlider.java
@@ -227,13 +227,13 @@ public class JSlider extends JComponent implements SwingConstants, Accessible,
}
/** Whether or not this slider paints its ticks. */
- private transient boolean paintTicks = false;
+ private transient boolean paintTicks;
/** Whether or not this slider paints its track. */
private transient boolean paintTrack = true;
/** Whether or not this slider paints its labels. */
- private transient boolean paintLabels = false;
+ private transient boolean paintLabels;
/**
* A dictionary of (Integer, Component) pairs where each Component is a
@@ -251,7 +251,7 @@ public class JSlider extends JComponent implements SwingConstants, Accessible,
protected int minorTickSpacing;
/** Whether the slider snaps its values to ticks. */
- protected boolean snapToTicks = false;
+ protected boolean snapToTicks;
/** The orientation (horizontal or vertical) of the slider. */
protected int orientation = HORIZONTAL;
diff --git a/javax/swing/JSpinner.java b/javax/swing/JSpinner.java
index 70045ed53..16a210600 100644
--- a/javax/swing/JSpinner.java
+++ b/javax/swing/JSpinner.java
@@ -106,7 +106,7 @@ public class JSpinner extends JComponent
add(ftf);
ftf.setValue(spinner.getValue());
ftf.addPropertyChangeListener(this);
- if(getComponentOrientation().isLeftToRight())
+ if (getComponentOrientation().isLeftToRight())
ftf.setHorizontalAlignment(JTextField.RIGHT);
else
ftf.setHorizontalAlignment(JTextField.LEFT);
diff --git a/javax/swing/JSplitPane.java b/javax/swing/JSplitPane.java
index c11512198..2747686a3 100644
--- a/javax/swing/JSplitPane.java
+++ b/javax/swing/JSplitPane.java
@@ -108,7 +108,7 @@ public class JSplitPane extends JComponent implements Accessible
/**
* Returns an object that provides access to the current, minimum and
- * maximum values for the {@link JSlider}. Since this class implements
+ * maximum values for the {@link JSplitPane}. Since this class implements
* {@link AccessibleValue}, it returns itself.
*
* @return The accessible value.
@@ -136,9 +136,9 @@ public class JSplitPane extends JComponent implements Accessible
* listeners. If the supplied value is <code>null</code>, this method
* does nothing and returns <code>false</code>.
*
- * @param value the new slider value (<code>null</code> permitted).
+ * @param value the new divider location (<code>null</code> permitted).
*
- * @return <code>true</code> if the slider value is updated, and
+ * @return <code>true</code> if the divider location value is updated, and
* <code>false</code> otherwise.
*/
public boolean setCurrentAccessibleValue(Number value)
@@ -699,7 +699,8 @@ public class JSplitPane extends JComponent implements Accessible
* @param proportionalLocation A double that describes the location of the
* divider.
*
- * @throws IllegalArgumentException DOCUMENT ME!
+ * @throws IllegalArgumentException if <code>proportionalLocation</code> is
+ * not in the range from 0.0 to 1.0 inclusive.
*/
public void setDividerLocation(double proportionalLocation)
{
diff --git a/javax/swing/JTabbedPane.java b/javax/swing/JTabbedPane.java
index 76cc74eab..ee6af857e 100644
--- a/javax/swing/JTabbedPane.java
+++ b/javax/swing/JTabbedPane.java
@@ -38,8 +38,6 @@ exception statement from your version. */
package javax.swing;
-import gnu.classpath.NotImplementedException;
-
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
@@ -53,6 +51,7 @@ import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;
import javax.accessibility.AccessibleSelection;
+import javax.accessibility.AccessibleState;
import javax.accessibility.AccessibleStateSet;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
@@ -97,14 +96,17 @@ public class JTabbedPane extends JComponent implements Serializable,
/**
* Receives notification when the selection state of the
- * <code>JTabbedPane</code> changes.
+ * <code>JTabbedPane</code> changes and fires appropriate property change
+ * events to interested listeners.
*
* @param e the change event describing the change
*/
public void stateChanged(ChangeEvent e)
- throws NotImplementedException
{
- // FIXME: Implement this properly.
+ // I couldn't figure out what else should be done here.
+ Object source = e.getSource();
+ firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
+ null, source);
}
/**
@@ -623,18 +625,31 @@ public class JTabbedPane extends JComponent implements Serializable,
return AccessibleRole.PAGE_TAB;
}
+ /**
+ * Returns the accessible state set of this object.
+ *
+ * @return the accessible state set of this object
+ */
public AccessibleStateSet getAccessibleStateSet()
- throws NotImplementedException
{
- // FIXME: Implement this properly.
- return null;
+ AccessibleContext parentCtx = JTabbedPane.this.getAccessibleContext();
+ AccessibleStateSet state = parentCtx.getAccessibleStateSet();
+ state.add(AccessibleState.SELECTABLE);
+ if (component == getSelectedComponent())
+ state.add(AccessibleState.SELECTED);
+ return state;
}
+ /**
+ * Returns the index of this tab inside its parent.
+ *
+ * @return the index of this tab inside its parent
+ */
public int getAccessibleIndexInParent()
- throws NotImplementedException
{
- // FIXME: Implement this properly.
- return 0;
+ // TODO: Not sure if the title is unambiguous, but I can't figure
+ // another way of doing this.
+ return indexOfTab(title);
}
/**
@@ -975,10 +990,6 @@ public class JTabbedPane extends JComponent implements Serializable,
checkIndex(index, -1, tabs.size());
if (index != getSelectedIndex())
{
- if (getSelectedIndex() != -1 && getSelectedComponent() != null)
- getSelectedComponent().hide();
- if (index != -1 && getComponentAt(index) != null)
- getComponentAt(index).show();
model.setSelectedIndex(index);
}
}
@@ -1671,7 +1682,12 @@ public class JTabbedPane extends JComponent implements Serializable,
public AccessibleContext getAccessibleContext()
{
if (accessibleContext == null)
- accessibleContext = new AccessibleJTabbedPane();
+ {
+ AccessibleJTabbedPane ctx = new AccessibleJTabbedPane();
+ addChangeListener(ctx);
+ accessibleContext = ctx;
+ }
+
return accessibleContext;
}
}
diff --git a/javax/swing/JTable.java b/javax/swing/JTable.java
index a81cb71ee..f61ce47da 100644
--- a/javax/swing/JTable.java
+++ b/javax/swing/JTable.java
@@ -38,8 +38,6 @@ exception statement from your version. */
package javax.swing;
-import gnu.classpath.NotImplementedException;
-
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
@@ -65,6 +63,7 @@ import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleExtendedTable;
import javax.accessibility.AccessibleRole;
import javax.accessibility.AccessibleSelection;
+import javax.accessibility.AccessibleState;
import javax.accessibility.AccessibleStateSet;
import javax.accessibility.AccessibleTable;
import javax.accessibility.AccessibleTableModelChange;
@@ -165,9 +164,10 @@ public class JTable
* @return the accessible row for the table cell
*/
public AccessibleRole getAccessibleRole()
- throws NotImplementedException
{
// TODO: What is the role of the table cell?
+ // Seems like the RI returns UNKNOWN here for 'normal' cells, might
+ // be different for special renderers though (not tested yet).
return AccessibleRole.UNKNOWN;
}
@@ -177,10 +177,28 @@ public class JTable
* @return the accessible state set of this accessible table cell
*/
public AccessibleStateSet getAccessibleStateSet()
- throws NotImplementedException
{
- // TODO: What state shoiuld be returned here?
- return new AccessibleStateSet();
+ AccessibleStateSet state = new AccessibleStateSet();
+
+ // Figure out the SHOWING state.
+ Rectangle visibleRect = getVisibleRect();
+ Rectangle cellRect = getCellRect(row, column, false);
+ if (visibleRect.intersects(cellRect))
+ state.add(AccessibleState.SHOWING);
+
+ // Figure out SELECTED state.
+ if (isCellSelected(row, column))
+ state.add(AccessibleState.SELECTED);
+
+ // Figure out ACTIVE state.
+ if (row == getSelectedRow() && column == getSelectedColumn())
+ state.add(AccessibleState.ACTIVE);
+
+ // TRANSIENT seems to be always set in the RI.
+ state.add(AccessibleState.TRANSIENT);
+
+ // TODO: Any other state to handle here?
+ return state;
}
/**
@@ -598,7 +616,504 @@ public class JTable
return lastColumn;
}
}
-
+
+ /**
+ * The RI returns an instance with this name in
+ * {@link #getAccessibleColumnHeader()}, this makes sense, so we do the
+ * same.
+ */
+ private class AccessibleTableHeader
+ implements AccessibleTable
+ {
+
+ /**
+ * The JTableHeader wrapped by this class.
+ */
+ private JTableHeader header;
+
+ /**
+ * Creates a new instance.
+ *
+ * @param h the JTableHeader to wrap
+ */
+ private AccessibleTableHeader(JTableHeader h)
+ {
+ header = h;
+ }
+
+ /**
+ * Returns the caption for the table header.
+ *
+ * @return the caption for the table header
+ */
+ public Accessible getAccessibleCaption()
+ {
+ // The RI seems to always return null here, so do we.
+ return null;
+ }
+
+ /**
+ * Sets the caption for the table header.
+ *
+ * @param caption the caption to set
+ */
+ public void setAccessibleCaption(Accessible caption)
+ {
+ // This seems to be a no-op in the RI, so we do the same.
+ }
+
+ /**
+ * Returns the caption for the table header.
+ *
+ * @return the caption for the table header
+ */
+ public Accessible getAccessibleSummary()
+ {
+ // The RI seems to always return null here, so do we.
+ return null;
+ }
+
+ /**
+ * Sets the summary for the table header.
+ *
+ * @param summary the caption to set
+ */
+ public void setAccessibleSummary(Accessible summary)
+ {
+ // This seems to be a no-op in the RI, so we do the same.
+ }
+
+ /**
+ * Returns the number of rows, which is always 1 for the table header.
+ *
+ * @return the number of rows
+ */
+ public int getAccessibleRowCount()
+ {
+ return 1;
+ }
+
+ /**
+ * Returns the number of columns in the table header.
+ *
+ * @return the number of columns in the table header
+ */
+ public int getAccessibleColumnCount()
+ {
+ return header.getColumnModel().getColumnCount();
+ }
+
+ /**
+ * Returns the accessible child at the specified row and column.
+ * The row number is ignored here, and we return an
+ * AccessibleJTableHeaderCell here with the renderer component as
+ * component.
+ *
+ * @param r the row number
+ * @param c the column number
+ *
+ * @return the accessible child at the specified row and column
+ */
+ public Accessible getAccessibleAt(int r, int c)
+ {
+ TableColumn column = header.getColumnModel().getColumn(c);
+ TableCellRenderer rend = column.getHeaderRenderer();
+ if (rend == null)
+ rend = header.getDefaultRenderer();
+ Component comp =
+ rend.getTableCellRendererComponent(header.getTable(),
+ column.getHeaderValue(), false,
+ false, -1, c);
+ return new AccessibleJTableHeaderCell(header, comp, r, c);
+ }
+
+ public int getAccessibleRowExtentAt(int r, int c)
+ {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ public int getAccessibleColumnExtentAt(int r, int c)
+ {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ public AccessibleTable getAccessibleRowHeader()
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void setAccessibleRowHeader(AccessibleTable header)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public AccessibleTable getAccessibleColumnHeader()
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void setAccessibleColumnHeader(AccessibleTable header)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public Accessible getAccessibleRowDescription(int r)
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void setAccessibleRowDescription(int r, Accessible description)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public Accessible getAccessibleColumnDescription(int c)
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void setAccessibleColumnDescription(int c, Accessible description)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public boolean isAccessibleSelected(int r, int c)
+ {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public boolean isAccessibleRowSelected(int r)
+ {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public boolean isAccessibleColumnSelected(int c)
+ {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public int[] getSelectedAccessibleRows()
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public int[] getSelectedAccessibleColumns()
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ }
+
+ /**
+ * The RI returns an instance of such class for table header cells. This
+ * makes sense so I added this class. This still needs to be fully
+ * implemented, I just don't feel motivated enough to do so just now.
+ */
+ private class AccessibleJTableHeaderCell
+ extends AccessibleContext
+ implements Accessible, AccessibleComponent
+ {
+
+ JTableHeader header;
+
+ int columnIndex;
+
+ /**
+ *
+ * @param h the table header.
+ * @param comp
+ * @param r
+ * @param c the column index.
+ */
+ private AccessibleJTableHeaderCell(JTableHeader h, Component comp, int r,
+ int c)
+ {
+ header = h;
+ columnIndex = c;
+ }
+
+ /**
+ * Returns the header renderer.
+ *
+ * @return The header renderer.
+ */
+ Component getColumnHeaderRenderer()
+ {
+ TableColumn tc = header.getColumnModel().getColumn(columnIndex);
+ TableCellRenderer r = tc.getHeaderRenderer();
+ if (r == null)
+ r = header.getDefaultRenderer();
+ return r.getTableCellRendererComponent(header.getTable(),
+ tc.getHeaderValue(), false, false, -1, columnIndex);
+ }
+
+ /**
+ * Returns the accessible role for the table header cell.
+ *
+ * @return The accessible role.
+ */
+ public AccessibleRole getAccessibleRole()
+ {
+ Component renderer = getColumnHeaderRenderer();
+ if (renderer instanceof Accessible)
+ {
+ Accessible ac = (Accessible) renderer;
+ return ac.getAccessibleContext().getAccessibleRole();
+ }
+ return null;
+ }
+
+ public AccessibleStateSet getAccessibleStateSet()
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public int getAccessibleIndexInParent()
+ {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ public int getAccessibleChildrenCount()
+ {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ public Accessible getAccessibleChild(int i)
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Locale getLocale()
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ /**
+ * Returns the accessible context.
+ *
+ * @return <code>this</code>.
+ */
+ public AccessibleContext getAccessibleContext()
+ {
+ return this;
+ }
+
+ public Color getBackground()
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void setBackground(Color color)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public Color getForeground()
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void setForeground(Color color)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public Cursor getCursor()
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void setCursor(Cursor cursor)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public Font getFont()
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void setFont(Font font)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public FontMetrics getFontMetrics(Font font)
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public boolean isEnabled()
+ {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public void setEnabled(boolean b)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public boolean isVisible()
+ {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public void setVisible(boolean b)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public boolean isShowing()
+ {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public boolean contains(Point point)
+ {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public Point getLocationOnScreen()
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Point getLocation()
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void setLocation(Point point)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public Rectangle getBounds()
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void setBounds(Rectangle rectangle)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public Dimension getSize()
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void setSize(Dimension dimension)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public Accessible getAccessibleAt(Point point)
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public boolean isFocusTraversable()
+ {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public void requestFocus()
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void addFocusListener(FocusListener listener)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void removeFocusListener(FocusListener listener)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+
+ /**
+ * The last selected row. This is needed to track the selection in
+ * {@link #valueChanged(ListSelectionEvent)}.
+ */
+ private int lastSelectedRow;
+
+ /**
+ * The last selected column. This is needed to track the selection in
+ * {@link #valueChanged(ListSelectionEvent)}.
+ */
+ private int lastSelectedColumn;
+
+ /**
+ * The caption of the table.
+ */
+ private Accessible caption;
+
+ /**
+ * The summary of the table.
+ */
+ private Accessible summary;
+
+ /**
+ * Accessible descriptions for rows.
+ */
+ private Accessible[] rowDescriptions;
+
+ /**
+ * Accessible descriptions for columns.
+ */
+ private Accessible[] columnDescriptions;
+
/**
* Creates a new <code>AccessibleJTable</code>.
*
@@ -609,10 +1124,34 @@ public class JTable
getModel().addTableModelListener(this);
getSelectionModel().addListSelectionListener(this);
getColumnModel().addColumnModelListener(this);
- getCellEditor().addCellEditorListener(this);
+ lastSelectedRow = getSelectedRow();
+ lastSelectedColumn = getSelectedColumn();
+ TableCellEditor editor = getCellEditor();
+ if (editor != null)
+ editor.addCellEditorListener(this);
}
/**
+ * Returns the accessible role for the <code>JTable</code> component.
+ *
+ * @return {@link AccessibleRole#TABLE}.
+ */
+ public AccessibleRole getAccessibleRole()
+ {
+ return AccessibleRole.TABLE;
+ }
+
+ /**
+ * Returns the accessible table.
+ *
+ * @return <code>this</code>.
+ */
+ public AccessibleTable getAccessibleTable()
+ {
+ return this;
+ }
+
+ /**
* Returns the number of selected items in this table.
*/
public int getAccessibleSelectionCount()
@@ -620,48 +1159,197 @@ public class JTable
return getSelectedColumnCount();
}
+ /**
+ * Returns the selected accessible object with the specified index
+ * <code>i</code>. This basically returns the i-th selected cell in the
+ * table when going though it row-wise, and inside the rows, column-wise.
+ *
+ * @param i the index of the selected object to find
+ *
+ * @return the selected accessible object with the specified index
+ * <code>i</code>
+ */
public Accessible getAccessibleSelection(int i)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return null;
+ Accessible found = null;
+
+ int[] selectedRows = getSelectedRows();
+ int[] selectedColumns = getSelectedColumns();
+ int numCols = getColumnCount();
+ int numRows = getRowCount();
+
+ // We have to go through every selected row and column and count until we
+ // find the specified index. This is potentially inefficient, but I can't
+ // think of anything better atm.
+ if (getRowSelectionAllowed() && getColumnSelectionAllowed())
+ {
+ int current = -1;
+ int newIndex = current;
+ int lastSelectedRow = -1;
+ // Go through the selected rows array, don't forget the selected
+ // cells inside the not-selected rows' columns.
+ for (int j = 0; i < selectedRows.length; i++)
+ {
+ // Handle unselected rows between this selected and the last
+ // selected row, if any.
+ int selectedRow = selectedRows[j];
+ int r = -1;
+ int ci = -1;
+ for (r = lastSelectedRow + 1;
+ r < selectedRow && current < i; r++)
+ {
+ for (ci = 0; ci < selectedColumns.length && current < i;
+ ci++)
+ {
+ current++;
+ }
+ }
+ if (current == i)
+ {
+ // We found the cell in the above loops, now get out of here.
+ found = getAccessibleChild(r * numCols
+ + selectedColumns[ci]);
+ break;
+ }
+
+ // If we're still here, handle the current selected row.
+ if (current < i && current + numCols >= i)
+ {
+ // The cell must be in that row, which one is it?
+ found = getAccessibleChild(r * numCols + (i - current));
+ break;
+ }
+ current += numCols;
+ }
+ if (found == null)
+ {
+ // The cell can still be in the last couple of unselected rows.
+ int r = 0;
+ int ci = 0;
+ for (r = lastSelectedRow + 1;
+ r < numRows && current < i; r++)
+ {
+ for (ci = 0; ci < selectedColumns.length && current < i;
+ ci++)
+ {
+ current++;
+ }
+ }
+ if (current == i)
+ {
+ // We found the cell in the above loops, now get out of here.
+ found = getAccessibleChild(r * numCols
+ + selectedColumns[ci]);
+ }
+ }
+ }
+ // One or more rows can be completely selected.
+ else if (getRowSelectionAllowed())
+ {
+ int c = i % numCols;
+ int r = selectedRows[i / numCols];
+ found = getAccessibleChild(r * numCols + c);
+ }
+ // One or more columns can be completely selected.
+ else if (getRowSelectionAllowed())
+ {
+ int numSelectedColumns = selectedColumns.length;
+ int c = selectedColumns[i % numSelectedColumns];
+ int r = i / numSelectedColumns;
+ found = getAccessibleChild(r * numCols + c);
+ }
+
+ return found;
}
+ /**
+ * Returns <code>true</code> if the accessible child with the index
+ * <code>i</code> is selected, <code>false</code> otherwise.
+ *
+ * @param i the index of the accessible to check
+ *
+ * @return <code>true</code> if the accessible child with the index
+ * <code>i</code> is selected, <code>false</code> otherwise
+ */
public boolean isAccessibleChildSelected(int i)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return false;
+ int r = getAccessibleRowAtIndex(i);
+ int c = getAccessibleColumnAtIndex(i);
+ return isCellSelected(r, c);
}
+ /**
+ * Adds the accessible child with the specified index <code>i</code> to the
+ * selection.
+ *
+ * @param i the index of the accessible child to add to the selection
+ */
public void addAccessibleSelection(int i)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ int r = getAccessibleRowAtIndex(i);
+ int c = getAccessibleColumnAtIndex(i);
+ changeSelection(r, c, true, false);
}
+ /**
+ * Removes the accessible child with the specified index <code>i</code>
+ * from the current selection. This will only work on tables that have
+ * cell selection enabled (<code>rowSelectionAllowed == false &&
+ * columnSelectionAllowed == false</code>).
+ *
+ * @param i the index of the accessible to be removed from the selection
+ */
public void removeAccessibleSelection(int i)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ if (! getRowSelectionAllowed() && ! getColumnSelectionAllowed())
+ {
+ int r = getAccessibleRowAtIndex(i);
+ int c = getAccessibleColumnAtIndex(i);
+ removeRowSelectionInterval(r, r);
+ removeColumnSelectionInterval(c, c);
+ }
}
+ /**
+ * Deselects all selected accessible children.
+ */
public void clearAccessibleSelection()
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ clearSelection();
}
+ /**
+ * Selects all accessible children that can be selected. This will only
+ * work on tables that support multiple selections and that have individual
+ * cell selection enabled.
+ */
public void selectAllAccessibleSelection()
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ selectAll();
}
+ /**
+ * Receives notification when the row selection changes and fires
+ * appropriate property change events.
+ *
+ * @param event the list selection event
+ */
public void valueChanged(ListSelectionEvent event)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
+ Boolean.FALSE, Boolean.TRUE);
+ int r = getSelectedRow();
+ int c = getSelectedColumn();
+ if (r != lastSelectedRow || c != lastSelectedColumn)
+ {
+ Accessible o = getAccessibleAt(lastSelectedRow,
+ lastSelectedColumn);
+ Accessible n = getAccessibleAt(r, c);
+ firePropertyChange(AccessibleContext
+ .ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY, o, n);
+ lastSelectedRow = r;
+ lastSelectedColumn = c;
+ }
}
/**
@@ -686,15 +1374,13 @@ public class JTable
/**
* Receives notification when one or more rows have been inserted into the
- * table.
+ * table and fires appropriate property change events.
*
* @param event the table model event
*/
public void tableRowsInserted(TableModelEvent event)
- throws NotImplementedException
{
- // TODO: What to do here, if anything? This might be a hook method for
- // subclasses...
+ handleRowChange(event);
}
/**
@@ -704,52 +1390,94 @@ public class JTable
* @param event the table model event
*/
public void tableRowsDeleted(TableModelEvent event)
- throws NotImplementedException
{
- // TODO: What to do here, if anything? This might be a hook method for
- // subclasses...
+ handleRowChange(event);
+ }
+
+ /**
+ * Fires a PropertyChangeEvent for inserted or deleted rows.
+ *
+ * @param event the table model event
+ */
+ private void handleRowChange(TableModelEvent event)
+ {
+ firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
+ null, null);
+ int firstColumn = event.getColumn();
+ int lastColumn = event.getColumn();
+ if (firstColumn == TableModelEvent.ALL_COLUMNS)
+ {
+ firstColumn = 0;
+ lastColumn = getColumnCount() - 1;
+ }
+ AccessibleJTableModelChange change = new AccessibleJTableModelChange
+ (event.getType(), event.getFirstRow(), event.getLastRow(),
+ firstColumn, lastColumn);
+ firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
+ null, change);
}
public void columnAdded(TableColumnModelEvent event)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
+ null, null);
+ handleColumnChange(AccessibleTableModelChange.INSERT,
+ event.getFromIndex(), event.getToIndex());
}
- public void columnMarginChanged(ChangeEvent event)
- throws NotImplementedException
+ public void columnRemoved(TableColumnModelEvent event)
{
- // TODO Auto-generated method stub
+ firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
+ null, null);
+ handleColumnChange(AccessibleTableModelChange.DELETE,
+ event.getFromIndex(), event.getToIndex());
}
public void columnMoved(TableColumnModelEvent event)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
+ null, null);
+ handleColumnChange(AccessibleTableModelChange.DELETE,
+ event.getFromIndex(), event.getFromIndex());
+ handleColumnChange(AccessibleTableModelChange.INSERT,
+ event.getFromIndex(), event.getToIndex());
}
- public void columnRemoved(TableColumnModelEvent event)
- throws NotImplementedException
+ /**
+ * Fires a PropertyChangeEvent for inserted or deleted columns.
+ *
+ * @param type the type of change
+ * @param from the start of the change
+ * @param to the target of the change
+ */
+ private void handleColumnChange(int type, int from, int to)
+ {
+ AccessibleJTableModelChange change =
+ new AccessibleJTableModelChange(type, 0, 0, from, to);
+ firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
+ null, change);
+ }
+
+ public void columnMarginChanged(ChangeEvent event)
{
- // TODO Auto-generated method stub
+ firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
+ null, null);
}
public void columnSelectionChanged(ListSelectionEvent event)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ // AFAICS, nothing is done here.
}
public void editingCanceled(ChangeEvent event)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ // AFAICS, nothing is done here.
}
public void editingStopped(ChangeEvent event)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
+ null, null);
}
/**
@@ -792,174 +1520,343 @@ public class JTable
}
}
+ /**
+ * Returns the row number of an accessible child (cell) with the specified
+ * index.
+ *
+ * @param index the index of the cell of which the row number is queried
+ *
+ * @return the row number of an accessible child (cell) with the specified
+ * index
+ */
public int getAccessibleRow(int index)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return 0;
+ return getAccessibleRowAtIndex(index);
}
+ /**
+ * Returns the column number of an accessible child (cell) with the
+ * specified index.
+ *
+ * @param index the index of the cell of which the column number is queried
+ *
+ * @return the column number of an accessible child (cell) with the
+ * specified index
+ */
public int getAccessibleColumn(int index)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return 0;
+ return getAccessibleColumnAtIndex(index);
}
+ /**
+ * Returns the index of the accessible child at the specified row and
+ * column.
+ *
+ * @param r the row number
+ * @param c the column number
+ *
+ * @return the index of the accessible child at the specified row and
+ * column
+ */
public int getAccessibleIndex(int r, int c)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return 0;
+ return getAccessibleIndexAt(r, c);
}
+ /**
+ * Returns the caption of the table.
+ *
+ * @return the caption of the table
+ *
+ * @see #setAccessibleCaption(Accessible)
+ */
public Accessible getAccessibleCaption()
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return null;
+ return caption;
}
- public void setAccessibleCaption(Accessible caption)
- throws NotImplementedException
+ /**
+ * Sets the caption for the table.
+ *
+ * @param c the caption to set
+ */
+ public void setAccessibleCaption(Accessible c)
{
- // TODO Auto-generated method stub
+ caption = c;
}
+ /**
+ * Returns the summary for the table.
+ *
+ * @return the summary for the table
+ */
public Accessible getAccessibleSummary()
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return null;
+ return summary;
}
- public void setAccessibleSummary(Accessible summary)
- throws NotImplementedException
+ /**
+ * Sets the summary for the table.
+ *
+ * @param s the summary to set
+ */
+ public void setAccessibleSummary(Accessible s)
{
- // TODO Auto-generated method stub
+ summary = s;
}
+ /**
+ * Returns the number of rows in the table.
+ *
+ * @return the number of rows in the table
+ */
public int getAccessibleRowCount()
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return 0;
+ return getRowCount();
}
+ /**
+ * Returns the number of columns in the table.
+ *
+ * @return the number of columns in the table
+ */
public int getAccessibleColumnCount()
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return 0;
+ return getColumnCount();
}
+ /**
+ * Returns the accessible child at the given index.
+ *
+ * @param index the child index.
+ *
+ * @return The accessible child.
+ */
+ public Accessible getAccessibleChild(int index)
+ {
+ int r = getAccessibleRow(index);
+ int c = getAccessibleColumn(index);
+ return getAccessibleAt(r, c);
+ }
+
+ /**
+ * Returns the accessible child (table cell) at the specified row and
+ * column.
+ *
+ * @param r the row number
+ * @param c the column number
+ *
+ * @return the accessible child (table cell) at the specified row and
+ * column
+ */
public Accessible getAccessibleAt(int r, int c)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ TableCellRenderer cellRenderer = getCellRenderer(r, c);
+ Component renderer = cellRenderer.getTableCellRendererComponent(
+ JTable.this, getValueAt(r, c), isCellSelected(r, c), false, r, c);
+ if (renderer instanceof Accessible)
+ return (Accessible) renderer;
return null;
}
+ /**
+ * Returns the number of rows that the specified cell occupies. The
+ * standard table cells only occupy one row, so we return <code>1</code>
+ * here.
+ *
+ * @param r the row number
+ * @param c the column number
+ *
+ * @return the number of rows that the specified cell occupies
+ */
public int getAccessibleRowExtentAt(int r, int c)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return 0;
+ return 1;
}
+ /**
+ * Returns the number of columns that the specified cell occupies. The
+ * standard table cells only occupy one column, so we return <code>1</code>
+ * here.
+ *
+ * @param r the row number
+ * @param c the column number
+ *
+ * @return the number of rows that the specified cell occupies
+ */
public int getAccessibleColumnExtentAt(int r, int c)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return 0;
+ return 1;
}
+ /**
+ * Returns the accessible row header.
+ *
+ * @return the accessible row header
+ */
public AccessibleTable getAccessibleRowHeader()
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ // The RI seems to always return null here, so do we.
return null;
}
+ /**
+ * Sets the accessible row header.
+ *
+ * @param header the header to set
+ */
public void setAccessibleRowHeader(AccessibleTable header)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ // In the RI this seems to be a no-op.
}
+ /**
+ * Returns the column header.
+ *
+ * @return the column header, or <code>null</code> if there is no column
+ * header
+ */
public AccessibleTable getAccessibleColumnHeader()
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return null;
+ JTableHeader h = getTableHeader();
+ AccessibleTable header = null;
+ if (h != null)
+ header = new AccessibleTableHeader(h);
+ return header;
}
+ /**
+ * Sets the accessible column header. The default implementation doesn't
+ * allow changing the header this way, so this is a no-op.
+ *
+ * @param header the accessible column header to set
+ */
public void setAccessibleColumnHeader(AccessibleTable header)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ // The RI doesn't seem to do anything, so we also do nothing.
}
+ /**
+ * Returns the accessible description for the row with the specified index,
+ * or <code>null</code> if no description has been set.
+ *
+ * @param r the row for which the description is queried
+ *
+ * @return the accessible description for the row with the specified index,
+ * or <code>null</code> if no description has been set
+ */
public Accessible getAccessibleRowDescription(int r)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return null;
+ Accessible descr = null;
+ if (rowDescriptions != null)
+ descr = rowDescriptions[r];
+ return descr;
}
+ /**
+ * Sets the accessible description for the row with the specified index.
+ *
+ * @param r the row number for which to set the description
+ * @param description the description to set
+ */
public void setAccessibleRowDescription(int r, Accessible description)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
+ if (rowDescriptions == null)
+ rowDescriptions = new Accessible[getAccessibleRowCount()];
+ rowDescriptions[r] = description;
}
+ /**
+ * Returns the accessible description for the column with the specified
+ * index, or <code>null</code> if no description has been set.
+ *
+ * @param c the column for which the description is queried
+ *
+ * @return the accessible description for the column with the specified
+ * index, or <code>null</code> if no description has been set
+ */
public Accessible getAccessibleColumnDescription(int c)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return null;
+ Accessible descr = null;
+ if (columnDescriptions != null)
+ descr = columnDescriptions[c];
+ return descr;
}
+ /**
+ * Sets the accessible description for the column with the specified index.
+ *
+ * @param c the column number for which to set the description
+ * @param description the description to set
+ */
public void setAccessibleColumnDescription(int c, Accessible description)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
-
+ if (columnDescriptions == null)
+ columnDescriptions = new Accessible[getAccessibleRowCount()];
+ columnDescriptions[c] = description;
}
+ /**
+ * Returns <code>true</code> if the accessible child at the specified
+ * row and column is selected, <code>false</code> otherwise.
+ *
+ * @param r the row number of the child
+ * @param c the column number of the child
+ *
+ * @return <code>true</code> if the accessible child at the specified
+ * row and column is selected, <code>false</code> otherwise
+ */
public boolean isAccessibleSelected(int r, int c)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return false;
+ return isCellSelected(r, c);
}
+ /**
+ * Returns <code>true</code> if the row with the specified index is
+ * selected, <code>false</code> otherwise.
+ *
+ * @param r the row number
+ *
+ * @return <code>true</code> if the row with the specified index is
+ * selected, <code>false</code> otherwise
+ */
public boolean isAccessibleRowSelected(int r)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return false;
+ return isRowSelected(r);
}
+ /**
+ * Returns <code>true</code> if the column with the specified index is
+ * selected, <code>false</code> otherwise.
+ *
+ * @param c the column number
+ *
+ * @return <code>true</code> if the column with the specified index is
+ * selected, <code>false</code> otherwise
+ */
public boolean isAccessibleColumnSelected(int c)
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return false;
+ return isColumnSelected(c);
}
+ /**
+ * Returns the indices of all selected rows.
+ *
+ * @return the indices of all selected rows
+ */
public int[] getSelectedAccessibleRows()
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return null;
+ return getSelectedRows();
}
+ /**
+ * Returns the indices of all selected columns.
+ *
+ * @return the indices of all selected columns
+ */
public int[] getSelectedAccessibleColumns()
- throws NotImplementedException
{
- // TODO Auto-generated method stub
- return null;
+ return getSelectedColumns();
}
/**
@@ -1944,12 +2841,6 @@ public class JTable
*/
public void columnSelectionChanged (ListSelectionEvent event)
{
- // Does not make sense for the table with the single column.
- if (getColumnCount() < 2)
- return;
-
- int x0 = 0;
-
// We must limit the indices to the bounds of the JTable's model, because
// we might get values of -1 or greater then columnCount in the case
// when columns get removed.
@@ -1957,17 +2848,39 @@ public class JTable
event.getFirstIndex()));
int idxn = Math.max(0, Math.min(getColumnCount() - 1,
event.getLastIndex()));
- int i;
- for (i = 0; i < idx0; i++)
- x0 += columnModel.getColumn(i).getWidth();
-
- int xn = x0;
-
- for (i = idx0; i <= idxn; i++)
- xn += columnModel.getColumn(i).getWidth();
-
- repaint(x0, 0, xn-x0, getHeight());
+ int minRow = 0;
+ int maxRow = getRowCount() - 1;
+ if (getRowSelectionAllowed())
+ {
+ minRow = selectionModel.getMinSelectionIndex();
+ maxRow = selectionModel.getMaxSelectionIndex();
+ int leadRow = selectionModel.getLeadSelectionIndex();
+ if (minRow == -1 && maxRow == -1)
+ {
+ minRow = leadRow;
+ maxRow = leadRow;
+ }
+ else
+ {
+ // In this case we need to repaint also the range to leadRow, not
+ // only between min and max.
+ if (leadRow != -1)
+ {
+ minRow = Math.min(minRow, leadRow);
+ maxRow = Math.max(maxRow, leadRow);
+ }
+ }
+ }
+ if (minRow != -1 && maxRow != -1)
+ {
+ Rectangle first = getCellRect(minRow, idx0, false);
+ Rectangle last = getCellRect(maxRow, idxn, false);
+ Rectangle dirty = SwingUtilities.computeUnion(first.x, first.y,
+ first.width,
+ first.height, last);
+ repaint(dirty);
+ }
}
/**
@@ -2076,9 +2989,10 @@ public class JTable
int last = Math.max(0, Math.min(getRowCount() - 1, event.getLastIndex()));
Rectangle rect1 = getCellRect(first, 0, false);
Rectangle rect2 = getCellRect(last, getColumnCount() - 1, false);
- SwingUtilities.computeUnion(rect2.x, rect2.y, rect2.width, rect2.height,
- rect1);
- repaint(rect1);
+ Rectangle dirty = SwingUtilities.computeUnion(rect2.x, rect2.y,
+ rect2.width, rect2.height,
+ rect1);
+ repaint(dirty);
}
/**
@@ -2742,6 +3656,17 @@ public class JTable
*/
public AccessibleContext getAccessibleContext()
{
+ if (accessibleContext == null)
+ {
+ AccessibleJTable ctx = new AccessibleJTable();
+ addPropertyChangeListener(ctx);
+ TableColumnModel tcm = getColumnModel();
+ tcm.addColumnModelListener(ctx);
+ tcm.getSelectionModel().addListSelectionListener(ctx);
+ getSelectionModel().addListSelectionListener(ctx);
+
+ accessibleContext = ctx;
+ }
return accessibleContext;
}
@@ -4043,5 +4968,4 @@ public class JTable
super.setUIProperty(propertyName, value);
}
}
-
}
diff --git a/javax/swing/JTree.java b/javax/swing/JTree.java
index eb54523e2..47dae1075 100644
--- a/javax/swing/JTree.java
+++ b/javax/swing/JTree.java
@@ -1142,9 +1142,9 @@ public class JTree extends JComponent implements Scrollable, Accessible
public boolean isLeaf()
{
- return (childValue == null || !(childValue instanceof Hashtable
- || childValue instanceof Vector || childValue.getClass()
- .isArray()));
+ return childValue == null || !(childValue instanceof Hashtable
+ || childValue instanceof Vector
+ || childValue.getClass().isArray());
}
public static void createChildren(DefaultMutableTreeNode parent,
@@ -1478,7 +1478,7 @@ public class JTree extends JComponent implements Scrollable, Accessible
*/
public JTree()
{
- this(createTreeModel(null));
+ this(getDefaultTreeModel());
}
/**
@@ -1509,13 +1509,18 @@ public class JTree extends JComponent implements Scrollable, Accessible
public JTree(TreeModel model)
{
setRootVisible(true);
- // The setModel also calls the updateUI
- setModel(model);
setSelectionModel(new EmptySelectionModel());
selectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
// The root node appears expanded by default.
- nodeStates.put(new TreePath(model.getRoot()), EXPANDED);
+ nodeStates = new Hashtable();
+
+ // Install the UI before installing the model. This way we avoid double
+ // initialization of lots of UI and model stuff inside the UI and related
+ // classes. The necessary UI updates are performed via property change
+ // events to the UI.
+ updateUI();
+ setModel(model);
}
/**
@@ -1897,6 +1902,10 @@ public class JTree extends JComponent implements Scrollable, Accessible
if (treeModel == model)
return;
+ // Remove listeners from old model.
+ if (treeModel != null && treeModelListener != null)
+ treeModel.removeTreeModelListener(treeModelListener);
+
// add treeModelListener to the new model
if (treeModelListener == null)
treeModelListener = createTreeModelListener();
@@ -1905,9 +1914,22 @@ public class JTree extends JComponent implements Scrollable, Accessible
TreeModel oldValue = treeModel;
treeModel = model;
+ clearToggledPaths();
+
+ if (treeModel != null)
+ {
+ if (treeModelListener == null)
+ treeModelListener = createTreeModelListener();
+ if (treeModelListener != null)
+ treeModel.addTreeModelListener(treeModelListener);
+ Object root = treeModel.getRoot();
+ if (root != null && !treeModel.isLeaf(root))
+ {
+ nodeStates.put(new TreePath(root), Boolean.TRUE);
+ }
+ }
firePropertyChange(TREE_MODEL_PROPERTY, oldValue, model);
- updateUI();
}
/**
@@ -2316,7 +2338,7 @@ public class JTree extends JComponent implements Scrollable, Accessible
selectionModel.addSelectionPath(path);
}
- if (oldValue!=null)
+ if (oldValue != null)
repaint(getPathBounds(oldValue));
firePropertyChange(LEAD_SELECTION_PATH_PROPERTY, oldValue, path);
diff --git a/javax/swing/JViewport.java b/javax/swing/JViewport.java
index 2b5d1cd5a..7cf393996 100644
--- a/javax/swing/JViewport.java
+++ b/javax/swing/JViewport.java
@@ -877,7 +877,7 @@ public class JViewport extends JComponent implements Accessible
{
// If the image has not been scrolled at all, only the changed
// clip must be updated in the buffer.
- if (dx==0 && dy==0)
+ if (dx == 0 && dy == 0)
g2.setClip(g.getClip());
paintSimple(g2);
diff --git a/javax/swing/ListSelectionModel.java b/javax/swing/ListSelectionModel.java
index 324c05643..499362d04 100644
--- a/javax/swing/ListSelectionModel.java
+++ b/javax/swing/ListSelectionModel.java
@@ -1,5 +1,5 @@
/* ListSelectionModel.java --
- Copyright (C) 2002 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2006, Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,59 +38,295 @@ exception statement from your version. */
package javax.swing;
+import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
/**
- * The model that is used in {@link JList} to define the selected/not-selected
- * cells of that list.
+ * A model that tracks the selection status of a list of items. Each item in
+ * the list is identified by a zero-based index only, so the model can be used
+ * to track the selection status of any type of list. The model
+ * supports three modes:
+ * <ul>
+ * <li><code>SINGLE_SELECTION</code> - only one item in the list may be
+ * selected;</li>
+ * <li><code>SINGLE_INTERVAL_SELECTION</code> - only one interval in the list
+ * may be selected;</li>
+ * <li><code>MULTIPLE_INTERVAL_SELECTION</code> - any combination of items in
+ * the list may be selected.</li>
+ * </ul>
+ * The model uses an event notification mechanism to notify listeners (see
+ * {@link ListSelectionListener}) about updates to the selection model.
+ * <p>
+ * This model is used to track row selections in the {@link JList} component,
+ * and row and column selections in the {@link JTable} component.
*/
public interface ListSelectionModel
{
-
+
+ /**
+ * A selection mode in which only one item can be selected.
+ *
+ * @see #setSelectionMode(int)
+ */
int SINGLE_SELECTION = 0;
+ /**
+ * A selection mode in which a single interval can be selected (an interval
+ * is a range containing one or more contiguous items).
+ *
+ * @see #setSelectionMode(int)
+ */
int SINGLE_INTERVAL_SELECTION = 1;
+ /**
+ * A selection mode in which any combination of items can be selected.
+ *
+ * @see #setSelectionMode(int)
+ */
int MULTIPLE_INTERVAL_SELECTION = 2;
- void setSelectionMode(int a);
-
+ /**
+ * Sets the selection mode.
+ * <p>
+ * FIXME: The spec is silent about what happens to existing selections, for
+ * example when changing from an interval selection to single selection.
+ *
+ * @param mode one of {@link #SINGLE_SELECTION},
+ * {@link #SINGLE_INTERVAL_SELECTION} and
+ * {@link #MULTIPLE_INTERVAL_SELECTION}.
+ *
+ * @see #getSelectionMode()
+ *
+ * @throws IllegalArgumentException if <code>mode</code> is not one of the
+ * specified values.
+ */
+ void setSelectionMode(int mode);
+
+ /**
+ * Returns the selection mode, which is one of {@link #SINGLE_SELECTION},
+ * {@link #SINGLE_INTERVAL_SELECTION} and
+ * {@link #MULTIPLE_INTERVAL_SELECTION}.
+ *
+ * @return The selection mode.
+ *
+ * @see #setSelectionMode(int)
+ */
int getSelectionMode();
+ /**
+ * Clears the current selection from the model. If the selection state
+ * changes (that is, the existing selection is non-empty) a
+ * {@link ListSelectionEvent} should be sent to all registered listeners.
+ * <p>
+ * FIXME: what happens to the anchor and lead selection indices (the spec
+ * is silent about this)? See:
+ * <p>
+ * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4334792
+ */
void clearSelection();
+ /**
+ * Returns the lowest selected index, or <code>-1</code> if there is no
+ * selection.
+ *
+ * @return The lowest selected index.
+ *
+ * @see #getMaxSelectionIndex()
+ */
int getMinSelectionIndex();
+ /**
+ * Returns the highest selected index, or <code>-1</code> if there is no
+ * selection.
+ *
+ * @return The highest selected index.
+ *
+ * @see #getMinSelectionIndex()
+ */
int getMaxSelectionIndex();
- boolean isSelectedIndex(int a);
-
+ /**
+ * Returns <code>true</code> if the specified item is selected, and
+ * <code>false</code> otherwise. Special note: if <code>index</code> is
+ * negative, this method should return <code>false</code> (no exception
+ * should be thrown).
+ *
+ * @param index the item index (zero-based).
+ *
+ * @return <code>true</code> if the specified item is selected, and
+ * <code>false</code> otherwise.
+ */
+ boolean isSelectedIndex(int index);
+
+ /**
+ * Returns <code>true</code> if there is no selection, and <code>false</code>
+ * otherwise.
+ *
+ * @return <code>true</code> if there is no selection, and
+ * <code>false</code> otherwise.
+ */
boolean isSelectionEmpty();
- void setSelectionInterval(int index0, int index1);
-
- void addSelectionInterval(int index0, int index1);
-
- void removeSelectionInterval(int index0, int index1);
-
+ /**
+ * Sets the selection interval to the specified range (note that
+ * <code>anchor</code> can be less than, equal to, or greater than
+ * <code>lead</code>). If this results in the selection being changed,
+ * a {@link ListSelectionEvent} is sent to all registered listeners.
+ * <p>
+ * If the selection mode is {@link #SINGLE_SELECTION}, only the
+ * <code>lead</code> item is selected.
+ *
+ * @param anchor the anchor index.
+ * @param lead the lead index.
+ */
+ void setSelectionInterval(int anchor, int lead);
+
+ /**
+ * Marks the items in the specified interval as selected. The behaviour of
+ * this method depends on the selection mode:
+ * <ul>
+ * <li><code>SINGLE_SELECTION</code> - only the <code>lead</code> item is
+ * selected;</li>
+ * <li><code>SINGLE_INTERVAL_SELECTION</code> - the existing selection
+ * interval is replaced by the specified interval;</li>
+ * <li><code>MULTIPLE_INTERVAL_SELECTION</code> - the specified interval is
+ * merged into the currently selected intervals.</li>
+ * </ul>
+ * Note that <code>anchor</code> can be less than, equal to, or greater than
+ * <code>lead</code>.
+ *
+ * @param anchor the index of the anchor item
+ * @param lead the index of the lead item.
+ */
+ void addSelectionInterval(int anchor, int lead);
+
+ /**
+ * Marks the items in the specified interval as not selected. The behaviour
+ * of this method depends on the selection mode:
+ * <ul>
+ * <li><code>SINGLE_SELECTION</code> - XXX;</li>
+ * <li><code>SINGLE_INTERVAL_SELECTION</code> - XXX;</li>
+ * <li><code>MULTIPLE_INTERVAL_SELECTION</code> - XXX.</li>
+ * </ul>
+ * Note that <code>anchor</code> can be less than, equal to, or greater than
+ * <code>lead</code>.
+ *
+ * @param anchor the index of the anchor item
+ * @param lead the index of the lead item.
+ */
+ void removeSelectionInterval(int anchor, int lead);
+
+ /**
+ * Inserts a new interval containing <code>length</code> items at the
+ * specified <code>index</code> (the <code>before</code> flag indicates
+ * whether the range is inserted before or after the existing item at
+ * <code>index</code>).
+ *
+ * FIXME: What is the selection status of the new items? Bug 4870694.
+ * FIXME: What event is generated?
+ *
+ * @param index the index of the item.
+ * @param length the number of items in the interval to be inserted.
+ * @param before if <code>true</code>, the interval should be inserted
+ * before <code>index</code>, otherwise it is inserted after.
+ *
+ * @see #removeIndexInterval(int, int)
+ */
void insertIndexInterval(int index, int length, boolean before);
+ /**
+ * Removes the items in the specified range (inclusive) from the selection
+ * model. This method should be called when an interval is deleted from
+ * the underlying list.
+ *
+ * FIXME: what happens to the lead and anchor indices if they are part of
+ * the range that is removed?
+ * FIXME: what event is generated
+ *
+ * @param index0 XXX
+ * @param index1 XXX
+ *
+ * @see #insertIndexInterval(int, int, boolean)
+ */
void removeIndexInterval(int index0, int index1);
+ /**
+ * Returns the index of the anchor item.
+ *
+ * @return The index of the anchor item.
+ *
+ * @see #setAnchorSelectionIndex(int)
+ */
int getAnchorSelectionIndex();
+ /**
+ * Sets the index of the anchor item.
+ *
+ * @param index the item index.
+ *
+ * @see #getAnchorSelectionIndex()
+ */
void setAnchorSelectionIndex(int index);
+ /**
+ * Returns the index of the lead item.
+ *
+ * @return The index of the lead item.
+ *
+ * @see #setLeadSelectionIndex(int)
+ */
int getLeadSelectionIndex();
+ /**
+ * Sets the index of the lead item.
+ *
+ * @param index the item index.
+ *
+ * @see #getLeadSelectionIndex()
+ */
void setLeadSelectionIndex(int index);
+ /**
+ * Sets the flag that is passed to listeners for each change notification.
+ * If a sequence of changes is made to the selection model, this flag should
+ * be set to <code>true</code> at the start of the sequence, and
+ * <code>false</code> for the last change - this gives listeners the option
+ * to ignore interim changes if that is more efficient.
+ *
+ * @param valueIsAdjusting the flag value.
+ *
+ * @see #getValueIsAdjusting()
+ */
void setValueIsAdjusting(boolean valueIsAdjusting);
+ /**
+ * Returns a flag that is passed to registered listeners when changes are
+ * made to the model. See the description for
+ * {@link #setValueIsAdjusting(boolean)} for more information.
+ *
+ * @return The flag.
+ */
boolean getValueIsAdjusting();
+ /**
+ * Registers a listener with the model so that it receives notification
+ * of changes to the model.
+ *
+ * @param listener the listener (<code>null</code> ignored).
+ *
+ * @see #removeListSelectionListener(ListSelectionListener)
+ */
void addListSelectionListener(ListSelectionListener listener);
+ /**
+ * Deregisters a listener so that it no longer receives notification of
+ * changes to the model. If the specified listener is not registered with
+ * the model, or is <code>null</code>, this method does nothing.
+ *
+ * @param listener the listener (<code>null</code> ignored).
+ *
+ * @see #addListSelectionListener(ListSelectionListener)
+ */
void removeListSelectionListener(ListSelectionListener listener);
}
diff --git a/javax/swing/MenuSelectionManager.java b/javax/swing/MenuSelectionManager.java
index df7b42037..beafbf442 100644
--- a/javax/swing/MenuSelectionManager.java
+++ b/javax/swing/MenuSelectionManager.java
@@ -258,6 +258,9 @@ public class MenuSelectionManager
{
MenuElement[] selection = (MenuElement[])
selectedPath.toArray(new MenuElement[selectedPath.size()]);
+ if (selection.length == 0)
+ return;
+
MenuElement[] path;
for (int index = selection.length - 1; index >= 0; index--)
{
diff --git a/javax/swing/RepaintManager.java b/javax/swing/RepaintManager.java
index e1416a422..424a27671 100644
--- a/javax/swing/RepaintManager.java
+++ b/javax/swing/RepaintManager.java
@@ -767,10 +767,22 @@ public class RepaintManager
public Image getVolatileOffscreenBuffer(Component comp, int proposedWidth,
int proposedHeight)
{
- int maxWidth = doubleBufferMaximumSize.width;
- int maxHeight = doubleBufferMaximumSize.height;
- return comp.createVolatileImage(Math.min(maxWidth, proposedWidth),
- Math.min(maxHeight, proposedHeight));
+ Component root = getRoot(comp);
+ Image buffer = (Image) offscreenBuffers.get(root);
+ if (buffer == null
+ || buffer.getWidth(null) < proposedWidth
+ || buffer.getHeight(null) < proposedHeight
+ || !(buffer instanceof VolatileImage))
+ {
+ int width = Math.max(proposedWidth, root.getWidth());
+ width = Math.min(doubleBufferMaximumSize.width, width);
+ int height = Math.max(proposedHeight, root.getHeight());
+ height = Math.min(doubleBufferMaximumSize.height, height);
+ buffer = root.createVolatileImage(width, height);
+ if (buffer != null)
+ offscreenBuffers.put(root, buffer);
+ }
+ return buffer;
}
diff --git a/javax/swing/UIDefaults.java b/javax/swing/UIDefaults.java
index e627be785..9766cb05c 100644
--- a/javax/swing/UIDefaults.java
+++ b/javax/swing/UIDefaults.java
@@ -96,15 +96,15 @@ public class UIDefaults extends Hashtable<Object, Object>
}
public Object createValue(UIDefaults table)
{
- InputMapUIResource im = new InputMapUIResource ();
- for (int i = 0; 2*i+1 < bind.length; ++i)
+ InputMapUIResource im = new InputMapUIResource();
+ for (int i = 0; 2 * i + 1 < bind.length; ++i)
{
- Object curr = bind[2*i];
+ Object curr = bind[2 * i];
if (curr instanceof KeyStroke)
- im.put((KeyStroke) curr, bind[2*i+1]);
+ im.put((KeyStroke) curr, bind[2 * i + 1]);
else
im.put(KeyStroke.getKeyStroke((String) curr),
- bind[2*i+1]);
+ bind[2 * i + 1]);
}
return im;
}
@@ -128,9 +128,9 @@ public class UIDefaults extends Hashtable<Object, Object>
public ProxyLazyValue(String s)
{
final String className = s;
- inner = new LazyValue ()
+ inner = new LazyValue()
{
- public Object createValue (UIDefaults table)
+ public Object createValue(UIDefaults table)
{
try
{
@@ -151,16 +151,16 @@ public class UIDefaults extends Hashtable<Object, Object>
{
final String className = c;
final String methodName = m;
- inner = new LazyValue ()
+ inner = new LazyValue()
{
- public Object createValue (UIDefaults table)
+ public Object createValue(UIDefaults table)
{
try
{
return Class
- .forName (className)
- .getMethod (methodName, new Class[] {})
- .invoke (null, new Object[] {});
+ .forName(className)
+ .getMethod(methodName, new Class[] {})
+ .invoke(null, new Object[] {});
}
catch (Exception e)
{
@@ -674,7 +674,7 @@ public class UIDefaults extends Hashtable<Object, Object>
*/
public Class<? extends ComponentUI> getUIClass(String id, ClassLoader loader)
{
- String className = (String) get (id);
+ String className = (String) get(id);
if (className == null)
return null;
try
diff --git a/javax/swing/UIManager.java b/javax/swing/UIManager.java
index e1ee28b3f..e6f801163 100644
--- a/javax/swing/UIManager.java
+++ b/javax/swing/UIManager.java
@@ -145,18 +145,19 @@ public class UIManager implements Serializable
static
{
String defaultlaf = System.getProperty("swing.defaultlaf");
- try {
- if (defaultlaf != null)
- {
- Class lafClass = Class.forName(defaultlaf);
- LookAndFeel laf = (LookAndFeel) lafClass.newInstance();
- setLookAndFeel(laf);
- }
- else
- {
- setLookAndFeel(new MetalLookAndFeel());
- }
- }
+ try
+ {
+ if (defaultlaf != null)
+ {
+ Class lafClass = Class.forName(defaultlaf);
+ LookAndFeel laf = (LookAndFeel) lafClass.newInstance();
+ setLookAndFeel(laf);
+ }
+ else
+ {
+ setLookAndFeel(new MetalLookAndFeel());
+ }
+ }
catch (Exception ex)
{
System.err.println("cannot initialize Look and Feel: " + defaultlaf);
@@ -455,7 +456,7 @@ public class UIManager implements Serializable
*/
public static Font getFont(Object key, Locale locale)
{
- return (Font) get(key ,locale);
+ return (Font) get(key, locale);
}
/**
diff --git a/javax/swing/border/MatteBorder.java b/javax/swing/border/MatteBorder.java
index 114cac623..944cd2866 100644
--- a/javax/swing/border/MatteBorder.java
+++ b/javax/swing/border/MatteBorder.java
@@ -1,5 +1,5 @@
/* MatteBorder.java --
- Copyright (C) 2003, 2004 Free Software Foundation, Inc.
+ Copyright (C) 2003, 2004, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -147,9 +147,6 @@ public class MatteBorder extends EmptyBorder
{
super(top, left, bottom, right);
- if (tileIcon == null)
- throw new IllegalArgumentException();
-
this.tileIcon = tileIcon;
}
@@ -375,6 +372,10 @@ public class MatteBorder extends EmptyBorder
}
return;
}
+
+ // If this border has no icon end painting here.
+ if (tileIcon == null)
+ return;
/* Determine the width and height of the icon. Some icons return
* -1 if it is an image whose dimensions have not yet been
diff --git a/javax/swing/event/EventListenerList.java b/javax/swing/event/EventListenerList.java
index 7be32036c..81e96c082 100644
--- a/javax/swing/event/EventListenerList.java
+++ b/javax/swing/event/EventListenerList.java
@@ -1,5 +1,5 @@
/* EventListenerList.java --
- Copyright (C) 2002, 2004, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2004, 2005, 2006, Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -187,11 +187,15 @@ public class EventListenerList
/**
- * Get a list of listenerType/listener pairs
- * @return Listener list
+ * Returns an array containing a sequence of listenerType/listener pairs, one
+ * for each listener.
+ *
+ * @return An array containing the listener types and references.
*/
public Object[] getListenerList()
{
+ // returning the internal storage is a bad idea, but tests show that the
+ // reference implementation does this...
return listenerList;
}
diff --git a/javax/swing/plaf/basic/BasicButtonUI.java b/javax/swing/plaf/basic/BasicButtonUI.java
index 7dbcb9146..0a537c4bd 100644
--- a/javax/swing/plaf/basic/BasicButtonUI.java
+++ b/javax/swing/plaf/basic/BasicButtonUI.java
@@ -72,7 +72,7 @@ public class BasicButtonUI extends ButtonUI
* A constant added to the defaultTextIconGap to adjust the text
* within this particular button.
*/
- protected int defaultTextShiftOffset = 0;
+ protected int defaultTextShiftOffset;
private int textShiftOffset;
@@ -268,10 +268,9 @@ public class BasicButtonUI extends ButtonUI
*/
public Dimension getPreferredSize(JComponent c)
{
- AbstractButton b = (AbstractButton)c;
- Dimension d =
- BasicGraphicsUtils.getPreferredButtonSize
- (b, defaultTextIconGap + defaultTextShiftOffset);
+ AbstractButton b = (AbstractButton) c;
+ Dimension d = BasicGraphicsUtils.getPreferredButtonSize(b,
+ defaultTextIconGap + defaultTextShiftOffset);
return d;
}
diff --git a/javax/swing/plaf/basic/BasicComboBoxRenderer.java b/javax/swing/plaf/basic/BasicComboBoxRenderer.java
index 48195ff29..3c8d1e8c5 100644
--- a/javax/swing/plaf/basic/BasicComboBoxRenderer.java
+++ b/javax/swing/plaf/basic/BasicComboBoxRenderer.java
@@ -75,12 +75,24 @@ public class BasicComboBoxRenderer
/**
* Returns preferredSize of the renderer
- *
+ *
* @return preferredSize of the renderer
*/
public Dimension getPreferredSize()
{
- return super.getPreferredSize();
+ if (this.getText() != null && ! this.getText().equals(""))
+ return super.getPreferredSize();
+ else
+ {
+ // If the combo box option's text is empty or null, it won't size
+ // properly (ie, it'll be way too short)... so we throw in a dummy
+ // space to trick the superclass's sizing methods.
+ String oldText = this.getText();
+ this.setText(" ");
+ Dimension d = super.getPreferredSize();
+ this.setText(oldText);
+ return d;
+ }
}
/**
diff --git a/javax/swing/plaf/basic/BasicDirectoryModel.java b/javax/swing/plaf/basic/BasicDirectoryModel.java
index 3bcd062e5..0c46a5112 100644
--- a/javax/swing/plaf/basic/BasicDirectoryModel.java
+++ b/javax/swing/plaf/basic/BasicDirectoryModel.java
@@ -227,16 +227,16 @@ public class BasicDirectoryModel extends AbstractListModel
if (aTrav == bTrav)
{
- String aname = a.getName().toLowerCase();
- String bname = b.getName().toLowerCase();
- return ((aname.compareTo(bname) < 0) ? true : false);
+ String aname = a.getName().toLowerCase();
+ String bname = b.getName().toLowerCase();
+ return (aname.compareTo(bname) < 0) ? true : false;
}
else
{
- if (aTrav)
- return true;
- else
- return false;
+ if (aTrav)
+ return true;
+ else
+ return false;
}
}
diff --git a/javax/swing/plaf/basic/BasicFileChooserUI.java b/javax/swing/plaf/basic/BasicFileChooserUI.java
index e6dd60bde..fb7e49149 100644
--- a/javax/swing/plaf/basic/BasicFileChooserUI.java
+++ b/javax/swing/plaf/basic/BasicFileChooserUI.java
@@ -365,10 +365,10 @@ public class BasicFileChooserUI extends FileChooserUI
{
/** DOCUMENT ME! */
- private Object lastSelected = null;
+ private Object lastSelected;
/** DOCUMENT ME! */
- private JList list = null;
+ private JList list;
/**
* Creates a new DoubleClickListener object.
diff --git a/javax/swing/plaf/basic/BasicIconFactory.java b/javax/swing/plaf/basic/BasicIconFactory.java
index 6debd6495..cad0d0e8a 100644
--- a/javax/swing/plaf/basic/BasicIconFactory.java
+++ b/javax/swing/plaf/basic/BasicIconFactory.java
@@ -56,8 +56,14 @@ public class BasicIconFactory implements Serializable
private static class DummyIcon
implements Icon
{
- public int getIconHeight() { return 10; }
- public int getIconWidth() { return 10; }
+ public int getIconHeight()
+ {
+ return 10;
+ }
+ public int getIconWidth()
+ {
+ return 10;
+ }
public void paintIcon(Component c, Graphics g, int x, int y)
{
Color save = g.getColor();
diff --git a/javax/swing/plaf/basic/BasicInternalFrameUI.java b/javax/swing/plaf/basic/BasicInternalFrameUI.java
index a5f87653f..6beac6c97 100644
--- a/javax/swing/plaf/basic/BasicInternalFrameUI.java
+++ b/javax/swing/plaf/basic/BasicInternalFrameUI.java
@@ -38,8 +38,6 @@ exception statement from your version. */
package javax.swing.plaf.basic;
-import gnu.classpath.NotImplementedException;
-
import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.Component;
@@ -52,6 +50,7 @@ import java.awt.LayoutManager;
import java.awt.LayoutManager2;
import java.awt.Point;
import java.awt.Rectangle;
+import java.awt.event.ActionEvent;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
@@ -59,6 +58,8 @@ import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
+import javax.swing.AbstractAction;
+import javax.swing.ActionMap;
import javax.swing.DefaultDesktopManager;
import javax.swing.DesktopManager;
import javax.swing.JComponent;
@@ -74,6 +75,7 @@ import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.MouseInputListener;
+import javax.swing.plaf.ActionMapUIResource;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.InternalFrameUI;
import javax.swing.plaf.UIResource;
@@ -1086,6 +1088,23 @@ public class BasicInternalFrameUI extends InternalFrameUI
}
/**
+ * This action triggers the system menu.
+ *
+ * @author Roman Kennke (kennke@aicas.com)
+ */
+ private class ShowSystemMenuAction
+ extends AbstractAction
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ if (titlePane != null)
+ {
+ titlePane.showSystemMenu();
+ }
+ }
+ }
+
+ /**
* The MouseListener that is responsible for dragging and resizing the
* JInternalFrame in response to MouseEvents.
*/
@@ -1226,9 +1245,17 @@ public class BasicInternalFrameUI extends InternalFrameUI
* This method installs the keyboard actions for the JInternalFrame.
*/
protected void installKeyboardActions()
- throws NotImplementedException
{
- // FIXME: Implement.
+ ActionMapUIResource am = new ActionMapUIResource();
+ am.put("showSystemMenu", new ShowSystemMenuAction());
+
+ // The RI impl installs the audio actions as parent of the UI action map,
+ // so do we.
+ BasicLookAndFeel blaf = (BasicLookAndFeel) UIManager.getLookAndFeel();
+ ActionMap audioActionMap = blaf.getAudioActionMap();
+ am.setParent(audioActionMap);
+
+ SwingUtilities.replaceUIActionMap(frame, am);
}
/**
@@ -1309,9 +1336,10 @@ public class BasicInternalFrameUI extends InternalFrameUI
* This method uninstalls the keyboard actions for the JInternalFrame.
*/
protected void uninstallKeyboardActions()
- throws NotImplementedException
{
- // FIXME: Implement.
+ SwingUtilities.replaceUIActionMap(frame, null);
+ SwingUtilities.replaceUIInputMap(frame, JComponent.WHEN_IN_FOCUSED_WINDOW,
+ null);
}
/**
diff --git a/javax/swing/plaf/basic/BasicListUI.java b/javax/swing/plaf/basic/BasicListUI.java
index e5dcd1c4f..a47d116c4 100644
--- a/javax/swing/plaf/basic/BasicListUI.java
+++ b/javax/swing/plaf/basic/BasicListUI.java
@@ -218,11 +218,12 @@ public class BasicListUI extends ListUI
class ListAction extends AbstractAction
{
- public void actionPerformed (ActionEvent e)
+ public void actionPerformed(ActionEvent e)
{
int lead = list.getLeadSelectionIndex();
int max = list.getModel().getSize() - 1;
- DefaultListSelectionModel selModel = (DefaultListSelectionModel)list.getSelectionModel();
+ DefaultListSelectionModel selModel
+ = (DefaultListSelectionModel) list.getSelectionModel();
String command = e.getActionCommand();
// Do nothing if list is empty
if (max == -1)
@@ -260,9 +261,8 @@ public class BasicListUI extends ListUI
int target;
if (lead == list.getLastVisibleIndex())
{
- target = Math.min
- (max, lead + (list.getLastVisibleIndex() -
- list.getFirstVisibleIndex() + 1));
+ target = Math.min(max, lead + (list.getLastVisibleIndex()
+ - list.getFirstVisibleIndex() + 1));
}
else
target = list.getLastVisibleIndex();
@@ -273,9 +273,8 @@ public class BasicListUI extends ListUI
int target;
if (lead == list.getLastVisibleIndex())
{
- target = Math.min
- (max, lead + (list.getLastVisibleIndex() -
- list.getFirstVisibleIndex() + 1));
+ target = Math.min(max, lead + (list.getLastVisibleIndex()
+ - list.getFirstVisibleIndex() + 1));
}
else
target = list.getLastVisibleIndex();
@@ -286,9 +285,8 @@ public class BasicListUI extends ListUI
int target;
if (lead == list.getFirstVisibleIndex())
{
- target = Math.max
- (0, lead - (list.getLastVisibleIndex() -
- list.getFirstVisibleIndex() + 1));
+ target = Math.max(0, lead - (list.getLastVisibleIndex()
+ - list.getFirstVisibleIndex() + 1));
}
else
target = list.getFirstVisibleIndex();
@@ -299,9 +297,8 @@ public class BasicListUI extends ListUI
int target;
if (lead == list.getFirstVisibleIndex())
{
- target = Math.max
- (0, lead - (list.getLastVisibleIndex() -
- list.getFirstVisibleIndex() + 1));
+ target = Math.max(0, lead - (list.getLastVisibleIndex()
+ - list.getFirstVisibleIndex() + 1));
}
else
target = list.getFirstVisibleIndex();
@@ -309,32 +306,31 @@ public class BasicListUI extends ListUI
}
else if (command.equals("selectNextRowExtendSelection"))
{
- selModel.setLeadSelectionIndex(Math.min(lead + 1,max));
+ selModel.setLeadSelectionIndex(Math.min(lead + 1, max));
}
else if (command.equals("selectFirstRow"))
{
list.setSelectedIndex(0);
}
else if (command.equals("selectFirstRowChangeLead"))
- {
- selModel.moveLeadSelectionIndex(0);
- }
+ {
+ selModel.moveLeadSelectionIndex(0);
+ }
else if (command.equals("selectFirstRowExtendSelection"))
{
selModel.setLeadSelectionIndex(0);
}
else if (command.equals("selectPreviousRowExtendSelection"))
{
- selModel.setLeadSelectionIndex(Math.max(0,lead - 1));
+ selModel.setLeadSelectionIndex(Math.max(0, lead - 1));
}
else if (command.equals("scrollUp"))
{
int target;
if (lead == list.getFirstVisibleIndex())
{
- target = Math.max
- (0, lead - (list.getLastVisibleIndex() -
- list.getFirstVisibleIndex() + 1));
+ target = Math.max(0, lead - (list.getLastVisibleIndex()
+ - list.getFirstVisibleIndex() + 1));
}
else
target = list.getFirstVisibleIndex();
@@ -349,9 +345,8 @@ public class BasicListUI extends ListUI
int target;
if (lead == list.getLastVisibleIndex())
{
- target = Math.min
- (max, lead + (list.getLastVisibleIndex() -
- list.getFirstVisibleIndex() + 1));
+ target = Math.min(max, lead + (list.getLastVisibleIndex()
+ - list.getFirstVisibleIndex() + 1));
}
else
target = list.getLastVisibleIndex();
@@ -451,9 +446,9 @@ public class BasicListUI extends ListUI
if (list.getSelectionMode() == ListSelectionModel.SINGLE_SELECTION)
list.setSelectedIndex(index);
else if (list.isSelectedIndex(index))
- list.removeSelectionInterval(index,index);
+ list.removeSelectionInterval(index, index);
else
- list.addSelectionInterval(index,index);
+ list.addSelectionInterval(index, index);
}
else
list.setSelectedIndex(index);
@@ -1006,14 +1001,14 @@ public class BasicListUI extends ListUI
// Register key bindings in the UI InputMap-ActionMap pair
for (int i = 0; i < keys.length; i++)
{
- KeyStroke stroke = (KeyStroke)keys[i];
+ KeyStroke stroke = (KeyStroke) keys[i];
String actionString = (String) focusInputMap.get(stroke);
parentInputMap.put(KeyStroke.getKeyStroke(stroke.getKeyCode(),
stroke.getModifiers()),
actionString);
- parentActionMap.put (actionString,
- new ActionListenerProxy(action, actionString));
+ parentActionMap.put(actionString,
+ new ActionListenerProxy(action, actionString));
}
// Register the new InputMap-ActionMap as the parents of the list's
// InputMap and ActionMap
diff --git a/javax/swing/plaf/basic/BasicLookAndFeel.java b/javax/swing/plaf/basic/BasicLookAndFeel.java
index 78c16ef08..2ed90f174 100644
--- a/javax/swing/plaf/basic/BasicLookAndFeel.java
+++ b/javax/swing/plaf/basic/BasicLookAndFeel.java
@@ -1,5 +1,5 @@
/* BasicLookAndFeel.java --
- Copyright (C) 2002, 2004, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2004, 2005, 2006, Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -1069,14 +1069,14 @@ public abstract class BasicLookAndFeel extends LookAndFeel
"PAGE_DOWN", "positiveBlockIncrement",
"END", "maxScroll",
"HOME", "minScroll",
- "LEFT", "positiveUnitIncrement",
+ "LEFT", "negativeUnitIncrement",
"KP_UP", "negativeUnitIncrement",
"KP_DOWN", "positiveUnitIncrement",
"UP", "negativeUnitIncrement",
- "RIGHT", "negativeUnitIncrement",
- "KP_LEFT", "positiveUnitIncrement",
+ "RIGHT", "positiveUnitIncrement",
+ "KP_LEFT", "negativeUnitIncrement",
"DOWN", "positiveUnitIncrement",
- "KP_RIGHT", "negativeUnitIncrement"
+ "KP_RIGHT", "positiveUnitIncrement"
}),
"ScrollBar.foreground", new ColorUIResource(light),
"ScrollBar.maximumThumbSize", new DimensionUIResource(4096, 4096),
@@ -1147,14 +1147,16 @@ public abstract class BasicLookAndFeel extends LookAndFeel
"F8", "startResize",
"END", "selectMax",
"HOME", "selectMin",
- "LEFT", "negativeIncremnent",
+ "LEFT", "negativeIncrement",
"KP_UP", "negativeIncrement",
"KP_DOWN", "positiveIncrement",
"UP", "negativeIncrement",
"RIGHT", "positiveIncrement",
"KP_LEFT", "negativeIncrement",
"DOWN", "positiveIncrement",
- "KP_RIGHT", "positiveIncrement"
+ "KP_RIGHT", "positiveIncrement",
+ "shift ctrl pressed TAB", "focusOutBackward",
+ "ctrl pressed TAB", "focusOutForward"
}),
"SplitPane.background", new ColorUIResource(light),
"SplitPane.border", new BasicBorders.SplitPaneBorder(null, null),
diff --git a/javax/swing/plaf/basic/BasicOptionPaneUI.java b/javax/swing/plaf/basic/BasicOptionPaneUI.java
index 88bca3b53..91bf61434 100644
--- a/javax/swing/plaf/basic/BasicOptionPaneUI.java
+++ b/javax/swing/plaf/basic/BasicOptionPaneUI.java
@@ -977,7 +977,7 @@ public class BasicOptionPaneUI extends OptionPaneUI
case JOptionPane.OK_CANCEL_OPTION:
return new Object[] { OK_STRING, CANCEL_STRING };
case JOptionPane.DEFAULT_OPTION:
- return (optionPane.getWantsInput() ) ?
+ return (optionPane.getWantsInput()) ?
new Object[] { OK_STRING, CANCEL_STRING } :
( optionPane.getMessageType() == JOptionPane.QUESTION_MESSAGE ) ?
new Object[] { YES_STRING, NO_STRING, CANCEL_STRING } :
diff --git a/javax/swing/plaf/basic/BasicProgressBarUI.java b/javax/swing/plaf/basic/BasicProgressBarUI.java
index d3674664d..2518a9199 100644
--- a/javax/swing/plaf/basic/BasicProgressBarUI.java
+++ b/javax/swing/plaf/basic/BasicProgressBarUI.java
@@ -52,6 +52,7 @@ import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
+import java.awt.geom.AffineTransform;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
@@ -725,26 +726,22 @@ public class BasicProgressBarUI extends ProgressBarUI
protected void paintString(Graphics g, int x, int y, int width, int height,
int amountFull, Insets b)
{
- // FIXME: We do not support vertical text painting because Java2D is needed
- // for this.
- if (progressBar.getOrientation() == JProgressBar.VERTICAL)
- return;
-
- // We want to place in the exact center of the bar.
+ String str = progressBar.getString();
+ int full = getAmountFull(b, width, height);
Point placement = getStringPlacement(g, progressBar.getString(),
- x + b.left, y + b.top,
+ x + b.left, y + b.top,
width - b.left - b.right,
height - b.top - b.bottom);
-
Color savedColor = g.getColor();
Shape savedClip = g.getClip();
FontMetrics fm = g.getFontMetrics(progressBar.getFont());
- int full = getAmountFull(b, width, height);
- String str = progressBar.getString();
-
- // We draw this string two times with different clips so that the text
- // over the filled area is painted with selectionForeground and over
- // the clear area with selectionBackground.
+
+ if (progressBar.getOrientation() == JProgressBar.VERTICAL)
+ {
+ AffineTransform rotate = AffineTransform.getRotateInstance(Math.PI / 2);
+ g.setFont(progressBar.getFont().deriveFont(rotate));
+ }
+
g.setColor(getSelectionForeground());
g.setClip(0, 0, full + b.left, height);
g.drawString(str, placement.x, placement.y + fm.getAscent());
@@ -756,9 +753,9 @@ public class BasicProgressBarUI extends ProgressBarUI
}
/**
- * This method sets the current animation index. If the index
- * is greater than the number of frames, it resets to 0.
- *
+ * This method sets the current animation index. If the index is greater than
+ * the number of frames, it resets to 0.
+ *
* @param newValue The new animation index.
*/
protected void setAnimationIndex(int newValue)
diff --git a/javax/swing/plaf/basic/BasicRootPaneUI.java b/javax/swing/plaf/basic/BasicRootPaneUI.java
index 933db4c6b..e20bc2bb3 100644
--- a/javax/swing/plaf/basic/BasicRootPaneUI.java
+++ b/javax/swing/plaf/basic/BasicRootPaneUI.java
@@ -215,9 +215,8 @@ public class BasicRootPaneUI extends RootPaneUI
JComponent.WHEN_IN_FOCUSED_WINDOW);
if (newValue != null)
{
- Object[] keybindings =
- (Object[]) UIManager.get
- ("RootPane.defaultButtonWindowKeyBindings");
+ Object[] keybindings = (Object[]) UIManager.get(
+ "RootPane.defaultButtonWindowKeyBindings");
LookAndFeel.loadKeyBindings(im, keybindings);
}
else
diff --git a/javax/swing/plaf/basic/BasicScrollBarUI.java b/javax/swing/plaf/basic/BasicScrollBarUI.java
index f24485484..a81120abd 100644
--- a/javax/swing/plaf/basic/BasicScrollBarUI.java
+++ b/javax/swing/plaf/basic/BasicScrollBarUI.java
@@ -1,5 +1,5 @@
/* BasicScrollBarUI.java --
- Copyright (C) 2004, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2005, 2006, Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,8 +38,6 @@ exception statement from your version. */
package javax.swing.plaf.basic;
-import gnu.classpath.NotImplementedException;
-
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
@@ -56,10 +54,14 @@ import java.awt.event.MouseMotionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
+import javax.swing.AbstractAction;
+import javax.swing.ActionMap;
import javax.swing.BoundedRangeModel;
+import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JScrollBar;
+import javax.swing.JSlider;
import javax.swing.LookAndFeel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
@@ -67,6 +69,7 @@ import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
+import javax.swing.plaf.ActionMapUIResource;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.ScrollBarUI;
@@ -762,15 +765,151 @@ public class BasicScrollBarUI extends ScrollBarUI implements LayoutManager,
}
/**
- * This method installs the keyboard actions for the scrollbar.
+ * Installs the input map from the look and feel defaults, and a
+ * corresponding action map. Note the the keyboard bindings will only
+ * work when the {@link JScrollBar} component has the focus, which is rare.
*/
protected void installKeyboardActions()
- throws NotImplementedException
{
- // FIXME: implement.
+ InputMap keyMap = getInputMap(
+ JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
+ SwingUtilities.replaceUIInputMap(scrollbar,
+ JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, keyMap);
+ ActionMap map = getActionMap();
+ SwingUtilities.replaceUIActionMap(scrollbar, map);
+ }
+
+ /**
+ * Uninstalls the input map and action map installed by
+ * {@link #installKeyboardActions()}.
+ */
+ protected void uninstallKeyboardActions()
+ {
+ SwingUtilities.replaceUIActionMap(scrollbar, null);
+ SwingUtilities.replaceUIInputMap(scrollbar,
+ JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null);
+ }
+
+ InputMap getInputMap(int condition)
+ {
+ if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
+ return (InputMap) UIManager.get("ScrollBar.focusInputMap");
+ return null;
+ }
+
+ /**
+ * Returns the action map for the {@link JScrollBar}. All scroll bars
+ * share a single action map which is created the first time this method is
+ * called, then stored in the UIDefaults table for subsequent access.
+ *
+ * @return The shared action map.
+ */
+ ActionMap getActionMap()
+ {
+ ActionMap map = (ActionMap) UIManager.get("ScrollBar.actionMap");
+
+ if (map == null) // first time here
+ {
+ map = createActionMap();
+ if (map != null)
+ UIManager.put("ScrollBar.actionMap", map);
+ }
+ return map;
}
/**
+ * Creates the action map shared by all {@link JSlider} instances.
+ * This method is called once by {@link #getActionMap()} when it
+ * finds no action map in the UIDefaults table...after the map is
+ * created, it gets added to the defaults table so that subsequent
+ * calls to {@link #getActionMap()} will return the same shared
+ * instance.
+ *
+ * @return The action map.
+ */
+ ActionMap createActionMap()
+ {
+ ActionMap map = new ActionMapUIResource();
+ map.put("positiveUnitIncrement",
+ new AbstractAction("positiveUnitIncrement") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollBar sb = (JScrollBar) event.getSource();
+ if (sb.isVisible())
+ {
+ int delta = sb.getUnitIncrement(1);
+ sb.setValue(sb.getValue() + delta);
+ }
+ }
+ }
+ );
+ map.put("positiveBlockIncrement",
+ new AbstractAction("positiveBlockIncrement") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollBar sb = (JScrollBar) event.getSource();
+ if (sb.isVisible())
+ {
+ int delta = sb.getBlockIncrement(1);
+ sb.setValue(sb.getValue() + delta);
+ }
+ }
+ }
+ );
+ map.put("negativeUnitIncrement",
+ new AbstractAction("negativeUnitIncrement") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollBar sb = (JScrollBar) event.getSource();
+ if (sb.isVisible())
+ {
+ int delta = sb.getUnitIncrement(-1);
+ sb.setValue(sb.getValue() + delta);
+ }
+ }
+ }
+ );
+ map.put("negativeBlockIncrement",
+ new AbstractAction("negativeBlockIncrement") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollBar sb = (JScrollBar) event.getSource();
+ if (sb.isVisible())
+ {
+ int delta = sb.getBlockIncrement(-1);
+ sb.setValue(sb.getValue() + delta);
+ }
+ }
+ }
+ );
+ map.put("minScroll",
+ new AbstractAction("minScroll") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollBar sb = (JScrollBar) event.getSource();
+ if (sb.isVisible())
+ {
+ sb.setValue(sb.getMinimum());
+ }
+ }
+ }
+ );
+ map.put("maxScroll",
+ new AbstractAction("maxScroll") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollBar sb = (JScrollBar) event.getSource();
+ if (sb.isVisible())
+ {
+ sb.setValue(sb.getMaximum());
+ }
+ }
+ }
+ );
+ return map;
+ }
+
+ /**
* This method installs any listeners for the scrollbar. This method also
* installs listeners for things such as the JButtons and the timer.
*/
@@ -806,19 +945,20 @@ public class BasicScrollBarUI extends ScrollBarUI implements LayoutManager,
super.installUI(c);
if (c instanceof JScrollBar)
{
- scrollbar = (JScrollBar) c;
+ scrollbar = (JScrollBar) c;
- trackRect = new Rectangle();
- thumbRect = new Rectangle();
+ trackRect = new Rectangle();
+ thumbRect = new Rectangle();
- scrollTimer = new Timer(300, null);
+ scrollTimer = new Timer(300, null);
installDefaults();
- installComponents();
- configureScrollBarColors();
- installListeners();
+ installComponents();
+ configureScrollBarColors();
+ installListeners();
+ installKeyboardActions();
- calculatePreferredSize();
+ calculatePreferredSize();
}
}
@@ -1140,16 +1280,6 @@ public class BasicScrollBarUI extends ScrollBarUI implements LayoutManager,
}
/**
- * This method uninstalls any keyboard actions this scrollbar acquired
- * during install.
- */
- protected void uninstallKeyboardActions()
- throws NotImplementedException
- {
- // FIXME: implement.
- }
-
- /**
* This method uninstalls any listeners that were registered during install.
*/
protected void uninstallListeners()
@@ -1186,6 +1316,7 @@ public class BasicScrollBarUI extends ScrollBarUI implements LayoutManager,
*/
public void uninstallUI(JComponent c)
{
+ uninstallKeyboardActions();
uninstallListeners();
uninstallDefaults();
uninstallComponents();
diff --git a/javax/swing/plaf/basic/BasicScrollPaneUI.java b/javax/swing/plaf/basic/BasicScrollPaneUI.java
index e6a4eaf4f..a0616a8c1 100644
--- a/javax/swing/plaf/basic/BasicScrollPaneUI.java
+++ b/javax/swing/plaf/basic/BasicScrollPaneUI.java
@@ -1,5 +1,5 @@
/* BasicScrollPaneUI.java
- Copyright (C) 2002, 2004, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2004, 2005, 2006, Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -45,6 +45,7 @@ import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
+import java.awt.event.ActionEvent;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.MouseWheelEvent;
@@ -52,20 +53,31 @@ import java.awt.event.MouseWheelListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.ActionMap;
+import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
+import javax.swing.JSlider;
import javax.swing.JViewport;
import javax.swing.LookAndFeel;
import javax.swing.ScrollPaneConstants;
import javax.swing.ScrollPaneLayout;
import javax.swing.Scrollable;
import javax.swing.SwingConstants;
+import javax.swing.SwingUtilities;
+import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
+import javax.swing.plaf.ActionMapUIResource;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.ScrollPaneUI;
+/**
+ * A UI delegate for the {@link JScrollPane} component.
+ */
public class BasicScrollPaneUI extends ScrollPaneUI
implements ScrollPaneConstants
{
@@ -236,7 +248,7 @@ public class BasicScrollPaneUI extends ScrollPaneUI
final Rectangle rect = new Rectangle();
/**
- * Scroll with the mouse whell.
+ * Scroll with the mouse wheel.
*
* @author Audrius Meskauskas (audriusa@Bioinformatics.org)
*/
@@ -311,7 +323,11 @@ public class BasicScrollPaneUI extends ScrollPaneUI
}
/**
- * Get the scroll bar value or null if there is no such scroll bar.
+ * Get the scroll bar value or 0 if there is no such scroll bar.
+ *
+ * @param bar the scroll bar (<code>null</code> permitted).
+ *
+ * @return The scroll bar value, or 0.
*/
final int getValue(JScrollBar bar)
{
@@ -478,6 +494,197 @@ public class BasicScrollPaneUI extends ScrollPaneUI
v.getComponent(i).addMouseWheelListener(mouseWheelListener);
}
+ InputMap getInputMap(int condition)
+ {
+ if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
+ return (InputMap) UIManager.get("ScrollPane.ancestorInputMap");
+ return null;
+ }
+
+ /**
+ * Returns the action map for the {@link JScrollPane}. All scroll panes
+ * share a single action map which is created the first time this method is
+ * called, then stored in the UIDefaults table for subsequent access.
+ *
+ * @return The shared action map.
+ */
+ ActionMap getActionMap()
+ {
+ ActionMap map = (ActionMap) UIManager.get("ScrollPane.actionMap");
+
+ if (map == null) // first time here
+ {
+ map = createActionMap();
+ if (map != null)
+ UIManager.put("ScrollPane.actionMap", map);
+ }
+ return map;
+ }
+
+ /**
+ * Creates the action map shared by all {@link JSlider} instances.
+ * This method is called once by {@link #getActionMap()} when it
+ * finds no action map in the UIDefaults table...after the map is
+ * created, it gets added to the defaults table so that subsequent
+ * calls to {@link #getActionMap()} will return the same shared
+ * instance.
+ *
+ * @return The action map.
+ */
+ ActionMap createActionMap()
+ {
+ ActionMap map = new ActionMapUIResource();
+ map.put("scrollLeft",
+ new AbstractAction("scrollLeft") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollPane sp = (JScrollPane) event.getSource();
+ JScrollBar sb = sp.getHorizontalScrollBar();
+ if (sb.isVisible())
+ {
+ int delta = sb.getBlockIncrement(-1);
+ sb.setValue(sb.getValue() + delta);
+ }
+ }
+ }
+ );
+ map.put("scrollEnd",
+ new AbstractAction("scrollEnd") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollPane sp = (JScrollPane) event.getSource();
+ JScrollBar sb1 = sp.getHorizontalScrollBar();
+ if (sb1.isVisible())
+ {
+ sb1.setValue(sb1.getMaximum());
+ }
+ JScrollBar sb2 = sp.getVerticalScrollBar();
+ if (sb2.isVisible())
+ {
+ sb2.setValue(sb2.getMaximum());
+ }
+ }
+ }
+ );
+ map.put("unitScrollUp",
+ new AbstractAction("unitScrollUp") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollPane sp = (JScrollPane) event.getSource();
+ JScrollBar sb = sp.getVerticalScrollBar();
+ if (sb.isVisible())
+ {
+ int delta = sb.getUnitIncrement(-1);
+ sb.setValue(sb.getValue() + delta);
+ }
+ }
+ }
+ );
+ map.put("unitScrollLeft",
+ new AbstractAction("unitScrollLeft") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollPane sp = (JScrollPane) event.getSource();
+ JScrollBar sb = sp.getHorizontalScrollBar();
+ if (sb.isVisible())
+ {
+ int delta = sb.getUnitIncrement(-1);
+ sb.setValue(sb.getValue() + delta);
+ }
+ }
+ }
+ );
+ map.put("scrollUp",
+ new AbstractAction("scrollUp") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollPane sp = (JScrollPane) event.getSource();
+ JScrollBar sb = sp.getVerticalScrollBar();
+ if (sb.isVisible())
+ {
+ int delta = sb.getBlockIncrement(-1);
+ sb.setValue(sb.getValue() + delta);
+ }
+ }
+ }
+ );
+ map.put("scrollRight",
+ new AbstractAction("scrollRight") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollPane sp = (JScrollPane) event.getSource();
+ JScrollBar sb = sp.getHorizontalScrollBar();
+ if (sb.isVisible())
+ {
+ int delta = sb.getBlockIncrement(1);
+ sb.setValue(sb.getValue() + delta);
+ }
+ }
+ }
+ );
+ map.put("scrollHome",
+ new AbstractAction("scrollHome") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollPane sp = (JScrollPane) event.getSource();
+ JScrollBar sb1 = sp.getHorizontalScrollBar();
+ if (sb1.isVisible())
+ {
+ sb1.setValue(sb1.getMinimum());
+ }
+ JScrollBar sb2 = sp.getVerticalScrollBar();
+ if (sb2.isVisible())
+ {
+ sb2.setValue(sb2.getMinimum());
+ }
+ }
+ }
+ );
+ map.put("scrollDown",
+ new AbstractAction("scrollDown") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollPane sp = (JScrollPane) event.getSource();
+ JScrollBar sb = sp.getVerticalScrollBar();
+ if (sb.isVisible())
+ {
+ int delta = sb.getBlockIncrement(1);
+ sb.setValue(sb.getValue() + delta);
+ }
+ }
+ }
+ );
+ map.put("unitScrollDown",
+ new AbstractAction("unitScrollDown") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollPane sp = (JScrollPane) event.getSource();
+ JScrollBar sb = sp.getVerticalScrollBar();
+ if (sb.isVisible())
+ {
+ int delta = sb.getUnitIncrement(1);
+ sb.setValue(sb.getValue() + delta);
+ }
+ }
+ }
+ );
+ map.put("unitScrollRight",
+ new AbstractAction("unitScrollRight") {
+ public void actionPerformed(ActionEvent event)
+ {
+ JScrollPane sp = (JScrollPane) event.getSource();
+ JScrollBar sb = sp.getHorizontalScrollBar();
+ if (sb.isVisible())
+ {
+ int delta = sb.getUnitIncrement(1);
+ sb.setValue(sb.getValue() + delta);
+ }
+ }
+ }
+ );
+ return map;
+ }
+
/**
* Installs additional keyboard actions on the scrollpane. This is a hook
* method provided to subclasses in order to install their own keyboard
@@ -486,13 +693,30 @@ public class BasicScrollPaneUI extends ScrollPaneUI
* @param sp the scrollpane to install keyboard actions on
*/
protected void installKeyboardActions(JScrollPane sp)
- throws NotImplementedException
{
- // TODO: Is this only a hook method or should we actually do something
- // here? If the latter, than figure out what and implement this.
+ InputMap keyMap = getInputMap(
+ JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
+ SwingUtilities.replaceUIInputMap(sp,
+ JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, keyMap);
+ ActionMap map = getActionMap();
+ SwingUtilities.replaceUIActionMap(sp, map);
}
/**
+ * Uninstalls all keyboard actions from the JScrollPane that have been
+ * installed by {@link #installKeyboardActions}. This is a hook method
+ * provided to subclasses to add their own keyboard actions.
+ *
+ * @param sp the scrollpane to uninstall keyboard actions from
+ */
+ protected void uninstallKeyboardActions(JScrollPane sp)
+ {
+ SwingUtilities.replaceUIActionMap(sp, null);
+ SwingUtilities.replaceUIInputMap(sp,
+ JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null);
+ }
+
+ /**
* Creates and returns the change listener for the horizontal scrollbar.
*
* @return the change listener for the horizontal scrollbar
@@ -536,6 +760,8 @@ public class BasicScrollPaneUI extends ScrollPaneUI
* Creates and returns the mouse wheel listener for the scrollpane.
*
* @return the mouse wheel listener for the scrollpane
+ *
+ * @since 1.4
*/
protected MouseWheelListener createMouseWheelListener()
{
@@ -545,7 +771,7 @@ public class BasicScrollPaneUI extends ScrollPaneUI
public void uninstallUI(final JComponent c)
{
super.uninstallUI(c);
- this.uninstallDefaults((JScrollPane)c);
+ this.uninstallDefaults((JScrollPane) c);
uninstallListeners((JScrollPane) c);
installKeyboardActions((JScrollPane) c);
}
@@ -574,23 +800,9 @@ public class BasicScrollPaneUI extends ScrollPaneUI
}
- /**
- * Uninstalls all keyboard actions from the JScrollPane that have been
- * installed by {@link #installKeyboardActions}. This is a hook method
- * provided to subclasses to add their own keyboard actions.
- *
- * @param sp the scrollpane to uninstall keyboard actions from
- */
- protected void uninstallKeyboardActions(JScrollPane sp)
- throws NotImplementedException
- {
- // TODO: Is this only a hook method or should we actually do something
- // here? If the latter, than figure out what and implement this.
- }
-
public Dimension getMinimumSize(JComponent c)
{
- JScrollPane p = (JScrollPane ) c;
+ JScrollPane p = (JScrollPane) c;
ScrollPaneLayout sl = (ScrollPaneLayout) p.getLayout();
return sl.minimumLayoutSize(c);
}
diff --git a/javax/swing/plaf/basic/BasicSpinnerUI.java b/javax/swing/plaf/basic/BasicSpinnerUI.java
index 465374bfd..254a9a4fa 100644
--- a/javax/swing/plaf/basic/BasicSpinnerUI.java
+++ b/javax/swing/plaf/basic/BasicSpinnerUI.java
@@ -220,7 +220,7 @@ public class BasicSpinnerUI extends SpinnerUI
BasicSpinnerUI.this.spinner.getModel().setValue(next);
}
- volatile boolean mouseDown = false;
+ volatile boolean mouseDown;
Timer timer = new Timer(50,
new ActionListener()
{
@@ -260,7 +260,7 @@ public class BasicSpinnerUI extends SpinnerUI
BasicSpinnerUI.this.spinner.getModel().setValue(prev);
}
- volatile boolean mouseDown = false;
+ volatile boolean mouseDown;
Timer timer = new Timer(50,
new ActionListener()
{
diff --git a/javax/swing/plaf/basic/BasicSplitPaneUI.java b/javax/swing/plaf/basic/BasicSplitPaneUI.java
index 694baadda..2d5955974 100644
--- a/javax/swing/plaf/basic/BasicSplitPaneUI.java
+++ b/javax/swing/plaf/basic/BasicSplitPaneUI.java
@@ -1,5 +1,5 @@
/* BasicSplitPaneUI.java --
- Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2003, 2004, 2005, 2006, Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,8 +38,6 @@ exception statement from your version. */
package javax.swing.plaf.basic;
-import gnu.classpath.NotImplementedException;
-
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
@@ -57,11 +55,17 @@ import java.awt.event.FocusListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
+import javax.swing.AbstractAction;
+import javax.swing.ActionMap;
+import javax.swing.InputMap;
import javax.swing.JComponent;
+import javax.swing.JSlider;
import javax.swing.JSplitPane;
import javax.swing.KeyStroke;
import javax.swing.LookAndFeel;
+import javax.swing.SwingUtilities;
import javax.swing.UIManager;
+import javax.swing.plaf.ActionMapUIResource;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.SplitPaneUI;
import javax.swing.plaf.UIResource;
@@ -676,7 +680,9 @@ public class BasicSplitPaneUI extends SplitPaneUI
*/
public void focusGained(FocusEvent ev)
{
- // FIXME: implement.
+ // repaint the divider because its background color may change due to
+ // the focus state...
+ divider.repaint();
}
/**
@@ -686,7 +692,9 @@ public class BasicSplitPaneUI extends SplitPaneUI
*/
public void focusLost(FocusEvent ev)
{
- // FIXME: implement.
+ // repaint the divider because its background color may change due to
+ // the focus state...
+ divider.repaint();
}
}
@@ -1046,21 +1054,143 @@ public class BasicSplitPaneUI extends SplitPaneUI
}
/**
- * This method installs the keyboard actions for the JSplitPane.
+ * Returns the input map for the specified condition.
+ *
+ * @param condition the condition.
+ *
+ * @return The input map.
+ */
+ InputMap getInputMap(int condition)
+ {
+ if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
+ return (InputMap) UIManager.get("SplitPane.ancestorInputMap");
+ return null;
+ }
+
+ /**
+ * Returns the action map for the {@link JSplitPane}. All sliders share
+ * a single action map which is created the first time this method is
+ * called, then stored in the UIDefaults table for subsequent access.
+ *
+ * @return The shared action map.
+ */
+ ActionMap getActionMap()
+ {
+ ActionMap map = (ActionMap) UIManager.get("SplitPane.actionMap");
+
+ if (map == null) // first time here
+ {
+ map = createActionMap();
+ if (map != null)
+ UIManager.put("SplitPane.actionMap", map);
+ }
+ return map;
+ }
+
+ /**
+ * Creates the action map shared by all {@link JSlider} instances.
+ * This method is called once by {@link #getActionMap()} when it
+ * finds no action map in the UIDefaults table...after the map is
+ * created, it gets added to the defaults table so that subsequent
+ * calls to {@link #getActionMap()} will return the same shared
+ * instance.
+ *
+ * @return The action map.
+ */
+ ActionMap createActionMap()
+ {
+ ActionMap map = new ActionMapUIResource();
+ map.put("toggleFocus",
+ new AbstractAction("toggleFocus") {
+ public void actionPerformed(ActionEvent event)
+ {
+ // FIXME: What to do here?
+ }
+ }
+ );
+ map.put("startResize",
+ new AbstractAction("startResize") {
+ public void actionPerformed(ActionEvent event)
+ {
+ splitPane.requestFocus();
+ }
+ }
+ );
+ map.put("selectMax",
+ new AbstractAction("selectMax") {
+ public void actionPerformed(ActionEvent event)
+ {
+ splitPane.setDividerLocation(1.0);
+ }
+ }
+ );
+ map.put("selectMin",
+ new AbstractAction("selectMin") {
+ public void actionPerformed(ActionEvent event)
+ {
+ splitPane.setDividerLocation(0.0);
+ }
+ }
+ );
+ map.put("negativeIncrement",
+ new AbstractAction("negativeIncrement") {
+ public void actionPerformed(ActionEvent event)
+ {
+ setDividerLocation(splitPane, Math.max(dividerLocation
+ - KEYBOARD_DIVIDER_MOVE_OFFSET, 0));
+ }
+ }
+ );
+ map.put("positiveIncrement",
+ new AbstractAction("positiveIncrement") {
+ public void actionPerformed(ActionEvent event)
+ {
+ setDividerLocation(splitPane, dividerLocation
+ + KEYBOARD_DIVIDER_MOVE_OFFSET);
+ }
+ }
+ );
+ map.put("focusOutBackward",
+ new AbstractAction("focusOutBackward") {
+ public void actionPerformed(ActionEvent event)
+ {
+ // FIXME: implement this
+ }
+ }
+ );
+ map.put("focusOutForward",
+ new AbstractAction("focusOutForward") {
+ public void actionPerformed(ActionEvent event)
+ {
+ // FIXME: implement this
+ }
+ }
+ );
+ return map;
+ }
+
+ /**
+ * Installs any keyboard actions. The list of keys that need to be bound are
+ * listed in Basic look and feel's defaults.
*/
protected void installKeyboardActions()
- throws NotImplementedException
{
- // FIXME: implement.
+ InputMap keyMap = getInputMap(
+ JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
+ SwingUtilities.replaceUIInputMap(splitPane,
+ JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, keyMap);
+ ActionMap map = getActionMap();
+ SwingUtilities.replaceUIActionMap(splitPane, map);
}
/**
* This method reverses the work done in installKeyboardActions.
*/
protected void uninstallKeyboardActions()
- throws NotImplementedException
{
- // FIXME: implement.
+ SwingUtilities.replaceUIActionMap(splitPane, null);
+ SwingUtilities.replaceUIInputMap(splitPane,
+ JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null);
}
/**
diff --git a/javax/swing/plaf/basic/BasicTabbedPaneUI.java b/javax/swing/plaf/basic/BasicTabbedPaneUI.java
index 6d9bed331..d500a077d 100644
--- a/javax/swing/plaf/basic/BasicTabbedPaneUI.java
+++ b/javax/swing/plaf/basic/BasicTabbedPaneUI.java
@@ -286,7 +286,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants
width = Math.max(min, width);
int tabAreaHeight = preferredTabAreaHeight(tabPlacement,
width - tabAreaInsets.left
- -tabAreaInsets.right);
+ - tabAreaInsets.right);
height += tabAreaHeight;
}
else
@@ -476,7 +476,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants
else
nextIndex = i + 1;
int next = tabRuns[nextIndex];
- int end = (next != 0 ? next - 1 : tabCount - 1);
+ int end = next != 0 ? next - 1 : tabCount - 1;
if (tabPlacement == SwingConstants.TOP
|| tabPlacement == SwingConstants.BOTTOM)
{
@@ -491,9 +491,9 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants
padTabRun(tabPlacement, start, end, breakAt);
}
if (tabPlacement == BOTTOM)
- y -= (maxTabHeight - tabRunOverlay);
+ y -= maxTabHeight - tabRunOverlay;
else
- y += (maxTabHeight - tabRunOverlay);
+ y += maxTabHeight - tabRunOverlay;
}
else
{
@@ -508,9 +508,9 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants
padTabRun(tabPlacement, start, end, breakAt);
}
if (tabPlacement == RIGHT)
- x -= (maxTabWidth - tabRunOverlay);
+ x -= maxTabWidth - tabRunOverlay;
else
- x += (maxTabWidth - tabRunOverlay);
+ x += maxTabWidth - tabRunOverlay;
}
}
@@ -530,6 +530,17 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants
int tabPlacement = tabPane.getTabPlacement();
Insets insets = tabPane.getInsets();
+
+ int selectedIndex = tabPane.getSelectedIndex();
+ Component selectedComponent = tabPane.getComponentAt(selectedIndex);
+ // The RI doesn't seem to change the component if the new selected
+ // component == null. This is probably so that applications can add
+ // one single component for every tab.
+ if (selectedComponent != null)
+ {
+ setVisibleComponent(selectedComponent);
+ }
+
int childCount = tabPane.getComponentCount();
if (childCount > 0)
{
@@ -1411,6 +1422,11 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants
private boolean tabsOpaque;
/**
+ * The currently visible component.
+ */
+ private Component visibleComponent;
+
+ /**
* Creates a new BasicTabbedPaneUI object.
*/
public BasicTabbedPaneUI()
@@ -1818,7 +1834,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants
next = tabRuns[0];
else
next = tabRuns[i + 1];
- int end = (next != 0 ? next - 1 : tabCount - 1);
+ int end = next != 0 ? next - 1 : tabCount - 1;
for (int j = start; j <= end; ++j)
{
if (j != selectedIndex)
@@ -2194,7 +2210,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants
{
case LEFT:
x += calculateTabAreaWidth(tabPlacement, runCount, maxTabWidth);
- w -= (x - insets.left);
+ w -= x - insets.left;
break;
case RIGHT:
w -= calculateTabAreaWidth(tabPlacement, runCount, maxTabWidth);
@@ -2205,7 +2221,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants
case TOP:
default:
y += calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight);
- h -= (y - insets.top);
+ h -= y - insets.top;
}
// Fill background if necessary.
@@ -2410,6 +2426,9 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants
*/
public Rectangle getTabBounds(JTabbedPane pane, int i)
{
+ // Need to re-layout container if tab does not exist.
+ if (i >= rects.length)
+ layoutManager.layoutContainer(pane);
return rects[i];
}
@@ -2476,7 +2495,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants
*/
protected Component getVisibleComponent()
{
- return tabPane.getComponentAt(tabPane.getSelectedIndex());
+ return visibleComponent;
}
/**
@@ -2486,8 +2505,19 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants
*/
protected void setVisibleComponent(Component component)
{
- component.setVisible(true);
- tabPane.setSelectedComponent(component);
+ // Make old component invisible.
+ if (visibleComponent != null && visibleComponent != component
+ && visibleComponent.getParent() == tabPane)
+ {
+ visibleComponent.setVisible(false);
+ }
+
+ // Make new component visible.
+ if (component != null && ! component.isVisible())
+ {
+ component.setVisible(true);
+ }
+ visibleComponent = component;
}
/**
@@ -3015,7 +3045,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants
{
int currRun = getRunForTab(tabCount, tabIndex);
int offset;
- int nextRun = (forward) ? getNextTabRun(currRun) : getPreviousTabRun(currRun);
+ int nextRun = forward ? getNextTabRun(currRun) : getPreviousTabRun(currRun);
if (tabPlacement == SwingConstants.TOP
|| tabPlacement == SwingConstants.BOTTOM)
offset = rects[lastTabInRun(tabCount, nextRun)].y
diff --git a/javax/swing/plaf/basic/BasicTableUI.java b/javax/swing/plaf/basic/BasicTableUI.java
index bd5d2d916..d3abba217 100644
--- a/javax/swing/plaf/basic/BasicTableUI.java
+++ b/javax/swing/plaf/basic/BasicTableUI.java
@@ -78,6 +78,7 @@ import javax.swing.plaf.InputMapUIResource;
import javax.swing.plaf.TableUI;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
+import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
@@ -385,10 +386,8 @@ public class BasicTableUI extends TableUI
int maxTotalColumnWidth = 0;
for (int i = 0; i < table.getColumnCount(); i++)
maxTotalColumnWidth += table.getColumnModel().getColumn(i).getMaxWidth();
- if (maxTotalColumnWidth == 0 || table.getRowCount() == 0)
- return null;
- return new Dimension(maxTotalColumnWidth, table.getRowCount()*
- (table.getRowHeight()+table.getRowMargin()));
+
+ return new Dimension(maxTotalColumnWidth, getHeight());
}
/**
@@ -406,16 +405,45 @@ public class BasicTableUI extends TableUI
int minTotalColumnWidth = 0;
for (int i = 0; i < table.getColumnCount(); i++)
minTotalColumnWidth += table.getColumnModel().getColumn(i).getMinWidth();
- if (minTotalColumnWidth == 0 || table.getRowCount() == 0)
- return null;
- return new Dimension(minTotalColumnWidth, table.getRowCount()*table.getRowHeight());
+
+ return new Dimension(minTotalColumnWidth, getHeight());
}
+ /**
+ * Returns the preferred size for the table of that UI.
+ *
+ * @param comp ignored, the <code>table</code> field is used instead
+ *
+ * @return the preferred size for the table of that UI
+ */
public Dimension getPreferredSize(JComponent comp)
{
- int width = table.getColumnModel().getTotalColumnWidth();
- int height = table.getRowCount() * (table.getRowHeight()+table.getRowMargin());
- return new Dimension(width, height);
+ int prefTotalColumnWidth = 0;
+ for (int i = 0; i < table.getColumnCount(); i++)
+ {
+ TableColumn col = table.getColumnModel().getColumn(i);
+ prefTotalColumnWidth += col.getPreferredWidth();
+ }
+ return new Dimension(prefTotalColumnWidth, getHeight());
+ }
+
+ /**
+ * Returns the table height. This helper method is used by
+ * {@link #getMinimumSize(JComponent)}, {@link #getPreferredSize(JComponent)}
+ * and {@link #getMaximumSize(JComponent)} to determine the table height.
+ *
+ * @return the table height
+ */
+ private int getHeight()
+ {
+ int height = 0;
+ int rowCount = table.getRowCount();
+ if (rowCount > 0 && table.getColumnCount() > 0)
+ {
+ Rectangle r = table.getCellRect(rowCount - 1, 0, true);
+ height = r.y + r.height;
+ }
+ return height;
}
protected void installDefaults()
@@ -1314,7 +1342,7 @@ public class BasicTableUI extends TableUI
{
// The horizontal grid is draw below the cells, so we
// add before drawing.
- y += table.getRowHeight(r);// + rowMargin;
+ y += table.getRowHeight(r);
gfx.drawLine(left, y, p2.x, y);
}
gfx.setColor(save);
diff --git a/javax/swing/plaf/basic/BasicTextAreaUI.java b/javax/swing/plaf/basic/BasicTextAreaUI.java
index 93e119b31..3f5aa27cf 100644
--- a/javax/swing/plaf/basic/BasicTextAreaUI.java
+++ b/javax/swing/plaf/basic/BasicTextAreaUI.java
@@ -73,7 +73,7 @@ public class BasicTextAreaUI extends BasicTextUI
*/
public View create(Element elem)
{
- JTextArea comp = (JTextArea)getComponent();
+ JTextArea comp = (JTextArea) getComponent();
if (comp.getLineWrap())
{
if (comp.getWrapStyleWord())
@@ -105,7 +105,7 @@ public class BasicTextAreaUI extends BasicTextUI
*/
protected void propertyChange(PropertyChangeEvent ev)
{
- JTextArea comp = (JTextArea)getComponent();
+ JTextArea comp = (JTextArea) getComponent();
if (ev.getPropertyName() == "lineWrap"
|| ev.getPropertyName() == "wrapStyleWord")
{
diff --git a/javax/swing/plaf/basic/BasicTextUI.java b/javax/swing/plaf/basic/BasicTextUI.java
index 6fa37af5c..b058175a4 100644
--- a/javax/swing/plaf/basic/BasicTextUI.java
+++ b/javax/swing/plaf/basic/BasicTextUI.java
@@ -62,10 +62,12 @@ import javax.swing.JComponent;
import javax.swing.LookAndFeel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
+import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.plaf.ActionMapUIResource;
+import javax.swing.plaf.InputMapUIResource;
import javax.swing.plaf.TextUI;
import javax.swing.plaf.UIResource;
import javax.swing.text.AbstractDocument;
@@ -732,18 +734,8 @@ public abstract class BasicTextUI extends TextUI
// load any bindings for the newer InputMap / ActionMap interface
SwingUtilities.replaceUIInputMap(textComponent, JComponent.WHEN_FOCUSED,
- getInputMap(JComponent.WHEN_FOCUSED));
- SwingUtilities.replaceUIActionMap(textComponent, createActionMap());
-
- ActionMap parentActionMap = new ActionMapUIResource();
- Action[] actions = textComponent.getActions();
- for (int j = 0; j < actions.length; j++)
- {
- Action currAction = actions[j];
- parentActionMap.put(currAction.getValue(Action.NAME), currAction);
- }
-
- SwingUtilities.replaceUIActionMap(textComponent, parentActionMap);
+ getInputMap());
+ SwingUtilities.replaceUIActionMap(textComponent, getActionMap());
}
/**
@@ -751,40 +743,71 @@ public abstract class BasicTextUI extends TextUI
*
* @return an ActionMap to be installed on the text component
*/
- ActionMap createActionMap()
+ private ActionMap getActionMap()
+ {
+ // Note: There are no .actionMap entries in the standard L&Fs. However,
+ // with the RI it is possible to install action maps via such keys, so
+ // we must load them too. It can be observed that when there is no
+ // .actionMap entry in the UIManager, one gets installed after a text
+ // component of that type has been loaded.
+ String prefix = getPropertyPrefix();
+ String amName = prefix + ".actionMap";
+ ActionMap am = (ActionMap) UIManager.get(amName);
+ if (am == null)
+ {
+ am = createActionMap();
+ UIManager.put(amName, am);
+ }
+
+ ActionMap map = new ActionMapUIResource();
+ map.setParent(am);
+
+ return map;
+ }
+
+ /**
+ * Creates a default ActionMap for text components that have no UI default
+ * for this (the standard for the built-in L&Fs). The ActionMap is copied
+ * from the text component's getActions() method.
+ *
+ * @returna default ActionMap
+ */
+ private ActionMap createActionMap()
{
- Action[] actions = textComponent.getActions();
ActionMap am = new ActionMapUIResource();
- for (int i = 0; i < actions.length; ++i)
+ Action[] actions = textComponent.getActions();
+ for (int i = actions.length - 1; i >= 0; i--)
{
- String name = (String) actions[i].getValue(Action.NAME);
- if (name != null)
- am.put(name, actions[i]);
+ Action action = actions[i];
+ am.put(action.getValue(Action.NAME), action);
}
+ // Add TransferHandler's actions here. They don't seem to be in the
+ // JTextComponent's default actions, and I can't make up a better place
+ // to add them.
+ Action copyAction = TransferHandler.getCopyAction();
+ am.put(copyAction.getValue(Action.NAME), copyAction);
+ Action cutAction = TransferHandler.getCutAction();
+ am.put(cutAction.getValue(Action.NAME), cutAction);
+ Action pasteAction = TransferHandler.getPasteAction();
+ am.put(pasteAction.getValue(Action.NAME), pasteAction);
+
return am;
}
/**
* Gets the input map for the specified <code>condition</code>.
*
- * @param condition the condition for the InputMap
- *
* @return the InputMap for the specified condition
*/
- InputMap getInputMap(int condition)
+ private InputMap getInputMap()
{
+ InputMap im = new InputMapUIResource();
String prefix = getPropertyPrefix();
- switch (condition)
- {
- case JComponent.WHEN_IN_FOCUSED_WINDOW:
- // FIXME: is this the right string? nobody seems to use it.
- return (InputMap) UIManager.get(prefix + ".windowInputMap");
- case JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT:
- return (InputMap) UIManager.get(prefix + ".ancestorInputMap");
- default:
- case JComponent.WHEN_FOCUSED:
- return (InputMap) UIManager.get(prefix + ".focusInputMap");
- }
+ InputMap shared =
+ (InputMap) SharedUIDefaults.get(prefix + ".focusInputMap");
+ if (shared != null)
+ im.setParent(shared);
+ return im;
}
/**
@@ -1039,7 +1062,12 @@ public abstract class BasicTextUI extends TextUI
Rectangle l1 = modelToView(t, p0, firstBias);
Rectangle l2 = modelToView(t, p1, secondBias);
- if (l1.y == l2.y)
+ if (l1 == null || l2 == null)
+ {
+ // Unable to determine the start or end of the selection.
+ t.repaint();
+ }
+ else if (l1.y == l2.y)
{
SwingUtilities.computeUnion(l2.x, l2.y, l2.width, l2.height, l1);
t.repaint(l1);
diff --git a/javax/swing/plaf/basic/BasicTreeUI.java b/javax/swing/plaf/basic/BasicTreeUI.java
index 6756a3ac5..05f0a3bbd 100644
--- a/javax/swing/plaf/basic/BasicTreeUI.java
+++ b/javax/swing/plaf/basic/BasicTreeUI.java
@@ -49,7 +49,6 @@ import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Label;
-import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@@ -81,7 +80,6 @@ import javax.swing.JComponent;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTree;
-import javax.swing.KeyStroke;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
@@ -97,7 +95,6 @@ import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.plaf.ActionMapUIResource;
import javax.swing.plaf.ComponentUI;
-import javax.swing.plaf.InputMapUIResource;
import javax.swing.plaf.TreeUI;
import javax.swing.tree.AbstractLayoutCache;
import javax.swing.tree.DefaultTreeCellEditor;
@@ -307,17 +304,6 @@ public class BasicTreeUI
nodeDimensions = createNodeDimensions();
configureLayoutCache();
- propertyChangeListener = createPropertyChangeListener();
- focusListener = createFocusListener();
- treeSelectionListener = createTreeSelectionListener();
- mouseListener = createMouseListener();
- keyListener = createKeyListener();
- selectionModelPropertyChangeListener = createSelectionModelPropertyChangeListener();
- componentListener = createComponentListener();
- cellEditorListener = createCellEditorListener();
- treeExpansionListener = createTreeExpansionListener();
- treeModelListener = createTreeModelListener();
-
editingRow = - 1;
lastSelectedRow = - 1;
}
@@ -513,9 +499,22 @@ public class BasicTreeUI
*/
protected void setModel(TreeModel model)
{
- tree.setModel(model);
+ completeEditing();
+
+ if (treeModel != null && treeModelListener != null)
+ treeModel.removeTreeModelListener(treeModelListener);
+
treeModel = tree.getModel();
- treeState.setModel(treeModel);
+
+ if (treeModel != null && treeModelListener != null)
+ treeModel.addTreeModelListener(treeModelListener);
+
+ if (treeState != null)
+ {
+ treeState.setModel(treeModel);
+ updateLayoutCacheExpandedNodes();
+ updateSize();
+ }
}
/**
@@ -555,7 +554,13 @@ public class BasicTreeUI
*/
protected void setShowsRootHandles(boolean newValue)
{
- tree.setShowsRootHandles(newValue);
+ completeEditing();
+ updateDepthOffset();
+ if (treeState != null)
+ {
+ treeState.invalidateSizes();
+ updateSize();
+ }
}
/**
@@ -822,9 +827,12 @@ public class BasicTreeUI
* default/listeners have been installed.
*/
protected void prepareForUIInstall()
- throws NotImplementedException
{
- // TODO: Implement this properly.
+ lastSelectedRow = -1;
+ preferredSize = new Dimension();
+ largeModel = tree.isLargeModel();
+ preferredSize = new Dimension();
+ setModel(tree.getModel());
}
/**
@@ -832,9 +840,15 @@ public class BasicTreeUI
* installed.
*/
protected void completeUIInstall()
- throws NotImplementedException
{
- // TODO: Implement this properly.
+ setShowsRootHandles(tree.getShowsRootHandles());
+ updateRenderer();
+ updateDepthOffset();
+ setSelectionModel(tree.getSelectionModel());
+ treeState = createLayoutCache();
+ treeSelectionModel.setRowMapper(treeState);
+ configureLayoutCache();
+ updateSize();
}
/**
@@ -842,9 +856,8 @@ public class BasicTreeUI
* uninstalled.
*/
protected void completeUIUninstall()
- throws NotImplementedException
{
- // TODO: Implement this properly.
+ tree = null;
}
/**
@@ -997,15 +1010,14 @@ public class BasicTreeUI
*/
protected TreeCellEditor createDefaultCellEditor()
{
- if (currentCellRenderer != null)
- return new DefaultTreeCellEditor(
- tree,
- (DefaultTreeCellRenderer) currentCellRenderer,
- cellEditor);
- return new DefaultTreeCellEditor(
- tree,
- (DefaultTreeCellRenderer) createDefaultCellRenderer(),
- cellEditor);
+ DefaultTreeCellEditor ed;
+ if (currentCellRenderer != null
+ && currentCellRenderer instanceof DefaultTreeCellRenderer)
+ ed = new DefaultTreeCellEditor(tree,
+ (DefaultTreeCellRenderer) currentCellRenderer);
+ else
+ ed = new DefaultTreeCellEditor(tree, null);
+ return ed;
}
/**
@@ -1102,7 +1114,7 @@ public class BasicTreeUI
*/
protected void updateLayoutCacheExpandedNodes()
{
- if (treeModel != null)
+ if (treeModel != null && treeModel.getRoot() != null)
updateExpandedDescendants(new TreePath(treeModel.getRoot()));
}
@@ -1161,6 +1173,8 @@ public class BasicTreeUI
if (currentCellRenderer == null)
currentCellRenderer = createDefaultCellRenderer();
+
+ updateCellEditor();
}
/**
@@ -1240,40 +1254,103 @@ public class BasicTreeUI
*/
protected void installKeyboardActions()
{
- InputMap focusInputMap = (InputMap) UIManager.get("Tree.focusInputMap");
- InputMapUIResource parentInputMap = new InputMapUIResource();
- ActionMap parentActionMap = new ActionMapUIResource();
+ InputMap focusInputMap =
+ (InputMap) SharedUIDefaults.get("Tree.focusInputMap");
+ SwingUtilities.replaceUIInputMap(tree, JComponent.WHEN_FOCUSED,
+ focusInputMap);
+ InputMap ancestorInputMap =
+ (InputMap) SharedUIDefaults.get("Tree.ancestorInputMap");
+ SwingUtilities.replaceUIInputMap(tree,
+ JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,
+ ancestorInputMap);
+
action = new TreeAction();
- Object keys[] = focusInputMap.allKeys();
- for (int i = 0; i < keys.length; i++)
- {
- parentInputMap.put(
- KeyStroke.getKeyStroke(
- ((KeyStroke) keys[i]).getKeyCode(),
- convertModifiers(((KeyStroke) keys[i]).getModifiers())),
- (String) focusInputMap.get((KeyStroke) keys[i]));
-
- parentInputMap.put(
- KeyStroke.getKeyStroke(
- ((KeyStroke) keys[i]).getKeyCode(),
- ((KeyStroke) keys[i]).getModifiers()),
- (String) focusInputMap.get((KeyStroke) keys[i]));
-
- parentActionMap.put(
- (String) focusInputMap.get((KeyStroke) keys[i]),
- new ActionListenerProxy(
- action,
- (String) focusInputMap.get((KeyStroke) keys[i])));
+ SwingUtilities.replaceUIActionMap(tree, getActionMap());
+ }
+ /**
+ * Creates and returns the shared action map for JTrees.
+ *
+ * @return the shared action map for JTrees
+ */
+ private ActionMap getActionMap()
+ {
+ ActionMap am = (ActionMap) UIManager.get("Tree.actionMap");
+ if (am == null)
+ {
+ am = createDefaultActions();
+ UIManager.getLookAndFeelDefaults().put("Tree.actionMap", am);
}
+ return am;
+ }
+
+ /**
+ * Creates the default actions when there are none specified by the L&F.
+ *
+ * @return the default actions
+ */
+ private ActionMap createDefaultActions()
+ {
+ ActionMapUIResource am = new ActionMapUIResource();
+ Action action;
+
+ action= new TreeAction();
+ am.put(action.getValue(Action.NAME), action);
+
+ // TreeHomeAction.
+ action= new TreeHomeAction(-1, "selectFirst");
+ am.put(action.getValue(Action.NAME), action);
+ action= new TreeHomeAction(-1, "selectFirstChangeLead");
+ am.put(action.getValue(Action.NAME), action);
+ action= new TreeHomeAction(-1, "selectFirstExtendSelection");
+ am.put(action.getValue(Action.NAME), action);
+ action= new TreeHomeAction(1, "selectLast");
+ am.put(action.getValue(Action.NAME), action);
+ action= new TreeHomeAction(1, "selectLastChangeLead");
+ am.put(action.getValue(Action.NAME), action);
+ action= new TreeHomeAction(1, "selectLastExtendSelection");
+ am.put(action.getValue(Action.NAME), action);
+
+ // TreeIncrementAction.
+ action = new TreeIncrementAction(-1, "selectPrevious");
+ am.put(action.getValue(Action.NAME), action);
+ action = new TreeIncrementAction(-1, "selectPreviousExtendSelection");
+ am.put(action.getValue(Action.NAME), action);
+ action = new TreeIncrementAction(-1, "selectPreviousChangeLead");
+ am.put(action.getValue(Action.NAME), action);
+ action = new TreeIncrementAction(1, "selectNext");
+ am.put(action.getValue(Action.NAME), action);
+ action = new TreeIncrementAction(1, "selectNextExtendSelection");
+ am.put(action.getValue(Action.NAME), action);
+ action = new TreeIncrementAction(1, "selectNextChangeLead");
+ am.put(action.getValue(Action.NAME), action);
+
+ // TreeTraverseAction.
+ action = new TreeTraverseAction(-1, "selectParent");
+ am.put(action.getValue(Action.NAME), action);
+ action = new TreeTraverseAction(1, "selectChild");
+ am.put(action.getValue(Action.NAME), action);
+
+ // TreeToggleAction.
+ action = new TreeToggleAction("toggleAndAnchor");
+ am.put(action.getValue(Action.NAME), action);
- parentInputMap.setParent(tree.getInputMap(
- JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).getParent());
- parentActionMap.setParent(tree.getActionMap().getParent());
- tree.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).setParent(
- parentInputMap);
- tree.getActionMap().setParent(parentActionMap);
+ // TreePageAction.
+ action = new TreePageAction(-1, "scrollUpChangeSelection");
+ am.put(action.getValue(Action.NAME), action);
+ action = new TreePageAction(-1, "scrollUpExtendSelection");
+ am.put(action.getValue(Action.NAME), action);
+ action = new TreePageAction(-1, "scrollUpChangeLead");
+ am.put(action.getValue(Action.NAME), action);
+ action = new TreePageAction(1, "scrollDownChangeSelection");
+ am.put(action.getValue(Action.NAME), action);
+ action = new TreePageAction(1, "scrollDownExtendSelection");
+ am.put(action.getValue(Action.NAME), action);
+ action = new TreePageAction(1, "scrollDownChangeLead");
+ am.put(action.getValue(Action.NAME), action);
+
+ return am;
}
/**
@@ -1317,16 +1394,41 @@ public class BasicTreeUI
*/
protected void installListeners()
{
+ propertyChangeListener = createPropertyChangeListener();
tree.addPropertyChangeListener(propertyChangeListener);
+
+ focusListener = createFocusListener();
tree.addFocusListener(focusListener);
+
+ treeSelectionListener = createTreeSelectionListener();
tree.addTreeSelectionListener(treeSelectionListener);
+
+ mouseListener = createMouseListener();
tree.addMouseListener(mouseListener);
+
+ keyListener = createKeyListener();
tree.addKeyListener(keyListener);
- tree.addPropertyChangeListener(selectionModelPropertyChangeListener);
+
+ selectionModelPropertyChangeListener =
+ createSelectionModelPropertyChangeListener();
+ if (treeSelectionModel != null
+ && selectionModelPropertyChangeListener != null)
+ {
+ treeSelectionModel.addPropertyChangeListener
+ (selectionModelPropertyChangeListener);
+ }
+
+ componentListener = createComponentListener();
tree.addComponentListener(componentListener);
+
+ treeExpansionListener = createTreeExpansionListener();
tree.addTreeExpansionListener(treeExpansionListener);
+
+ treeModelListener = createTreeModelListener();
if (treeModel != null)
treeModel.addTreeModelListener(treeModelListener);
+
+ cellEditorListener = createCellEditorListener();
}
/**
@@ -1337,25 +1439,12 @@ public class BasicTreeUI
public void installUI(JComponent c)
{
tree = (JTree) c;
- treeModel = tree.getModel();
prepareForUIInstall();
- super.installUI(c);
installDefaults();
installComponents();
installKeyboardActions();
installListeners();
-
- setCellEditor(createDefaultCellEditor());
- createdCellEditor = true;
- isEditing = false;
-
- setModel(tree.getModel());
- treeSelectionModel = tree.getSelectionModel();
- setRootVisible(tree.isRootVisible());
- treeState.setRootVisible(tree.isRootVisible());
- updateExpandedDescendants(new TreePath(new Object[] { treeModel.getRoot() }));
-
completeUIInstall();
}
@@ -1376,11 +1465,12 @@ public class BasicTreeUI
*/
public void uninstallUI(JComponent c)
{
+ completeEditing();
+
prepareForUIUninstall();
uninstallDefaults();
uninstallKeyboardActions();
uninstallListeners();
- tree = null;
uninstallComponents();
completeUIUninstall();
}
@@ -1613,6 +1703,9 @@ public class BasicTreeUI
protected void completeEditing(boolean messageStop, boolean messageCancel,
boolean messageTree)
{
+ if (! stopEditingInCompleteEditing || editingComponent == null)
+ return;
+
if (messageStop)
{
getCellEditor().stopCellEditing();
@@ -1698,7 +1791,7 @@ public class BasicTreeUI
int mouseY)
{
if (isLocationInExpandControl(path, mouseX, mouseY))
- toggleExpandState(path);
+ handleExpandControlClick(path, mouseX, mouseY);
}
/**
@@ -1717,16 +1810,17 @@ public class BasicTreeUI
int mouseY)
{
boolean cntlClick = false;
- int row = getRowForPath(tree, path);
-
- if (! isLeaf(row))
+ if (! treeModel.isLeaf(path.getLastPathComponent()))
{
- Rectangle bounds = getPathBounds(tree, path);
-
- if (hasControlIcons()
- && (mouseX < bounds.x)
- && (mouseX > (bounds.x - getCurrentControlIcon(path).getIconWidth() - gap)))
- cntlClick = true;
+ int width = 8; // Only guessing.
+ Icon expandedIcon = getExpandedIcon();
+ if (expandedIcon != null)
+ width = expandedIcon.getIconWidth();
+
+ Insets i = tree.getInsets();
+ int left = getRowX(tree.getRowForPath(path), path.getPathCount() - 1)
+ -getRightChildIndent() - width / 2 + i.left;
+ cntlClick = mouseX >= left && mouseX <= left + width;
}
return cntlClick;
}
@@ -1808,10 +1902,15 @@ public class BasicTreeUI
* the event.
*/
protected boolean isToggleEvent(MouseEvent event)
- throws NotImplementedException
{
- // FIXME: Not implemented.
- return true;
+ boolean toggle = false;
+ if (SwingUtilities.isLeftMouseButton(event))
+ {
+ int clickCount = tree.getToggleClickCount();
+ if (clickCount > 0 && event.getClickCount() == clickCount)
+ toggle = true;
+ }
+ return toggle;
}
/**
@@ -1856,7 +1955,8 @@ public class BasicTreeUI
{
// This is an ordinary event that just selects the clicked row.
tree.setSelectionPath(path);
- tree.setAnchorSelectionPath(path);
+ if (isToggleEvent(event))
+ toggleExpandState(path);
}
}
@@ -1993,9 +2093,33 @@ public class BasicTreeUI
* @param e the event that occurs when moving the component
*/
public void componentMoved(ComponentEvent e)
- throws NotImplementedException
{
- // TODO: What should be done here, if anything?
+ if (timer == null)
+ {
+ JScrollPane scrollPane = getScrollPane();
+ if (scrollPane == null)
+ updateSize();
+ else
+ {
+ // Determine the scrollbar that is adjusting, if any, and
+ // start the timer for that. If no scrollbar is adjusting,
+ // we simply call updateSize().
+ scrollBar = scrollPane.getVerticalScrollBar();
+ if (scrollBar == null || !scrollBar.getValueIsAdjusting())
+ {
+ // It's not the vertical scrollbar, try the horizontal one.
+ scrollBar = scrollPane.getHorizontalScrollBar();
+ if (scrollBar != null && scrollBar.getValueIsAdjusting())
+ startTimer();
+ else
+ updateSize();
+ }
+ else
+ {
+ startTimer();
+ }
+ }
+ }
}
/**
@@ -2003,9 +2127,13 @@ public class BasicTreeUI
* the bounds
*/
protected void startTimer()
- throws NotImplementedException
{
- // TODO: Implement this properly.
+ if (timer == null)
+ {
+ timer = new Timer(200, this);
+ timer.setRepeats(true);
+ }
+ timer.start();
}
/**
@@ -2014,10 +2142,14 @@ public class BasicTreeUI
* @return JScrollPane housing the JTree, or null if one isn't found.
*/
protected JScrollPane getScrollPane()
- throws NotImplementedException
{
- // FIXME: Not implemented.
- return null;
+ JScrollPane found = null;
+ Component p = tree.getParent();
+ while (p != null && !(p instanceof JScrollPane))
+ p = p.getParent();
+ if (p instanceof JScrollPane)
+ found = (JScrollPane) p;
+ return found;
}
/**
@@ -2027,9 +2159,15 @@ public class BasicTreeUI
* @param ae is the action performed
*/
public void actionPerformed(ActionEvent ae)
- throws NotImplementedException
{
- // TODO: Implement this properly.
+ if (scrollBar == null || !scrollBar.getValueIsAdjusting())
+ {
+ if (timer != null)
+ timer.stop();
+ updateSize();
+ timer = null;
+ scrollBar = null;
+ }
}
}
@@ -2203,94 +2341,29 @@ public class BasicTreeUI
*/
public void mousePressed(MouseEvent e)
{
- // Any mouse click cancels the previous waiting edit action, initiated
- // by the single click on the selected node.
- if (startEditTimer != null)
- {
- startEditTimer.stop();
- startEditTimer = null;
- }
-
- Point click = e.getPoint();
- TreePath path = getClosestPathForLocation(tree, click.x, click.y);
- if (path != null)
+ if (tree != null && tree.isEnabled())
{
- Rectangle bounds = getPathBounds(tree, path);
- int row = getRowForPath(tree, path);
-
- // Cancel the editing session if clicked on the different row.
- if (tree.isEditing() && row != editingRow)
- cancelEditing(tree);
-
- boolean cntlClick = isLocationInExpandControl(path, click.x, click.y);
-
- boolean isLeaf = isLeaf(row);
-
- TreeCellRenderer tcr = getCellRenderer();
- Icon icon;
- if (isLeaf)
- icon = UIManager.getIcon("Tree.leafIcon");
- else if (tree.isExpanded(path))
- icon = UIManager.getIcon("Tree.openIcon");
- else
- icon = UIManager.getIcon("Tree.closedIcon");
-
- if (tcr instanceof DefaultTreeCellRenderer)
- {
- Icon tmp = ((DefaultTreeCellRenderer) tcr).getIcon();
- if (tmp != null)
- icon = tmp;
- }
+ // Maybe stop editing and return.
+ if (isEditing(tree) && tree.getInvokesStopCellEditing()
+ && !stopEditing(tree))
+ return;
- // add gap*2 for the space before and after the text
- if (icon != null)
- bounds.width += icon.getIconWidth() + gap * 2;
+ int x = e.getX();
+ int y = e.getY();
+ TreePath path = getClosestPathForLocation(tree, x, y);
- boolean inBounds = bounds.contains(click.x, click.y);
- if ((inBounds || cntlClick) && tree.isVisible(path))
+ if (path != null)
{
- if (inBounds)
- {
- TreePath currentLead = tree.getLeadSelectionPath();
- if (currentLead != null && currentLead.equals(path)
- && e.getClickCount() == 1 && tree.isEditable())
- {
- // Schedule the editing session.
- final TreePath editPath = path;
-
- if (startEditTimer != null)
- startEditTimer.stop();
-
- startEditTimer = new Timer(WAIT_TILL_EDITING,
- new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- startEditing(editPath, EDIT);
- }
- });
- startEditTimer.setRepeats(false);
- startEditTimer.start();
- }
- else
- {
- if (e.getClickCount() == 2 && ! isLeaf(row))
- toggleExpandState(path);
- else
- selectPathForEvent(path, e);
- }
- }
+ Rectangle bounds = getPathBounds(tree, path);
+ if (SwingUtilities.isLeftMouseButton(e))
+ checkForClickInExpandControl(path, x, y);
- if (cntlClick)
+ if (x > bounds.x && x <= (bounds.x + bounds.width))
{
- handleExpandControlClick(path, click.x, click.y);
- if (cellEditor != null)
- cellEditor.cancelCellEditing();
- tree.scrollPathToVisible(path);
+ if (! startEditing(path, e))
+ selectPathForEvent(path, e);
}
- else if (tree.isEditable())
- startEditing(path, e);
}
}
}
@@ -2555,8 +2628,14 @@ public class BasicTreeUI
}
else if (property.equals(JTree.TREE_MODEL_PROPERTY))
{
- treeModel = tree.getModel();
- treeModel.addTreeModelListener(treeModelListener);
+ setModel(tree.getModel());
+ }
+ else if (property.equals(JTree.CELL_RENDERER_PROPERTY))
+ {
+ setCellRenderer(tree.getCellRenderer());
+ // Update layout.
+ if (treeState != null)
+ treeState.invalidateSizes();
}
}
}
@@ -2677,15 +2756,16 @@ public class BasicTreeUI
protected int direction;
/**
- * Constructor
+ * Creates a new TreeHomeAction instance.
*
- * @param direction - it is home or end
- * @param name is the name of the direction
+ * @param dir the direction to go to, <code>-1</code> for home,
+ * <code>1</code> for end
+ * @param name the name of the action
*/
- public TreeHomeAction(int direction, String name)
- throws NotImplementedException
+ public TreeHomeAction(int dir, String name)
{
- // TODO: Implement this properly
+ direction = dir;
+ putValue(Action.NAME, name);
}
/**
@@ -2694,9 +2774,62 @@ public class BasicTreeUI
* @param e is the event that occured
*/
public void actionPerformed(ActionEvent e)
- throws NotImplementedException
{
- // TODO: Implement this properly
+ if (tree != null)
+ {
+ String command = (String) getValue(Action.NAME);
+ if (command.equals("selectFirst"))
+ {
+ ensureRowsAreVisible(0, 0);
+ tree.setSelectionInterval(0, 0);
+ }
+ if (command.equals("selectFirstChangeLead"))
+ {
+ ensureRowsAreVisible(0, 0);
+ tree.setLeadSelectionPath(getPathForRow(tree, 0));
+ }
+ if (command.equals("selectFirstExtendSelection"))
+ {
+ ensureRowsAreVisible(0, 0);
+ TreePath anchorPath = tree.getAnchorSelectionPath();
+ if (anchorPath == null)
+ tree.setSelectionInterval(0, 0);
+ else
+ {
+ int anchorRow = getRowForPath(tree, anchorPath);
+ tree.setSelectionInterval(0, anchorRow);
+ tree.setAnchorSelectionPath(anchorPath);
+ tree.setLeadSelectionPath(getPathForRow(tree, 0));
+ }
+ }
+ else if (command.equals("selectLast"))
+ {
+ int end = getRowCount(tree) - 1;
+ ensureRowsAreVisible(end, end);
+ tree.setSelectionInterval(end, end);
+ }
+ else if (command.equals("selectLastChangeLead"))
+ {
+ int end = getRowCount(tree) - 1;
+ ensureRowsAreVisible(end, end);
+ tree.setLeadSelectionPath(getPathForRow(tree, end));
+ }
+ else if (command.equals("selectLastExtendSelection"))
+ {
+ int end = getRowCount(tree) - 1;
+ ensureRowsAreVisible(end, end);
+ TreePath anchorPath = tree.getAnchorSelectionPath();
+ if (anchorPath == null)
+ tree.setSelectionInterval(end, end);
+ else
+ {
+ int anchorRow = getRowForPath(tree, anchorPath);
+ tree.setSelectionInterval(end, anchorRow);
+ tree.setAnchorSelectionPath(anchorPath);
+ tree.setLeadSelectionPath(getPathForRow(tree, end));
+ }
+ }
+ }
}
/**
@@ -2705,10 +2838,8 @@ public class BasicTreeUI
* @return true if the action is enabled.
*/
public boolean isEnabled()
- throws NotImplementedException
{
- // TODO: Implement this properly
- return false;
+ return (tree != null) && tree.isEnabled();
}
}
@@ -2717,22 +2848,24 @@ public class BasicTreeUI
* up or down based on direction.
*/
public class TreeIncrementAction
- extends AbstractAction
+ extends AbstractAction
{
- /** Specifies the direction to adjust the selection by. */
+ /**
+ * Specifies the direction to adjust the selection by.
+ */
protected int direction;
/**
- * Constructor
+ * Creates a new TreeIncrementAction.
*
- * @param direction up or down
+ * @param dir up or down, <code>-1</code> for up, <code>1</code> for down
* @param name is the name of the direction
*/
- public TreeIncrementAction(int direction, String name)
- throws NotImplementedException
+ public TreeIncrementAction(int dir, String name)
{
- // TODO: Implement this properly
+ direction = dir;
+ putValue(Action.NAME, name);
}
/**
@@ -2757,7 +2890,7 @@ public class BasicTreeUI
boolean hasNext = nextRow < rows;
boolean hasPrev = prevRow >= 0 && rows > 0;
TreePath newPath;
- String command = e.getActionCommand();
+ String command = (String) getValue(Action.NAME);
if (command.equals("selectPreviousChangeLead") && hasPrev)
{
@@ -2820,10 +2953,8 @@ public class BasicTreeUI
* @return true if the action is enabled.
*/
public boolean isEnabled()
- throws NotImplementedException
{
- // TODO: Implement this properly
- return false;
+ return (tree != null) && tree.isEnabled();
}
}
@@ -2929,6 +3060,7 @@ public class BasicTreeUI
public TreePageAction(int direction, String name)
{
this.direction = direction;
+ putValue(Action.NAME, name);
}
/**
@@ -2937,9 +3069,95 @@ public class BasicTreeUI
* @param e is the event that occured
*/
public void actionPerformed(ActionEvent e)
- throws NotImplementedException
{
- // TODO: Implement this properly.
+ String command = (String) getValue(Action.NAME);
+ boolean extendSelection = command.equals("scrollUpExtendSelection")
+ || command.equals("scrollDownExtendSelection");
+ boolean changeSelection = command.equals("scrollUpChangeSelection")
+ || command.equals("scrollDownChangeSelection");
+
+ // Disable change lead, unless we are in discontinuous mode.
+ if (!extendSelection && !changeSelection
+ && tree.getSelectionModel().getSelectionMode() !=
+ TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION)
+ {
+ changeSelection = true;
+ }
+
+ int rowCount = getRowCount(tree);
+ if (rowCount > 0 && treeSelectionModel != null)
+ {
+ Dimension maxSize = tree.getSize();
+ TreePath lead = tree.getLeadSelectionPath();
+ TreePath newPath = null;
+ Rectangle visible = tree.getVisibleRect();
+ if (direction == -1) // The RI handles -1 as up.
+ {
+ newPath = getClosestPathForLocation(tree, visible.x, visible.y);
+ if (newPath.equals(lead)) // Corner case, adjust one page up.
+ {
+ visible.y = Math.max(0, visible.y - visible.height);
+ newPath = getClosestPathForLocation(tree, visible.x,
+ visible.y);
+ }
+ }
+ else // +1 is down.
+ {
+ visible.y = Math.min(maxSize.height,
+ visible.y + visible.height - 1);
+ newPath = getClosestPathForLocation(tree, visible.x, visible.y);
+ if (newPath.equals(lead)) // Corner case, adjust one page down.
+ {
+ visible.y = Math.min(maxSize.height,
+ visible.y + visible.height - 1);
+ newPath = getClosestPathForLocation(tree, visible.x,
+ visible.y);
+ }
+ }
+
+ // Determine new visible rect.
+ Rectangle newVisible = getPathBounds(tree, newPath);
+ newVisible.x = visible.x;
+ newVisible.width = visible.width;
+ if (direction == -1)
+ {
+ newVisible.height = visible.height;
+ }
+ else
+ {
+ newVisible.y -= (visible.height - newVisible.height);
+ newVisible.height = visible.height;
+ }
+
+ if (extendSelection)
+ {
+ // Extend selection.
+ TreePath anchorPath = tree.getAnchorSelectionPath();
+ if (anchorPath == null)
+ {
+ tree.setSelectionPath(newPath);
+ }
+ else
+ {
+ int newIndex = getRowForPath(tree, newPath);
+ int anchorIndex = getRowForPath(tree, anchorPath);
+ tree.setSelectionInterval(Math.min(anchorIndex, newIndex),
+ Math.max(anchorIndex, newIndex));
+ tree.setAnchorSelectionPath(anchorPath);
+ tree.setLeadSelectionPath(newPath);
+ }
+ }
+ else if (changeSelection)
+ {
+ tree.setSelectionPath(newPath);
+ }
+ else // Change lead.
+ {
+ tree.setLeadSelectionPath(newPath);
+ }
+
+ tree.scrollRectToVisible(newVisible);
+ }
}
/**
@@ -2948,10 +3166,8 @@ public class BasicTreeUI
* @return true if the action is enabled.
*/
public boolean isEnabled()
- throws NotImplementedException
{
- // FIXME: Not implemented.
- return false;
+ return (tree != null) && tree.isEnabled();
}
}// TreePageAction
@@ -3007,13 +3223,13 @@ public class BasicTreeUI
extends AbstractAction
{
/**
- * Constructor
+ * Creates a new TreeToggleAction.
*
* @param name is the name of <code>Action</code> field
*/
public TreeToggleAction(String name)
{
- // Nothing to do here.
+ putValue(Action.NAME, name);
}
/**
@@ -3022,9 +3238,18 @@ public class BasicTreeUI
* @param e the event that occured
*/
public void actionPerformed(ActionEvent e)
- throws NotImplementedException
{
- // TODO: Implement this properly.
+ int selected = tree.getLeadSelectionRow();
+ if (selected != -1 && isLeaf(selected))
+ {
+ TreePath anchorPath = tree.getAnchorSelectionPath();
+ TreePath leadPath = tree.getLeadSelectionPath();
+ toggleExpandState(getPathForRow(tree, selected));
+ // Need to do this, so that the toggling doesn't mess up the lead
+ // and anchor.
+ tree.setLeadSelectionPath(leadPath);
+ tree.setAnchorSelectionPath(anchorPath);
+ }
}
/**
@@ -3033,10 +3258,8 @@ public class BasicTreeUI
* @return true if the action is enabled, false otherwise
*/
public boolean isEnabled()
- throws NotImplementedException
{
- // FIXME: Not implemented.
- return false;
+ return (tree != null) && tree.isEnabled();
}
} // TreeToggleAction
@@ -3061,6 +3284,7 @@ public class BasicTreeUI
public TreeTraverseAction(int direction, String name)
{
this.direction = direction;
+ putValue(Action.NAME, name);
}
/**
@@ -3074,7 +3298,8 @@ public class BasicTreeUI
if (current == null)
return;
- if (e.getActionCommand().equals("selectParent"))
+ String command = (String) getValue(Action.NAME);
+ if (command.equals("selectParent"))
{
if (current == null)
return;
@@ -3094,7 +3319,7 @@ public class BasicTreeUI
tree.setSelectionPath(parent);
}
}
- else if (e.getActionCommand().equals("selectChild"))
+ else if (command.equals("selectChild"))
{
Object node = current.getLastPathComponent();
int nc = treeModel.getChildCount(node);
@@ -3119,10 +3344,8 @@ public class BasicTreeUI
* @return true if the action is enabled, false otherwise
*/
public boolean isEnabled()
- throws NotImplementedException
{
- // TODO: Implement this properly
- return false;
+ return (tree != null) && tree.isEnabled();
}
}
@@ -3474,9 +3697,8 @@ public class BasicTreeUI
* Prepares for the UI to uninstall.
*/
protected void prepareForUIUninstall()
- throws NotImplementedException
{
- // TODO: Implement this properly.
+ // Nothing to do here yet.
}
/**
diff --git a/javax/swing/plaf/basic/SharedUIDefaults.java b/javax/swing/plaf/basic/SharedUIDefaults.java
new file mode 100644
index 000000000..478764911
--- /dev/null
+++ b/javax/swing/plaf/basic/SharedUIDefaults.java
@@ -0,0 +1,78 @@
+/* SharedUIDefaults.java -- Manages shared instances for UIDefaults
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.swing.plaf.basic;
+
+import java.util.HashMap;
+
+import javax.swing.UIManager;
+
+/**
+ * Manages shared instances for UI defaults. For example, all Swing components
+ * of one type usually share one InputMap/ActionMap pair. In order to avoid
+ * duplication of such objects we store them in a Map here.
+ *
+ * @author Roman Kennke (kennke@aicas.com)
+ */
+public class SharedUIDefaults
+{
+
+ /**
+ * Stores the shared instances, indexed by their UI names
+ * (i.e. "TextField.InputMap").
+ */
+ private static HashMap sharedDefaults = new HashMap();
+
+ /**
+ * Returns a shared UI defaults object.
+ *
+ * @param key the key for the shared object
+ *
+ * @return a shared UI defaults object for the specified key
+ */
+ static Object get(String key)
+ {
+ Object o = sharedDefaults.get(key);
+ if (o == null)
+ {
+ o = UIManager.get(key);
+ sharedDefaults.put(key, o);
+ }
+ return o;
+ }
+}
diff --git a/javax/swing/plaf/metal/MetalButtonUI.java b/javax/swing/plaf/metal/MetalButtonUI.java
index d6cc1bc07..8addfc66c 100644
--- a/javax/swing/plaf/metal/MetalButtonUI.java
+++ b/javax/swing/plaf/metal/MetalButtonUI.java
@@ -39,7 +39,7 @@ exception statement from your version. */
package javax.swing.plaf.metal;
import java.awt.Color;
-import java.awt.Container;
+import java.awt.Component;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
@@ -51,7 +51,6 @@ import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
-import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.UIResource;
@@ -240,63 +239,61 @@ public class MetalButtonUI
public void update(Graphics g, JComponent c)
{
AbstractButton b = (AbstractButton) c;
- if (b.isContentAreaFilled()
- && (UIManager.get(getPropertyPrefix() + "gradient") != null)
- && b.isEnabled()
- && (b.getBackground() instanceof UIResource))
- updateWidthGradient(g, b, b.getParent());
- else
- super.update(g, c);
- }
-
- private void updateWidthGradient(Graphics g, AbstractButton b, Container parent)
- {
- ButtonModel m = b.getModel();
- String gradientPropertyName = getPropertyPrefix() + "gradient";
-
- // Gradient painting behavior depends on whether the button is part of a
- // JToolBar.
- if (parent instanceof JToolBar)
+ if ((b.getBackground() instanceof UIResource)
+ && b.isContentAreaFilled() && b.isEnabled())
{
- if (! m.isPressed() && ! m.isArmed())
+ ButtonModel m = b.getModel();
+ String uiKey = "Button.gradient";
+ if (! isToolbarButton(b))
{
- if (m.isRollover())
+ if (! m.isArmed() && ! m.isPressed() && isDrawingGradient(uiKey))
{
- // Paint the gradient when the mouse cursor hovers over the
- // button but is not pressed down.
MetalUtils.paintGradient(g, 0, 0, b.getWidth(), b.getHeight(),
SwingConstants.VERTICAL,
- gradientPropertyName);
- }
- else
- {
- // If mouse does not hover over the button let the JToolBar
- // paint itself at the location where the button is (the button
- // is transparent).
-
- // There where cases where the button was not repainted and
- // therefore showed its old state. With this statement it does
- // not happen.
- b.repaint();
-
- Rectangle area = new Rectangle();
- SwingUtilities.calculateInnerArea(b, area);
- SwingUtilities.convertRectangle(b, area, b.getParent());
- b.getParent().repaint(area.x, area.y, area.width, area.height);
+ uiKey);
+ paint(g, c);
+ return;
}
}
-
- }
- else if (! m.isPressed() && ! m.isArmed())
- {
- // When the button is not part of a JToolBar just paint itself with a
- // gradient and everything is fine.
- MetalUtils.paintGradient(g, 0, 0, b.getWidth(), b.getHeight(),
- SwingConstants.VERTICAL,
- gradientPropertyName);
+ else if (m.isRollover() && isDrawingGradient(uiKey))
+ {
+ MetalUtils.paintGradient(g, 0, 0, b.getWidth(), b.getHeight(),
+ SwingConstants.VERTICAL,
+ uiKey);
+ paint(g, c);
+ return;
+ }
}
-
- paint(g, b);
+ // Fallback if we didn't have any of the two above cases.
+ super.update(g, c);
+ }
+
+ /**
+ * Returns <code>true</code> when the button is a toolbar button,
+ * <code>false</code> otherwise.
+ *
+ * @param b the button component to test
+ *
+ * @return <code>true</code> when the button is a toolbar button,
+ * <code>false</code> otherwise
+ */
+ private boolean isToolbarButton(Component b)
+ {
+ Component parent = b.getParent();
+ return parent instanceof JToolBar;
+ }
+
+ /**
+ * Returns <code>true</code> if we should draw the button gradient,
+ * <code>false</code> otherwise.
+ *
+ * @param uiKey the UIManager key for the gradient
+ *
+ * @return <code>true</code> if we should draw the button gradient,
+ * <code>false</code> otherwise
+ */
+ private boolean isDrawingGradient(String uiKey)
+ {
+ return (UIManager.get(uiKey) != null);
}
-
}
diff --git a/javax/swing/plaf/metal/MetalInternalFrameUI.java b/javax/swing/plaf/metal/MetalInternalFrameUI.java
index 6be573f4b..abe6a2817 100644
--- a/javax/swing/plaf/metal/MetalInternalFrameUI.java
+++ b/javax/swing/plaf/metal/MetalInternalFrameUI.java
@@ -41,8 +41,10 @@ package javax.swing.plaf.metal;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
+import javax.swing.ActionMap;
import javax.swing.JComponent;
import javax.swing.JInternalFrame;
+import javax.swing.SwingUtilities;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicInternalFrameUI;
@@ -162,4 +164,20 @@ public class MetalInternalFrameUI
frame.removePropertyChangeListener(IS_PALETTE, paletteListener);
paletteListener = null;
}
+
+ /**
+ * Installs keyboard actions. This is overridden to remove the
+ * <code>showSystemMenu</code> Action that is installed by the
+ * <code>BasicInternalFrameUI</code>, since Metal JInternalFrames don't have
+ * a system menu.
+ */
+ protected void installKeyboardActions()
+ {
+ super.installKeyboardActions();
+ ActionMap am = SwingUtilities.getUIActionMap(frame);
+ if (am != null)
+ {
+ am.remove("showSystemMenu");
+ }
+ }
}
diff --git a/javax/swing/plaf/metal/MetalSplitPaneDivider.java b/javax/swing/plaf/metal/MetalSplitPaneDivider.java
index ba4e314f3..6081c355c 100644
--- a/javax/swing/plaf/metal/MetalSplitPaneDivider.java
+++ b/javax/swing/plaf/metal/MetalSplitPaneDivider.java
@@ -1,5 +1,5 @@
/* MetalSplitPaneDivider.java
-Copyright (C) 2005 Free Software Foundation, Inc.
+Copyright (C) 2005, 2006, Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -47,15 +47,15 @@ import java.awt.Point;
import javax.swing.JSplitPane;
import javax.swing.SwingConstants;
+import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.plaf.basic.BasicArrowButton;
import javax.swing.plaf.basic.BasicSplitPaneDivider;
/**
- * The divider that is used by the MetalSplitPaneUI.
+ * The divider that is used by the {@link MetalSplitPaneUI}.
*
* @author Roman Kennke (roman@kennke.org)
- *
*/
class MetalSplitPaneDivider extends BasicSplitPaneDivider
{
@@ -72,7 +72,7 @@ class MetalSplitPaneDivider extends BasicSplitPaneDivider
int orientation;
/**
- * Creates a new instance of MetalSplitPaneDivider.
+ * Creates a new instance of <code>MetalSplitPaneDivider</code>.
*
* @param ui the <code>MetalSplitPaneUI</code> that uses this divider
*/
@@ -95,6 +95,12 @@ class MetalSplitPaneDivider extends BasicSplitPaneDivider
{
Dimension s = getSize();
+ if (splitPane.hasFocus())
+ {
+ g.setColor(UIManager.getColor("SplitPane.dividerFocusColor"));
+ g.fillRect(0, 0, s.width, s.height);
+ }
+
// Paint border if one exists.
Border border = getBorder();
if (border != null)
diff --git a/javax/swing/table/JTableHeader.java b/javax/swing/table/JTableHeader.java
index c11a96fb3..482317ff0 100644
--- a/javax/swing/table/JTableHeader.java
+++ b/javax/swing/table/JTableHeader.java
@@ -38,8 +38,6 @@ exception statement from your version. */
package javax.swing.table;
-import gnu.classpath.NotImplementedException;
-
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
@@ -98,23 +96,32 @@ public class JTableHeader extends JComponent
}
/**
- * Returns the accessible context for the column header renderer, or
- * <code>null</code>.
+ * Returns the column header renderer.
*
- * @return The accessible context.
+ * @return The column header renderer.
*/
- AccessibleContext getAccessibleColumnHeaderRenderer()
+ Component getColumnHeaderRenderer()
{
- AccessibleContext ac = null;
TableColumn tc = parent.getColumnModel().getColumn(columnIndex);
TableCellRenderer r = tc.getHeaderRenderer();
if (r == null)
r = parent.getDefaultRenderer();
- Component c = r.getTableCellRendererComponent(table, tc.headerValue,
+ return r.getTableCellRendererComponent(table, tc.headerValue,
false, false, -1, columnIndex);
+ }
+
+ /**
+ * Returns the accessible context for the column header renderer, or
+ * <code>null</code>.
+ *
+ * @return The accessible context.
+ */
+ AccessibleContext getAccessibleColumnHeaderRenderer()
+ {
+ Component c = getColumnHeaderRenderer();
if (c instanceof Accessible)
- ac = c.getAccessibleContext();
- return ac;
+ return c.getAccessibleContext();
+ return null;
}
/**
@@ -361,10 +368,11 @@ public class JTableHeader extends JComponent
}
public Locale getLocale()
- throws NotImplementedException
{
- // FIXME
- throw new Error("not implemented");
+ Component c = getColumnHeaderRenderer();
+ if (c != null)
+ return c.getLocale();
+ return null;
}
public Point getLocation()
diff --git a/javax/swing/text/DefaultStyledDocument.java b/javax/swing/text/DefaultStyledDocument.java
index 9ce0a7805..8aee51e5c 100644
--- a/javax/swing/text/DefaultStyledDocument.java
+++ b/javax/swing/text/DefaultStyledDocument.java
@@ -1053,14 +1053,6 @@ public class DefaultStyledDocument extends AbstractDocument implements
Edit edit = getEditForParagraphAndIndex(paragraph, index);
edit.addAddedElement(leaf);
-
- if (end != toRec.getEndOffset())
- {
- recreateLeaves(end, toRec, onlyContent);
-
- if (onlyContent)
- edit.addRemovedElement(target);
- }
}
else
paragraph.replace(0, 0, new Element[] { leaf });
diff --git a/javax/swing/text/GapContent.java b/javax/swing/text/GapContent.java
index 780297ce9..4f06003b4 100644
--- a/javax/swing/text/GapContent.java
+++ b/javax/swing/text/GapContent.java
@@ -730,9 +730,9 @@ public class GapContent
for (Iterator i = positionSet.iterator(); i.hasNext();)
{
GapContentPosition p = (GapContentPosition) i.next();
- if (p.index > start || p.index <= end)
- p.index = start;
- else if (p.index > end)
+ if (p.index > startIndex || p.index <= endIndex)
+ p.index = startIndex;
+ else if (p.index > endIndex)
p.index -= removed;
}
}
@@ -846,7 +846,7 @@ public class GapContent
private void dumpMarks()
{
System.err.print("positionMarks: ");
- for (int i = 0; i < positionMarks.length; i++)
+ for (int i = 0; i < numMarks; i++)
System.err.print(positionMarks[i] + ", ");
System.err.println();
}
@@ -918,7 +918,7 @@ public class GapContent
int mid = 0;
while (low <= hi)
{
- mid = (low + hi) >> 1;
+ mid = (low + hi) >>> 1;
final int d = a[mid];
if (d == key)
return mid;
diff --git a/javax/swing/text/PlainView.java b/javax/swing/text/PlainView.java
index 18818c0ba..48fe37ce8 100644
--- a/javax/swing/text/PlainView.java
+++ b/javax/swing/text/PlainView.java
@@ -437,132 +437,92 @@ public class PlainView extends View implements TabExpander
*/
protected void updateDamage(DocumentEvent changes, Shape a, ViewFactory f)
{
- // Return early and do no updates if the allocation area is null
- // (like the RI).
- if (a == null)
- return;
-
- float oldMaxLineLength = maxLineLength;
- Rectangle alloc = a.getBounds();
- Element el = getElement();
- ElementChange ec = changes.getChange(el);
-
- // If ec is null then no lines were added or removed, just
- // repaint the changed line
- if (ec == null)
- {
- int line = el.getElementIndex(changes.getOffset());
-
- // If characters have been removed from the current longest line
- // we have to find out which one is the longest now otherwise
- // the preferred x-axis span will not shrink.
- if (changes.getType() == DocumentEvent.EventType.REMOVE
- && el.getElement(line) == longestLine)
- {
- maxLineLength = -1;
- if (determineMaxLineLength() != alloc.width)
- preferenceChanged(this, true, false);
- }
-
- damageLineRange(line, line, a, getContainer());
- return;
- }
-
- Element[] removed = ec.getChildrenRemoved();
- Element[] newElements = ec.getChildrenAdded();
-
- // If no Elements were added or removed, we just want to repaint
- // the area containing the line that was modified
- if (removed == null && newElements == null)
+ // This happens during initialization.
+ if (metrics == null)
{
- int line = getElement().getElementIndex(changes.getOffset());
-
- damageLineRange(line, line, a, getContainer());
+ updateMetrics();
+ preferenceChanged(null, true, true);
return;
}
- // Check to see if we removed the longest line, if so we have to
- // search through all lines and find the longest one again.
- if (removed != null)
- {
- for (int i = 0; i < removed.length; i++)
- if (removed[i].equals(longestLine))
- {
- // reset maxLineLength and search through all lines for longest one
- maxLineLength = -1;
- if (determineMaxLineLength() != alloc.width)
- preferenceChanged(this, true, removed.length != newElements.length);
-
- ((JTextComponent)getContainer()).repaint();
-
- return;
- }
- }
-
- // If we've reached here, that means we haven't removed the longest line
- if (newElements == null)
- {
- // No lines were added, just repaint the container and exit
- ((JTextComponent)getContainer()).repaint();
-
- return;
- }
+ Element element = getElement();
- // Make sure we have the metrics
- updateMetrics();
-
- // If we've reached here, that means we haven't removed the longest line
- // and we have added at least one line, so we have to check if added lines
- // are longer than the previous longest line
- Segment seg = getLineBuffer();
- float longestNewLength = 0;
- Element longestNewLine = null;
+ // Find longest line if it hasn't been initialized yet.
+ if (longestLine == null)
+ findLongestLine(0, element.getElementCount() - 1);
- // Loop through the added lines to check their length
- for (int i = 0; i < newElements.length; i++)
+ ElementChange change = changes.getChange(element);
+ if (changes.getType() == DocumentEvent.EventType.INSERT)
{
- Element child = newElements[i];
- int start = child.getStartOffset();
- int end = child.getEndOffset() - 1;
- try
- {
- el.getDocument().getText(start, end - start, seg);
- }
- catch (BadLocationException ex)
+ // Handles character/line insertion.
+
+ // Determine if lines have been added. In this case we repaint
+ // differently.
+ boolean linesAdded = true;
+ if (change == null)
+ linesAdded = false;
+
+ // Determine the start line.
+ int start;
+ if (linesAdded)
+ start = change.getIndex();
+ else
+ start = element.getElementIndex(changes.getOffset());
+
+ // Determine the length of the updated region.
+ int length = 0;
+ if (linesAdded)
+ length = change.getChildrenAdded().length - 1;
+
+ // Update the longest line and length.
+ int oldMaxLength = (int) maxLineLength;
+ if (longestLine.getEndOffset() < changes.getOffset()
+ || longestLine.getStartOffset() > changes.getOffset()
+ + changes.getLength())
{
- AssertionError ae = new AssertionError("Unexpected bad location");
- ae.initCause(ex);
- throw ae;
+ findLongestLine(start, start + length);
}
-
- if (seg == null || seg.array == null || seg.count == 0)
- continue;
-
- int width = metrics.charsWidth(seg.array, seg.offset, seg.count);
- if (width > longestNewLength)
+ else
{
- longestNewLine = child;
- longestNewLength = width;
+ findLongestLine(0, element.getElementCount() - 1);
}
+
+ // Trigger a preference change so that the layout gets updated
+ // correctly.
+ preferenceChanged(null, maxLineLength != oldMaxLength, linesAdded);
+
+ // Damage the updated line range.
+ int endLine = start;
+ if (linesAdded)
+ endLine = element.getElementCount() - 1;
+ damageLineRange(start, endLine, a, getContainer());
+
}
-
- // Check if the longest of the new lines is longer than our previous
- // longest line, and if so update our values
- if (longestNewLength > maxLineLength)
+ else
{
- maxLineLength = longestNewLength;
- longestLine = longestNewLine;
+ // Handles character/lines removals.
+
+ // Update the longest line and length and trigger preference changed.
+ int oldMaxLength = (int) maxLineLength;
+ if (change != null)
+ {
+ // Line(s) have been removed.
+ findLongestLine(0, element.getElementCount() - 1);
+ preferenceChanged(null, maxLineLength != oldMaxLength, true);
+ }
+ else
+ {
+ // No line has been removed.
+ int lineNo = getElement().getElementIndex(changes.getOffset());
+ Element line = getElement().getElement(lineNo);
+ if (longestLine == line)
+ {
+ findLongestLine(0, element.getElementCount() - 1);
+ preferenceChanged(null, maxLineLength != oldMaxLength, false);
+ }
+ damageLineRange(lineNo, lineNo, a, getContainer());
+ }
}
-
- // Report any changes to the preferred sizes of the view
- // which may cause the underlying component to be revalidated.
- boolean widthChanged = oldMaxLineLength != maxLineLength;
- boolean heightChanged = removed.length != newElements.length;
- if (widthChanged || heightChanged)
- preferenceChanged(this, widthChanged, heightChanged);
-
- // Repaint the container
- ((JTextComponent)getContainer()).repaint();
}
/**
@@ -648,5 +608,54 @@ public class PlainView extends View implements TabExpander
lineBuffer = new Segment();
return lineBuffer;
}
+
+ /**
+ * Finds and updates the longest line in the view inside an interval of
+ * lines.
+ *
+ * @param start the start of the search interval
+ * @param end the end of the search interval
+ */
+ private void findLongestLine(int start, int end)
+ {
+ for (int i = start; i <= end; i++)
+ {
+ int w = getLineLength(i);
+ if (w > maxLineLength)
+ {
+ maxLineLength = w;
+ longestLine = getElement().getElement(i);
+ }
+ }
+ }
+
+ /**
+ * Determines the length of the specified line.
+ *
+ * @param line the number of the line
+ *
+ * @return the length of the line in pixels
+ */
+ private int getLineLength(int line)
+ {
+ Element lineEl = getElement().getElement(line);
+ Segment buffer = getLineBuffer();
+ try
+ {
+ Document doc = getDocument();
+ doc.getText(lineEl.getStartOffset(),
+ lineEl.getEndOffset() - lineEl.getStartOffset() - 1,
+ buffer);
+ }
+ catch (BadLocationException ex)
+ {
+ AssertionError err = new AssertionError("Unexpected bad location");
+ err.initCause(ex);
+ throw err;
+ }
+
+ return Utilities.getTabbedTextWidth(buffer, metrics, 0, this,
+ lineEl.getStartOffset());
+ }
}
diff --git a/javax/swing/text/StyleContext.java b/javax/swing/text/StyleContext.java
index 5150351dd..1e869485c 100644
--- a/javax/swing/text/StyleContext.java
+++ b/javax/swing/text/StyleContext.java
@@ -38,8 +38,6 @@ exception statement from your version. */
package javax.swing.text;
-import gnu.classpath.NotImplementedException;
-
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
@@ -50,7 +48,6 @@ import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.EventListener;
-import java.util.HashSet;
import java.util.Hashtable;
import javax.swing.event.ChangeEvent;
@@ -770,16 +767,29 @@ public class StyleContext
}
/**
- * TODO: DOCUMENT ME!
+ * Serialize an attribute set in a way that is compatible with it
+ * being read in again by {@link #readAttributeSet(ObjectInputStream, MutableAttributeSet)}.
+ * In particular registered static keys are transformed properly.
*
* @param out - stream to write to
* @param a - the attribute set
* @throws IOException - any I/O error
*/
public static void writeAttributeSet(ObjectOutputStream out, AttributeSet a)
- throws IOException, NotImplementedException
+ throws IOException
{
- // FIXME: Not implemented
+ Enumeration e = a.getAttributeNames();
+ while (e.hasMoreElements())
+ {
+ Object oldKey = e.nextElement();
+ Object newKey = getStaticAttribute(oldKey);
+ Object key = (newKey == null) ? oldKey : newKey;
+
+ out.writeObject(key);
+ out.writeObject(a.getAttribute(oldKey));
+ }
+ out.writeObject(null);
+ out.writeObject(null);
}
/**
@@ -813,7 +823,7 @@ public class StyleContext
/**
* Registers an attribute key as a well-known keys. When an attribute with
- * such a key is written to a stream,, a special syntax is used so that it
+ * such a key is written to a stream, a special syntax is used so that it
* can be recognized when it is read back in. All attribute keys defined
* in <code>StyleContext</code> are registered as static keys. If you define
* additional attribute keys that you want to exist as nonreplicated objects,
diff --git a/javax/swing/text/html/HTMLDocument.java b/javax/swing/text/html/HTMLDocument.java
index c3d276178..a9f267271 100644
--- a/javax/swing/text/html/HTMLDocument.java
+++ b/javax/swing/text/html/HTMLDocument.java
@@ -39,13 +39,15 @@ exception statement from your version. */
package javax.swing.text.html;
import gnu.classpath.NotImplementedException;
-
import gnu.javax.swing.text.html.CharacterAttributeTranslator;
+
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Stack;
import java.util.Vector;
+
+import javax.swing.JEditorPane;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
@@ -59,9 +61,15 @@ import javax.swing.text.StyleConstants;
import javax.swing.text.html.HTML.Tag;
/**
- * TODO: Add more comments here
+ * Represents the HTML document that is constructed by defining the text and
+ * other components (images, buttons, etc) in HTML language. This class can
+ * becomes the default document for {@link JEditorPane} after setting its
+ * content type to "text/html". HTML document also serves as an intermediate
+ * data structure when it is needed to parse HTML and then obtain the content of
+ * the certain types of tags. This class also has methods for modifying the HTML
+ * content.
*
- * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org)
+ * @author Audrius Meskauskas (AudriusA@Bioinformatics.org)
* @author Anthony Balkissoon (abalkiss@redhat.com)
* @author Lillian Angel (langel@redhat.com)
*/
@@ -640,17 +648,25 @@ public class HTMLDocument extends DefaultStyledDocument
}
}
- public class HiddenAction extends TagAction
+ /**
+ * This action indicates that the content between starting and closing HTML
+ * elements (like script - /script) should not be visible. The content is
+ * still inserted and can be accessed when iterating the HTML document. The
+ * parser will only fire
+ * {@link javax.swing.text.html.HTMLEditorKit.ParserCallback#handleText} for
+ * the hidden tags, regardless from that html tags the hidden section may
+ * contain.
+ */
+ public class HiddenAction
+ extends TagAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
- throws NotImplementedException
{
- // FIXME: Implement.
- print ("HiddenAction.start not implemented");
+ blockOpen(t, a);
}
/**
@@ -658,10 +674,8 @@ public class HTMLDocument extends DefaultStyledDocument
* with this Action.
*/
public void end(HTML.Tag t)
- throws NotImplementedException
{
- // FIXME: Implement.
- print ("HiddenAction.end not implemented");
+ blockClose(t);
}
}
@@ -677,17 +691,6 @@ public class HTMLDocument extends DefaultStyledDocument
// FIXME: Implement.
print ("IsindexAction.start not implemented");
}
-
- /**
- * Called when an end tag is seen for one of the types of tags associated
- * with this Action.
- */
- public void end(HTML.Tag t)
- throws NotImplementedException
- {
- // FIXME: Implement.
- print ("IsindexAction.end not implemented");
- }
}
public class ParagraphAction extends BlockAction
@@ -738,29 +741,22 @@ public class HTMLDocument extends DefaultStyledDocument
}
}
+ /**
+ * Inserts the elements that are represented by ths single tag with
+ * attributes (only). The closing tag, even if present, mut follow
+ * immediately after the starting tag without providing any additional
+ * information. Hence the {@link TagAction#end} method need not be
+ * overridden and still does nothing.
+ */
public class SpecialAction extends TagAction
{
/**
- * This method is called when a start tag is seen for one of the types
- * of tags associated with this Action.
+ * The functionality is delegated to {@link HTMLReader#addSpecialElement}
*/
public void start(HTML.Tag t, MutableAttributeSet a)
- throws NotImplementedException
{
- // FIXME: Implement.
- print ("SpecialAction.start not implemented");
+ addSpecialElement(t, a);
}
-
- /**
- * Called when an end tag is seen for one of the types of tags associated
- * with this Action.
- */
- public void end(HTML.Tag t)
- throws NotImplementedException
- {
- // FIXME: Implement.
- print ("SpecialAction.end not implemented");
- }
}
class AreaAction extends TagAction
@@ -1431,10 +1427,21 @@ public class HTMLDocument extends DefaultStyledDocument
* @param a the attribute set specifying the special content
*/
protected void addSpecialElement(HTML.Tag t, MutableAttributeSet a)
- throws NotImplementedException
{
- // FIXME: Implement
- print ("HTMLReader.addSpecialElement not implemented yet");
+ a.addAttribute(StyleConstants.NameAttribute, t);
+
+ // Migrate from the rather htmlAttributeSet to the faster, lighter and
+ // unchangeable alternative implementation.
+ AttributeSet copy = a.copyAttributes();
+
+ // TODO: Figure out why we must always insert this single character
+ // (otherwise the element does not appear). Either fix or add explaining
+ // comment or at least report a normal bug.
+ DefaultStyledDocument.ElementSpec spec;
+ spec = new DefaultStyledDocument.ElementSpec(copy,
+ DefaultStyledDocument.ElementSpec.ContentType,
+ new char[] {' '}, 0, 1 );
+ parseBuffer.add(spec);
}
void printBuffer()
diff --git a/javax/swing/text/html/HTMLEditorKit.java b/javax/swing/text/html/HTMLEditorKit.java
index 22a133a2c..d5e355bdf 100644
--- a/javax/swing/text/html/HTMLEditorKit.java
+++ b/javax/swing/text/html/HTMLEditorKit.java
@@ -548,6 +548,8 @@ public class HTMLEditorKit
|| tag.equals(HTML.Tag.BLOCKQUOTE)
|| tag.equals(HTML.Tag.PRE))
view = new BlockView(element, View.Y_AXIS);
+ else if (tag.equals(HTML.Tag.IMG))
+ view = new ImageView(element);
// FIXME: Uncomment when the views have been implemented
else if (tag.equals(HTML.Tag.CONTENT))
@@ -558,13 +560,12 @@ public class HTMLEditorKit
view = new HTMLTableView(element);
else if (tag.equals(HTML.Tag.TD))
view = new ParagraphView(element);
+
/*
else if (tag.equals(HTML.Tag.MENU) || tag.equals(HTML.Tag.DIR)
|| tag.equals(HTML.Tag.UL) || tag.equals(HTML.Tag.OL))
view = new ListView(element);
- else if (tag.equals(HTML.Tag.IMG))
- view = new ImageView(element);
else if (tag.equals(HTML.Tag.HR))
view = new HRuleView(element);
else if (tag.equals(HTML.Tag.BR))
diff --git a/javax/swing/text/html/ImageView.java b/javax/swing/text/html/ImageView.java
new file mode 100644
index 000000000..84b021070
--- /dev/null
+++ b/javax/swing/text/html/ImageView.java
@@ -0,0 +1,441 @@
+package javax.swing.text.html;
+
+import gnu.javax.swing.text.html.CombinedAttributes;
+import gnu.javax.swing.text.html.ImageViewIconFactory;
+
+import java.awt.Graphics;
+import java.awt.Image;
+import java.awt.MediaTracker;
+import java.awt.Rectangle;
+import java.awt.Shape;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+import javax.swing.text.AttributeSet;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.Document;
+import javax.swing.text.Element;
+import javax.swing.text.View;
+import javax.swing.text.Position.Bias;
+import javax.swing.text.html.HTML.Attribute;
+
+/**
+ * A view, representing a single image, represented by the HTML IMG tag.
+ *
+ * @author Audrius Meskauskas (AudriusA@Bioinformatics.org)
+ */
+public class ImageView extends View
+{
+ /**
+ * True if the image loads synchronuosly (on demand). By default, the image
+ * loads asynchronuosly.
+ */
+ boolean loadOnDemand;
+
+ /**
+ * The image icon, wrapping the image,
+ */
+ ImageIcon imageIcon;
+
+ /**
+ * The image state.
+ */
+ byte imageState = MediaTracker.LOADING;
+
+ /**
+ * Creates the image view that represents the given element.
+ *
+ * @param element the element, represented by this image view.
+ */
+ public ImageView(Element element)
+ {
+ super(element);
+ }
+
+ /**
+ * Load or reload the image. This method initiates the image reloading. After
+ * the image is ready, the repaint event will be scheduled. The current image,
+ * if it already exists, will be discarded.
+ *
+ * @param itsTime
+ * also load if the "on demand" property is set
+ */
+ void reloadImage(boolean itsTime)
+ {
+ URL url = getImageURL();
+ if (url == null)
+ imageState = (byte) MediaTracker.ERRORED;
+ else if (!(loadOnDemand && !itsTime))
+ imageIcon = new ImageIcon(url);
+ else
+ imageState = (byte) MediaTracker.LOADING;
+ }
+
+ /**
+ * Get the image alignment. This method works handling standart alignment
+ * attributes in the HTML IMG tag (align = top bottom middle left right).
+ * Depending from the parameter, either horizontal or vertical alingment
+ * information is returned.
+ *
+ * @param axis -
+ * either X_AXIS or Y_AXIS
+ */
+ public float getAlignment(int axis)
+ {
+ AttributeSet attrs = getAttributes();
+ Object al = attrs.getAttribute(Attribute.ALIGN);
+
+ // Default is top left aligned.
+ if (al == null)
+ return 0.0f;
+
+ String align = al.toString();
+
+ if (axis == View.X_AXIS)
+ {
+ if (align.equals("middle"))
+ return 0.5f;
+ else if (align.equals("left"))
+ return 0.0f;
+ else if (align.equals("right"))
+ return 1.0f;
+ else
+ return 0.0f;
+ }
+ else if (axis == View.Y_AXIS)
+ {
+ if (align.equals("middle"))
+ return 0.5f;
+ else if (align.equals("top"))
+ return 0.0f;
+ else if (align.equals("bottom"))
+ return 1.0f;
+ else
+ return 0.0f;
+ }
+ else
+ throw new IllegalArgumentException("axis " + axis);
+ }
+
+ /**
+ * Get the text that should be shown as the image replacement and also as the
+ * image tool tip text. The method returns the value of the attribute, having
+ * the name {@link Attribute#ALT}. If there is no such attribute, the image
+ * name from the url is returned. If the URL is not available, the empty
+ * string is returned.
+ */
+ public String getAltText()
+ {
+ Object rt = getAttributes().getAttribute(Attribute.ALT);
+ if (rt != null)
+ return rt.toString();
+ else
+ {
+ URL u = getImageURL();
+ if (u == null)
+ return "";
+ else
+ return u.getFile();
+ }
+ }
+
+ /**
+ * Returns the combination of the document and the style sheet attributes.
+ */
+ public AttributeSet getAttributes()
+ {
+ StyleSheet styles = getStyleSheet();
+ if (styles == null)
+ return super.getAttributes();
+ else
+ return CombinedAttributes.combine(super.getAttributes(),
+ styles.getViewAttributes(this));
+ }
+
+ /**
+ * Get the image to render. May return null if the image is not yet loaded.
+ */
+ public Image getImage()
+ {
+ if (imageIcon == null)
+ return null;
+ else
+ return imageIcon.getImage();
+ }
+
+ /**
+ * Get the URL location of the image to render. If this method returns null,
+ * the "no image" icon is rendered instead. By defaul, url must be present as
+ * the "src" property of the IMG tag. If it is missing, null is returned and
+ * the "no image" icon is rendered.
+ *
+ * @return the URL location of the image to render.
+ */
+ public URL getImageURL()
+ {
+ Object url = getAttributes().getAttribute(Attribute.SRC);
+ if (url == null)
+ return null;
+
+ try
+ {
+ return new URL(url.toString());
+ }
+ catch (MalformedURLException e)
+ {
+ // The URL is malformed - no image.
+ return null;
+ }
+ }
+
+ /**
+ * Get the icon that should be displayed while the image is loading and hence
+ * not yet available.
+ *
+ * @return an icon, showing a non broken sheet of paper with image.
+ */
+ public Icon getLoadingImageIcon()
+ {
+ return ImageViewIconFactory.getLoadingImageIcon();
+ }
+
+ /**
+ * Get the image loading strategy.
+ *
+ * @return false (default) if the image is loaded when the view is
+ * constructed, true if the image is only loaded on demand when
+ * rendering.
+ */
+ public boolean getLoadsSynchronously()
+ {
+ return loadOnDemand;
+ }
+
+ /**
+ * Get the icon that should be displayed when the image is not available.
+ *
+ * @return an icon, showing a broken sheet of paper with image.
+ */
+ public Icon getNoImageIcon()
+ {
+ return ImageViewIconFactory.getNoImageIcon();
+ }
+
+ /**
+ * Get the preferred span of the image along the axis. The image size is first
+ * requested to the attributes {@link Attribute#WIDTH} and
+ * {@link Attribute#HEIGHT}. If they are missing, and the image is already
+ * loaded, the image size is returned. If there are no attributes, and the
+ * image is not loaded, zero is returned.
+ *
+ * @param axis -
+ * either X_AXIS or Y_AXIS
+ * @return either width of height of the image, depending on the axis.
+ */
+ public float getPreferredSpan(int axis)
+ {
+ AttributeSet attrs = getAttributes();
+
+ Image image = getImage();
+
+ if (axis == View.X_AXIS)
+ {
+ Object w = attrs.getAttribute(Attribute.WIDTH);
+ if (w != null)
+ return Integer.parseInt(w.toString());
+ else if (image != null)
+ return image.getWidth(getContainer());
+ else
+ return getNoImageIcon().getIconWidth();
+ }
+ else if (axis == View.Y_AXIS)
+ {
+ Object w = attrs.getAttribute(Attribute.HEIGHT);
+ if (w != null)
+ return Integer.parseInt(w.toString());
+ else if (image != null)
+ return image.getHeight(getContainer());
+ else
+ return getNoImageIcon().getIconHeight();
+ }
+ else
+ throw new IllegalArgumentException("axis " + axis);
+ }
+
+ /**
+ * Get the associated style sheet from the document.
+ *
+ * @return the associated style sheet.
+ */
+ protected StyleSheet getStyleSheet()
+ {
+ Document d = getElement().getDocument();
+ if (d instanceof HTMLDocument)
+ return ((HTMLDocument) d).getStyleSheet();
+ else
+ return null;
+ }
+
+ /**
+ * Get the tool tip text. This is overridden to return the value of the
+ * {@link #getAltText()}. The parameters are ignored.
+ *
+ * @return that is returned by getAltText().
+ */
+ public String getToolTipText(float x, float y, Shape shape)
+ {
+ return getAltText();
+ }
+
+ /**
+ * Paints the image or one of the two image state icons. The image is resized
+ * to the shape bounds. If there is no image available, the alternative text
+ * is displayed besides the image state icon.
+ *
+ * @param g
+ * the Graphics, used for painting.
+ * @param bounds
+ * the bounds of the region where the image or replacing icon must be
+ * painted.
+ */
+ public void paint(Graphics g, Shape bounds)
+ {
+ Rectangle r = bounds.getBounds();
+
+ if (imageIcon == null)
+
+ {
+ // Loading image on demand, rendering the loading icon so far.
+ reloadImage(true);
+
+ // The reloadImage sets the imageIcon, unless the URL is broken
+ // or malformed.
+ if (imageIcon != null)
+ {
+ if (imageIcon.getImageLoadStatus() != MediaTracker.COMPLETE)
+ {
+ // Render "not ready" icon, unless the image is ready
+ // immediately.
+ renderIcon(g, r, getLoadingImageIcon());
+ // Add the listener to repaint when the icon will be ready.
+ imageIcon.setImageObserver(getContainer());
+ return;
+ }
+ }
+ else
+ {
+ renderIcon(g, r, getNoImageIcon());
+ return;
+ }
+ }
+
+ imageState = (byte) imageIcon.getImageLoadStatus();
+
+ switch (imageState)
+ {
+ case MediaTracker.ABORTED:
+ case MediaTracker.ERRORED:
+ renderIcon(g, r, getNoImageIcon());
+ break;
+ case MediaTracker.LOADING:
+ // If the image is not loaded completely, we still render it, as the
+ // partial image may be available.
+ case MediaTracker.COMPLETE:
+ {
+ // Paint the scaled image.
+ Image scaled = imageIcon.getImage().getScaledInstance(
+ r.width,
+ r.height,
+ Image.SCALE_DEFAULT);
+ ImageIcon painter = new ImageIcon(scaled);
+ painter.paintIcon(getContainer(), g, r.x, r.y);
+ }
+ break;
+ }
+ }
+
+ /**
+ * Render "no image" icon and the alternative "no image" text. The text is
+ * rendered right from the icon and is aligned to the icon bottom.
+ */
+ private void renderIcon(Graphics g, Rectangle bounds, Icon icon)
+ {
+ Shape current = g.getClip();
+ try
+ {
+ g.setClip(bounds);
+ if (icon != null)
+ {
+ icon.paintIcon(getContainer(), g, bounds.x, bounds.y);
+ g.drawString(getAltText(), bounds.x + icon.getIconWidth(),
+ bounds.y + icon.getIconHeight());
+ }
+ }
+ finally
+ {
+ g.setClip(current);
+ }
+ }
+
+ /**
+ * Set if the image should be loaded only when needed (synchronuosly). By
+ * default, the image loads asynchronuosly. If the image is not yet ready, the
+ * icon, returned by the {@link #getLoadingImageIcon()}, is displayed.
+ */
+ public void setLoadsSynchronously(boolean load_on_demand)
+ {
+ loadOnDemand = load_on_demand;
+ }
+
+ /**
+ * Update all cached properties from the attribute set, returned by the
+ * {@link #getAttributes}.
+ */
+ protected void setPropertiesFromAttributes()
+ {
+ // In the current implementation, nothing is cached yet, unless the image
+ // itself.
+ imageIcon = null;
+ }
+
+ /**
+ * Maps the picture co-ordinates into the image position in the model. As the
+ * image is not divideable, this is currently implemented always to return the
+ * start offset.
+ */
+ public int viewToModel(float x, float y, Shape shape, Bias[] bias)
+ {
+ return getStartOffset();
+ }
+
+ /**
+ * This is currently implemented always to return the area of the image view,
+ * as the image is not divideable by character positions.
+ *
+ * @param pos character position
+ * @param area of the image view
+ * @param bias bias
+ *
+ * @return the shape, where the given character position should be mapped.
+ */
+ public Shape modelToView(int pos, Shape area, Bias bias)
+ throws BadLocationException
+ {
+ return area;
+ }
+
+ /**
+ * Starts loading the image asynchronuosly. If the image must be loaded
+ * synchronuosly instead, the {@link #setLoadsSynchronously} must be
+ * called before calling this method. The passed parameters are not used.
+ */
+ public void setSize(float width, float height)
+ {
+ if (imageIcon == null)
+ reloadImage(false);
+ }
+
+
+}
diff --git a/javax/swing/tree/DefaultTreeCellEditor.java b/javax/swing/tree/DefaultTreeCellEditor.java
index cc19501d2..b0a4d8db8 100644
--- a/javax/swing/tree/DefaultTreeCellEditor.java
+++ b/javax/swing/tree/DefaultTreeCellEditor.java
@@ -382,7 +382,6 @@ public class DefaultTreeCellEditor
editingContainer = createContainer();
setFont(UIManager.getFont("Tree.font"));
setBorderSelectionColor(UIManager.getColor("Tree.selectionBorderColor"));
- editingIcon = renderer.getIcon();
}
/**
diff --git a/javax/swing/tree/TreePath.java b/javax/swing/tree/TreePath.java
index 4671c4be5..93b59b07e 100644
--- a/javax/swing/tree/TreePath.java
+++ b/javax/swing/tree/TreePath.java
@@ -262,14 +262,16 @@ public class TreePath implements Serializable
if (path == null)
return false;
int count = getPathCount();
- if (path.getPathCount() < count)
+ int otherPathLength = path.getPathCount();
+ if (otherPathLength < count)
return false;
- for (int i = 0; i < count; i++)
- {
- if (!this.path[i].equals(path.getPathComponent(i)))
- return false;
- }
- return true;
+ while (otherPathLength > count)
+ {
+ otherPathLength--;
+ path = path.getParentPath();
+ }
+
+ return equals(path);
}
/**
diff --git a/javax/swing/tree/VariableHeightLayoutCache.java b/javax/swing/tree/VariableHeightLayoutCache.java
index f2bbc2bfe..11509b1b0 100644
--- a/javax/swing/tree/VariableHeightLayoutCache.java
+++ b/javax/swing/tree/VariableHeightLayoutCache.java
@@ -232,6 +232,9 @@ public class VariableHeightLayoutCache
totalHeight = maximalWidth = 0;
+ if (treeModel == null)
+ return;
+
Object root = treeModel.getRoot();
if (rootVisible)
@@ -555,9 +558,16 @@ public class VariableHeightLayoutCache
public void setModel(TreeModel newModel)
{
treeModel = newModel;
- // The root node is expanded by default.
- expanded.add(treeModel.getRoot());
- dirty = true;
+ // We need to clear the table and update the layout,
+ // so that we don't end up with wrong data in the tables.
+ expanded.clear();
+ update();
+ if (treeModel != null)
+ {
+ // The root node is expanded by default.
+ expanded.add(treeModel.getRoot());
+ dirty = true;
+ }
}
/**
diff --git a/lib/.cvsignore b/lib/.cvsignore
index fb82f0fd0..8ac5f9ba6 100644
--- a/lib/.cvsignore
+++ b/lib/.cvsignore
@@ -29,6 +29,7 @@ gen_nio.sh
classes.1
resources
org
+sun
META-INF
Makefile.deps
lists
diff --git a/lib/Makefile.am b/lib/Makefile.am
index 0d803c95b..20116bb4c 100644
--- a/lib/Makefile.am
+++ b/lib/Makefile.am
@@ -73,6 +73,7 @@ install-data-local: genclasses compile-classes
cp -R java $(DESTDIR)$(pkgdatadir)
cp -R javax $(DESTDIR)$(pkgdatadir)
cp -R org $(DESTDIR)$(pkgdatadir)
+ cp -R sun $(DESTDIR)$(pkgdatadir)
cp -R META-INF $(DESTDIR)$(pkgdatadir)
# FIXME - should mimic doc/api/Makefile.am instead...
@@ -81,6 +82,7 @@ uninstall-local:
rm -rf $(DESTDIR)$(pkgdatadir)/java
rm -rf $(DESTDIR)$(pkgdatadir)/javax
rm -rf $(DESTDIR)$(pkgdatadir)/org
+ rm -rf $(DESTDIR)$(pkgdatadir)/sun
rm -rf $(DESTDIR)$(pkgdatadir)/META-INF
endif # INSTALL_CLASS_FILES
@@ -95,8 +97,8 @@ glibj.zip:
else
glibj.zip: classes compile-classes resources
- if test "$(ZIP)" != ""; then $(ZIP) -r -D glibj.zip gnu java javax org META-INF > /dev/null; fi
- if test "$(FASTJAR)" != ""; then $(FASTJAR) cf glibj.zip gnu java javax org META-INF; fi
+ if test "$(ZIP)" != ""; then $(ZIP) -r -D glibj.zip gnu java javax org sun META-INF > /dev/null; fi
+ if test "$(FASTJAR)" != ""; then $(FASTJAR) cf glibj.zip gnu java javax org sun META-INF; fi
endif # USE_PREBUILT_GLIBJ_ZIP
@@ -175,16 +177,17 @@ clean-local:
-rm -rf javax
-rm -rf org
-rm -rf com
+ -rm -rf sun
-rm -rf META-INF
-rm -rf lists
-rm -f Makefile.deps
dist-hook:
mkdir -p $(distdir)
- cp -pdfR $(top_srcdir)/gnu $(top_srcdir)/java $(top_srcdir)/javax $(top_srcdir)/org $(top_srcdir)/vm $(top_srcdir)/resource $(distdir)/..
+ cp -pdfR $(top_srcdir)/gnu $(top_srcdir)/java $(top_srcdir)/javax $(top_srcdir)/org $(top_srcdir)/sun $(top_srcdir)/vm $(top_srcdir)/resource $(distdir)/..
# Delete not wanted files.
- $(FIND) $(distdir)/../gnu $(distdir)/../java $(distdir)/../javax $(distdir)/../org $(distdir)/../vm $(distdir)/../resource -name CVS -print | xargs rm -fr
- $(FIND) $(distdir)/../gnu $(distdir)/../java $(distdir)/../javax $(distdir)/../org $(distdir)/../vm $(distdir)/../resource -name .cvsignore -print | xargs rm -f
- $(FIND) $(distdir)/../gnu $(distdir)/../java $(distdir)/../javax $(distdir)/../org $(distdir)/../vm -name class-dependencies.conf -print | xargs rm -f
+ $(FIND) $(distdir)/../gnu $(distdir)/../java $(distdir)/../javax $(distdir)/../org $(distdir)/../sun $(distdir)/../vm $(distdir)/../resource -name CVS -print | xargs rm -fr
+ $(FIND) $(distdir)/../gnu $(distdir)/../java $(distdir)/../javax $(distdir)/../org $(distdir)/../sun $(distdir)/../vm $(distdir)/../resource -name .cvsignore -print | xargs rm -f
+ $(FIND) $(distdir)/../gnu $(distdir)/../java $(distdir)/../javax $(distdir)/../org $(distdir)/../sun $(distdir)/../vm -name class-dependencies.conf -print | xargs rm -f
rm -f $(distdir)/../gnu/classpath/Configuration.java
rm -f $(distdir)/../gnu/java/locale/LocaleData.java
diff --git a/lib/gen-classlist.sh.in b/lib/gen-classlist.sh.in
index 5f7055ffd..ff76a22ea 100755
--- a/lib/gen-classlist.sh.in
+++ b/lib/gen-classlist.sh.in
@@ -18,7 +18,7 @@ echo "Adding java source files from srcdir '@top_srcdir@'."
# We do this because it makes splitting for the gcj build much
# cheaper.
(cd @top_srcdir@
- @FIND@ java javax gnu org -follow -name '*.java' -print |
+ @FIND@ java javax gnu org sun -follow -name '*.java' -print |
sort -r | sed -e 's,/\([^/]*\)$, \1,' |
while read pkg file; do
echo $pkg @top_srcdir@ $pkg/$file
@@ -43,7 +43,7 @@ vm_dirlist=`echo "@vm_classes@" | sed -e 's/:/ /g'`
echo "Adding java source files from VM directory $vm_dirlist"
for dir in $vm_dirlist; do
(cd $dir
- for subdir in java javax gnu org com; do
+ for subdir in java javax gnu org com sun; do
if test -d $subdir; then
@FIND@ $subdir -name '*.java' -print
fi
diff --git a/native/fdlibm/dtoa.c b/native/fdlibm/dtoa.c
index 6d5ad3b42..5fb6aae2c 100644
--- a/native/fdlibm/dtoa.c
+++ b/native/fdlibm/dtoa.c
@@ -2,7 +2,7 @@
*
* The author of this software is David M. Gay.
*
- * Copyright (c) 1991 by AT&T.
+ * Copyright (c) 1991, 2006 by AT&T.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
@@ -897,10 +897,23 @@ _DEFUN (_dtoa,
{
struct _Jv_reent reent;
char *p;
+ int i;
+
memset (&reent, 0, sizeof reent);
p = _dtoa_r (&reent, _d, mode, ndigits, decpt, sign, rve, float_type);
strcpy (buf, p);
- return;
+ for (i = 0; i < reent._result_k; ++i)
+ {
+ struct _Jv_Bigint *l = reent._freelist[i];
+ while (l)
+ {
+ struct _Jv_Bigint *next = l->_next;
+ free (l);
+ l = next;
+ }
+ }
+ if (reent._freelist)
+ free (reent._freelist);
}
diff --git a/native/fdlibm/mprec.c b/native/fdlibm/mprec.c
index 0badf60c4..e53722f7b 100644
--- a/native/fdlibm/mprec.c
+++ b/native/fdlibm/mprec.c
@@ -80,72 +80,112 @@
* down depends on the machine and the number being converted.
*/
+/*#include <_ansi.h>*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>
+/* #include <reent.h> */
#include "mprec.h"
/* reent.c knows this value */
-#define _Kmax 15
-#include <stdio.h>
+/* #define _Kmax 15 */
-_Jv_Bigint *
-_DEFUN (Balloc, (ptr, k), struct _Jv_reent *ptr _AND int k)
-{
- _Jv_Bigint *rv = NULL;
+#define _reent _Jv_reent
+#define _Bigint _Jv_Bigint
- int i = 0;
- int j = 1;
+#define _REENT_CHECK_MP(x)
+#define _REENT_MP_FREELIST(x) ((x)->_freelist)
+#define _REENT_MP_P5S(x) ((x)->_p5s)
- /* FIXME - assert disabled because of PR classpath/23863
- * assert ((1 << k) < MAX_BIGNUM_WDS);
- */
+typedef unsigned long __ULong;
+typedef long __Long;
- while ((ptr->_allocation_map & j) && i < MAX_BIGNUMS)
- i++, j <<= 1;
+static void *
+_calloc_r (void *ignore, size_t x1, size_t x2)
+{
+ char *result = (char *) malloc (x1 * x2);
+ memset (result, 0, x1 * x2);
+ return result;
+}
- assert (i < MAX_BIGNUMS);
+_Bigint *
+_DEFUN (Balloc, (ptr, k), struct _reent *ptr _AND int k)
+{
+ int x;
+ _Bigint *rv ;
+ int new_k = k + 1;
+
+ _REENT_CHECK_MP(ptr);
+ if (_REENT_MP_FREELIST(ptr) == NULL)
+ {
+ /* Allocate a list of pointers to the mprec objects */
+ _REENT_MP_FREELIST(ptr) = (struct _Bigint **) _calloc_r (ptr,
+ sizeof (struct _Bigint *),
+ new_k);
+ if (_REENT_MP_FREELIST(ptr) == NULL)
+ {
+ return NULL;
+ }
+ ptr->_max_k = new_k;
+ }
+ else if (new_k > ptr->_max_k)
+ {
+ struct _Bigint **new_list
+ = (struct _Bigint **) realloc (ptr->_freelist,
+ new_k * sizeof (struct _Bigint *));
+ memset (&new_list[ptr->_max_k], 0,
+ (new_k - ptr->_max_k) * sizeof (struct _Bigint *));
+ ptr->_freelist = new_list;
+ ptr->_max_k = new_k;
- if (i >= MAX_BIGNUMS)
- return NULL;
+ }
- ptr->_allocation_map |= j;
- rv = &ptr->_freelist[i];
-
- rv->_k = k;
- rv->_maxwds = 32;
+ assert (k <= ptr->_max_k);
+ if ((rv = _REENT_MP_FREELIST(ptr)[k]) != 0)
+ {
+ _REENT_MP_FREELIST(ptr)[k] = rv->_next;
+ }
+ else
+ {
+ x = 1 << k;
+ /* Allocate an mprec Bigint and stick in in the freelist */
+ rv = (_Bigint *) _calloc_r (ptr,
+ 1,
+ sizeof (_Bigint) +
+ (x-1) * sizeof(rv->_x));
+ if (rv == NULL) return NULL;
+ rv->_k = k;
+ rv->_maxwds = x;
+ }
+ rv->_sign = rv->_wds = 0;
return rv;
}
-
void
-_DEFUN (Bfree, (ptr, v), struct _Jv_reent *ptr _AND _Jv_Bigint * v)
+_DEFUN (Bfree, (ptr, v), struct _reent *ptr _AND _Bigint * v)
{
- long i;
-
- i = v - ptr->_freelist;
-
- assert (i >= 0 && i < MAX_BIGNUMS);
-
- if (i >= 0 && i < MAX_BIGNUMS)
- ptr->_allocation_map &= ~ (1 << i);
+ _REENT_CHECK_MP(ptr);
+ if (v)
+ {
+ v->_next = _REENT_MP_FREELIST(ptr)[v->_k];
+ _REENT_MP_FREELIST(ptr)[v->_k] = v;
+ }
}
-
-_Jv_Bigint *
+_Bigint *
_DEFUN (multadd, (ptr, b, m, a),
- struct _Jv_reent *ptr _AND
- _Jv_Bigint * b _AND
+ struct _reent *ptr _AND
+ _Bigint * b _AND
int m _AND
int a)
{
int i, wds;
- unsigned long *x, y;
+ __ULong *x, y;
#ifdef Pack_32
- unsigned long xi, z;
+ __ULong xi, z;
#endif
- _Jv_Bigint *b1;
+ _Bigint *b1;
wds = b->_wds;
x = b->_x;
@@ -180,17 +220,17 @@ _DEFUN (multadd, (ptr, b, m, a),
return b;
}
-_Jv_Bigint *
+_Bigint *
_DEFUN (s2b, (ptr, s, nd0, nd, y9),
- struct _Jv_reent * ptr _AND
+ struct _reent * ptr _AND
_CONST char *s _AND
int nd0 _AND
int nd _AND
- unsigned long y9)
+ __ULong y9)
{
- _Jv_Bigint *b;
+ _Bigint *b;
int i, k;
- long x, y;
+ __Long x, y;
x = (nd + 8) / 9;
for (k = 0, y = 1; x > y; y <<= 1, k++);
@@ -222,7 +262,7 @@ _DEFUN (s2b, (ptr, s, nd0, nd, y9),
int
_DEFUN (hi0bits,
- (x), register unsigned long x)
+ (x), register __ULong x)
{
register int k = 0;
@@ -256,10 +296,10 @@ _DEFUN (hi0bits,
}
int
-_DEFUN (lo0bits, (y), unsigned long *y)
+_DEFUN (lo0bits, (y), __ULong *y)
{
register int k;
- register unsigned long x = *y;
+ register __ULong x = *y;
if (x & 7)
{
@@ -298,17 +338,17 @@ _DEFUN (lo0bits, (y), unsigned long *y)
{
k++;
x >>= 1;
- if (!(x & 1))
+ if (!x & 1)
return 32;
}
*y = x;
return k;
}
-_Jv_Bigint *
-_DEFUN (i2b, (ptr, i), struct _Jv_reent * ptr _AND int i)
+_Bigint *
+_DEFUN (i2b, (ptr, i), struct _reent * ptr _AND int i)
{
- _Jv_Bigint *b;
+ _Bigint *b;
b = Balloc (ptr, 1);
b->_x[0] = i;
@@ -316,15 +356,15 @@ _DEFUN (i2b, (ptr, i), struct _Jv_reent * ptr _AND int i)
return b;
}
-_Jv_Bigint *
-_DEFUN (mult, (ptr, a, b), struct _Jv_reent * ptr _AND _Jv_Bigint * a _AND _Jv_Bigint * b)
+_Bigint *
+_DEFUN (mult, (ptr, a, b), struct _reent * ptr _AND _Bigint * a _AND _Bigint * b)
{
- _Jv_Bigint *c;
+ _Bigint *c;
int k, wa, wb, wc;
- unsigned long carry, y, z;
- unsigned long *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
+ __ULong carry, y, z;
+ __ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
#ifdef Pack_32
- unsigned long z2;
+ __ULong z2;
#endif
if (a->_wds < b->_wds)
@@ -350,7 +390,7 @@ _DEFUN (mult, (ptr, a, b), struct _Jv_reent * ptr _AND _Jv_Bigint * a _AND _Jv_B
#ifdef Pack_32
for (; xb < xbe; xb++, xc0++)
{
- if ((y = *xb & 0xffff))
+ if ((y = *xb & 0xffff) != 0)
{
x = xa;
xc = xc0;
@@ -366,7 +406,7 @@ _DEFUN (mult, (ptr, a, b), struct _Jv_reent * ptr _AND _Jv_Bigint * a _AND _Jv_B
while (x < xae);
*xc = carry;
}
- if ((y = *xb >> 16))
+ if ((y = *xb >> 16) != 0)
{
x = xa;
xc = xc0;
@@ -387,7 +427,7 @@ _DEFUN (mult, (ptr, a, b), struct _Jv_reent * ptr _AND _Jv_Bigint * a _AND _Jv_B
#else
for (; xb < xbe; xc0++)
{
- if ((y = *xb++))
+ if (y = *xb++)
{
x = xa;
xc = xc0;
@@ -408,23 +448,24 @@ _DEFUN (mult, (ptr, a, b), struct _Jv_reent * ptr _AND _Jv_Bigint * a _AND _Jv_B
return c;
}
-_Jv_Bigint *
+_Bigint *
_DEFUN (pow5mult,
- (ptr, b, k), struct _Jv_reent * ptr _AND _Jv_Bigint * b _AND int k)
+ (ptr, b, k), struct _reent * ptr _AND _Bigint * b _AND int k)
{
- _Jv_Bigint *b1, *p5, *p51;
+ _Bigint *b1, *p5, *p51;
int i;
static _CONST int p05[3] = {5, 25, 125};
- if ((i = k & 3))
+ if ((i = k & 3) != 0)
b = multadd (ptr, b, p05[i - 1], 0);
if (!(k >>= 2))
return b;
- if (!(p5 = ptr->_p5s))
+ _REENT_CHECK_MP(ptr);
+ if (!(p5 = _REENT_MP_P5S(ptr)))
{
/* first time */
- p5 = ptr->_p5s = i2b (ptr, 625);
+ p5 = _REENT_MP_P5S(ptr) = i2b (ptr, 625);
p5->_next = 0;
}
for (;;)
@@ -447,12 +488,12 @@ _DEFUN (pow5mult,
return b;
}
-_Jv_Bigint *
-_DEFUN (lshift, (ptr, b, k), struct _Jv_reent * ptr _AND _Jv_Bigint * b _AND int k)
+_Bigint *
+_DEFUN (lshift, (ptr, b, k), struct _reent * ptr _AND _Bigint * b _AND int k)
{
int i, k1, n, n1;
- _Jv_Bigint *b1;
- unsigned long *x, *x1, *xe, z;
+ _Bigint *b1;
+ __ULong *x, *x1, *xe, z;
#ifdef Pack_32
n = k >> 5;
@@ -480,7 +521,7 @@ _DEFUN (lshift, (ptr, b, k), struct _Jv_reent * ptr _AND _Jv_Bigint * b _AND int
z = *x++ >> k1;
}
while (x < xe);
- if ((*x1 = z))
+ if ((*x1 = z) != 0)
++n1;
}
#else
@@ -490,11 +531,11 @@ _DEFUN (lshift, (ptr, b, k), struct _Jv_reent * ptr _AND _Jv_Bigint * b _AND int
z = 0;
do
{
- *x1++ = (*x << k & 0xffff) | z;
+ *x1++ = *x << k & 0xffff | z;
z = *x++ >> k1;
}
while (x < xe);
- if ((*x1 = z))
+ if (*x1 = z)
++n1;
}
#endif
@@ -508,9 +549,9 @@ _DEFUN (lshift, (ptr, b, k), struct _Jv_reent * ptr _AND _Jv_Bigint * b _AND int
}
int
-_DEFUN (cmp, (a, b), _Jv_Bigint * a _AND _Jv_Bigint * b)
+_DEFUN (cmp, (a, b), _Bigint * a _AND _Bigint * b)
{
- unsigned long *xa, *xa0, *xb, *xb0;
+ __ULong *xa, *xa0, *xb, *xb0;
int i, j;
i = a->_wds;
@@ -537,16 +578,16 @@ _DEFUN (cmp, (a, b), _Jv_Bigint * a _AND _Jv_Bigint * b)
return 0;
}
-_Jv_Bigint *
-_DEFUN (diff, (ptr, a, b), struct _Jv_reent * ptr _AND
- _Jv_Bigint * a _AND _Jv_Bigint * b)
+_Bigint *
+_DEFUN (diff, (ptr, a, b), struct _reent * ptr _AND
+ _Bigint * a _AND _Bigint * b)
{
- _Jv_Bigint *c;
+ _Bigint *c;
int i, wa, wb;
- long borrow, y; /* We need signed shifts here. */
- unsigned long *xa, *xae, *xb, *xbe, *xc;
+ __Long borrow, y; /* We need signed shifts here. */
+ __ULong *xa, *xae, *xb, *xbe, *xc;
#ifdef Pack_32
- long z;
+ __Long z;
#endif
i = cmp (a, b);
@@ -625,7 +666,7 @@ double
_DEFUN (ulp, (_x), double _x)
{
union double_union x, a;
- register long L;
+ register __Long L;
x.d = _x;
@@ -659,7 +700,7 @@ _DEFUN (ulp, (_x), double _x)
word0 (a) = 0;
L -= Exp_shift;
#ifndef _DOUBLE_IS_32BITS
- word1 (a) = L >= 31 ? 1 : 1 << (31 - L);
+ word1 (a) = L >= 31 ? 1 : 1 << (31 - L);
#endif
}
}
@@ -669,13 +710,13 @@ _DEFUN (ulp, (_x), double _x)
double
_DEFUN (b2d, (a, e),
- _Jv_Bigint * a _AND int *e)
+ _Bigint * a _AND int *e)
{
- unsigned long *xa, *xa0, w, y, z;
+ __ULong *xa, *xa0, w, y, z;
int k;
union double_union d;
#ifdef VAX
- unsigned long d0, d1;
+ __ULong d0, d1;
#else
#define d0 word0(d)
#define d1 word1(d)
@@ -696,7 +737,7 @@ _DEFUN (b2d, (a, e),
d0 = Exp_1 | y >> (Ebits - k);
w = xa > xa0 ? *--xa : 0;
#ifndef _DOUBLE_IS_32BITS
- d1 = y << (32 - Ebits + k) | w >> (Ebits - k);
+ d1 = y << ((32 - Ebits) + k) | w >> (Ebits - k);
#endif
goto ret_d;
}
@@ -720,18 +761,18 @@ _DEFUN (b2d, (a, e),
if (k < Ebits + 16)
{
z = xa > xa0 ? *--xa : 0;
- d0 = Exp_1 | y << (k - Ebits) | z >> (Ebits + 16 - k);
+ d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
w = xa > xa0 ? *--xa : 0;
y = xa > xa0 ? *--xa : 0;
- d1 = z << (k + 16 - Ebits) | w << (k - Ebits) | y >> (16 + Ebits - k);
+ d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
goto ret_d;
}
z = xa > xa0 ? *--xa : 0;
w = xa > xa0 ? *--xa : 0;
k -= Ebits + 16;
- d0 = Exp_1 | y << (k + 16) | z << k | w >> (16 - k);
+ d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
y = xa > xa0 ? *--xa : 0;
- d1 = w << (k + 16) | y << k;
+ d1 = w << k + 16 | y << k;
#endif
ret_d:
#ifdef VAX
@@ -744,22 +785,24 @@ ret_d:
return d.d;
}
-_Jv_Bigint *
+_Bigint *
_DEFUN (d2b,
(ptr, _d, e, bits),
- struct _Jv_reent * ptr _AND
+ struct _reent * ptr _AND
double _d _AND
int *e _AND
int *bits)
{
union double_union d;
- _Jv_Bigint *b;
+ _Bigint *b;
int de, i, k;
- unsigned long *x, y, z;
+ __ULong *x, y, z;
#ifdef VAX
- unsigned long d0, d1;
+ __ULong d0, d1;
+#endif
d.d = _d;
+#ifdef VAX
d0 = word0 (d) >> 16 | word0 (d) << 16;
d1 = word1 (d) >> 16 | word1 (d) << 16;
#else
@@ -783,16 +826,18 @@ _DEFUN (d2b,
z |= Exp_msk11;
#endif
#else
- if ((de = (int) (d0 >> Exp_shift)))
+ if ((de = (int) (d0 >> Exp_shift)) != 0)
z |= Exp_msk1;
#endif
#ifdef Pack_32
#ifndef _DOUBLE_IS_32BITS
- if ((y = d1))
+ if (d1)
{
- if ((k = lo0bits (&y)))
+ y = d1;
+ k = lo0bits (&y);
+ if (k)
{
- x[0] = y | z << (32 - k);
+ x[0] = y | z << (32 - k);
z >>= k;
}
else
@@ -814,22 +859,24 @@ _DEFUN (d2b,
#endif
}
#else
- if ((y = d1))
+ if (d1)
{
- if ((k = lo0bits (&y)))
+ y = d1;
+ k = lo0bits (&y);
+ if (k)
if (k >= 16)
{
- x[0] = y | (z << (32 - k) & 0xffff);
- x[1] = z >> (k - 16) & 0xffff;
+ x[0] = y | z << 32 - k & 0xffff;
+ x[1] = z >> k - 16 & 0xffff;
x[2] = z >> k;
i = 2;
}
else
{
x[0] = y & 0xffff;
- x[1] = (y >> 16 | z << (16 - k)) & 0xffff;
+ x[1] = y >> 16 | z << 16 - k & 0xffff;
x[2] = z >> k & 0xffff;
- x[3] = z >> (k + 16);
+ x[3] = z >> k + 16;
i = 3;
}
else
@@ -894,7 +941,7 @@ _DEFUN (d2b,
#undef d1
double
-_DEFUN (ratio, (a, b), _Jv_Bigint * a _AND _Jv_Bigint * b)
+_DEFUN (ratio, (a, b), _Bigint * a _AND _Bigint * b)
{
union double_union da, db;
@@ -958,3 +1005,17 @@ _CONST double tinytens[] =
#endif
+double
+_DEFUN (_mprec_log10, (dig),
+ int dig)
+{
+ double v = 1.0;
+ if (dig < 24)
+ return tens[dig];
+ while (dig > 0)
+ {
+ v *= 10;
+ dig--;
+ }
+ return v;
+}
diff --git a/native/fdlibm/mprec.h b/native/fdlibm/mprec.h
index cd8f928a8..7c7471bc8 100644
--- a/native/fdlibm/mprec.h
+++ b/native/fdlibm/mprec.h
@@ -282,7 +282,7 @@ struct _Jv_Bigint
{
struct _Jv_Bigint *_next;
int _k, _maxwds, _sign, _wds;
- unsigned long _x[MAX_BIGNUM_WDS];
+ unsigned long _x[1];
};
@@ -310,10 +310,8 @@ struct _Jv_reent
int _result_k;
struct _Jv_Bigint *_p5s;
- struct _Jv_Bigint _freelist[MAX_BIGNUMS];
- int _allocation_map;
-
- int num;
+ struct _Jv_Bigint **_freelist;
+ int _max_k;
};
diff --git a/native/jawt/Makefile.am b/native/jawt/Makefile.am
index 30e5a345b..01abf3bb9 100644
--- a/native/jawt/Makefile.am
+++ b/native/jawt/Makefile.am
@@ -3,7 +3,7 @@ nativeexeclib_LTLIBRARIES = libjawt.la
libjawt_la_SOURCES = jawt.c
libjawt_la_LIBADD = $(top_builddir)/native/jni/gtk-peer/libgtkpeer.la
-AM_LDFLAGS = @CLASSPATH_MODULE@ @GTK_LIBS@ @PANGOFT2_LIBS@ @X_LIBS@ -lXtst
+AM_LDFLAGS = @CLASSPATH_MODULE@ @GTK_LIBS@ @PANGOFT2_LIBS@ @X_LIBS@ @XTEST_LIBS@
AM_CPPFLAGS = @CLASSPATH_INCLUDES@
# Just the WARNING_CFLAGS. We cannot use the strict flags since the gtk
diff --git a/native/jni/classpath/jcl.h b/native/jni/classpath/jcl.h
index 514b78262..d358aeb9c 100644
--- a/native/jni/classpath/jcl.h
+++ b/native/jni/classpath/jcl.h
@@ -1,5 +1,5 @@
/* jcl.h
- Copyright (C) 1998 Free Software Foundation, Inc.
+ Copyright (C) 1998, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -50,6 +50,10 @@ typedef jlong jpointer;
#error "Unknown pointer size"
#endif
+/* Helper macros for going between pointers and jlongs. */
+#define JLONG_TO_PTR(T,P) ((T *)(long)P)
+#define PTR_TO_JLONG(P) ((jlong)(long)P)
+
JNIEXPORT jclass JNICALL JCL_FindClass (JNIEnv * env, const char *className);
JNIEXPORT void JNICALL JCL_ThrowException (JNIEnv * env,
const char *className,
diff --git a/native/jni/gtk-peer/Makefile.am b/native/jni/gtk-peer/Makefile.am
index 4b113c978..8a39f34fe 100644
--- a/native/jni/gtk-peer/Makefile.am
+++ b/native/jni/gtk-peer/Makefile.am
@@ -1,12 +1,17 @@
nativeexeclib_LTLIBRARIES = libgtkpeer.la
# GTK JNI sources.
-libgtkpeer_la_SOURCES = gnu_java_awt_peer_gtk_GThreadNativeMethodRunner.c \
+libgtkpeer_la_SOURCES = gnu_java_awt_peer_gtk_CairoSurface.c \
+ gnu_java_awt_peer_gtk_CairoGraphics2D.c \
+ gnu_java_awt_peer_gtk_ComponentGraphics.c \
+ gnu_java_awt_peer_gtk_ComponentGraphicsCopy.c \
+ gnu_java_awt_peer_gtk_FreetypeGlyphVector.c \
+ gnu_java_awt_peer_gtk_GThreadNativeMethodRunner.c \
gnu_java_awt_peer_gtk_GdkFontPeer.c \
- gnu_java_awt_peer_gtk_GdkGraphics2D.c \
gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.c \
gnu_java_awt_peer_gtk_GdkPixbufDecoder.c \
gnu_java_awt_peer_gtk_GdkRobotPeer.c \
+ gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.c \
gnu_java_awt_peer_gtk_GdkTextLayout.c \
gnu_java_awt_peer_gtk_GtkButtonPeer.c \
gnu_java_awt_peer_gtk_GtkCanvasPeer.c \
@@ -36,7 +41,10 @@ libgtkpeer_la_SOURCES = gnu_java_awt_peer_gtk_GThreadNativeMethodRunner.c \
gnu_java_awt_peer_gtk_GtkTextFieldPeer.c \
gnu_java_awt_peer_gtk_GtkToolkit.c \
gnu_java_awt_peer_gtk_GtkWindowPeer.c \
+ gnu_java_awt_peer_gtk_GtkVolatileImage.c \
+ cairographics2d.h \
gthread-jni.c \
+ gdkdisplay.h \
gdkfont.h \
gthread-jni.h \
gtk_jawt.c \
@@ -46,7 +54,7 @@ libgtkpeer_la_LIBADD = $(top_builddir)/native/jni/classpath/native_state.lo \
$(top_builddir)/native/jni/classpath/jcl.lo
AM_LDFLAGS = @CLASSPATH_MODULE@ @GTK_LIBS@ @FREETYPE2_LIBS@ \
- @PANGOFT2_LIBS@ @X_PRE_LIBS@ @X_LIBS@ @X_EXTRA_LIBS@ -lX11 -lXtst
+ @PANGOFT2_LIBS@ @X_PRE_LIBS@ @X_LIBS@ @X_EXTRA_LIBS@ @XTEST_LIBS@
AM_CPPFLAGS = @CLASSPATH_INCLUDES@
# Just the WARNING_CFLAGS. We cannot use the strict flags since the gtk
diff --git a/native/jni/gtk-peer/cairographics2d.h b/native/jni/gtk-peer/cairographics2d.h
new file mode 100644
index 000000000..675bc0b17
--- /dev/null
+++ b/native/jni/gtk-peer/cairographics2d.h
@@ -0,0 +1,116 @@
+/* cairographics2d.h --
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+#ifndef CAIROGRAPHICS2D_H
+#define CAIROGRAPHICS2D_H
+
+
+#include <cairo.h>
+#include <gtk/gtk.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <config.h>
+#include "native_state.h"
+#include <gdk-pixbuf/gdk-pixbuf.h>
+
+#include <jni.h>
+
+/*
+ * These public final constants are part of the java2d public API, so we
+ * write them explicitly here to save fetching them from the constant pool
+ * all the time.
+ */
+enum java_awt_alpha_composite_rule
+ {
+ java_awt_alpha_composite_CLEAR = 1,
+ java_awt_alpha_composite_SRC = 2,
+ java_awt_alpha_composite_SRC_OVER = 3,
+ java_awt_alpha_composite_DST_OVER = 4,
+ java_awt_alpha_composite_SRC_IN = 5,
+ java_awt_alpha_composite_DST_IN = 6,
+ java_awt_alpha_composite_SRC_OUT = 7,
+ java_awt_alpha_composite_DST_OUT = 8,
+ java_awt_alpha_composite_DST = 9,
+ java_awt_alpha_composite_SRC_ATOP = 10,
+ java_awt_alpha_composite_DST_ATOP = 11,
+ java_awt_alpha_composite_XOR = 12
+ };
+
+enum java_awt_basic_stroke_join_rule
+ {
+ java_awt_basic_stroke_JOIN_MITER = 0,
+ java_awt_basic_stroke_JOIN_ROUND = 1,
+ java_awt_basic_stroke_JOIN_BEVEL = 2
+ };
+
+enum java_awt_basic_stroke_cap_rule
+ {
+ java_awt_basic_stroke_CAP_BUTT = 0,
+ java_awt_basic_stroke_CAP_ROUND = 1,
+ java_awt_basic_stroke_CAP_SQUARE = 2
+ };
+
+enum java_awt_geom_path_iterator_winding_rule
+ {
+ java_awt_geom_path_iterator_WIND_EVEN_ODD = 0,
+ java_awt_geom_path_iterator_WIND_NON_ZERO = 1
+ };
+
+enum java_awt_rendering_hints_filter
+ {
+ java_awt_rendering_hints_VALUE_INTERPOLATION_NEAREST_NEIGHBOR = 0,
+ java_awt_rendering_hints_VALUE_INTERPOLATION_BILINEAR = 1,
+ java_awt_rendering_hints_VALUE_ALPHA_INTERPOLATION_SPEED = 2,
+ java_awt_rendering_hints_VALUE_ALPHA_INTERPOLATION_QUALITY = 3,
+ java_awt_rendering_hints_VALUE_ALPHA_INTERPOLATION_DEFAULT = 4
+
+ };
+
+/**
+ * A structure which basically contains the cairo_t pointer.
+ * The rest is for gradient and texture fills.
+ */
+struct cairographics2d
+{
+ cairo_t *cr;
+ cairo_surface_t *pattern_surface;
+ cairo_pattern_t *pattern;
+ char *pattern_pixels;
+};
+
+#endif
diff --git a/native/jni/gtk-peer/gdkdisplay.h b/native/jni/gtk-peer/gdkdisplay.h
new file mode 100644
index 000000000..238ff9e26
--- /dev/null
+++ b/native/jni/gtk-peer/gdkdisplay.h
@@ -0,0 +1,67 @@
+#ifndef __GDKDISPLAY_H__
+#define __GDKDISPLAY_H__
+
+/* gdkdisplay.h -- Some global stuff related to displays & screens
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+ This file is part of GNU Classpath.
+
+ GNU Classpath is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2, or (at your option)
+ any later version.
+
+ GNU Classpath is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with GNU Classpath; see the file COPYING. If not, write to the
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ 02110-1301 USA.
+
+ Linking this library statically or dynamically with other modules is
+ making a combined work based on this library. Thus, the terms and
+ conditions of the GNU General Public License cover the whole
+ combination.
+
+ As a special exception, the copyright holders of this library give you
+ permission to link this library with independent modules to produce an
+ executable, regardless of the license terms of these independent
+ modules, and to copy and distribute the resulting executable under
+ terms of your choice, provided that you also meet, for each linked
+ independent module, the terms and conditions of the license of that
+ module. An independent module is a module which is not derived from
+ or based on this library. If you modify this library, you may extend
+ this exception to your version of the library, but you are not
+ obligated to do so. If you do not wish to do so, delete this
+ exception statement from your version. */
+
+#include "gtkpeer.h"
+
+/* Allows storing GdkDisplay pointers in GdkGraphicsEnvironment instances. */
+extern struct state_table *cp_gtk_native_display_state_table;
+
+/* Allows storing GdkScreen pointers in GdkScreenGraphicsDevice instances. */
+extern struct state_table *cp_gtk_native_screen_state_table;
+
+#define NSA_DISPLAY_INIT(env, clazz) \
+ cp_gtk_native_display_state_table = cp_gtk_init_state_table (env, clazz)
+
+#define NSA_GET_DISPLAY_PTR(env, obj) \
+ cp_gtk_get_state (env, obj, cp_gtk_native_display_state_table)
+
+#define NSA_SET_DISPLAY_PTR(env, obj, ptr) \
+ cp_gtk_set_state (env, obj, cp_gtk_native_display_state_table, (void *)ptr)
+
+#define NSA_SCREEN_INIT(env, clazz) \
+ cp_gtk_native_screen_state_table = cp_gtk_init_state_table (env, clazz)
+
+#define NSA_GET_SCREEN_PTR(env, obj) \
+ cp_gtk_get_state (env, obj, cp_gtk_native_screen_state_table)
+
+#define NSA_SET_SCREEN_PTR(env, obj, ptr) \
+ cp_gtk_set_state (env, obj, cp_gtk_native_screen_state_table, (void *)ptr)
+
+#endif /* __GDKDISPLAY_H__ */
diff --git a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoGraphics2D.c b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoGraphics2D.c
new file mode 100644
index 000000000..8ac89cffe
--- /dev/null
+++ b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoGraphics2D.c
@@ -0,0 +1,706 @@
+/* gnu_java_awt_peer_gtk_CairoGraphics2d.c
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+#include "jcl.h"
+#include "gdkfont.h"
+#include "cairographics2d.h"
+#include "gnu_java_awt_peer_gtk_CairoGraphics2D.h"
+#include <gdk/gdktypes.h>
+#include <gdk/gdkprivate.h>
+#include <gdk/gdkx.h>
+
+#include <cairo-ft.h>
+#include <cairo-xlib.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+
+static void install_font_peer(cairo_t *cr, struct peerfont *pfont);
+static void update_pattern_transform (struct cairographics2d *gr);
+
+/**
+ * Allocates the cairographics2d structure.
+ */
+JNIEXPORT jlong JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_init
+ (JNIEnv *env __attribute__ ((unused)),
+ jobject obj __attribute__ ((unused)),
+ jlong cairo_t_pointer)
+{
+ struct cairographics2d *g = NULL;
+ cairo_t *cr = JLONG_TO_PTR(cairo_t, cairo_t_pointer);
+ g_assert(cr != NULL);
+
+ g = (struct cairographics2d *) g_malloc (sizeof (struct cairographics2d));
+
+ g_assert (g != NULL);
+ memset (g, 0, sizeof(struct cairographics2d));
+ g->cr = cr;
+
+ return PTR_TO_JLONG(g);
+}
+
+/**
+ * Disposes of the cairographics2d structure.
+ */
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_disposeNative
+ (JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+
+ if (gr == NULL)
+ return;
+
+ if (gr->cr)
+ cairo_destroy (gr->cr);
+
+ if (gr->pattern)
+ cairo_pattern_destroy (gr->pattern);
+ gr->pattern = NULL;
+
+ if (gr->pattern_surface)
+ cairo_surface_destroy (gr->pattern_surface);
+ gr->pattern_surface = NULL;
+
+ if (gr->pattern_pixels)
+ g_free(gr->pattern_pixels);
+ gr->pattern_pixels = NULL;
+
+ g_free( gr );
+}
+
+/**
+ * Set the gradient.
+ */
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_setGradient
+ (JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer,
+ jdouble x1, jdouble y1,
+ jdouble x2, jdouble y2,
+ jint r1, jint g1, jint b1, jint a1,
+ jint r2, jint g2, jint b2, jint a2,
+ jboolean cyclic)
+{
+ struct cairographics2d *gr = NULL;
+ cairo_pattern_t* pattern;
+ cairo_extend_t extend;
+
+ gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert( gr != NULL );
+
+ pattern = cairo_pattern_create_linear(x1, y1, x2, y2);
+ g_assert( pattern != NULL );
+
+ cairo_pattern_add_color_stop_rgba(pattern, 0.0, r1 / 255.0, g1 / 255.0,
+ b1 / 255.0, a1 / 255.0);
+
+ cairo_pattern_add_color_stop_rgba(pattern, 1.0, r2 / 255.0, g2 / 255.0,
+ b2 / 255.0, a2 / 255.0);
+
+ extend = (cyclic == JNI_TRUE) ? CAIRO_EXTEND_REFLECT : CAIRO_EXTEND_NONE;
+
+ cairo_pattern_set_extend( pattern, extend );
+
+ gr->pattern = pattern;
+ cairo_set_source(gr->cr, gr->pattern);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_setTexturePixels
+ (JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jintArray jarr, jint w, jint h, jint stride)
+{
+ struct cairographics2d *gr = NULL;
+ jint *jpixels = NULL;
+
+ gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ if (gr->pattern)
+ cairo_pattern_destroy (gr->pattern);
+
+ if (gr->pattern_surface)
+ cairo_surface_destroy (gr->pattern_surface);
+
+ if (gr->pattern_pixels)
+ g_free (gr->pattern_pixels);
+
+ gr->pattern = NULL;
+ gr->pattern_surface = NULL;
+ gr->pattern_pixels = NULL;
+
+ gr->pattern_pixels = (char *) g_malloc (h * stride * 4);
+ g_assert (gr->pattern_pixels != NULL);
+
+ jpixels = (*env)->GetIntArrayElements (env, jarr, NULL);
+ g_assert (jpixels != NULL);
+ memcpy (gr->pattern_pixels, jpixels, h * stride * 4);
+ (*env)->ReleaseIntArrayElements (env, jarr, jpixels, 0);
+
+ gr->pattern_surface = cairo_image_surface_create_for_data ((unsigned char *)gr->pattern_pixels,
+ CAIRO_FORMAT_ARGB32,
+ w, h, stride * 4);
+ g_assert (gr->pattern_surface != NULL);
+ gr->pattern = cairo_pattern_create_for_surface (gr->pattern_surface);
+ g_assert (gr->pattern != NULL);
+ cairo_pattern_set_extend (gr->pattern, CAIRO_EXTEND_REPEAT);
+ cairo_set_source (gr->cr, gr->pattern);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_drawPixels
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jintArray java_pixels,
+ jint w, jint h, jint stride, jdoubleArray java_matrix)
+{
+ jint *native_pixels = NULL;
+ jdouble *native_matrix = NULL;
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ native_pixels = (*env)->GetIntArrayElements (env, java_pixels, NULL);
+ native_matrix = (*env)->GetDoubleArrayElements (env, java_matrix, NULL);
+ g_assert (native_pixels != NULL);
+ g_assert (native_matrix != NULL);
+ g_assert ((*env)->GetArrayLength (env, java_matrix) == 6);
+
+ {
+ cairo_matrix_t mat;
+ cairo_pattern_t *p;
+ cairo_surface_t *surf = cairo_image_surface_create_for_data ((unsigned char *)native_pixels,
+ CAIRO_FORMAT_ARGB32,
+ w, h, stride * 4);
+ cairo_matrix_init_identity (&mat);
+ cairo_matrix_init (&mat,
+ native_matrix[0], native_matrix[1],
+ native_matrix[2], native_matrix[3],
+ native_matrix[4], native_matrix[5]);
+
+ p = cairo_pattern_create_for_surface (surf);
+ cairo_pattern_set_matrix (p, &mat);
+ if (gr->pattern)
+ cairo_pattern_set_filter (p, cairo_pattern_get_filter (gr->pattern));
+ cairo_set_source (gr->cr, p);
+ cairo_paint (gr->cr);
+ cairo_pattern_destroy (p);
+ cairo_surface_destroy (surf);
+ }
+
+ (*env)->ReleaseIntArrayElements (env, java_pixels, native_pixels, 0);
+ (*env)->ReleaseDoubleArrayElements (env, java_matrix, native_matrix, 0);
+}
+
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSetMatrix
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jdoubleArray java_matrix)
+{
+ jdouble *native_matrix = NULL;
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (obj != NULL);
+ g_assert (gr != NULL);
+
+ native_matrix = (*env)->GetDoubleArrayElements (env, java_matrix, NULL);
+ g_assert (native_matrix != NULL);
+ g_assert ((*env)->GetArrayLength (env, java_matrix) == 6);
+
+ {
+ cairo_matrix_t mat;
+
+ cairo_matrix_init_identity (&mat);
+ cairo_matrix_init (&mat,
+ native_matrix[0], native_matrix[1],
+ native_matrix[2], native_matrix[3],
+ native_matrix[4], native_matrix[5]);
+ g_assert (gr != NULL);
+ cairo_set_matrix (gr->cr, &mat);
+ }
+
+ (*env)->ReleaseDoubleArrayElements (env, java_matrix, native_matrix, 0);
+ update_pattern_transform (gr);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoDrawGlyphVector
+(JNIEnv *env, jobject obj, jlong pointer,
+ jobject font,
+ jfloat x, jfloat y, jint n,
+ jintArray java_codes,
+ jfloatArray java_positions)
+{
+
+ struct cairographics2d *gr = NULL;
+ struct peerfont *pfont = NULL;
+ cairo_glyph_t *glyphs = NULL;
+ int *native_codes;
+ float *native_positions;
+ jint i = 0;
+
+ g_assert (obj != NULL);
+ g_assert (java_codes != NULL);
+ g_assert (java_positions != NULL);
+
+ gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ pfont = (struct peerfont *)NSA_GET_FONT_PTR (env, font);
+ g_assert (pfont != NULL);
+
+ install_font_peer(gr->cr, pfont);
+
+ glyphs = g_malloc( sizeof(cairo_glyph_t) * n);
+ g_assert (glyphs != NULL);
+
+ native_codes = (*env)->GetIntArrayElements (env, java_codes, NULL);
+ native_positions = (*env)->GetFloatArrayElements (env, java_positions, NULL);
+
+ for (i = 0; i < n; ++i)
+ {
+ glyphs[i].index = native_codes[i];
+ glyphs[i].x = x + native_positions[ 2*i ];
+ glyphs[i].y = y + native_positions[ 2*i + 1];
+ }
+
+ (*env)->ReleaseFloatArrayElements (env, java_positions, native_positions, 0);
+ (*env)->ReleaseIntArrayElements (env, java_codes, native_codes, 0);
+
+ cairo_show_glyphs (gr->cr, glyphs, n);
+
+ g_free(glyphs);
+}
+
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSetOperator
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jint op)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ switch ((enum java_awt_alpha_composite_rule) op)
+ {
+ case java_awt_alpha_composite_CLEAR:
+ cairo_set_operator (gr->cr, CAIRO_OPERATOR_CLEAR);
+ break;
+
+ case java_awt_alpha_composite_SRC:
+ cairo_set_operator (gr->cr, CAIRO_OPERATOR_SOURCE);
+ break;
+
+ case java_awt_alpha_composite_SRC_OVER:
+ cairo_set_operator (gr->cr, CAIRO_OPERATOR_OVER);
+ break;
+
+ case java_awt_alpha_composite_DST_OVER:
+ cairo_set_operator (gr->cr, CAIRO_OPERATOR_DEST_OVER);
+ break;
+
+ case java_awt_alpha_composite_SRC_IN:
+ cairo_set_operator (gr->cr, CAIRO_OPERATOR_IN);
+ break;
+
+ case java_awt_alpha_composite_DST_IN:
+ cairo_set_operator (gr->cr, CAIRO_OPERATOR_DEST_IN);
+ break;
+
+ case java_awt_alpha_composite_SRC_OUT:
+ cairo_set_operator (gr->cr, CAIRO_OPERATOR_OUT);
+ break;
+
+ case java_awt_alpha_composite_DST_OUT:
+ cairo_set_operator (gr->cr, CAIRO_OPERATOR_DEST_OUT);
+ break;
+
+ case java_awt_alpha_composite_DST:
+ cairo_set_operator (gr->cr, CAIRO_OPERATOR_DEST);
+ break;
+
+ case java_awt_alpha_composite_SRC_ATOP:
+ cairo_set_operator (gr->cr, CAIRO_OPERATOR_ATOP);
+ break;
+
+ case java_awt_alpha_composite_DST_ATOP:
+ cairo_set_operator (gr->cr, CAIRO_OPERATOR_DEST_ATOP);
+ break;
+
+ case java_awt_alpha_composite_XOR:
+ cairo_set_operator (gr->cr, CAIRO_OPERATOR_XOR);
+ break;
+ }
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSetRGBAColor
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jdouble r, jdouble g, jdouble b, jdouble a)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ cairo_set_source_rgba (gr->cr, r, g, b, a);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSetFillRule
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jint rule)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ switch ((enum java_awt_geom_path_iterator_winding_rule) rule)
+ {
+ case java_awt_geom_path_iterator_WIND_NON_ZERO:
+ cairo_set_fill_rule (gr->cr, CAIRO_FILL_RULE_WINDING);
+ break;
+ case java_awt_geom_path_iterator_WIND_EVEN_ODD:
+ cairo_set_fill_rule (gr->cr, CAIRO_FILL_RULE_EVEN_ODD);
+ break;
+ }
+}
+
+/**
+ * Set the line style, except for dashes.
+ */
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSetLine
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jdouble width, int cap, int join, double miterLimit)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ /* set width */
+ cairo_set_line_width (gr->cr, width);
+
+ /* set cap */
+ switch ((enum java_awt_basic_stroke_cap_rule) cap)
+ {
+ case java_awt_basic_stroke_CAP_BUTT:
+ cairo_set_line_cap (gr->cr, CAIRO_LINE_CAP_BUTT);
+ break;
+
+ case java_awt_basic_stroke_CAP_ROUND:
+ cairo_set_line_cap (gr->cr, CAIRO_LINE_CAP_ROUND);
+ break;
+
+ case java_awt_basic_stroke_CAP_SQUARE:
+ cairo_set_line_cap (gr->cr, CAIRO_LINE_CAP_SQUARE);
+ break;
+ }
+
+ /* set join */
+ switch ((enum java_awt_basic_stroke_join_rule) join)
+ {
+ case java_awt_basic_stroke_JOIN_MITER:
+ cairo_set_line_join (gr->cr, CAIRO_LINE_JOIN_MITER);
+ break;
+
+ case java_awt_basic_stroke_JOIN_ROUND:
+ cairo_set_line_join (gr->cr, CAIRO_LINE_JOIN_ROUND);
+ break;
+
+ case java_awt_basic_stroke_JOIN_BEVEL:
+ cairo_set_line_join (gr->cr, CAIRO_LINE_JOIN_BEVEL);
+ break;
+ }
+
+ /* set miter */
+ cairo_set_miter_limit (gr->cr, miterLimit);
+}
+
+/**
+ * Set the line dashes
+ */
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSetDash
+(JNIEnv *env, jobject obj __attribute__((unused)),
+ jlong pointer, jdoubleArray dashes, jint ndash, jdouble offset)
+{
+ jdouble *dasharr = NULL;
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ dasharr = (*env)->GetDoubleArrayElements (env, dashes, NULL);
+ g_assert (dasharr != NULL);
+
+ cairo_set_dash (gr->cr, dasharr, ndash, offset);
+
+ (*env)->ReleaseDoubleArrayElements (env, dashes, dasharr, 0);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoNewPath
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ cairo_new_path (gr->cr);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoMoveTo
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jdouble x, jdouble y)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ cairo_move_to (gr->cr, x, y);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoLineTo
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jdouble x, jdouble y)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ cairo_line_to (gr->cr, x, y);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoCurveTo
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jdouble x1, jdouble y1,
+ jdouble x2, jdouble y2, jdouble x3, jdouble y3)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+ cairo_curve_to (gr->cr, x1, y1, x2, y2, x3, y3);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoRelMoveTo
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jdouble dx, jdouble dy)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ cairo_rel_move_to (gr->cr, dx, dy);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoRelLineTo
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jdouble dx, jdouble dy)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ cairo_rel_line_to (gr->cr, dx, dy);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoRelCurveTo
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jdouble dx1, jdouble dy1,
+ jdouble dx2, jdouble dy2, jdouble dx3, jdouble dy3)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ cairo_rel_curve_to (gr->cr, dx1, dy1, dx2, dy2, dx3, dy3);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoRectangle
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jdouble x, jdouble y, jdouble width, jdouble height)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+
+ cairo_rectangle (gr->cr, x, y, width, height);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoClosePath
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ cairo_close_path (gr->cr);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoStroke
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ cairo_stroke (gr->cr);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoFill
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ cairo_fill (gr->cr);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoClip
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert( gr != NULL );
+
+ cairo_clip( gr->cr );
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoResetClip
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ cairo_reset_clip( gr->cr );
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoPreserveClip
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ cairo_clip_preserve( gr->cr );
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoGraphics2D_cairoSurfaceSetFilter
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong pointer, jint filter)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, pointer);
+ g_assert (gr != NULL);
+
+ if (gr->pattern == NULL)
+ return;
+
+ switch ((enum java_awt_rendering_hints_filter) filter)
+ {
+ case java_awt_rendering_hints_VALUE_INTERPOLATION_NEAREST_NEIGHBOR:
+ cairo_pattern_set_filter (gr->pattern, CAIRO_FILTER_NEAREST);
+ break;
+ case java_awt_rendering_hints_VALUE_INTERPOLATION_BILINEAR:
+ cairo_pattern_set_filter (gr->pattern, CAIRO_FILTER_BILINEAR);
+ break;
+ case java_awt_rendering_hints_VALUE_ALPHA_INTERPOLATION_SPEED:
+ cairo_pattern_set_filter (gr->pattern, CAIRO_FILTER_FAST);
+ break;
+ case java_awt_rendering_hints_VALUE_ALPHA_INTERPOLATION_DEFAULT:
+ cairo_pattern_set_filter (gr->pattern, CAIRO_FILTER_NEAREST);
+ break;
+ case java_awt_rendering_hints_VALUE_ALPHA_INTERPOLATION_QUALITY:
+ cairo_pattern_set_filter (gr->pattern, CAIRO_FILTER_BEST);
+ break;
+ }
+}
+
+/************************** FONT STUFF ****************************/
+static void
+install_font_peer(cairo_t *cr,
+ struct peerfont *pfont)
+{
+ cairo_font_face_t *ft;
+ FT_Face face = NULL;
+
+ g_assert(cr != NULL);
+ g_assert(pfont != NULL);
+
+ if (pfont->graphics_resource == NULL)
+ {
+ face = pango_ft2_font_get_face (pfont->font);
+ g_assert (face != NULL);
+
+ ft = cairo_ft_font_face_create_for_ft_face (face, 0);
+ g_assert (ft != NULL);
+
+ cairo_set_font_face (cr, ft);
+ cairo_font_face_destroy (ft);
+ cairo_set_font_size (cr,
+ (pango_font_description_get_size (pfont->desc) /
+ (double)PANGO_SCALE));
+ ft = cairo_get_font_face (cr);
+ pfont->graphics_resource = ft;
+ }
+ else
+ {
+ ft = (cairo_font_face_t *) pfont->graphics_resource;
+ cairo_set_font_face (cr, ft);
+ cairo_set_font_size (cr,
+ (pango_font_description_get_size (pfont->desc) /
+ (double)PANGO_SCALE));
+ }
+}
+
+static void
+update_pattern_transform (struct cairographics2d *gr)
+{
+ cairo_matrix_t mat;
+
+ g_assert (gr != NULL);
+ if (gr->pattern == NULL)
+ return;
+
+ cairo_get_matrix (gr->cr, &mat);
+ cairo_pattern_set_matrix (gr->pattern, &mat);
+}
+
+
diff --git a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
new file mode 100644
index 000000000..3efa60d62
--- /dev/null
+++ b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_CairoSurface.c
@@ -0,0 +1,302 @@
+/* gnu_java_awt_peer_gtk_CairoSurface.c
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+#include "jcl.h"
+#include "gtkpeer.h"
+#include <cairo-xlib.h>
+#include <gdk/gdkx.h>
+
+#include "gnu_java_awt_peer_gtk_CairoSurface.h"
+#include "cairographics2d.h"
+
+/**
+ * Field names in CairoSurface.java
+ */
+#define SURFACE "surfacePointer"
+#define BUFFER "bufferPointer"
+
+/* prototypes */
+static void setNativeObject( JNIEnv *env, jobject obj, void *ptr, const char *pointer );
+
+/**
+ * Creates a cairo surface, ARGB32, native ordering, premultiplied alpha.
+ */
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoSurface_create (JNIEnv *env, jobject obj, jint width, jint height, jint stride)
+{
+ cairo_surface_t* surface;
+ void *data = g_malloc(stride * height * 4);
+ memset(data, 0, stride * height * 4);
+ setNativeObject(env, obj, data, BUFFER);
+
+ surface = cairo_image_surface_create_for_data
+ (data, CAIRO_FORMAT_ARGB32, width, height, stride);
+
+ setNativeObject(env, obj, surface, SURFACE);
+}
+
+/**
+ * Destroy the surface
+ */
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoSurface_destroy
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong surfacePointer, jlong bufferPointer)
+{
+ void *buffer;
+ cairo_surface_t* surface = JLONG_TO_PTR(void, surfacePointer);
+ if( surface != NULL )
+ cairo_surface_destroy(surface);
+
+ buffer = JLONG_TO_PTR(void, bufferPointer);
+ if( buffer != NULL )
+ g_free(buffer);
+}
+
+/**
+ * Gets a pixel
+ */
+JNIEXPORT jint JNICALL
+Java_gnu_java_awt_peer_gtk_CairoSurface_nativeGetElem
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong bufferPointer, jint i)
+{
+ jint *pixeldata = JLONG_TO_PTR(void, bufferPointer);
+
+ if( pixeldata == NULL )
+ return 0;
+
+ return pixeldata[i];
+}
+
+/**
+ * Sets a pixel
+ */
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoSurface_nativeSetElem
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong bufferPointer, jint i, jint val)
+{
+ jint *pixeldata = JLONG_TO_PTR(void, bufferPointer);
+
+ if( pixeldata == NULL )
+ return;
+
+ pixeldata[i] = val;
+}
+
+/**
+ * Gets all pixels in an array
+ */
+JNIEXPORT jintArray JNICALL
+Java_gnu_java_awt_peer_gtk_CairoSurface_nativeGetPixels
+(JNIEnv *env __attribute((unused)), jobject obj __attribute((unused)),
+ jlong bufferPointer, int size)
+{
+ jint *pixeldata, *jpixdata;
+ jintArray jpixels;
+
+ pixeldata = JLONG_TO_PTR(void, bufferPointer);
+ g_assert(pixeldata != NULL);
+
+ jpixels = (*env)->NewIntArray (env, size);
+ jpixdata = (*env)->GetIntArrayElements (env, jpixels, NULL);
+ memcpy (jpixdata, pixeldata, size * sizeof( jint ));
+
+ (*env)->ReleaseIntArrayElements (env, jpixels, jpixdata, 0);
+ return jpixels;
+}
+
+/**
+ * Sets all pixels by an array.
+ */
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoSurface_nativeSetPixels
+(JNIEnv *env, jobject obj, jlong bufferPointer, jintArray jpixels)
+{
+ jint *pixeldata, *jpixdata;
+ int size;
+ int width, height;
+ jclass cls;
+ jfieldID field;
+
+ if( jpixels == NULL )
+ return;
+
+ cls = (*env)->GetObjectClass (env, obj);
+ field = (*env)->GetFieldID (env, cls, "width", "I");
+ g_assert (field != 0);
+ width = (*env)->GetIntField (env, obj, field);
+
+ field = (*env)->GetFieldID (env, cls, "height", "I");
+ g_assert (field != 0);
+ height = (*env)->GetIntField (env, obj, field);
+
+ pixeldata = JLONG_TO_PTR(void, bufferPointer);
+ g_assert(pixeldata != NULL);
+
+ jpixdata = (*env)->GetIntArrayElements (env, jpixels, NULL);
+ size = (*env)->GetArrayLength( env, jpixels );
+ if( size > width * height ) size = width * height; /* stop overflows. */
+
+ memcpy (pixeldata, jpixdata, size * sizeof( jint ));
+
+ (*env)->ReleaseIntArrayElements (env, jpixels, jpixdata, 0);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoSurface_nativeDrawSurface
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong surfacePointer, jlong context, jdoubleArray java_matrix)
+{
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, context);
+ cairo_t *cr = gr->cr;
+ jdouble *native_matrix = NULL;
+ cairo_surface_t* surface = JLONG_TO_PTR(void, surfacePointer);
+ g_assert(surface != NULL);
+ g_assert(cr != NULL);
+
+ native_matrix = (*env)->GetDoubleArrayElements (env, java_matrix, NULL);
+ g_assert (native_matrix != NULL);
+ g_assert ((*env)->GetArrayLength (env, java_matrix) == 6);
+
+ {
+ cairo_matrix_t mat;
+ cairo_pattern_t *p;
+ cairo_matrix_init_identity (&mat);
+ cairo_matrix_init (&mat,
+ native_matrix[0], native_matrix[1],
+ native_matrix[2], native_matrix[3],
+ native_matrix[4], native_matrix[5]);
+
+ p = cairo_pattern_create_for_surface (surface);
+ cairo_pattern_set_matrix (p, &mat);
+
+ cairo_set_source(cr, p);
+ cairo_paint(cr);
+ cairo_pattern_destroy(p);
+ }
+
+ (*env)->ReleaseDoubleArrayElements (env, java_matrix, native_matrix, 0);
+}
+
+JNIEXPORT jlong JNICALL
+Java_gnu_java_awt_peer_gtk_CairoSurface_getFlippedBuffer
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong bufferPointer, jint size)
+{
+ jint *dst;
+ jint *src = JLONG_TO_PTR(void, bufferPointer);
+ int i;
+ int t;
+
+ g_assert( src != NULL );
+ dst = g_malloc( size * sizeof( jint ) );
+
+ for(i = 0; i < size; i++ )
+ {
+ t = (src[i] & 0x0000FF) << 16;
+ dst[i] = (src[i] & 0x00FF0000) >> 16;
+ dst[i] |= (src[i] & 0xFF00FF00);
+ dst[i] |= t;
+ }
+
+ return PTR_TO_JLONG(dst);
+}
+
+/**
+ * Create and return a cairo context for drawing to the surface.
+ */
+JNIEXPORT jlong JNICALL
+Java_gnu_java_awt_peer_gtk_CairoSurface_nativeNewCairoContext
+(JNIEnv *env __attribute((unused)), jobject obj __attribute((unused)),
+ jlong surfacePointer)
+{
+ cairo_surface_t* surface = JLONG_TO_PTR(cairo_surface_t, surfacePointer);
+ cairo_t *ptr;
+ g_assert(surface != NULL);
+ ptr = cairo_create(surface);
+ g_assert(ptr != NULL);
+
+ return PTR_TO_JLONG(ptr);
+}
+
+/**
+ * copyArea.
+ */
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_CairoSurface_copyAreaNative2
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong bufferPointer,
+ jint x, jint y, jint w, jint h, jint dx, jint dy, jint stride)
+{
+ int row;
+ int srcOffset, dstOffset;
+ jint *temp;
+ jint *pixeldata = JLONG_TO_PTR(jint, bufferPointer);
+ g_assert( pixeldata != NULL );
+
+ temp = g_malloc( h * w * 4 );
+ g_assert( temp != NULL );
+
+ srcOffset = x + (y * stride);
+ dstOffset = (x + dx) + ((y + dy) * stride);
+
+ for( row = 0; row < h; row++ )
+ memcpy( temp + (w * row), pixeldata + srcOffset + (stride * row), w * 4 );
+
+ for( row = 0; row < h; row++ )
+ memcpy( pixeldata + dstOffset + (stride * row), temp + (w * row), w * 4 );
+
+ g_free( temp );
+}
+
+/*
+ * Sets the native object field.
+ */
+static void
+setNativeObject( JNIEnv *env, jobject obj, void *ptr, const char *pointer )
+{
+ jclass cls;
+ jlong value;
+ jfieldID nofid;
+ cls = (*env)->GetObjectClass( env, obj );
+ value = PTR_TO_JLONG(ptr);
+ nofid = (*env)->GetFieldID( env, cls, pointer, "J" );
+ (*env)->SetLongField( env, obj, nofid, value );
+ (*env)->DeleteLocalRef( env, cls );
+}
diff --git a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
new file mode 100644
index 000000000..d85ba326f
--- /dev/null
+++ b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphics.c
@@ -0,0 +1,311 @@
+/* gnu_java_awt_peer_gtk_ComponentGraphics.c
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+#include "jcl.h"
+#include "gtkpeer.h"
+#include <cairo-xlib.h>
+#include <gdk/gdktypes.h>
+#include <gdk/gdkprivate.h>
+#include <gdk/gdkx.h>
+#include <X11/extensions/Xrender.h>
+
+#include <gdk-pixbuf/gdk-pixbuf.h>
+#include <gdk-pixbuf/gdk-pixdata.h>
+
+#include <cairo-ft.h>
+#include <cairo-xlib.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "gnu_java_awt_peer_gtk_ComponentGraphics.h"
+
+#include "cairographics2d.h"
+
+static short flush_scheduled = 0;
+
+static gboolean flush (gpointer data __attribute__((unused)))
+{
+ gdk_threads_enter ();
+
+ XFlush (GDK_DISPLAY ());
+ flush_scheduled = 0;
+
+ gdk_threads_leave ();
+
+ return FALSE;
+}
+
+/* The minimum time period between calls to XFlush, in
+ milliseconds. */
+#define MINIMUM_FLUSH_PERIOD 20
+
+/* schedule_flush must be called with the GDK lock held. */
+static void
+schedule_flush ()
+{
+ if (!flush_scheduled)
+ {
+ g_timeout_add (MINIMUM_FLUSH_PERIOD, flush, NULL);
+ flush_scheduled = 1;
+ }
+}
+
+void cp_gtk_grab_current_drawable(GtkWidget *widget, GdkDrawable **draw,
+ GdkWindow **win)
+{
+ g_assert (widget != NULL);
+ g_assert (draw != NULL);
+ g_assert (win != NULL);
+
+ *win = widget->window;
+
+ *draw = *win;
+ gdk_window_get_internal_paint_info (*win, draw, 0, 0);
+}
+
+/**
+ * Returns whether the XRender extension is supported
+ */
+JNIEXPORT jboolean JNICALL
+Java_gnu_java_awt_peer_gtk_ComponentGraphics_hasXRender
+ (JNIEnv *env __attribute__ ((unused)), jclass cls __attribute__ ((unused)))
+{
+#if HAVE_XRENDER
+ int ev = 0, err = 0;
+ if( XRenderQueryExtension (GDK_DISPLAY (), &ev, &err) )
+ return JNI_TRUE;
+#endif
+ return JNI_FALSE;
+}
+
+
+JNIEXPORT jlong JNICALL
+Java_gnu_java_awt_peer_gtk_ComponentGraphics_initState
+ (JNIEnv *env, jobject obj __attribute__ ((unused)), jobject peer)
+{
+ Drawable draw;
+ Display * dpy;
+ Visual * vis;
+ GdkDrawable *drawable;
+ cairo_surface_t *surface;
+ GdkWindow *win;
+ GtkWidget *widget = NULL;
+ void *ptr = NULL;
+ int width, height;
+ cairo_t *cr;
+
+ gdk_threads_enter();
+
+ ptr = NSA_GET_PTR (env, peer);
+ g_assert (ptr != NULL);
+
+ widget = GTK_WIDGET (ptr);
+ g_assert (widget != NULL);
+
+ cp_gtk_grab_current_drawable (widget, &drawable, &win);
+ g_assert (drawable != NULL);
+
+ width = widget->allocation.width;
+ height = widget->allocation.height;
+
+ g_assert (drawable != NULL);
+
+ draw = gdk_x11_drawable_get_xid(drawable);
+ g_assert (draw != (XID) 0);
+
+ dpy = gdk_x11_drawable_get_xdisplay(drawable);
+ g_assert (dpy != NULL);
+
+ vis = gdk_x11_visual_get_xvisual(gdk_drawable_get_visual(drawable));
+ g_assert (vis != NULL);
+
+ surface = cairo_xlib_surface_create (dpy, draw, vis, width, height);
+ g_assert (surface != NULL);
+
+ cr = cairo_create (surface);
+ g_assert(cr != NULL);
+
+ gdk_threads_leave();
+
+ return PTR_TO_JLONG(cr);
+}
+
+/**
+ * Disposes of the surface
+ */
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_ComponentGraphics_disposeSurface
+ (JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)),
+ jlong value)
+{
+ struct cairographics2d *gr;
+ cairo_surface_t *surface;
+
+ gr = JLONG_TO_PTR(struct cairographics2d, value);
+
+ if (gr == NULL)
+ return;
+
+ if (gr->cr == NULL)
+ return;
+
+ surface = cairo_get_target (gr->cr);
+ if (surface != NULL)
+ {
+ gdk_threads_enter();
+ cairo_surface_destroy (surface);
+ gdk_threads_leave();
+ }
+}
+
+JNIEXPORT jlong JNICALL
+Java_gnu_java_awt_peer_gtk_ComponentGraphics_initFromVolatile
+ (JNIEnv *env __attribute__ ((unused)), jobject obj __attribute__ ((unused)),
+ jlong ptr, jint width, jint height)
+{
+ Drawable draw;
+ Display * dpy;
+ Visual * vis;
+ GdkDrawable *drawable;
+ cairo_surface_t *surface;
+ cairo_t *cr;
+
+ gdk_threads_enter();
+
+ drawable = JLONG_TO_PTR(GdkDrawable, ptr);
+ g_assert (drawable != NULL);
+
+ draw = gdk_x11_drawable_get_xid(drawable);
+ g_assert (draw != (XID) 0);
+
+ dpy = gdk_x11_drawable_get_xdisplay(drawable);
+ g_assert (dpy != NULL);
+
+ vis = gdk_x11_visual_get_xvisual(gdk_drawable_get_visual(drawable));
+ g_assert (vis != NULL);
+
+ surface = cairo_xlib_surface_create (dpy, draw, vis, width, height);
+ g_assert (surface != NULL);
+
+ cr = cairo_create (surface);
+ g_assert(cr != NULL);
+
+ gdk_threads_leave();
+
+ return PTR_TO_JLONG(cr);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_ComponentGraphics_start_1gdk_1drawing
+ (JNIEnv *env __attribute__ ((unused)), jobject obj __attribute__ ((unused)))
+{
+ gdk_threads_enter();
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_ComponentGraphics_end_1gdk_1drawing
+ (JNIEnv *env __attribute__ ((unused)), jobject obj __attribute__ ((unused)))
+{
+ schedule_flush ();
+ gdk_threads_leave();
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_ComponentGraphics_copyAreaNative
+ (JNIEnv *env, jobject obj __attribute__((unused)), jobject peer,
+ jint x, jint y, jint w, jint h, jint dx, jint dy)
+{
+ GdkPixbuf *pixbuf;
+ GdkDrawable *drawable;
+ GdkWindow *win;
+ GtkWidget *widget = NULL;
+ void *ptr = NULL;
+
+ gdk_threads_enter();
+
+ ptr = NSA_GET_PTR (env, peer);
+ g_assert (ptr != NULL);
+
+ widget = GTK_WIDGET (ptr);
+ g_assert (widget != NULL);
+
+ cp_gtk_grab_current_drawable (widget, &drawable, &win);
+ g_assert (drawable != NULL);
+
+ pixbuf = gdk_pixbuf_new( GDK_COLORSPACE_RGB, TRUE, 8, w, h );
+ gdk_pixbuf_get_from_drawable( pixbuf, drawable, NULL, x, y, 0, 0, w, h );
+ gdk_draw_pixbuf (drawable, NULL, pixbuf,
+ 0, 0, x + dx, y + dy,
+ w, h,
+ GDK_RGB_DITHER_NORMAL, 0, 0);
+ gdk_threads_leave();
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_ComponentGraphics_drawVolatile
+(JNIEnv *env, jobject obj __attribute__ ((unused)), jobject peer,
+ jlong img, jint x, jint y, jint w, jint h)
+{
+ GdkPixmap *pixmap;
+ GtkWidget *widget = NULL;
+ void *ptr = NULL;
+ GdkGC *gc;
+
+ gdk_threads_enter();
+ ptr = NSA_GET_PTR (env, peer);
+ g_assert (ptr != NULL);
+
+ widget = GTK_WIDGET (ptr);
+ g_assert (widget != NULL);
+
+ pixmap = JLONG_TO_PTR(GdkPixmap, img);
+
+ gc = gdk_gc_new(widget->window);
+ gdk_draw_drawable(widget->window,
+ gc,
+ pixmap,
+ 0, 0,
+ x, y,
+ w, h);
+
+ g_object_unref( gc );
+
+ schedule_flush ();
+
+ gdk_threads_leave();
+}
diff --git a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphicsCopy.c b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphicsCopy.c
new file mode 100644
index 000000000..76caa5d0c
--- /dev/null
+++ b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_ComponentGraphicsCopy.c
@@ -0,0 +1,132 @@
+/* gnu_java_awt_peer_gtk_ComponentGraphicsCopy.c
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+#include "jcl.h"
+#include "gtkpeer.h"
+#include <cairo-xlib.h>
+#include <gdk/gdktypes.h>
+#include <gdk/gdkprivate.h>
+#include <gdk/gdkx.h>
+
+#include <gdk-pixbuf/gdk-pixbuf.h>
+#include <gdk-pixbuf/gdk-pixdata.h>
+
+#include <cairo-ft.h>
+#include <cairo-xlib.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "gnu_java_awt_peer_gtk_ComponentGraphicsCopy.h"
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_ComponentGraphicsCopy_getPixbuf
+ (JNIEnv *env, jobject obj __attribute__((unused)),
+ jobject peer, jobject image)
+{
+ gint width, height;
+ GdkPixbuf *pixbuf;
+ GdkDrawable *drawable;
+ GdkWindow *win;
+ GtkWidget *widget = NULL;
+ void *ptr = NULL;
+
+ gdk_threads_enter();
+
+ ptr = NSA_GET_PTR (env, peer);
+ g_assert (ptr != NULL);
+
+ widget = GTK_WIDGET (ptr);
+ g_assert (widget != NULL);
+
+ cp_gtk_grab_current_drawable (widget, &drawable, &win);
+ g_assert (drawable != NULL);
+
+ pixbuf = cp_gtk_image_get_pixbuf( env, image );
+ g_assert( pixbuf != NULL);
+
+ width = gdk_pixbuf_get_width( pixbuf );
+ height = gdk_pixbuf_get_height( pixbuf );
+
+ gdk_pixbuf_get_from_drawable( pixbuf, /* destination pixbuf */
+ drawable,
+ NULL, /* colormap */
+ 0, 0, 0, 0,
+ width, height );
+ gdk_threads_leave();
+}
+
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_ComponentGraphicsCopy_copyPixbuf
+ (JNIEnv *env, jobject obj __attribute__((unused)),
+ jobject peer, jobject image,
+ int x __attribute__((unused)), int y __attribute__((unused)),
+ int width __attribute__((unused)), int height __attribute__((unused)))
+{
+ gint pwidth, pheight;
+ GdkPixbuf *pixbuf;
+ GdkDrawable *drawable;
+ GdkWindow *win;
+ GtkWidget *widget = NULL;
+ void *ptr = NULL;
+
+ gdk_threads_enter();
+
+ ptr = NSA_GET_PTR (env, peer);
+ g_assert (ptr != NULL);
+
+ widget = GTK_WIDGET (ptr);
+ g_assert (widget != NULL);
+
+ cp_gtk_grab_current_drawable (widget, &drawable, &win);
+ g_assert (drawable != NULL);
+
+ pixbuf = cp_gtk_image_get_pixbuf( env, image );
+ g_assert( pixbuf != NULL);
+
+ pwidth = gdk_pixbuf_get_width( pixbuf );
+ pheight = gdk_pixbuf_get_height( pixbuf );
+
+ gdk_draw_pixbuf (drawable, NULL, pixbuf,
+ 0, 0, 0, 0,
+ pwidth, pheight,
+ GDK_RGB_DITHER_NORMAL, 0, 0);
+
+ gdk_threads_leave();
+}
+
diff --git a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_FreetypeGlyphVector.c b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_FreetypeGlyphVector.c
new file mode 100644
index 000000000..c8b74d207
--- /dev/null
+++ b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_FreetypeGlyphVector.c
@@ -0,0 +1,348 @@
+/* gnu_java_awt_FreetypeGlyphVector.c
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+#include <jni.h>
+#include <gtk/gtk.h>
+#include <string.h>
+#include <pango/pango.h>
+#include <pango/pangoft2.h>
+#include <pango/pangofc-font.h>
+#include <freetype/ftglyph.h>
+#include <freetype/ftoutln.h>
+#include "native_state.h"
+#include "gdkfont.h"
+#include "gnu_java_awt_peer_gtk_FreetypeGlyphVector.h"
+#include "cairographics2d.h"
+
+typedef struct gp
+{
+ JNIEnv *env;
+ jobject obj;
+ double px;
+ double py;
+ double sx;
+ double sy;
+} generalpath ;
+
+static PangoFcFont *
+getFont(JNIEnv *env, jobject obj)
+{
+ jfieldID fid;
+ jobject data;
+ jclass cls;
+ struct peerfont *pfont;
+
+ cls = (*env)->GetObjectClass (env, obj);
+ fid = (*env)->GetFieldID (env, cls, "peer",
+ "Lgnu/java/awt/peer/gtk/GdkFontPeer;");
+ g_assert (fid != 0);
+
+ data = (*env)->GetObjectField (env, obj, fid);
+ g_assert (data != NULL);
+
+ pfont = (struct peerfont *)NSA_GET_FONT_PTR (env, data);
+ g_assert (pfont != NULL);
+ g_assert (pfont->font != NULL);
+
+ return (PangoFcFont *)pfont->font;
+}
+
+JNIEXPORT jintArray JNICALL
+Java_gnu_java_awt_peer_gtk_FreetypeGlyphVector_getGlyphs
+ (JNIEnv *env, jobject obj, jintArray codepoints)
+{
+ FT_Face ft_face;
+ jintArray retArray;
+ PangoFcFont *font;
+ jint *values, *cpvals;
+ jint length;
+ int i;
+
+ font = getFont(env, obj);
+
+ ft_face = pango_fc_font_lock_face( font );
+ g_assert (ft_face != NULL);
+
+ length = (*env)->GetArrayLength (env, codepoints);
+ cpvals = (*env)->GetIntArrayElements (env, codepoints, NULL);
+
+ retArray = (*env)->NewIntArray (env, length);
+ values = (*env)->GetIntArrayElements (env, retArray, NULL);
+
+ for( i = 0; i < length; i++ )
+ values[i] = FT_Get_Char_Index( ft_face, cpvals[i] );
+
+ (*env)->ReleaseIntArrayElements (env, retArray, values, 0);
+ (*env)->ReleaseIntArrayElements (env, codepoints, cpvals, 0);
+
+ pango_fc_font_unlock_face (font);
+
+ return retArray;
+}
+
+JNIEXPORT jobject JNICALL
+Java_gnu_java_awt_peer_gtk_FreetypeGlyphVector_getKerning
+(JNIEnv *env, jobject obj, jint rightGlyph, jint leftGlyph)
+{
+ FT_Face ft_face;
+ FT_Vector kern;
+ jclass cls;
+ jmethodID method;
+ jvalue values[2];
+ PangoFcFont *font;
+
+ font = getFont(env, obj);
+ ft_face = pango_fc_font_lock_face( font );
+ g_assert (ft_face != NULL);
+ FT_Get_Kerning( ft_face, rightGlyph, leftGlyph, FT_KERNING_DEFAULT, &kern );
+
+ pango_fc_font_unlock_face( font );
+
+ values[0].d = (jdouble)kern.x/64.0;
+ values[1].d = (jdouble)kern.y/64.0;
+
+ cls = (*env)->FindClass (env, "java/awt/geom/Point2D$Double");
+ method = (*env)->GetMethodID (env, cls, "<init>", "(DD)V");
+ return (*env)->NewObjectA(env, cls, method, values);
+}
+
+JNIEXPORT jdoubleArray JNICALL
+Java_gnu_java_awt_peer_gtk_FreetypeGlyphVector_getMetricsNative
+(JNIEnv *env, jobject obj, jint glyphIndex )
+{
+ FT_Face ft_face;
+ jdouble *values;
+ jdoubleArray retArray = NULL;
+ PangoFcFont *font;
+
+ font = getFont(env, obj);
+ ft_face = pango_fc_font_lock_face( font );
+
+ g_assert (ft_face != NULL);
+
+ FT_Set_Transform( ft_face, NULL, NULL );
+
+ if( FT_Load_Glyph( ft_face, glyphIndex, FT_LOAD_NO_BITMAP ) != 0 )
+ {
+ pango_fc_font_unlock_face( font );
+ printf("Couldn't load glyph %i\n", glyphIndex);
+ return NULL;
+ }
+
+ retArray = (*env)->NewDoubleArray (env, 8);
+ values = (*env)->GetDoubleArrayElements (env, retArray, NULL);
+
+ values[0] = 0;
+ values[1] = (jdouble)ft_face->glyph->advance.x/64.0;
+ values[2] = (jdouble)ft_face->glyph->advance.y/64.0;
+ values[3] = (jdouble)ft_face->glyph->metrics.horiBearingX/64.0;
+ values[4] = -(jdouble)ft_face->glyph->metrics.horiBearingY/64.0;
+ values[5] = (jdouble)ft_face->glyph->metrics.width/64.0;
+ values[6] = (jdouble)ft_face->glyph->metrics.height/64.0;
+ values[7] = 0;
+
+ (*env)->ReleaseDoubleArrayElements (env, retArray, values, 0);
+ pango_fc_font_unlock_face( font );
+
+ return retArray;
+}
+
+/* GetOutline code follows ****************************/
+/********* Freetype callback functions *****************************/
+
+static int _moveTo( const FT_Vector* to,
+ void *p)
+{
+ JNIEnv *env;
+ jobject obj;
+ jclass cls;
+ jmethodID method;
+ jvalue values[2];
+ generalpath *path = (generalpath *) p;
+
+ env = path->env;
+ obj = path->obj;
+
+ values[0].f = (jfloat)(to->x * path->sx + path->px);
+ values[1].f = (jfloat)(to->y * path->sy + path->py);
+
+ cls = (*env)->FindClass (env, "java/awt/geom/GeneralPath");
+ method = (*env)->GetMethodID (env, cls, "moveTo", "(FF)V");
+ (*env)->CallVoidMethodA(env, obj, method, values );
+
+ return 0;
+}
+
+static int _lineTo( const FT_Vector* to,
+ void *p)
+{
+ JNIEnv *env;
+ jobject obj;
+ jclass cls;
+ jmethodID method;
+ jvalue values[2];
+ generalpath *path = (generalpath *) p;
+
+ env = path->env;
+ obj = path->obj;
+ values[0].f = (jfloat)(to->x * path->sx + path->px);
+ values[1].f = (jfloat)(to->y * path->sy + path->py);
+
+ cls = (*env)->FindClass (env, "java/awt/geom/GeneralPath");
+ method = (*env)->GetMethodID (env, cls, "lineTo", "(FF)V");
+ (*env)->CallVoidMethodA(env, obj, method, values );
+
+ return 0;
+}
+
+static int _quadTo( const FT_Vector* cp,
+ const FT_Vector* to,
+ void *p)
+{
+ JNIEnv *env;
+ jobject obj;
+ jclass cls;
+ jmethodID method;
+ jvalue values[4];
+ generalpath *path = (generalpath *) p;
+
+ env = path->env;
+ obj = path->obj;
+ values[0].f = (jfloat)(cp->x * path->sx + path->px);
+ values[1].f = (jfloat)(cp->y * path->sy + path->py);
+ values[2].f = (jfloat)(to->x * path->sx + path->px);
+ values[3].f = (jfloat)(to->y * path->sy + path->py);
+
+ cls = (*env)->FindClass (env, "java/awt/geom/GeneralPath");
+ method = (*env)->GetMethodID (env, cls, "quadTo", "(FFFF)V");
+ (*env)->CallVoidMethodA(env, obj, method, values );
+
+ return 0;
+}
+
+static int _curveTo( const FT_Vector* cp1,
+ const FT_Vector* cp2,
+ const FT_Vector* to,
+ void *p)
+{
+ JNIEnv *env;
+ jobject obj;
+ jclass cls;
+ jmethodID method;
+ jvalue values[6];
+ generalpath *path = (generalpath *) p;
+
+ env = path->env;
+ obj = path->obj;
+ values[0].f = (jfloat)(cp1->x * path->sx + path->px);
+ values[1].f = (jfloat)(cp1->y * path->sy + path->py);
+ values[2].f = (jfloat)(cp2->x * path->sx + path->px);
+ values[3].f = (jfloat)(cp2->y * path->sy + path->py);
+ values[4].f = (jfloat)(to->x * path->sx + path->px);
+ values[5].f = (jfloat)(to->y * path->sy + path->py);
+
+ cls = (*env)->FindClass (env, "java/awt/geom/GeneralPath");
+ method = (*env)->GetMethodID (env, cls, "curveTo", "(FFFFFF)V");
+ (*env)->CallVoidMethodA(env, obj, method, values );
+
+ return 0;
+}
+
+
+JNIEXPORT jobject JNICALL
+Java_gnu_java_awt_peer_gtk_FreetypeGlyphVector_getGlyphOutlineNative
+ (JNIEnv *env, jobject obj, jint glyphIndex)
+{
+ generalpath *path;
+ jobject gp;
+ FT_Outline_Funcs ftCallbacks =
+ {
+ (FT_Outline_MoveToFunc) _moveTo,
+ (FT_Outline_LineToFunc) _lineTo,
+ (FT_Outline_ConicToFunc) _quadTo,
+ (FT_Outline_CubicToFunc) _curveTo,
+ 0,
+ 0
+ };
+ PangoFcFont *font;
+ FT_Face ft_face;
+ FT_Glyph glyph;
+
+ font = getFont(env, obj);
+ ft_face = pango_fc_font_lock_face( font );
+
+ g_assert (ft_face != NULL);
+
+ path = g_malloc0 (sizeof (generalpath));
+ g_assert(path != NULL);
+ path->env = env;
+
+ path->px = path->py = 0.0;
+ path->sx = 1.0/64.0;
+ path->sy = -1.0/64.0;
+
+ { /* create a GeneralPath instance */
+ jclass cls;
+ jmethodID method;
+
+ cls = (*env)->FindClass (env, "java/awt/geom/GeneralPath");
+ method = (*env)->GetMethodID (env, cls, "<init>", "()V");
+ gp = path->obj = (*env)->NewObject (env, cls, method);
+ }
+
+ if(FT_Load_Glyph(ft_face,
+ (FT_UInt)(glyphIndex),
+ FT_LOAD_DEFAULT | FT_LOAD_NO_BITMAP) != 0)
+ {
+ pango_fc_font_unlock_face( font );
+ g_free(path);
+ return NULL;
+ }
+
+ FT_Get_Glyph( ft_face->glyph, &glyph );
+ FT_Outline_Decompose (&(((FT_OutlineGlyph)glyph)->outline),
+ &ftCallbacks, path);
+ FT_Done_Glyph( glyph );
+
+ pango_fc_font_unlock_face( font );
+
+ g_free(path);
+
+ return gp;
+}
+
+
diff --git a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkFontPeer.c b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkFontPeer.c
index c0f776b20..ddaece1b2 100644
--- a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkFontPeer.c
+++ b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkFontPeer.c
@@ -59,25 +59,11 @@ enum java_awt_font_baseline {
java_awt_font_HANGING_BASELINE = 2
};
-static jmethodID glyphVector_ctor;
-static jclass glyphVector_class;
-static PangoAttrList *attrs = NULL;
-
JNIEXPORT void JNICALL
Java_gnu_java_awt_peer_gtk_GdkFontPeer_initStaticState
(JNIEnv *env, jclass clazz)
{
NSA_FONT_INIT (env, clazz);
-
- glyphVector_class = (*env)->FindClass
- (env, "gnu/java/awt/peer/gtk/GdkGlyphVector");
-
- glyphVector_class = (*env)->NewGlobalRef
- (env, glyphVector_class);
-
- glyphVector_ctor = (*env)->GetMethodID
- (env, glyphVector_class, "<init>",
- "([D[ILjava/awt/Font;Ljava/awt/font/FontRenderContext;)V");
}
JNIEXPORT void JNICALL
@@ -121,124 +107,26 @@ Java_gnu_java_awt_peer_gtk_GdkFontPeer_dispose
}
-JNIEXPORT jobject JNICALL
-Java_gnu_java_awt_peer_gtk_GdkFontPeer_getGlyphVector
- (JNIEnv *env, jobject self,
- jstring chars,
- jobject font,
- jobject fontRenderContext)
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_GdkFontPeer_releasePeerGraphicsResource
+ (JNIEnv *env, jobject java_font)
{
struct peerfont *pfont = NULL;
- GList *items = NULL;
- GList *i = NULL;
- gchar *str = NULL;
- int len = 0;
- int j = 0;
- double *native_extents = NULL;
- int *native_codes = NULL;
- jintArray java_codes = NULL;
- jdoubleArray java_extents = NULL;
- gdk_threads_enter ();
+ gdk_threads_enter();
- pfont = (struct peerfont *)NSA_GET_FONT_PTR (env, self);
+ pfont = (struct peerfont *) NSA_GET_FONT_PTR (env, java_font);
g_assert (pfont != NULL);
-
- len = (*cp_gtk_gdk_env())->GetStringUTFLength (env, chars);
- str = (gchar *)(*env)->GetStringUTFChars (env, chars, NULL);
- g_assert (str != NULL);
-
- if (attrs == NULL)
- attrs = pango_attr_list_new ();
-
- if (len > 0 && str[len-1] == '\0')
- len--;
-
- items = pango_itemize (pfont->ctx, str, 0, len, attrs, NULL);
-
- i = g_list_first (items);
-
- if (i == NULL)
+ if (pfont->graphics_resource != NULL)
{
- java_extents = (*env)->NewDoubleArray (env, 0);
- java_codes = (*env)->NewIntArray (env, 0);
- }
- else
- {
- PangoGlyphString *glyphs;
- PangoItem *item = (PangoItem *)i->data;
-
- pango_context_set_font_description (pfont->ctx, pfont->desc);
- pango_context_set_language (pfont->ctx, gtk_get_default_language());
- pango_context_load_font (pfont->ctx, pfont->desc);
-
- glyphs = pango_glyph_string_new ();
- g_assert (glyphs != NULL);
-
- pango_shape (str + item->offset, item->length,
- &(item->analysis), glyphs);
-
- if (glyphs->num_glyphs > 0)
- {
- int x = 0;
- double scale = ((double) PANGO_SCALE);
-
- java_extents = (*env)->NewDoubleArray (env, glyphs->num_glyphs * NUM_GLYPH_METRICS);
- java_codes = (*env)->NewIntArray (env, glyphs->num_glyphs);
-
- native_extents = (*env)->GetDoubleArrayElements (env, java_extents, NULL);
- native_codes = (*env)->GetIntArrayElements (env, java_codes, NULL);
-
- for (j = 0; j < glyphs->num_glyphs; ++j)
- {
- PangoRectangle ink;
- PangoRectangle logical;
- PangoGlyphGeometry *geom = &glyphs->glyphs[j].geometry;
-
- pango_font_get_glyph_extents (pfont->font,
- glyphs->glyphs[j].glyph,
- &ink, &logical);
-
- native_codes[j] = glyphs->glyphs[j].glyph;
-
- native_extents[ GLYPH_LOG_X(j) ] = (logical.x) / scale;
- native_extents[ GLYPH_LOG_Y(j) ] = (- logical.y) / scale;
- native_extents[ GLYPH_LOG_WIDTH(j) ] = (logical.width) / scale;
- native_extents[ GLYPH_LOG_HEIGHT(j) ] = (logical.height) / scale;
-
- native_extents[ GLYPH_INK_X(j) ] = (ink.x) / scale;
- native_extents[ GLYPH_INK_Y(j) ] = (- ink.y) / scale;
- native_extents[ GLYPH_INK_WIDTH(j) ] = (ink.width) / scale;
- native_extents[ GLYPH_INK_HEIGHT(j) ] = (ink.height) / scale;
-
- native_extents[ GLYPH_POS_X(j) ] = (x + geom->x_offset) / scale;
- native_extents[ GLYPH_POS_Y(j) ] = ( - geom->y_offset) / scale;
-
- x += geom->width;
- }
- (*env)->ReleaseDoubleArrayElements (env, java_extents, native_extents, 0);
- (*env)->ReleaseIntArrayElements (env, java_codes, native_codes, 0);
- }
-
- pango_glyph_string_free (glyphs);
+ cairo_font_face_destroy ((cairo_font_face_t *) pfont->graphics_resource);
+ pfont->graphics_resource = NULL;
}
- (*env)->ReleaseStringUTFChars (env, chars, str);
-
- for (i = g_list_first (items); i != NULL; i = g_list_next (i))
- pango_item_free(i->data);
-
- g_list_free (items);
-
- gdk_threads_leave ();
-
- return (*env)->NewObject (env,
- glyphVector_class,
- glyphVector_ctor,
- java_extents, java_codes,
- font, fontRenderContext);
+ gdk_threads_leave();
}
+
JNIEXPORT void JNICALL
Java_gnu_java_awt_peer_gtk_GdkFontPeer_getFontMetrics
(JNIEnv *env, jobject java_font, jdoubleArray java_metrics)
diff --git a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkGraphics2D.c b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkGraphics2D.c
deleted file mode 100644
index 56c13b6c1..000000000
--- a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkGraphics2D.c
+++ /dev/null
@@ -1,1898 +0,0 @@
-/* gnu_java_awt_peer_gtk_GdkGraphics2d.c
- Copyright (C) 2003, 2005, 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-#include "jcl.h"
-#include "gdkfont.h"
-#include "gnu_java_awt_peer_gtk_GdkGraphics2D.h"
-#include <gdk/gdktypes.h>
-#include <gdk/gdkprivate.h>
-#include <gdk/gdkx.h>
-#include <X11/extensions/Xrender.h>
-
-#include <gdk-pixbuf/gdk-pixbuf.h>
-#include <gdk-pixbuf/gdk-pixdata.h>
-
-#include <cairo-ft.h>
-#include <cairo-xlib.h>
-
-#include <stdio.h>
-#include <stdlib.h>
-
-struct state_table *cp_gtk_native_graphics2d_state_table;
-
-/*
- * AWT applications may call Graphics methods from threads other than
- * the GDK main thread, so we must call XFlush after each batch of
- * drawing operations, otherwise animations flicker. Flushing after
- * every graphics operation is excessive and negatively affects
- * performance (PR 26486). We set the maximum frequency to 50 times
- * per second, or a minimum period of 20 milliseconds between calls to
- * XFlush. See gnu.classpath.examples.awt.AnimationApplet for an
- * example applet that requires these XFlush calls.
- */
-
-static short flush_scheduled = 0;
-
-static gboolean flush (gpointer data __attribute__((unused)))
-{
- gdk_threads_enter ();
-
- XFlush (GDK_DISPLAY ());
- flush_scheduled = 0;
-
- gdk_threads_leave ();
-
- return FALSE;
-}
-
-/* The minimum time period between calls to XFlush, in
- milliseconds. */
-#define MINIMUM_FLUSH_PERIOD 20
-
-/* schedule_flush must be called with the GDK lock held. */
-static void
-schedule_flush ()
-{
- if (!flush_scheduled)
- {
- g_timeout_add (MINIMUM_FLUSH_PERIOD, flush, NULL);
- flush_scheduled = 1;
- }
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_initStaticState
- (JNIEnv *env, jclass clazz)
-{
- gdk_threads_enter();
-
- NSA_G2D_INIT (env, clazz);
-
- gdk_threads_leave();
-}
-
-/* these public final constants are part of the java2d public API, so we
- write them explicitly here to save fetching them from the constant pool
- all the time. */
-
-#ifndef min
-#define min(x,y) ((x) < (y) ? (x) : (y))
-#endif
-
-enum java_awt_alpha_composite_rule
- {
- java_awt_alpha_composite_CLEAR = 1,
- java_awt_alpha_composite_SRC = 2,
- java_awt_alpha_composite_SRC_OVER = 3,
- java_awt_alpha_composite_DST_OVER = 4,
- java_awt_alpha_composite_SRC_IN = 5,
- java_awt_alpha_composite_DST_IN = 6,
- java_awt_alpha_composite_SRC_OUT = 7,
- java_awt_alpha_composite_DST_OUT = 8,
- java_awt_alpha_composite_DST = 9,
- java_awt_alpha_composite_SRC_ATOP = 10,
- java_awt_alpha_composite_DST_ATOP = 11,
- java_awt_alpha_composite_XOR = 12
- };
-
-enum java_awt_basic_stroke_join_rule
- {
- java_awt_basic_stroke_JOIN_MITER = 0,
- java_awt_basic_stroke_JOIN_ROUND = 1,
- java_awt_basic_stroke_JOIN_BEVEL = 2
- };
-
-enum java_awt_basic_stroke_cap_rule
- {
- java_awt_basic_stroke_CAP_BUTT = 0,
- java_awt_basic_stroke_CAP_ROUND = 1,
- java_awt_basic_stroke_CAP_SQUARE = 2
- };
-
-enum java_awt_geom_path_iterator_winding_rule
- {
- java_awt_geom_path_iterator_WIND_EVEN_ODD = 0,
- java_awt_geom_path_iterator_WIND_NON_ZERO = 1
- };
-
-enum java_awt_rendering_hints_filter
- {
- java_awt_rendering_hints_VALUE_INTERPOLATION_NEAREST_NEIGHBOR = 0,
- java_awt_rendering_hints_VALUE_INTERPOLATION_BILINEAR = 1,
- java_awt_rendering_hints_VALUE_ALPHA_INTERPOLATION_SPEED = 2,
- java_awt_rendering_hints_VALUE_ALPHA_INTERPOLATION_QUALITY = 3,
- java_awt_rendering_hints_VALUE_ALPHA_INTERPOLATION_DEFAULT = 4
-
- };
-
-static int
-peer_is_disposed(JNIEnv *env, jobject obj)
-{
- static jfieldID fid = NULL;
- jclass cls;
- jobject peer;
-
- if (fid == NULL)
- {
- cls = (*env)->GetObjectClass(env, obj);
- fid = (*env)->GetFieldID(env, cls, "component",
- "Lgnu/java/awt/peer/gtk/GtkComponentPeer;");
- }
- g_assert(fid != NULL);
- peer = (*env)->GetObjectField(env, obj, fid);
- if (peer == NULL || NSA_GET_PTR (env, peer) != NULL)
- return 0;
- else
- return 1;
-}
-
-static void
-grab_current_drawable (GtkWidget *widget, GdkDrawable **draw, GdkWindow **win)
-{
- g_assert (widget != NULL);
- g_assert (draw != NULL);
- g_assert (win != NULL);
-
- *win = widget->window;
-
- *draw = *win;
- gdk_window_get_internal_paint_info (*win, draw, 0, 0);
- g_object_ref (*draw);
-}
-
-
-static int
-x_server_has_render_extension (void)
-{
- int ev = 0, err = 0;
- return (int) XRenderQueryExtension (GDK_DISPLAY (), &ev, &err);
-}
-
-static void
-init_graphics2d_as_pixbuf (struct graphics2d *gr)
-{
- gint width, height;
- gint bits_per_sample = 8;
- gint total_channels = 4;
- gboolean has_alpha = TRUE;
-
- g_assert (gr != NULL);
- g_assert (gr->drawable != NULL);
-
- if (gr->debug) printf ("initializing graphics2d as pixbuf\n");
- gdk_drawable_get_size (gr->drawable, &width, &height);
- gr->drawbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB,
- has_alpha, bits_per_sample,
- width, height);
- g_assert (gr->drawbuf != NULL);
- g_assert (gdk_pixbuf_get_bits_per_sample (gr->drawbuf) == bits_per_sample);
- g_assert (gdk_pixbuf_get_n_channels (gr->drawbuf) == total_channels);
-
- gr->surface = cairo_image_surface_create_for_data (gdk_pixbuf_get_pixels (gr->drawbuf),
- CAIRO_FORMAT_ARGB32,
- gdk_pixbuf_get_width (gr->drawbuf),
- gdk_pixbuf_get_height (gr->drawbuf),
- gdk_pixbuf_get_rowstride (gr->drawbuf));
- g_assert (gr->surface != NULL);
- gr->mode = MODE_DRAWABLE_NO_RENDER;
- if (gr->cr != NULL)
- cairo_destroy (gr->cr);
- gr->cr = cairo_create (gr->surface);
-}
-
-static void
-init_graphics2d_as_renderable (struct graphics2d *gr)
-{
- Drawable draw;
- Display * dpy;
- Visual * vis;
-
- g_assert (gr != NULL);
- g_assert (gr->drawable != NULL);
-
- gr->drawbuf = NULL;
-
- if (gr->debug) printf ("initializing graphics2d as renderable\n");
- draw = gdk_x11_drawable_get_xid (gr->drawable);
-
- dpy = gdk_x11_drawable_get_xdisplay (gr->drawable);
- g_assert (dpy != NULL);
-
- vis = gdk_x11_visual_get_xvisual (gdk_drawable_get_visual (gr->drawable));
- g_assert (vis != NULL);
-
- gr->surface = cairo_xlib_surface_create (dpy, draw, vis, gr->width, gr->height);
- g_assert (gr->surface != NULL);
- gr->mode = MODE_DRAWABLE_WITH_RENDER;
- if (gr->cr != NULL)
- cairo_destroy (gr->cr);
- gr->cr = cairo_create (gr->surface);
-}
-
-static void
-begin_drawing_operation (JNIEnv *env, struct graphics2d * gr)
-{
- cairo_status_t cst = cairo_status (gr->cr);
- if (cst != CAIRO_STATUS_SUCCESS)
- {
- const char *detail = cairo_status_to_string (cst);
- JCL_ThrowException (env, "java/lang/InternalError", detail);
- (*env)->ExceptionDescribe (env);
- return;
- }
-
- switch (gr->mode)
- {
- case MODE_DRAWABLE_WITH_RENDER:
- break;
-
- case MODE_DRAWABLE_NO_RENDER:
- {
-
- gint drawable_width, drawable_height;
- gint pixbuf_width, pixbuf_height;
- gint width, height;
-
- gdk_drawable_get_size (gr->drawable, &drawable_width, &drawable_height);
- pixbuf_width = gdk_pixbuf_get_width (gr->drawbuf);
- pixbuf_height = gdk_pixbuf_get_height (gr->drawbuf);
- width = min (drawable_width, pixbuf_width);
- height = min (drawable_height, pixbuf_height);
-
- gdk_pixbuf_get_from_drawable (gr->drawbuf, /* destination pixbuf */
- gr->drawable,
- NULL, /* colormap */
- 0, 0, 0, 0,
- width, height);
-
- if (gr->debug) printf ("copied (%d, %d) pixels from GDK drawable to pixbuf\n",
- width, height);
- }
- break;
-
- case MODE_JAVA_ARRAY:
- {
- jboolean isCopy;
- gr->javabuf = (*env)->GetPrimitiveArrayCritical (env, gr->jarray, &isCopy);
- gr->isCopy |= isCopy;
- if (gr->isCopy)
- {
- /* Make sure that the pixel buffer copy is already initalized,
- i.e. we already failed to get direct access in initState. */
- g_assert (gr->javabuf_copy != NULL);
- memcpy (gr->javabuf_copy, gr->javabuf, gr->width * gr->height * 4);
- }
- }
- break;
- }
-}
-
-static void
-end_drawing_operation (JNIEnv *env, struct graphics2d * gr)
-{
- cairo_status_t cst = cairo_status (gr->cr);
- if (cst != CAIRO_STATUS_SUCCESS)
- {
- /* Report error. */
- const char *detail = cairo_status_to_string (cst);
- JCL_ThrowException (env, "java/lang/InternalError", detail);
- (*env)->ExceptionDescribe (env);
-
- /* Recreate cairo status. */
- cairo_destroy (gr->cr);
- gr->cr = cairo_create (gr->surface);
- return;
- }
-
- switch (gr->mode)
- {
- case MODE_DRAWABLE_WITH_RENDER:
- break;
-
- case MODE_DRAWABLE_NO_RENDER:
- {
-
- gint drawable_width, drawable_height;
- gint pixbuf_width, pixbuf_height;
- gint width, height;
-
- gdk_drawable_get_size (gr->drawable, &drawable_width, &drawable_height);
- pixbuf_width = gdk_pixbuf_get_width (gr->drawbuf);
- pixbuf_height = gdk_pixbuf_get_height (gr->drawbuf);
- width = min (drawable_width, pixbuf_width);
- height = min (drawable_height, pixbuf_height);
-
- gdk_draw_pixbuf (gr->drawable, NULL, gr->drawbuf,
- 0, 0, 0, 0,
- width, height,
- GDK_RGB_DITHER_NORMAL, 0, 0);
-
- if (gr->debug) printf ("copied (%d, %d) pixels from pixbuf to GDK drawable\n",
- width, height);
- }
- break;
-
- case MODE_JAVA_ARRAY:
- if (gr->isCopy)
- memcpy (gr->javabuf, gr->javabuf_copy, gr->width * gr->height * 4);
- (*env)->ReleasePrimitiveArrayCritical (env, gr->jarray, gr->javabuf, JNI_COMMIT);
- }
-
- schedule_flush ();
-}
-
-
-static void
-update_pattern_transform (struct graphics2d *gr)
-{
- cairo_matrix_t mat;
-
- g_assert (gr != NULL);
- if (gr->pattern == NULL)
- return;
-
- cairo_get_matrix (gr->cr, &mat);
- cairo_pattern_set_matrix (gr->pattern, &mat);
-}
-
-static void
-check_for_debug (struct graphics2d *gr)
-{
- gr->debug = (gboolean)(getenv("DEBUGJ2D") != NULL);
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_copyState
- (JNIEnv *env, jobject obj, jobject old)
-{
- struct graphics2d *g = NULL, *g_old = NULL;
-
- gdk_threads_enter();
-
- g = (struct graphics2d *) g_malloc (sizeof (struct graphics2d));
- g_assert (g != NULL);
- memset (g, 0, sizeof(struct graphics2d));
-
- g_old = (struct graphics2d *) NSA_GET_G2D_PTR (env, old);
- g_assert (g_old != NULL);
-
- if (g_old->debug) printf ("copying state from existing graphics2d\n");
-
- g->debug = g_old->debug;
- g->mode = g_old->mode;
-
- g->width = g_old->width;
- g->height = g_old->height;
-
- if (g_old->mode == MODE_JAVA_ARRAY)
- {
- jint size = g->width * g->height * 4;
-
- g->jarray = (*env)->NewGlobalRef (env, g_old->jarray);
- g->javabuf = (*env)->GetIntArrayElements (env, g->jarray, &g->isCopy);
- g->isCopy = JNI_TRUE;
- g->javabuf_copy = (jint *) g_malloc (size);
- memcpy (g->javabuf_copy, g->javabuf, size);
- g->surface = cairo_image_surface_create_for_data ((unsigned char *) g->javabuf,
- CAIRO_FORMAT_ARGB32,
- g->width,
- g->height,
- g->width * 4);
- g_assert (g->surface != NULL);
- g->cr = cairo_create (g->surface);
- g_assert (g->cr != NULL);
- (*env)->ReleaseIntArrayElements (env, g->jarray, g->javabuf, JNI_ABORT);
- }
- else
- {
- g->drawable = g_old->drawable;
- g_object_ref (g->drawable);
-
- if (x_server_has_render_extension ())
- init_graphics2d_as_renderable (g);
- else
- init_graphics2d_as_pixbuf (g);
- }
-
- if (g->pattern)
- cairo_pattern_set_filter (g->pattern, CAIRO_FILTER_FAST);
-
- NSA_SET_G2D_PTR (env, obj, g);
-
- gdk_threads_leave();
-}
-
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_initState___3III
-(JNIEnv *env, jobject obj, jintArray jarr, jint width, jint height)
-{
- struct graphics2d *gr = NULL;
- jint *cairobuf = NULL;
-
- gdk_threads_enter();
-
- gr = (struct graphics2d *) g_malloc (sizeof (struct graphics2d));
- g_assert (gr != NULL);
- memset (gr, 0, sizeof(struct graphics2d));
-
- check_for_debug (gr);
-
- if (gr->debug) printf ("constructing java-backed image of size (%d,%d)\n",
- width, height);
-
- gr->width = width;
- gr->height = height;
- gr->jarray = (*env)->NewGlobalRef(env, jarr);
- gr->javabuf = (*env)->GetPrimitiveArrayCritical (env, gr->jarray, &gr->isCopy);
- if (gr->isCopy)
- {
- /* We didn't get direct access to the pixel buffer, so we'll have to
- maintain a separate copy for Cairo. */
- jint size = gr->width * gr->height * 4;
- gr->javabuf_copy = (jint *) g_malloc (size);
- memcpy (gr->javabuf_copy, gr->javabuf, size);
- cairobuf = gr->javabuf_copy;
- }
- else
- {
- /* Have Cairo write directly to the Java array. */
- cairobuf = gr->javabuf;
- }
- gr->surface = cairo_image_surface_create_for_data ((unsigned char *) cairobuf,
- CAIRO_FORMAT_ARGB32,
- gr->width,
- gr->height,
- gr->width * 4);
- g_assert (gr->surface != NULL);
- gr->cr = cairo_create (gr->surface);
- g_assert (gr->cr != NULL);
- (*env)->ReleasePrimitiveArrayCritical (env, gr->jarray, gr->javabuf, JNI_COMMIT);
-
- gr->mode = MODE_JAVA_ARRAY;
-
- if (gr->debug) printf ("constructed java-backed image of size (%d,%d)\n",
- width, height);
-
- NSA_SET_G2D_PTR (env, obj, gr);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_initState__II
- (JNIEnv *env, jobject obj, jint width, jint height)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- gr = (struct graphics2d *) g_malloc (sizeof (struct graphics2d));
- g_assert (gr != NULL);
- memset (gr, 0, sizeof(struct graphics2d));
-
- check_for_debug (gr);
-
- if (gr->debug) printf ("constructing offscreen drawable of size (%d,%d)\n",
- width, height);
-
- gr->drawable = (GdkDrawable *) gdk_pixmap_new (NULL, width, height,
- gdk_rgb_get_visual ()->depth);
- g_assert (gr->drawable != NULL);
-
- gr->width = width;
- gr->height = height;
-
- if (x_server_has_render_extension ())
- init_graphics2d_as_renderable (gr);
- else
- init_graphics2d_as_pixbuf (gr);
-
- if (gr->debug) printf ("constructed offscreen drawable of size (%d,%d)\n",
- width, height);
- NSA_SET_G2D_PTR (env, obj, gr);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_gdkDrawDrawable
- (JNIEnv *env, jobject obj, jobject other, jint x, jint y)
-{
- struct graphics2d *src = NULL;
- struct graphics2d *dst = NULL;
- gint s_height;
- gint s_width;
- gint d_height;
- gint d_width;
- gint height;
- gint width;
- cairo_matrix_t matrix;
- cairo_operator_t tmp_op;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- src = (struct graphics2d *)NSA_GET_G2D_PTR (env, other);
- dst = (struct graphics2d *)NSA_GET_G2D_PTR (env, obj);
- g_assert (src != NULL);
- g_assert (dst != NULL);
-
- if (src->debug) printf ("copying from offscreen drawable\n");
-
- begin_drawing_operation(env, dst);
-
- /* gdk_flush(); */
-
- if (!GDK_IS_DRAWABLE (src->drawable) ||
- !GDK_IS_DRAWABLE (dst->drawable))
- {
- gdk_threads_leave ();
- return;
- }
-
- gdk_drawable_get_size (src->drawable, &s_width, &s_height);
- gdk_drawable_get_size (dst->drawable, &d_width, &d_height);
- width = min (s_width, d_width);
- height = min (s_height, d_height);
-
- cairo_get_matrix (src->cr, &matrix);
- cairo_matrix_translate (&matrix, (double)-x, (double)-y);
- if (src->pattern)
- cairo_pattern_set_matrix (src->pattern, &matrix);
- tmp_op = cairo_get_operator (dst->cr);
- cairo_set_operator(dst->cr, CAIRO_OPERATOR_SOURCE);
- cairo_set_source_surface (dst->cr, src->surface, 0, 0);
- cairo_paint (dst->cr);
- cairo_set_operator(dst->cr, tmp_op);
-
- cairo_matrix_translate (&matrix, (double)x, (double)y);
- if (src->pattern)
- cairo_pattern_set_matrix (src->pattern, &matrix);
-
- end_drawing_operation(env, dst);
-
- if (src->debug) printf ("copied %d x %d pixels from offscreen drawable\n", width, height);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_initState__Lgnu_java_awt_peer_gtk_GtkComponentPeer_2
- (JNIEnv *env, jobject obj, jobject peer)
-{
- struct graphics2d *gr = NULL;
- GtkWidget *widget = NULL;
- void *ptr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- ptr = NSA_GET_PTR (env, peer);
- g_assert (ptr != NULL);
-
- gr = (struct graphics2d *) g_malloc (sizeof (struct graphics2d));
- g_assert (gr != NULL);
- memset (gr, 0, sizeof(struct graphics2d));
-
- check_for_debug (gr);
-
- widget = GTK_WIDGET (ptr);
- g_assert (widget != NULL);
-
- grab_current_drawable (widget, &(gr->drawable), &(gr->win));
- g_assert (gr->drawable != NULL);
-
- gr->width = widget->allocation.width;
- gr->height = widget->allocation.height;
-
- if (x_server_has_render_extension ())
- init_graphics2d_as_renderable (gr);
- else
- init_graphics2d_as_pixbuf (gr);
-
- NSA_SET_G2D_PTR (env, obj, gr);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_dispose
- (JNIEnv *env, jobject obj)
-{
- struct graphics2d *gr = NULL;
-
- gr = (struct graphics2d *) NSA_DEL_G2D_PTR (env, obj);
-
- /* dispose has been called more than once */
- if (gr == NULL)
- return;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- if (gr->surface)
- cairo_surface_destroy (gr->surface);
- gr->surface = NULL;
-
- cairo_destroy (gr->cr);
- gr->cr = NULL;
-
- if (gr->drawbuf)
- g_object_unref (gr->drawbuf);
- gr->drawbuf = NULL;
-
- if (gr->drawable)
- g_object_unref (gr->drawable);
- gr->drawable = NULL;
-
- if (gr->pattern)
- cairo_pattern_destroy (gr->pattern);
- gr->pattern = NULL;
-
- if (gr->pattern_surface)
- cairo_surface_destroy (gr->pattern_surface);
- gr->pattern_surface = NULL;
-
- if (gr->pattern_pixels)
- g_free (gr->pattern_pixels);
- gr->pattern_pixels = NULL;
-
- if (gr->mode == MODE_JAVA_ARRAY)
- {
- (*env)->DeleteGlobalRef (env, gr->jarray);
- if (gr->javabuf_copy)
- g_free (gr->javabuf_copy);
- gr->javabuf_copy = NULL;
- }
-
- if (gr->debug) printf ("disposed of graphics2d\n");
-
- g_free (gr);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_setGradient
- (JNIEnv *env, jobject obj,
- jdouble x1, jdouble y1,
- jdouble x2, jdouble y2,
- jint r1, jint g1, jint b1, jint a1,
- jint r2, jint g2, jint b2, jint a2,
- jboolean cyclic)
-{
- struct graphics2d *gr = NULL;
- cairo_surface_t *surf = NULL;
- cairo_t *cr2 = NULL;
- cairo_matrix_t mat;
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- if (gr->debug)
- printf ("setGradient (%f,%f) -> (%f,%f); (%d,%d,%d,%d) -> (%d,%d,%d,%d)\n",
- x1, y1,
- x2, y2,
- r1, g1, b1, a1,
- r2, g2, b2, a2);
-
- if (cyclic)
- surf = cairo_surface_create_similar (gr->surface, CAIRO_FORMAT_ARGB32, 3, 2);
- else
- surf = cairo_surface_create_similar (gr->surface, CAIRO_FORMAT_ARGB32, 2, 2);
- g_assert (surf != NULL);
-
- cr2 = cairo_create (surf);
-
- cairo_identity_matrix (cr2);
-
- cairo_set_source_rgba (cr2, r1 / 255.0, g1 / 255.0, b1 / 255.0, a1 / 255.0);
- cairo_rectangle (cr2, 0, 0, 1, 2);
- cairo_fill (cr2);
-
- cairo_set_source_rgba (cr2, r2 / 255.0, g2 / 255.0, b2 / 255.0, a2 / 255.0);
- cairo_rectangle (cr2, 1, 0, 1, 2);
- cairo_fill (cr2);
-
- if (cyclic)
- {
- cairo_set_source_rgba (cr2, r1 / 255.0, g1 / 255.0, b1 / 255.0, a1 / 255.0);
- cairo_rectangle (cr2, 2, 0, 1, 2);
- cairo_fill (cr2);
- }
-
- cairo_matrix_init_identity (&mat);
-
- /*
- consider the vector [x2 - x1, y2 - y1] = [p,q]
-
- this is a line in space starting at an 'origin' x1, y1.
-
- it can also be thought of as a "transformed" unit vector in either the
- x or y directions. we have just *drawn* our gradient as a unit vector
- (well, a 2-3x unit vector) in the x dimension. so what we want to know
- is which transformation turns our existing unit vector into [p,q].
-
- which means solving for M in
-
- [p,q] = M[1,0]
-
- [p,q] = |a b| [1,0]
- |c d|
-
- [p,q] = [a,c], with b = d = 0.
-
- what does this mean? it means that our gradient is 1-dimensional; as
- you move through the x axis of our 2 or 3 pixel gradient from logical
- x positions 0 to 1, the transformation of your x coordinate under the
- matrix M causes you to accumulate both x and y values in fill
- space. the y value of a gradient coordinate is ignored, since the
- gradient is one dimensional. which is correct.
-
- unfortunately we want the opposite transformation, it seems, because of
- the way cairo is going to use this transformation. I'm a bit confused by
- that, but it seems to work right, so we take reciprocals of values and
- negate offsets. oh well.
-
- */
- {
- double a = (x2 - x1 == 0.) ? 0. : ((cyclic ? 3.0 : 2.0) / (x2 - x1));
- double c = (y2 - y1 == 0.) ? 0. : (1. / (y2 - y1));
- double dx = (x1 == 0.) ? 0. : 1. / x1;
- double dy = (y1 == 0.) ? 0. : 1. / y1;
- cairo_pattern_t *p;
-
- cairo_matrix_init (&mat,
- a, 0.,
- c, 0.,
- dx, dy);
-
- p = cairo_pattern_create_for_surface (surf);
- cairo_pattern_set_matrix (p, &mat);
- cairo_pattern_set_filter (p, CAIRO_FILTER_BILINEAR);
- }
-
- /* FIXME: repeating gradients (not to mention hold gradients) don't seem to work. */
- /* cairo_surface_set_repeat (surf, cyclic ? 1 : 0); */
-
- if (gr->pattern)
- cairo_pattern_destroy (gr->pattern);
-
- if (gr->pattern_surface)
- cairo_surface_destroy (gr->pattern_surface);
-
- if (gr->pattern_pixels)
- g_free (gr->pattern_pixels);
-
- gr->pattern_pixels = NULL;
- gr->pattern_surface = surf;
- gr->pattern = cairo_pattern_create_for_surface(surf);
-
- cairo_set_source (gr->cr, gr->pattern);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_setTexturePixels
- (JNIEnv *env, jobject obj, jintArray jarr, jint w, jint h, jint stride)
-{
- struct graphics2d *gr = NULL;
- jint *jpixels = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
-
- if (gr->debug)
- printf ("setTexturePixels (%d pixels, %dx%d, stride: %d)\n",
- (*env)->GetArrayLength (env, jarr), w, h, stride);
-
- if (gr->pattern)
- cairo_pattern_destroy (gr->pattern);
-
- if (gr->pattern_surface)
- cairo_surface_destroy (gr->pattern_surface);
-
- if (gr->pattern_pixels)
- g_free (gr->pattern_pixels);
-
- gr->pattern = NULL;
- gr->pattern_surface = NULL;
- gr->pattern_pixels = NULL;
-
- gr->pattern_pixels = (char *) g_malloc (h * stride * 4);
- g_assert (gr->pattern_pixels != NULL);
-
- jpixels = (*env)->GetIntArrayElements (env, jarr, NULL);
- g_assert (jpixels != NULL);
- memcpy (gr->pattern_pixels, jpixels, h * stride * 4);
- (*env)->ReleaseIntArrayElements (env, jarr, jpixels, 0);
-
- gr->pattern_surface = cairo_image_surface_create_for_data ((unsigned char *)gr->pattern_pixels,
- CAIRO_FORMAT_ARGB32,
- w, h, stride * 4);
- g_assert (gr->pattern_surface != NULL);
- gr->pattern = cairo_pattern_create_for_surface (gr->pattern_surface);
- g_assert (gr->pattern != NULL);
- cairo_pattern_set_extend (gr->pattern, CAIRO_EXTEND_REPEAT);
- cairo_set_source (gr->cr, gr->pattern);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_drawPixels
- (JNIEnv *env, jobject obj, jintArray java_pixels,
- jint w, jint h, jint stride, jdoubleArray java_matrix)
-{
- struct graphics2d *gr = NULL;
- jint *native_pixels = NULL;
- jdouble *native_matrix = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
-
- if (gr->debug)
- printf ("drawPixels (%d pixels, %dx%d, stride: %d)\n",
- (*env)->GetArrayLength (env, java_pixels), w, h, stride);
-
- native_pixels = (*env)->GetIntArrayElements (env, java_pixels, NULL);
- native_matrix = (*env)->GetDoubleArrayElements (env, java_matrix, NULL);
- g_assert (native_pixels != NULL);
- g_assert (native_matrix != NULL);
- g_assert ((*env)->GetArrayLength (env, java_matrix) == 6);
-
- begin_drawing_operation (env, gr);
-
- {
- cairo_matrix_t mat;
- cairo_pattern_t *p;
- cairo_surface_t *surf = cairo_image_surface_create_for_data ((unsigned char *)native_pixels,
- CAIRO_FORMAT_ARGB32,
- w, h, stride * 4);
- cairo_matrix_init_identity (&mat);
- cairo_matrix_init (&mat,
- native_matrix[0], native_matrix[1],
- native_matrix[2], native_matrix[3],
- native_matrix[4], native_matrix[5]);
-
- p = cairo_pattern_create_for_surface (surf);
- cairo_pattern_set_matrix (p, &mat);
- if (gr->pattern)
- cairo_pattern_set_filter (p, cairo_pattern_get_filter (gr->pattern));
- cairo_set_source (gr->cr, p);
- cairo_paint (gr->cr);
- cairo_pattern_destroy (p);
- cairo_surface_destroy (surf);
- }
-
- end_drawing_operation (env, gr);
-
- (*env)->ReleaseIntArrayElements (env, java_pixels, native_pixels, 0);
- (*env)->ReleaseDoubleArrayElements (env, java_matrix, native_matrix, 0);
-
- gdk_threads_leave();
-}
-
-/* passthrough methods to cairo */
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSave
- (JNIEnv *env, jobject obj)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_save\n");
- cairo_save (gr->cr);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoRestore
- (JNIEnv *env, jobject obj)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_restore\n");
- cairo_restore (gr->cr);
- update_pattern_transform (gr);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetMatrix
- (JNIEnv *env, jobject obj, jdoubleArray java_matrix)
-{
- struct graphics2d *gr = NULL;
- jdouble *native_matrix = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
-
- native_matrix = (*env)->GetDoubleArrayElements (env, java_matrix, NULL);
- g_assert (native_matrix != NULL);
- g_assert ((*env)->GetArrayLength (env, java_matrix) == 6);
-
- if (gr->debug)
- printf ("cairo_matrix_init [ %f, %f, %f, %f, %f, %f ]\n",
- native_matrix[0], native_matrix[1],
- native_matrix[2], native_matrix[3],
- native_matrix[4], native_matrix[5]);
-
- {
- cairo_matrix_t mat;
-
- cairo_matrix_init_identity (&mat);
- cairo_matrix_init (&mat,
- native_matrix[0], native_matrix[1],
- native_matrix[2], native_matrix[3],
- native_matrix[4], native_matrix[5]);
- cairo_set_matrix (gr->cr, &mat);
- }
-
- (*env)->ReleaseDoubleArrayElements (env, java_matrix, native_matrix, 0);
- update_pattern_transform (gr);
-
- gdk_threads_leave();
-}
-
-static void
-install_font_peer(cairo_t *cr,
- struct peerfont *pfont,
- int debug)
-{
- cairo_font_face_t *ft;
- FT_Face face = NULL;
-
- g_assert(cr != NULL);
- g_assert(pfont != NULL);
-
- if (pfont->graphics_resource == NULL)
- {
- face = pango_ft2_font_get_face (pfont->font);
- g_assert (face != NULL);
-
- ft = cairo_ft_font_face_create_for_ft_face (face, 0);
- g_assert (ft != NULL);
-
- if (debug) printf ("install_font_peer made new cairo font for '%s' at %f\n",
- face->family_name,
- (pango_font_description_get_size (pfont->desc) /
- (double)PANGO_SCALE));
-
- cairo_set_font_face (cr, ft);
- cairo_font_face_destroy (ft);
- cairo_set_font_size (cr,
- (pango_font_description_get_size (pfont->desc) /
- (double)PANGO_SCALE));
- ft = cairo_get_font_face (cr);
- pfont->graphics_resource = ft;
- }
- else
- {
- if (debug) printf ("install_font_peer reused existing font resource"
- " for '%s' at %f\n",
- pango_font_description_get_family(pfont->desc),
- (pango_font_description_get_size (pfont->desc) /
- (double)PANGO_SCALE));
- ft = (cairo_font_face_t *) pfont->graphics_resource;
- cairo_set_font_face (cr, ft);
- cairo_set_font_size (cr,
- (pango_font_description_get_size (pfont->desc) /
- (double)PANGO_SCALE));
- }
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_releasePeerGraphicsResource
- (JNIEnv *env, jclass clazz __attribute__ ((unused)), jobject java_font)
-{
- struct peerfont *pfont = NULL;
-
- gdk_threads_enter();
-
- g_assert(java_font != NULL);
-
- pfont = (struct peerfont *) NSA_GET_FONT_PTR (env, java_font);
- g_assert (pfont != NULL);
- if (pfont->graphics_resource != NULL)
- {
- cairo_font_face_destroy ((cairo_font_face_t *) pfont->graphics_resource);
- pfont->graphics_resource = NULL;
- }
-
- gdk_threads_leave();
-}
-
-static void
-paint_glyph_run(JNIEnv *env,
- struct graphics2d *gr,
- cairo_glyph_t **glyphs,
- gint *n_glyphs,
- PangoLayoutRun *run)
-{
- gint i = 0;
- gint x = 0, y = 0;
-
- g_assert (gr != NULL);
- g_assert (glyphs != NULL);
- g_assert (n_glyphs != NULL);
- g_assert (run != NULL);
-
- if (run->glyphs != NULL && run->glyphs->num_glyphs > 0)
- {
- if (*n_glyphs < run->glyphs->num_glyphs)
- {
- *glyphs = g_realloc(*glyphs,
- (sizeof(cairo_glyph_t)
- * run->glyphs->num_glyphs));
- *n_glyphs = run->glyphs->num_glyphs;
- }
-
- g_assert (*glyphs != NULL);
-
- if (gr->debug) printf ("painting %d glyphs: ", run->glyphs->num_glyphs);
-
- for (i = 0; i < run->glyphs->num_glyphs; ++i)
- {
- (*glyphs)[i].index = run->glyphs->glyphs[i].glyph;
-
- (*glyphs)[i].x =
- ((double) (x + run->glyphs->glyphs[i].geometry.x_offset))
- / ((double) PANGO_SCALE);
-
- (*glyphs)[i].y =
- ((double) (y + run->glyphs->glyphs[i].geometry.y_offset))
- / ((double) PANGO_SCALE);
-
- if (gr->debug) printf(" (%ld @ %f,%f)",
- (*glyphs)[i].index,
- (*glyphs)[i].x,
- (*glyphs)[i].y);
-
- x += run->glyphs->glyphs[i].geometry.width;
- }
-
- if (gr->debug) printf("\n");
- begin_drawing_operation (env, gr);
- cairo_show_glyphs (gr->cr, *glyphs, run->glyphs->num_glyphs);
- end_drawing_operation (env, gr);
- }
-}
-
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoDrawGlyphVector
- (JNIEnv *env, jobject obj,
- jobject font,
- jfloat x, jfloat y, jint n,
- jintArray java_codes,
- jfloatArray java_positions)
-{
-
- struct graphics2d *gr = NULL;
- struct peerfont *pfont = NULL;
- cairo_glyph_t *glyphs = NULL;
- int *native_codes;
- float *native_positions;
- jint i = 0;
-
- gdk_threads_enter ();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- g_assert (obj != NULL);
- g_assert (java_codes != NULL);
- g_assert (java_positions != NULL);
-
- gr = (struct graphics2d *)NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
-
- pfont = (struct peerfont *)NSA_GET_FONT_PTR (env, font);
- g_assert (pfont != NULL);
-
- install_font_peer(gr->cr, pfont, gr->debug);
-
- glyphs = g_malloc( sizeof(cairo_glyph_t) * n);
- g_assert (glyphs != NULL);
-
- native_codes = (*env)->GetIntArrayElements (env, java_codes, NULL);
- native_positions = (*env)->GetFloatArrayElements (env, java_positions, NULL);
-
- for (i = 0; i < n; ++i)
- {
- glyphs[i].index = native_codes[i];
- glyphs[i].x = x + native_positions[ 2*i ];
- glyphs[i].y = y + native_positions[ 2*i + 1];
- }
-
- (*env)->ReleaseFloatArrayElements (env, java_positions, native_positions, 0);
- (*env)->ReleaseIntArrayElements (env, java_codes, native_codes, 0);
-
- begin_drawing_operation (env, gr);
- cairo_show_glyphs (gr->cr, glyphs, n);
- end_drawing_operation (env, gr);
-
- g_free(glyphs);
-
- gdk_threads_leave ();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoDrawGdkTextLayout
- (JNIEnv *env, jobject obj, jobject java_layout, jfloat x, jfloat y)
-{
- /*
- * FIXME: Some day we expect either cairo or pango will know how to make
- * a pango layout paint to a cairo surface. that day is not yet here.
- */
-
- struct graphics2d *gr = NULL;
- struct textlayout *tl = NULL;
- PangoLayoutIter *i = NULL;
- PangoLayoutRun *run = NULL;
- cairo_glyph_t *glyphs = NULL;
- gint n_glyphs = 0;
-
- g_assert (obj != NULL);
- g_assert (java_layout != NULL);
-
- gr = (struct graphics2d *)NSA_GET_G2D_PTR (env, obj);
- tl = (struct textlayout *)NSA_GET_TEXT_LAYOUT_PTR (env, java_layout);
-
- g_assert (gr != NULL);
- g_assert (tl != NULL);
- g_assert (tl->pango_layout != NULL);
-
- if (gr->debug) printf ("painting pango layout\n");
-
- gdk_threads_enter ();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- i = pango_layout_get_iter (tl->pango_layout);
- g_assert (i != NULL);
-
- cairo_translate (gr->cr, x, y);
-
- do
- {
- run = pango_layout_iter_get_run (i);
- if (run != NULL)
- paint_glyph_run (env, gr, &glyphs, &n_glyphs, run);
- }
- while (pango_layout_iter_next_run (i));
-
- if (glyphs != NULL)
- g_free (glyphs);
-
- cairo_translate (gr->cr, -x, -y);
-
- pango_layout_iter_free (i);
-
- gdk_threads_leave ();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetOperator
- (JNIEnv *env, jobject obj, jint op)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_set_operator %d\n", op);
- switch ((enum java_awt_alpha_composite_rule) op)
- {
- case java_awt_alpha_composite_CLEAR:
- cairo_set_operator (gr->cr, CAIRO_OPERATOR_CLEAR);
- break;
-
- case java_awt_alpha_composite_SRC:
- cairo_set_operator (gr->cr, CAIRO_OPERATOR_SOURCE);
- break;
-
- case java_awt_alpha_composite_SRC_OVER:
- cairo_set_operator (gr->cr, CAIRO_OPERATOR_OVER);
- break;
-
- case java_awt_alpha_composite_DST_OVER:
- cairo_set_operator (gr->cr, CAIRO_OPERATOR_DEST_OVER);
- break;
-
- case java_awt_alpha_composite_SRC_IN:
- cairo_set_operator (gr->cr, CAIRO_OPERATOR_IN);
- break;
-
- case java_awt_alpha_composite_DST_IN:
- cairo_set_operator (gr->cr, CAIRO_OPERATOR_DEST_IN);
- break;
-
- case java_awt_alpha_composite_SRC_OUT:
- cairo_set_operator (gr->cr, CAIRO_OPERATOR_OUT);
- break;
-
- case java_awt_alpha_composite_DST_OUT:
- cairo_set_operator (gr->cr, CAIRO_OPERATOR_DEST_OUT);
- break;
-
- case java_awt_alpha_composite_DST:
- cairo_set_operator (gr->cr, CAIRO_OPERATOR_DEST);
- break;
-
- case java_awt_alpha_composite_SRC_ATOP:
- cairo_set_operator (gr->cr, CAIRO_OPERATOR_ATOP);
- break;
-
- case java_awt_alpha_composite_DST_ATOP:
- cairo_set_operator (gr->cr, CAIRO_OPERATOR_DEST_ATOP);
- break;
-
- case java_awt_alpha_composite_XOR:
- cairo_set_operator (gr->cr, CAIRO_OPERATOR_XOR);
- break;
- }
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetRGBAColor
- (JNIEnv *env, jobject obj, jdouble r, jdouble g, jdouble b, jdouble a)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
-
- /* this is a very weird fact: GDK Pixbufs and RENDER drawables consider
- colors in opposite pixel order. I have no idea why. thus when you
- draw to a PixBuf, you must exchange the R and B components of your
- color. */
-
- if (gr->debug)
- printf ("cairo_set_source_rgba (%f, %f, %f, %f)\n", r, g, b, a);
-
- if (gr->drawbuf)
- cairo_set_source_rgba (gr->cr, b, g, r, a);
- else
- cairo_set_source_rgba (gr->cr, r, g, b, a);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetFillRule
- (JNIEnv *env, jobject obj, jint rule)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- if (gr->debug) printf ("cairo_set_fill_rule %d\n", rule);
- g_assert (gr != NULL);
- switch ((enum java_awt_geom_path_iterator_winding_rule) rule)
- {
- case java_awt_geom_path_iterator_WIND_NON_ZERO:
- cairo_set_fill_rule (gr->cr, CAIRO_FILL_RULE_WINDING);
- break;
- case java_awt_geom_path_iterator_WIND_EVEN_ODD:
- cairo_set_fill_rule (gr->cr, CAIRO_FILL_RULE_EVEN_ODD);
- break;
- }
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetLineWidth
- (JNIEnv *env, jobject obj, jdouble width)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_set_line_width %f\n", width);
- cairo_set_line_width (gr->cr, width);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetLineCap
- (JNIEnv *env, jobject obj, jint cap)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_set_line_cap %d\n", cap);
- switch ((enum java_awt_basic_stroke_cap_rule) cap)
- {
- case java_awt_basic_stroke_CAP_BUTT:
- cairo_set_line_cap (gr->cr, CAIRO_LINE_CAP_BUTT);
- break;
-
- case java_awt_basic_stroke_CAP_ROUND:
- cairo_set_line_cap (gr->cr, CAIRO_LINE_CAP_ROUND);
- break;
-
- case java_awt_basic_stroke_CAP_SQUARE:
- cairo_set_line_cap (gr->cr, CAIRO_LINE_CAP_SQUARE);
- break;
- }
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetLineJoin
- (JNIEnv *env, jobject obj, jint join)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_set_line_join %d\n", join);
- switch ((enum java_awt_basic_stroke_join_rule) join)
- {
- case java_awt_basic_stroke_JOIN_MITER:
- cairo_set_line_join (gr->cr, CAIRO_LINE_JOIN_MITER);
- break;
-
- case java_awt_basic_stroke_JOIN_ROUND:
- cairo_set_line_join (gr->cr, CAIRO_LINE_JOIN_ROUND);
- break;
-
- case java_awt_basic_stroke_JOIN_BEVEL:
- cairo_set_line_join (gr->cr, CAIRO_LINE_JOIN_BEVEL);
- break;
- }
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetDash
- (JNIEnv *env, jobject obj, jdoubleArray dashes, jint ndash, jdouble offset)
-{
- struct graphics2d *gr = NULL;
- jdouble *dasharr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_set_dash\n");
- dasharr = (*env)->GetDoubleArrayElements (env, dashes, NULL);
- g_assert (dasharr != NULL);
- cairo_set_dash (gr->cr, dasharr, ndash, offset);
- (*env)->ReleaseDoubleArrayElements (env, dashes, dasharr, 0);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSetMiterLimit
- (JNIEnv *env, jobject obj, jdouble miter)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_set_miter_limit %f\n", miter);
- cairo_set_miter_limit (gr->cr, miter);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoNewPath
- (JNIEnv *env, jobject obj)
-{
- struct graphics2d *gr = NULL;
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- if (gr->debug) printf ("cairo_new_path\n");
- cairo_new_path (gr->cr);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoMoveTo
- (JNIEnv *env, jobject obj, jdouble x, jdouble y)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_move_to (%f, %f)\n", x, y);
- cairo_move_to (gr->cr, x, y);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoLineTo
- (JNIEnv *env, jobject obj, jdouble x, jdouble y)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_line_to (%f, %f)\n", x, y);
- cairo_line_to (gr->cr, x, y);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoCurveTo
- (JNIEnv *env, jobject obj, jdouble x1, jdouble y1, jdouble x2, jdouble y2, jdouble x3, jdouble y3)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug)
- printf ("cairo_curve_to (%f, %f), (%f, %f), (%f, %f)\n",
- x1, y1, x2, y2, x3, y3);
- cairo_curve_to (gr->cr, x1, y1, x2, y2, x3, y3);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoRelMoveTo
- (JNIEnv *env, jobject obj, jdouble dx, jdouble dy)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_rel_move_to (%f, %f)\n", dx, dy);
- cairo_rel_move_to (gr->cr, dx, dy);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoRelLineTo
- (JNIEnv *env, jobject obj, jdouble dx, jdouble dy)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_rel_line_to (%f, %f)\n", dx, dy);
- cairo_rel_line_to (gr->cr, dx, dy);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoRelCurveTo
- (JNIEnv *env, jobject obj, jdouble dx1, jdouble dy1, jdouble dx2, jdouble dy2, jdouble dx3, jdouble dy3)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug)
- printf ("cairo_rel_curve_to (%f, %f), (%f, %f), (%f, %f)\n",
- dx1, dy1, dx2, dy2, dx3, dy3);
- cairo_rel_curve_to (gr->cr, dx1, dy1, dx2, dy2, dx3, dy3);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoRectangle
- (JNIEnv *env, jobject obj, jdouble x, jdouble y, jdouble width, jdouble height)
-{
- struct graphics2d *gr = NULL;
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- if (gr->debug)
- printf ("cairo_rectangle (%f, %f) (%f, %f)\n", x, y, width, height);
- cairo_rectangle (gr->cr, x, y, width, height);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoClosePath
- (JNIEnv *env, jobject obj)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_close_path\n");
- cairo_close_path (gr->cr);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoStroke
- (JNIEnv *env, jobject obj)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_stroke\n");
- begin_drawing_operation (env, gr);
- cairo_stroke (gr->cr);
- end_drawing_operation (env, gr);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoFill
- (JNIEnv *env, jobject obj)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
- if (gr->debug) printf ("cairo_fill\n");
- begin_drawing_operation (env, gr);
- cairo_fill (gr->cr);
- end_drawing_operation (env, gr);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoClip
- (JNIEnv *env, jobject obj)
-{
- struct graphics2d *gr = NULL;
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- if (gr->debug) printf ("cairo_clip\n");
- begin_drawing_operation (env, gr);
- cairo_reset_clip (gr->cr);
- cairo_clip (gr->cr);
- end_drawing_operation (env, gr);
-
- gdk_threads_leave();
-}
-
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GdkGraphics2D_cairoSurfaceSetFilter
- (JNIEnv *env, jobject obj, jint filter)
-{
- struct graphics2d *gr = NULL;
-
- gdk_threads_enter();
-
- if (peer_is_disposed(env, obj))
- {
- gdk_threads_leave();
- return;
- }
-
- gr = (struct graphics2d *) NSA_GET_G2D_PTR (env, obj);
- g_assert (gr != NULL);
-
- if (gr->pattern == NULL)
- return;
-
- if (gr->debug) printf ("cairo_pattern_set_filter %d\n", filter);
- switch ((enum java_awt_rendering_hints_filter) filter)
- {
- case java_awt_rendering_hints_VALUE_INTERPOLATION_NEAREST_NEIGHBOR:
- cairo_pattern_set_filter (gr->pattern, CAIRO_FILTER_NEAREST);
- break;
- case java_awt_rendering_hints_VALUE_INTERPOLATION_BILINEAR:
- cairo_pattern_set_filter (gr->pattern, CAIRO_FILTER_BILINEAR);
- break;
- case java_awt_rendering_hints_VALUE_ALPHA_INTERPOLATION_SPEED:
- cairo_pattern_set_filter (gr->pattern, CAIRO_FILTER_FAST);
- break;
- case java_awt_rendering_hints_VALUE_ALPHA_INTERPOLATION_DEFAULT:
- cairo_pattern_set_filter (gr->pattern, CAIRO_FILTER_NEAREST);
- break;
- case java_awt_rendering_hints_VALUE_ALPHA_INTERPOLATION_QUALITY:
- cairo_pattern_set_filter (gr->pattern, CAIRO_FILTER_BEST);
- break;
- }
-
- gdk_threads_leave();
-}
diff --git a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.c b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.c
index 7662800f0..89adcd1e5 100644
--- a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.c
+++ b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.c
@@ -1,5 +1,5 @@
/* gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.c
- Copyright (C) 2004 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -35,9 +35,43 @@
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
+#include <glib.h>
+#include <gdk/gdk.h>
+
#include "gdkfont.h"
+#include "gdkdisplay.h"
#include "gnu_java_awt_peer_gtk_GdkGraphicsEnvironment.h"
+struct state_table *cp_gtk_native_display_state_table;
+
+jclass gdkGraphicsEnvironment_class;
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment_initStaticState
+(JNIEnv *env, jclass klazz __attribute__((unused)))
+{
+ gdkGraphicsEnvironment_class = (*env)->NewGlobalRef
+ (env, klazz);
+
+ NSA_DISPLAY_INIT(env, gdkGraphicsEnvironment_class);
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment_nativeInitState
+(JNIEnv *env, jobject obj)
+{
+ GdkDisplay *defaultDisplay;
+
+ gdk_threads_enter();
+
+ /* Retrieve the default display. */
+ defaultDisplay = gdk_display_get_default();
+
+ gdk_threads_leave();
+
+ /* Store display pointer in GdkGraphicsEnvironment instance. */
+ NSA_SET_DISPLAY_PTR(env, obj, (void *) defaultDisplay);
+}
static gint
cmp_families (const void *a, const void *b)
@@ -101,3 +135,109 @@ Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment_nativeGetNumFontFamilies
return num;
}
+
+JNIEXPORT jobjectArray JNICALL
+Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment_nativeGetScreenDevices
+(JNIEnv *env, jobject obj)
+{
+ jmethodID gdkScreenGraphicsDevice_ctor, gdkScreenGraphicsDevice_init;
+ jclass gdkScreenGraphicsDevice_class;
+ int numScreens = 0, i = 0;
+ GdkDisplay *display;
+ jobjectArray array;
+ jobject instance;
+
+ gdkScreenGraphicsDevice_class = (*env)->FindClass
+ (env, "gnu/java/awt/peer/gtk/GdkScreenGraphicsDevice");
+
+ gdkScreenGraphicsDevice_ctor = (*env)->GetMethodID
+ (env, gdkScreenGraphicsDevice_class, "<init>",
+ "(Lgnu/java/awt/peer/gtk/GdkGraphicsEnvironment;)V");
+
+ gdkScreenGraphicsDevice_init = (*env)->GetMethodID
+ (env, gdkScreenGraphicsDevice_class, "init", "()V");
+
+ display = (GdkDisplay *) NSA_GET_DISPLAY_PTR(env, obj);
+
+ gdk_threads_enter();
+
+ numScreens = gdk_display_get_n_screens(display);
+
+
+ /* Create a suitably sized array. */
+ array = (*env)->NewObjectArray(env,
+ numScreens,
+ gdkScreenGraphicsDevice_class,
+ NULL);
+
+ /* Create GdkScreenGraphicsDevice instances, store the native pointer to
+ * the GScreen object with them, run a 2nd initialization phase and
+ * put the new instance into the result array.
+ */
+ for ( ; i < numScreens ; i++)
+ {
+ instance = (*env)->NewObject (env,
+ gdkScreenGraphicsDevice_class,
+ gdkScreenGraphicsDevice_ctor,
+ obj);
+
+ NSA_SET_SCREEN_PTR(env,
+ instance,
+ gdk_display_get_screen(display, i));
+
+ gdk_threads_leave();
+ (*env)->CallVoidMethod(env,
+ instance,
+ gdkScreenGraphicsDevice_init);
+ gdk_threads_enter();
+
+ (*env)->SetObjectArrayElement(env, array, i, instance);
+ }
+
+ gdk_threads_leave();
+
+ return array;
+}
+
+JNIEXPORT jobject JNICALL
+Java_gnu_java_awt_peer_gtk_GdkGraphicsEnvironment_nativeGetDefaultScreenDevice
+(JNIEnv *env, jobject obj)
+{
+ jclass gdkScreenGraphicsDevice_class;
+ jmethodID gdkScreenGraphicsDevice_ctor, gdkScreenGraphicsDevice_init;
+ jobject defaultDevice;
+ GdkScreen *defaultScreen;
+
+ gdkScreenGraphicsDevice_class = (*env)->FindClass
+ (env, "gnu/java/awt/peer/gtk/GdkScreenGraphicsDevice");
+
+ gdkScreenGraphicsDevice_ctor = (*env)->GetMethodID
+ (env, gdkScreenGraphicsDevice_class, "<init>",
+ "(Lgnu/java/awt/peer/gtk/GdkGraphicsEnvironment;)V");
+
+ gdkScreenGraphicsDevice_init = (*env)->GetMethodID
+ (env, gdkScreenGraphicsDevice_class, "init", "()V");
+
+ /* Create the GdkScreenGraphicsDevice instance. */
+ defaultDevice = (*env)->NewObject (env,
+ gdkScreenGraphicsDevice_class,
+ gdkScreenGraphicsDevice_ctor,
+ obj);
+
+ gdk_threads_enter();
+
+ defaultScreen = gdk_screen_get_default();
+
+ gdk_threads_leave();
+
+ /* Class initialization will have set up the native_state storage
+ * mechanism for GdkScreenGraphicsDevice.
+ */
+ NSA_SET_SCREEN_PTR(env, defaultDevice, defaultScreen);
+
+ (*env)->CallVoidMethod(env,
+ defaultDevice,
+ gdkScreenGraphicsDevice_init);
+
+ return defaultDevice;
+}
diff --git a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.c b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.c
new file mode 100644
index 000000000..965fb5a23
--- /dev/null
+++ b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.c
@@ -0,0 +1,354 @@
+/* gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.c
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+ This file is part of GNU Classpath.
+
+ GNU Classpath is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2, or (at your option)
+ any later version.
+
+ GNU Classpath is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with GNU Classpath; see the file COPYING. If not, write to the
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ 02110-1301 USA.
+
+ Linking this library statically or dynamically with other modules is
+ making a combined work based on this library. Thus, the terms and
+ conditions of the GNU General Public License cover the whole
+ combination.
+
+ As a special exception, the copyright holders of this library give you
+ permission to link this library with independent modules to produce an
+ executable, regardless of the license terms of these independent
+ modules, and to copy and distribute the resulting executable under
+ terms of your choice, provided that you also meet, for each linked
+ independent module, the terms and conditions of the license of that
+ module. An independent module is a module which is not derived from
+ or based on this library. If you modify this library, you may extend
+ this exception to your version of the library, but you are not
+ obligated to do so. If you do not wish to do so, delete this
+ exception statement from your version. */
+
+#include <jcl.h>
+
+#include <gdk/gdk.h>
+#include <gdk/gdkx.h>
+
+#ifdef HAVE_XRANDR
+#include <X11/Xlib.h>
+#include <X11/extensions/Xrandr.h>
+#endif
+
+#include "gdkdisplay.h"
+
+#include "gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice.h"
+
+struct state_table *cp_gtk_native_screen_state_table;
+
+jclass gdkScreenGraphicsDevice_class;
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_initStaticState
+(JNIEnv *env, jclass klazz)
+{
+ gdkScreenGraphicsDevice_class = (*env)->NewGlobalRef
+ (env, klazz);
+
+ NSA_SCREEN_INIT(env, gdkScreenGraphicsDevice_class);
+}
+
+JNIEXPORT jobject JNICALL
+Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_nativeGetFixedDisplayMode
+(JNIEnv *env, jobject obj, jobject gdkGraphicsEnv __attribute__((unused)))
+{
+ jclass displayMode_class;
+ jmethodID displayMode_ctor;
+ GdkScreen *screen;
+ jobject fixedDisplayMode = NULL;
+#ifdef HAVE_XRANDR
+ int temp1, temp2;
+ GdkDisplay *display;
+
+ display = (GdkDisplay *) NSA_GET_DISPLAY_PTR(env, gdkGraphicsEnv);
+
+ gdk_threads_enter();
+
+ if (!XRRQueryExtension(GDK_DISPLAY_XDISPLAY(display), &temp1, &temp2))
+ {
+ displayMode_class = (*env)->FindClass(env, "java/awt/DisplayMode");
+ displayMode_ctor = (*env)->GetMethodID(env,
+ displayMode_class,
+ "<init>",
+ "(IIII)V");
+
+ screen = (GdkScreen *) NSA_GET_SCREEN_PTR(env, obj);
+
+ fixedDisplayMode = (*env)->NewObject(env,
+ displayMode_class,
+ displayMode_ctor,
+ gdk_screen_get_width(screen),
+ gdk_screen_get_height(screen),
+ -1,
+ 0);
+ }
+
+ gdk_threads_leave();
+
+#else
+
+ displayMode_class = (*env)->FindClass(env, "java/awt/DisplayMode");
+ displayMode_ctor = (*env)->GetMethodID(env,
+ displayMode_class,
+ "<init>",
+ "(IIII)V");
+
+ screen = (GdkScreen *) NSA_GET_SCREEN_PTR(env, obj);
+
+ fixedDisplayMode = (*env)->NewObject(env,
+ displayMode_class,
+ displayMode_ctor,
+ gdk_screen_get_width(screen),
+ gdk_screen_get_height(screen),
+ -1,
+ 0);
+
+#endif
+ return fixedDisplayMode;
+}
+
+JNIEXPORT jstring JNICALL
+Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_nativeGetIDString
+(JNIEnv *env, jobject obj)
+{
+ GdkScreen *screen;
+ gchar* displayName;
+ jstring string;
+
+ screen = (GdkScreen *) NSA_GET_SCREEN_PTR(env, obj);
+
+ gdk_threads_enter();
+
+ displayName = gdk_screen_make_display_name(screen);
+
+ gdk_threads_leave();
+
+ string = (*env)->NewStringUTF(env, displayName);
+
+ g_free(displayName);
+
+ return string;
+}
+
+JNIEXPORT jint JNICALL
+Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_nativeGetDisplayModeRate
+(JNIEnv *env, jobject obj __attribute__((unused)), jobject gdkGraphicsEnv __attribute__((unused)))
+{
+#ifdef HAVE_XRANDR
+
+ GdkDisplay *display;
+ XRRScreenConfiguration *config;
+ int rate;
+
+ display = (GdkDisplay *) NSA_GET_DISPLAY_PTR(env, gdkGraphicsEnv);
+
+ gdk_threads_enter();
+
+ config = XRRGetScreenInfo (GDK_DISPLAY_XDISPLAY(display), GDK_ROOT_WINDOW());
+
+ rate = (int) XRRConfigCurrentRate (config);
+
+ XRRFreeScreenConfigInfo (config);
+
+ gdk_threads_leave();
+
+ return rate;
+#else
+ JCL_ThrowException(env,
+ "java/lang/InternalError",
+ "Method should not have been invoked.");
+
+ return -1;
+#endif
+}
+
+JNIEXPORT jint JNICALL
+Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_nativeGetDisplayModeIndex
+(JNIEnv *env, jobject obj __attribute__((unused)), jobject gdkGraphicsEnv __attribute__((unused)))
+{
+#ifdef HAVE_XRANDR
+
+ GdkDisplay *display;
+ XRRScreenConfiguration *config;
+ SizeID index;
+ Rotation rotation;
+
+ display = (GdkDisplay *) NSA_GET_DISPLAY_PTR(env, gdkGraphicsEnv);
+
+ gdk_threads_enter();
+
+ config = XRRGetScreenInfo (GDK_DISPLAY_XDISPLAY(display), GDK_ROOT_WINDOW());
+
+ index = XRRConfigCurrentConfiguration (config, &rotation);
+
+ XRRFreeScreenConfigInfo (config);
+
+ gdk_threads_leave();
+
+ return (int) index;
+
+#else
+
+ JCL_ThrowException(env,
+ "java/lang/InternalError",
+ "Method should not have been invoked.");
+
+ return -1;
+
+#endif
+}
+
+JNIEXPORT jobjectArray JNICALL
+Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_nativeGetDisplayModes
+(JNIEnv *env, jobject obj __attribute__((unused)), jobject gdkGraphicsEnv __attribute__((unused)))
+{
+#ifdef HAVE_XRANDR
+ GdkDisplay *display;
+ XRRScreenConfiguration *config;
+ XRRScreenSize *screenSizes;
+ int nsizes = 0, nrates = 0, i = 0;
+ jclass x11DisplayMode_class;
+ jmethodID x11DisplayMode_ctor;
+ jobjectArray array;
+ jobject instance;
+ short *rates;
+ jshortArray shortArray;
+
+ display = (GdkDisplay *) NSA_GET_DISPLAY_PTR(env, gdkGraphicsEnv);
+
+ gdk_threads_enter();
+
+ config = XRRGetScreenInfo (GDK_DISPLAY_XDISPLAY(display), GDK_ROOT_WINDOW());
+
+ screenSizes = XRRConfigSizes(config, &nsizes);
+
+ x11DisplayMode_class = (*env)->FindClass(env, "gnu/java/awt/peer/gtk/GdkScreenGraphicsDevice$X11DisplayMode");
+
+ x11DisplayMode_ctor = (*env)->GetMethodID(env, x11DisplayMode_class, "<init>", "(II[S)V");
+
+ array = (*env)->NewObjectArray(env, nsizes, x11DisplayMode_class, NULL);
+
+ for (; i < nsizes ; i++)
+ {
+ /* Retrieves refresh rate information. */
+ rates = XRRConfigRates(config, i, &nrates);
+
+ /* Create a Java int array and put them in. */
+ shortArray = (*env)->NewIntArray(env, nrates);
+ (*env)->SetShortArrayRegion(env, shortArray, 0, nrates, (jshort *) rates);
+
+ /* Create a GdkScreenGraphicsDevice.X11DisplayMode instance. */
+ instance = (*env)->NewObject(env,
+ x11DisplayMode_class,
+ x11DisplayMode_ctor,
+ screenSizes[i].width,
+ screenSizes[i].height,
+ shortArray);
+
+ /* Put it into the result array. */
+ (*env)->SetObjectArrayElement(env, array, i, instance);
+ }
+
+ /* Free everything acquired by xlib. */
+ XRRFreeScreenConfigInfo (config);
+
+ gdk_threads_leave();
+
+ return array;
+#else
+ JCL_ThrowException(env,
+ "java/lang/InternalError",
+ "Method should not have been invoked.");
+
+ return NULL;
+
+#endif
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_nativeSetDisplayMode
+(JNIEnv *env, jobject obj __attribute__((unused)), jobject gdkGraphicsEnv __attribute__((unused)), jint index __attribute__((unused)), jshort rate __attribute__((unused)))
+{
+#ifdef HAVE_XRANDR
+ GdkDisplay *display;
+ XRRScreenConfiguration *config;
+ Rotation rotation;
+
+ display = (GdkDisplay *) NSA_GET_DISPLAY_PTR(env, gdkGraphicsEnv);
+
+ gdk_threads_enter();
+
+ config = XRRGetScreenInfo (GDK_DISPLAY_XDISPLAY(display), GDK_ROOT_WINDOW());
+
+ /* The rotation is not exposed to the Java API. So we retrieve its current
+ * value and set it to the same when switching resolution.
+ */
+ XRRConfigCurrentConfiguration (config, &rotation);
+
+ XRRSetScreenConfigAndRate (GDK_DISPLAY_XDISPLAY(display),
+ config,
+ GDK_ROOT_WINDOW(),
+ index,
+ rotation,
+ rate,
+ CurrentTime);
+
+ XRRFreeScreenConfigInfo(config);
+
+ gdk_threads_leave();
+
+#else
+ JCL_ThrowException(env,
+ "java/lang/InternalError",
+ "Method should not have been invoked.");
+#endif
+}
+
+JNIEXPORT jobject JNICALL
+Java_gnu_java_awt_peer_gtk_GdkScreenGraphicsDevice_nativeGetBounds
+(JNIEnv *env, jobject obj)
+{
+ jclass rectangle_class;
+ jmethodID rectangle_ctor;
+ GdkScreen *screen;
+ GdkWindow *window;
+ int x, y, w, h;
+ jobject instance;
+
+ rectangle_class = (*env)->FindClass(env, "java/awt/Rectangle");
+
+ rectangle_ctor = (*env)->GetMethodID
+ (env, rectangle_class, "<init>", "(IIII)V");
+
+ screen = (GdkScreen *) NSA_GET_SCREEN_PTR(env, obj);
+
+ gdk_threads_enter();
+
+ window = gdk_screen_get_root_window(screen);
+
+ gdk_window_get_geometry(window, &x, &y, &w, &h, NULL);
+
+ gdk_threads_leave();
+
+ instance = (*env)->NewObject(env,
+ rectangle_class,
+ rectangle_ctor,
+ x, y, w, h);
+
+ return instance;
+}
diff --git a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkTextLayout.c b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkTextLayout.c
index edce3917d..849998791 100644
--- a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkTextLayout.c
+++ b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GdkTextLayout.c
@@ -1,5 +1,5 @@
/* gnu_java_awt_GdkTextLayout.c
- Copyright (C) 2004, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -44,9 +44,11 @@
#include <pango/pangofc-font.h>
#include <freetype/ftglyph.h>
#include <freetype/ftoutln.h>
+#include "jcl.h"
#include "native_state.h"
#include "gdkfont.h"
#include "gnu_java_awt_peer_gtk_GdkTextLayout.h"
+#include "cairographics2d.h"
struct state_table *cp_gtk_native_text_layout_state_table;
@@ -60,6 +62,9 @@ typedef struct gp
double sy;
} generalpath ;
+static void paint_glyph_run(cairo_t *cr, cairo_glyph_t **glyphs,
+ gint *n_glyphs, PangoLayoutRun *run);
+
JNIEXPORT void JNICALL
Java_gnu_java_awt_peer_gtk_GdkTextLayout_initStaticState
(JNIEnv *env, jclass clazz)
@@ -93,8 +98,6 @@ Java_gnu_java_awt_peer_gtk_GdkTextLayout_setText
gchar *str = NULL;
gint len = 0;
- gdk_threads_enter ();
-
g_assert(self != NULL);
g_assert(text != NULL);
@@ -106,13 +109,37 @@ Java_gnu_java_awt_peer_gtk_GdkTextLayout_setText
str = (gchar *)(*env)->GetStringUTFChars (env, text, NULL);
g_assert (str != NULL);
- pango_layout_set_text (tl->pango_layout, text, len);
+ gdk_threads_enter ();
+
+ pango_layout_set_text (tl->pango_layout, str, len);
(*env)->ReleaseStringUTFChars (env, text, str);
gdk_threads_leave ();
}
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_GdkTextLayout_setFont (JNIEnv *env, jobject obj, jobject font)
+{
+ struct textlayout *tl;
+ struct peerfont *pf;
+
+ g_assert(obj != NULL);
+ g_assert(font != NULL);
+
+ tl = (struct textlayout *)NSA_GET_TEXT_LAYOUT_PTR (env, obj);
+ g_assert(tl != NULL);
+ g_assert(tl->pango_layout != NULL);
+ pf = (struct peerfont *)NSA_GET_FONT_PTR (env, font);
+ g_assert(pf != NULL);
+
+ gdk_threads_enter ();
+
+ pango_layout_set_font_description(tl->pango_layout, pf->desc);
+
+ gdk_threads_leave ();
+}
+
JNIEXPORT void JNICALL
Java_gnu_java_awt_peer_gtk_GdkTextLayout_indexToPos
(JNIEnv *env, jobject self, jint idx, jdoubleArray javaPos)
@@ -207,10 +234,106 @@ Java_gnu_java_awt_peer_gtk_GdkTextLayout_dispose
gdk_threads_leave ();
}
+/**
+ * Draw this textlayout on a cairo surface
+ * FIXME: Seems completely broken.
+ */
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_GdkTextLayout_cairoDrawGdkTextLayout
+ (JNIEnv *env, jobject obj, jlong cg2d, jfloat x, jfloat y)
+{
+ /*
+ * FIXME: Some day we expect either cairo or pango will know how to make
+ * a pango layout paint to a cairo surface. that day is not yet here.
+ */
+
+ struct cairographics2d *gr = JLONG_TO_PTR(struct cairographics2d, cg2d);
+ cairo_t *cr = gr->cr;
+ struct textlayout *tl = NULL;
+ PangoLayoutIter *i = NULL;
+ PangoLayoutRun *run = NULL;
+ cairo_glyph_t *glyphs = NULL;
+ gint n_glyphs = 0;
+
+ tl = (struct textlayout *)NSA_GET_TEXT_LAYOUT_PTR (env, obj);
+
+ g_assert (cr != NULL);
+ g_assert (tl != NULL);
+ g_assert (tl->pango_layout != NULL);
+
+ gdk_threads_enter ();
+
+ i = pango_layout_get_iter (tl->pango_layout);
+ g_assert (i != NULL);
+
+ cairo_translate (cr, x, y);
+
+ do
+ {
+ run = pango_layout_iter_get_run (i);
+ if (run != NULL)
+ paint_glyph_run (cr, &glyphs, &n_glyphs, run);
+ }
+ while (pango_layout_iter_next_run (i));
+
+ if (glyphs != NULL)
+ g_free (glyphs);
+
+ cairo_translate (cr, -x, -y);
+
+ pango_layout_iter_free (i);
+
+ gdk_threads_leave ();
+}
+
+static void
+paint_glyph_run(cairo_t *cr,
+ cairo_glyph_t **glyphs,
+ gint *n_glyphs,
+ PangoLayoutRun *run)
+{
+ gint i = 0;
+ gint x = 0, y = 0;
+
+ g_assert (cr != NULL);
+ g_assert (glyphs != NULL);
+ g_assert (n_glyphs != NULL);
+ g_assert (run != NULL);
+
+ if (run->glyphs != NULL && run->glyphs->num_glyphs > 0)
+ {
+ if (*n_glyphs < run->glyphs->num_glyphs)
+ {
+ *glyphs = g_realloc(*glyphs,
+ (sizeof(cairo_glyph_t)
+ * run->glyphs->num_glyphs));
+ *n_glyphs = run->glyphs->num_glyphs;
+ }
+
+ g_assert (*glyphs != NULL);
+
+ for (i = 0; i < run->glyphs->num_glyphs; ++i)
+ {
+ (*glyphs)[i].index = run->glyphs->glyphs[i].glyph;
+
+ (*glyphs)[i].x =
+ ((double) (x + run->glyphs->glyphs[i].geometry.x_offset))
+ / ((double) PANGO_SCALE);
+
+ (*glyphs)[i].y =
+ ((double) (y + run->glyphs->glyphs[i].geometry.y_offset))
+ / ((double) PANGO_SCALE);
+
+ x += run->glyphs->glyphs[i].geometry.width;
+ }
+ cairo_show_glyphs (cr, *glyphs, run->glyphs->num_glyphs);
+ }
+}
+
/* GetOutline code follows ****************************/
/********* Freetype callback functions *****************************/
-static int _moveTo( FT_Vector* to,
+static int _moveTo( const FT_Vector* to,
void *p)
{
JNIEnv *env;
@@ -233,7 +356,7 @@ static int _moveTo( FT_Vector* to,
return 0;
}
-static int _lineTo( FT_Vector* to,
+static int _lineTo( const FT_Vector* to,
void *p)
{
JNIEnv *env;
@@ -255,8 +378,8 @@ static int _lineTo( FT_Vector* to,
return 0;
}
-static int _quadTo( FT_Vector* cp,
- FT_Vector* to,
+static int _quadTo( const FT_Vector* cp,
+ const FT_Vector* to,
void *p)
{
JNIEnv *env;
@@ -280,9 +403,9 @@ static int _quadTo( FT_Vector* cp,
return 0;
}
-static int _curveTo( FT_Vector* cp1,
- FT_Vector* cp2,
- FT_Vector* to,
+static int _curveTo( const FT_Vector* cp1,
+ const FT_Vector* cp2,
+ const FT_Vector* to,
void *p)
{
JNIEnv *env;
@@ -320,10 +443,10 @@ Java_gnu_java_awt_peer_gtk_GdkTextLayout_getOutline
PangoLayoutLine *current_line;
FT_Outline_Funcs ftCallbacks =
{
- _moveTo,
- _lineTo,
- _quadTo,
- _curveTo,
+ (FT_Outline_MoveToFunc) _moveTo,
+ (FT_Outline_LineToFunc) _lineTo,
+ (FT_Outline_ConicToFunc) _quadTo,
+ (FT_Outline_CubicToFunc) _curveTo,
0,
0
};
diff --git a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkClipboard.c b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkClipboard.c
index cb2c87238..7ce1185a4 100644
--- a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkClipboard.c
+++ b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkClipboard.c
@@ -242,14 +242,7 @@ clipboard_get_func (GtkClipboard *clipboard,
pixbuf = cp_gtk_image_get_pixbuf (env, gtkimage);
if (pixbuf != NULL)
- {
- gtk_selection_data_set_pixbuf (selection, pixbuf);
-
- /* if the GtkImage is offscreen, this is a temporary pixbuf
- which should be thrown out. */
- if(cp_gtk_image_is_offscreen (env, gtkimage) == JNI_TRUE)
- gdk_pixbuf_unref (pixbuf);
- }
+ gtk_selection_data_set_pixbuf (selection, pixbuf);
}
else if (info == URI_TARGET)
{
diff --git a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkFramePeer.c b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkFramePeer.c
index c60f48f51..766964314 100644
--- a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkFramePeer.c
+++ b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkFramePeer.c
@@ -186,10 +186,5 @@ Java_gnu_java_awt_peer_gtk_GtkFramePeer_nativeSetIconImage
gtk_window_set_icon (GTK_WINDOW (ptr), pixbuf);
- /* if the GtkImage is offscreen, this is a temporary pixbuf which should
- be thrown out. */
- if(cp_gtk_image_is_offscreen (env, gtkimage) == JNI_TRUE)
- gdk_pixbuf_unref (pixbuf);
-
gdk_threads_leave ();
}
diff --git a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkImage.c b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkImage.c
index dad6a1182..ff3fbe896 100644
--- a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkImage.c
+++ b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkImage.c
@@ -51,13 +51,11 @@ exception statement from your version. */
/* local stuff */
static GdkInterpType mapHints(jint hints);
-static jboolean offScreen (JNIEnv * env, jobject obj);
-static void *getData (JNIEnv * env, jobject obj);
static void createRawData (JNIEnv * env, jobject obj, void *ptr);
static void setWidthHeight (JNIEnv * env, jobject obj, int width, int height);
/**
- * Loads a pixmap from a file.
+ * Loads a pixbuf from a file.
*/
JNIEXPORT jboolean JNICALL
Java_gnu_java_awt_peer_gtk_GtkImage_loadPixbuf
@@ -119,10 +117,14 @@ Java_gnu_java_awt_peer_gtk_GtkImage_loadImageFromData
if (pixbuf == NULL)
{
+ g_object_unref (loader);
createRawData (env, obj, NULL);
return JNI_FALSE;
}
+ g_object_ref (pixbuf);
+ g_object_unref (loader);
+
width = gdk_pixbuf_get_width (pixbuf);
height = gdk_pixbuf_get_height (pixbuf);
@@ -137,7 +139,7 @@ Java_gnu_java_awt_peer_gtk_GtkImage_createFromPixbuf
(JNIEnv *env, jobject obj)
{
int width, heigth;
- GdkPixbuf *pixbuf = (GdkPixbuf *) getData (env, obj);
+ GdkPixbuf *pixbuf = cp_gtk_image_get_pixbuf (env, obj);
width = gdk_pixbuf_get_width (pixbuf);
heigth = gdk_pixbuf_get_height (pixbuf);
setWidthHeight(env, obj, width, heigth);
@@ -194,9 +196,6 @@ Java_gnu_java_awt_peer_gtk_GtkImage_getPixels(JNIEnv *env, jobject obj)
}
}
- if (offScreen (env, obj) == JNI_TRUE)
- gdk_pixbuf_unref (pixbuf);
-
(*env)->ReleaseIntArrayElements (env, result_array, result_array_iter, 0);
gdk_threads_leave ();
@@ -211,7 +210,7 @@ JNIEXPORT void JNICALL
Java_gnu_java_awt_peer_gtk_GtkImage_setPixels(JNIEnv *env, jobject obj,
jintArray pixels)
{
- GdkPixbuf *pixbuf = (GdkPixbuf *)getData (env, obj);
+ GdkPixbuf *pixbuf = cp_gtk_image_get_pixbuf (env, obj);
int width, height, rowstride;
guchar *pixeldata;
jint *src_array_iter, *src;
@@ -236,10 +235,10 @@ Java_gnu_java_awt_peer_gtk_GtkImage_setPixels(JNIEnv *env, jobject obj,
}
/**
- * Allocates a Gtk Pixbuf or Pixmap.
+ * Allocates a Gtk Pixbuf
*/
JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GtkImage_createPixmap(JNIEnv *env, jobject obj)
+Java_gnu_java_awt_peer_gtk_GtkImage_createPixbuf(JNIEnv *env, jobject obj)
{
int width, height;
jclass cls;
@@ -254,35 +253,58 @@ Java_gnu_java_awt_peer_gtk_GtkImage_createPixmap(JNIEnv *env, jobject obj)
g_assert (field != 0);
height = (*env)->GetIntField (env, obj, field);
- if (offScreen (env, obj) == JNI_FALSE)
- createRawData (env, obj, gdk_pixbuf_new (GDK_COLORSPACE_RGB,
- TRUE,
- 8,
- width,
- height));
- else
- createRawData (env, obj, gdk_pixmap_new (NULL, width, height,
- gdk_rgb_get_visual ()->depth));
+ createRawData (env, obj, gdk_pixbuf_new (GDK_COLORSPACE_RGB,
+ TRUE,
+ 8,
+ width,
+ height));
+}
+
+/**
+ * Allocates a Gtk Pixbuf
+ */
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_GtkImage_initFromBuffer(JNIEnv *env, jobject obj,
+ jlong bufferPointer)
+{
+ int width, height;
+ jclass cls;
+ jfieldID field;
+ GdkPixbuf *pixbuf;
+ const guchar *bp = JLONG_TO_PTR(const guchar, bufferPointer);
+
+ g_assert(bp != NULL);
+ cls = (*env)->GetObjectClass( env, obj );
+ field = (*env)->GetFieldID( env, cls, "width", "I" );
+ g_assert( field != 0 );
+ width = (*env)->GetIntField( env, obj, field );
+
+ field = (*env)->GetFieldID( env, cls, "height", "I" );
+ g_assert( field != 0 );
+ height = (*env)->GetIntField( env, obj, field );
+
+ pixbuf = gdk_pixbuf_new_from_data( bp,
+ GDK_COLORSPACE_RGB, TRUE, 8,
+ width, height, width * 4, NULL, NULL );
+ g_assert( pixbuf != NULL );
+ createRawData( env, obj, pixbuf );
}
/**
- * Frees the Gtk Pixmap.
+ * Frees the Gtk Pixbuf.
*/
JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GtkImage_freePixmap(JNIEnv *env, jobject obj)
+Java_gnu_java_awt_peer_gtk_GtkImage_freePixbuf(JNIEnv *env, jobject obj)
{
- if (offScreen (env, obj) == JNI_FALSE)
- gdk_pixbuf_unref ((GdkPixbuf *)getData (env, obj));
- else
- g_object_unref ((GdkPixmap *)getData (env, obj));
+ gdk_pixbuf_unref (cp_gtk_image_get_pixbuf (env, obj));
}
/**
- * Sets this pixmap to a scaled version of the source pixmap.
+ * Sets this to a scaled version of the original pixbuf
* width and height of the destination GtkImage must be set.
*/
JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GtkImage_createScaledPixmap(JNIEnv *env,
+Java_gnu_java_awt_peer_gtk_GtkImage_createScaledPixbuf(JNIEnv *env,
jobject destination,
jobject source,
jint hints)
@@ -309,238 +331,25 @@ Java_gnu_java_awt_peer_gtk_GtkImage_createScaledPixmap(JNIEnv *env,
width, height,
mapHints(hints));
- if (offScreen (env, source) == JNI_TRUE)
- gdk_pixbuf_unref (pixbuf);
-
createRawData (env, destination, (void *)dst);
}
/**
- * Draws the pixbuf at x, y, scaled to width and height and
- * optionally composited with a given background color.
- */
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GtkImage_drawPixelsScaled
- (JNIEnv *env, jobject obj, jobject gc_obj,
- jint bg_red, jint bg_green, jint bg_blue,
- jint x, jint y, jint width, jint height, jboolean composite)
-{
- GdkPixbuf* dst;
- struct graphics2d *g;
- guint32 bgColor;
-
- gdk_threads_enter ();
-
- if (width <= 0 || height <= 0)
- {
- gdk_threads_leave ();
- return;
- }
-
- bgColor = ((bg_red & 0xFF) << 16) |
- ((bg_green & 0xFF) << 8) | (bg_blue & 0xFF);
-
- g = (struct graphics2d *) NSA_GET_G2D_PTR (env, gc_obj);
-
- if (!g || !GDK_IS_DRAWABLE (g->drawable))
- {
- gdk_threads_leave ();
- return;
- }
-
- if (offScreen (env, obj) == JNI_FALSE)
- {
- GdkPixbuf* pixbuf = (GdkPixbuf *)getData (env, obj);
-
- /* Scale and composite the image */
- if (composite == JNI_TRUE)
- dst = gdk_pixbuf_composite_color_simple (pixbuf,
- width,
- height,
- GDK_INTERP_BILINEAR,
- 255,
- width,
- bgColor,
- bgColor);
- else
- dst = gdk_pixbuf_scale_simple(pixbuf,
- width, height,
- GDK_INTERP_BILINEAR);
-
- gdk_cairo_set_source_pixbuf (g->cr, dst, (double) x, (double) y);
- gdk_pixbuf_unref (dst);
-
- } else {
- /* Get a pixmap */
- GdkPixmap* pixmap = (GdkPixmap *)getData (env, obj);
- cairo_xlib_surface_set_drawable (g->surface,
- GDK_PIXMAP_XID(pixmap),
- width,
- height);
- }
-
- gdk_threads_leave ();
-}
-
-/**
- * Draws the pixbuf at x, y, scaled to width and height and
- * optionally composited and/or flipped with a given background color.
- */
-JNIEXPORT void JNICALL
-Java_gnu_java_awt_peer_gtk_GtkImage_drawPixelsScaledFlipped
-(JNIEnv *env, jobject obj, jobject gc_obj,
- jint bg_red, jint bg_green, jint bg_blue,
-#if GTK_MINOR_VERSION > 4
- jboolean flipx, jboolean flipy,
-#else
- jboolean flipx __attribute__((unused)),
- jboolean flipy __attribute__((unused)),
-#endif
- jint srcx, jint srcy, jint srcwidth, jint srcheight,
- jint dstx, jint dsty, jint dstwidth, jint dstheight,
- jboolean composite)
-{
- GdkPixbuf *pixbuf;
- GdkPixbuf *tmp, *dst;
- struct graphics2d *g;
- guint32 bgColor;
-
- gdk_threads_enter ();
-
- if (srcwidth <= 0 || srcheight <= 0
- || dstwidth <= 0 || dstheight <= 0)
- {
- gdk_threads_leave ();
- return;
- }
-
- bgColor = ((bg_red & 0xFF) << 16) |
- ((bg_green & 0xFF) << 8) | (bg_blue & 0xFF);
-
- g = (struct graphics2d *) NSA_GET_G2D_PTR (env, gc_obj);
-
- if (!g || !GDK_IS_DRAWABLE (g->drawable))
- {
- gdk_threads_leave ();
- return;
- }
-
- if (offScreen (env, obj) == JNI_FALSE)
- {
- pixbuf = (GdkPixbuf *)getData (env, obj);
-
- /* Get the source area */
- tmp = gdk_pixbuf_new (GDK_COLORSPACE_RGB,
- TRUE,
- 8,
- srcwidth,
- srcheight);
-
- gdk_pixbuf_copy_area (pixbuf,
- srcx, srcy,
- srcwidth, srcheight,
- tmp,
- 0, 0); /* dst x , dst y */
- } else {
- /* Get a pixbuf from the pixmap */
- GdkDrawable *pixmap = (GdkDrawable *)getData(env, obj);
- tmp = gdk_pixbuf_get_from_drawable (NULL,
- pixmap,
- gdk_drawable_get_colormap( pixmap ),
- srcx, srcy,
- 0, 0, /* dst x , dst y */
- srcwidth, srcheight);
- }
-
- /* FIXME: This #if should be discarded once I feel comfortable about
- GTK 2.6 dependence */
-#if GTK_MINOR_VERSION > 4
- /* Flip it if necessary. */
- if (flipx == JNI_TRUE)
- {
- GdkPixbuf *tmp2 = gdk_pixbuf_flip (tmp, TRUE);
- gdk_pixbuf_unref (tmp);
- tmp = tmp2;
- }
- if (flipy == JNI_TRUE)
- {
- GdkPixbuf *tmp2 = gdk_pixbuf_flip (tmp, FALSE);
- gdk_pixbuf_unref (tmp);
- tmp = tmp2;
- }
-#endif
-
- /* Scale and composite the image */
- if (composite == JNI_TRUE)
- dst = gdk_pixbuf_composite_color_simple (tmp,
- dstwidth,
- dstheight,
- GDK_INTERP_BILINEAR,
- 255,
- dstwidth,
- bgColor,
- bgColor);
- else
- dst = gdk_pixbuf_scale_simple(tmp,
- dstwidth, dstheight,
- GDK_INTERP_BILINEAR);
- gdk_pixbuf_unref (tmp);
-
- gdk_cairo_set_source_pixbuf (g->cr, dst, (double) dstx,
- (double) dsty);
- gdk_pixbuf_unref (dst);
-
- gdk_threads_leave ();
-}
-
-/**
* Used by GtkFramePeer
*/
GdkPixbuf *cp_gtk_image_get_pixbuf (JNIEnv *env, jobject obj)
{
- int width, height;
- GdkPixbuf *pixbuf;
- GdkPixmap* pixmap;
jclass cls;
- jfieldID field;
-
- if (offScreen (env, obj) == JNI_FALSE)
- return (GdkPixbuf *)getData (env, obj);
+ jfieldID data_fid;
+ jobject data;
cls = (*env)->GetObjectClass (env, obj);
- field = (*env)->GetFieldID (env, cls, "width", "I");
- g_assert (field != 0);
- width = (*env)->GetIntField (env, obj, field);
-
- field = (*env)->GetFieldID (env, cls, "height", "I");
- g_assert (field != 0);
- height = (*env)->GetIntField (env, obj, field);
-
- /* Get a pixmap */
- pixmap = (GdkPixmap *)getData (env, obj);
-
- pixbuf = gdk_pixbuf_get_from_drawable (NULL,
- pixmap,
- gdk_drawable_get_colormap( pixmap ),
- 0, 0, /* src x , src y */
- 0, 0, /* dst x , dst y */
- width, height);
- return pixbuf;
-}
-
-/**
- * Used by GdkGraphics
- */
-GdkPixmap *cp_gtk_image_get_pixmap (JNIEnv *env, jobject obj)
-{
- if (offScreen (env, obj) == JNI_FALSE)
- return NULL;
- return (GdkPixmap *)getData (env, obj);
-}
+ data_fid = (*env)->GetFieldID (env, cls, "pixbuf",
+ "Lgnu/classpath/Pointer;");
+ g_assert (data_fid != 0);
+ data = (*env)->GetObjectField (env, obj, data_fid);
-jboolean cp_gtk_image_is_offscreen (JNIEnv *env, jobject obj)
-{
- return offScreen(env, obj);
+ return (GdkPixbuf *)JCL_GetRawData (env, data);
}
/**
@@ -585,18 +394,6 @@ static void setWidthHeight (JNIEnv * env, jobject obj, int width, int height)
(*env)->SetIntField (env, obj, field, (jint)height);
}
-/* Returns the value of the offScreen field. */
-static jboolean offScreen (JNIEnv *env, jobject obj)
-{
- jclass cls;
- jfieldID field;
-
- cls = (*env)->GetObjectClass (env, obj);
- field = (*env)->GetFieldID (env, cls, "offScreen", "Z");
- g_assert (field != 0);
- return (*env)->GetBooleanField (env, obj, field);
-}
-
/* Store and get the pixbuf pointer */
static void
createRawData (JNIEnv * env, jobject obj, void *ptr)
@@ -606,7 +403,7 @@ createRawData (JNIEnv * env, jobject obj, void *ptr)
jfieldID data_fid;
cls = (*env)->GetObjectClass (env, obj);
- data_fid = (*env)->GetFieldID (env, cls, "pixmap",
+ data_fid = (*env)->GetFieldID (env, cls, "pixbuf",
"Lgnu/classpath/Pointer;");
g_assert (data_fid != 0);
@@ -615,18 +412,3 @@ createRawData (JNIEnv * env, jobject obj, void *ptr)
(*env)->SetObjectField (env, obj, data_fid, data);
}
-static void *
-getData (JNIEnv * env, jobject obj)
-{
- jclass cls;
- jfieldID data_fid;
- jobject data;
-
- cls = (*env)->GetObjectClass (env, obj);
- data_fid = (*env)->GetFieldID (env, cls, "pixmap",
- "Lgnu/classpath/Pointer;");
- g_assert (data_fid != 0);
- data = (*env)->GetObjectField (env, obj, data_fid);
-
- return JCL_GetRawData (env, data);
-}
diff --git a/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkVolatileImage.c b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkVolatileImage.c
new file mode 100644
index 000000000..d7ef474e0
--- /dev/null
+++ b/native/jni/gtk-peer/gnu_java_awt_peer_gtk_GtkVolatileImage.c
@@ -0,0 +1,195 @@
+/* gnu_java_awt_peer_gtk_VolatileImage.c
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+#include "jcl.h"
+#include "gtkpeer.h"
+#include <gdk/gdkx.h>
+#include <gdk/gdktypes.h>
+#include <gdk/gdkprivate.h>
+#include <gdk/gdkx.h>
+#include <gdk-pixbuf/gdk-pixbuf.h>
+#include <gdk-pixbuf/gdk-pixdata.h>
+
+#include "gnu_java_awt_peer_gtk_GtkVolatileImage.h"
+#include "cairographics2d.h"
+
+
+/**
+ * Creates a cairo surface, ARGB32, native ordering, premultiplied alpha.
+ */
+JNIEXPORT jlong JNICALL
+Java_gnu_java_awt_peer_gtk_GtkVolatileImage_init (JNIEnv *env,
+ jobject obj __attribute__ ((__unused__)),
+ jobject peer,
+ jint width, jint height)
+{
+ GtkWidget *widget = NULL;
+ GdkPixmap* pixmap;
+ void *ptr = NULL;
+
+ gdk_threads_enter();
+
+ if( peer != NULL )
+ {
+ ptr = NSA_GET_PTR (env, peer);
+ g_assert (ptr != NULL);
+
+ widget = GTK_WIDGET (ptr);
+ g_assert (widget != NULL);
+ pixmap = gdk_pixmap_new( widget->window, width, height, -1 );
+ }
+ else
+ pixmap = gdk_pixmap_new( NULL, width, height, 16 );
+
+ gdk_threads_leave();
+
+ g_assert( pixmap != NULL );
+
+ return PTR_TO_JLONG( pixmap );
+}
+
+/**
+ * Destroy the surface
+ */
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_GtkVolatileImage_destroy
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute((unused)),
+ jlong pointer)
+{
+ GdkPixmap* pixmap = JLONG_TO_PTR(GdkPixmap, pointer);
+ if( pixmap != NULL )
+ {
+ gdk_threads_enter();
+ g_object_unref( pixmap );
+ gdk_threads_leave();
+ }
+}
+
+/**
+ * Gets all pixels in an array
+ */
+JNIEXPORT jintArray JNICALL
+Java_gnu_java_awt_peer_gtk_GtkVolatileImage_nativeGetPixels
+(JNIEnv *env, jobject obj, jlong pointer)
+{
+ /* jint *pixeldata, *jpixdata; */
+ jint *jpixdata;
+ GdkPixmap *pixmap;
+ jintArray jpixels;
+ int width, height, depth, size;
+ jclass cls;
+ jfieldID field;
+
+ cls = (*env)->GetObjectClass (env, obj);
+ field = (*env)->GetFieldID (env, cls, "width", "I");
+ g_assert (field != 0);
+ width = (*env)->GetIntField (env, obj, field);
+
+ field = (*env)->GetFieldID (env, cls, "height", "I");
+ g_assert (field != 0);
+ height = (*env)->GetIntField (env, obj, field);
+
+ pixmap = JLONG_TO_PTR(GdkPixmap, pointer);
+ g_assert(pixmap != NULL);
+
+ gdk_threads_enter();
+
+ /* get depth in bytes */
+ depth = gdk_drawable_get_depth( pixmap ) >> 3;
+ size = width * height * 4;
+ jpixels = (*env)->NewIntArray ( env, size );
+ jpixdata = (*env)->GetIntArrayElements (env, jpixels, NULL);
+ /* memcpy (jpixdata, pixeldata, size * sizeof( jint )); */
+
+ (*env)->ReleaseIntArrayElements (env, jpixels, jpixdata, 0);
+
+ gdk_threads_leave();
+
+ return jpixels;
+}
+
+/**
+ * Copy area
+ */
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_GtkVolatileImage_nativeCopyArea
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute((unused)),
+ jlong pointer, jint x, jint y, jint w, jint h, jint dx, jint dy)
+{
+ GdkPixbuf *pixbuf;
+ GdkPixmap* pixmap = JLONG_TO_PTR(GdkPixmap, pointer);
+
+ g_assert (pixmap != NULL);
+
+ gdk_threads_enter();
+
+ pixbuf = gdk_pixbuf_new( GDK_COLORSPACE_RGB, TRUE, 8, w, h );
+ gdk_pixbuf_get_from_drawable( pixbuf, pixmap, NULL, x, y, 0, 0, w, h );
+ gdk_draw_pixbuf (pixmap, NULL, pixbuf,
+ 0, 0, x + dx, y + dy,
+ w, h,
+ GDK_RGB_DITHER_NORMAL, 0, 0);
+ gdk_threads_leave();
+}
+
+JNIEXPORT void JNICALL
+Java_gnu_java_awt_peer_gtk_GtkVolatileImage_nativeDrawVolatile
+(JNIEnv *env __attribute__((unused)), jobject obj __attribute((unused)),
+ jlong pointer, jlong srcptr, jint x, jint y, jint w, jint h)
+{
+ GdkPixmap *dst, *src;
+ GdkGC *gc;
+
+ src = JLONG_TO_PTR(GdkPixmap, srcptr);
+ dst = JLONG_TO_PTR(GdkPixmap, pointer);
+ g_assert (src != NULL);
+ g_assert (dst != NULL);
+
+ gdk_threads_enter();
+
+ gc = gdk_gc_new( dst );
+ gdk_draw_drawable(dst,
+ gc,
+ src,
+ 0, 0,
+ x, y,
+ w, h);
+ g_object_unref( gc );
+
+ gdk_threads_leave();
+}
+
diff --git a/native/jni/gtk-peer/gtkpeer.h b/native/jni/gtk-peer/gtkpeer.h
index 6ae7b06ae..065d20608 100644
--- a/native/jni/gtk-peer/gtkpeer.h
+++ b/native/jni/gtk-peer/gtkpeer.h
@@ -101,53 +101,6 @@ extern struct state_table *cp_gtk_native_graphics2d_state_table;
#define SWAPU32(w) \
(((w) << 24) | (((w) & 0xff00) << 8) | (((w) >> 8) & 0xff00) | ((w) >> 24))
-/*
- A graphics2d struct is both simpler and uglier than a graphics
- struct.
-
- Most of the graphics2d drawing state is held in the referenced cairo_t
- and corresponding cairo_surface_t, so we can ignore it.
-
- In addition to the cairo_t, we need to hold an extra reference to the
- underlying GdkDrawable so its refcount matches the lifecycle of the java
- Graphics object which is peering with us; also a reference to a byte
- buffer and cairo_surface_t which contain the pattern you're drawing from
- (if it exists).
-
- Finally, it is possible that we are using a non-RENDER capable X server,
- therefore we will be drawing to an cairo_surface_t which is actually a
- pixbuf. When this is the case, the pointer to a GdkPixbuf will be
- non-NULL and any drawing operation needs to be bracketed by pixbuf
- load/save operations. If the GdkPixbuf pointer is NULL, we will treat
- the cairo_surface_t as RENDER-capable.
- */
-struct graphics2d
-{
- cairo_t *cr;
- cairo_surface_t *surface;
- GdkDrawable *drawable;
- GdkWindow *win;
- GdkPixbuf *drawbuf;
- char *pattern_pixels;
- cairo_surface_t *pattern_surface;
- cairo_pattern_t *pattern;
- gboolean debug;
- enum
- {
- MODE_DRAWABLE_WITH_RENDER,
- MODE_DRAWABLE_NO_RENDER,
- MODE_JAVA_ARRAY
- }
- mode;
-
- /* Support for MODE_JAVA_ARRAY */
- jintArray jarray;
- jint width, height;
- jint *javabuf;
- jint *javabuf_copy;
- jboolean isCopy;
-};
-
/* New-style event masks. */
#define AWT_BUTTON1_DOWN_MASK (1 << 10)
#define AWT_BUTTON2_DOWN_MASK (1 << 11)
@@ -229,8 +182,10 @@ jint cp_gtk_state_to_awt_mods (guint state);
/* Image helpers */
GdkPixbuf *cp_gtk_image_get_pixbuf (JNIEnv *env, jobject obj);
-GdkPixmap *cp_gtk_image_get_pixmap (JNIEnv *env, jobject obj);
-jboolean cp_gtk_image_is_offscreen (JNIEnv *env, jobject obj);
+
+/* Component Graphics helpers */
+void cp_gtk_grab_current_drawable(GtkWidget *widget, GdkDrawable **draw,
+ GdkWindow **win);
/* JNI initialization functions */
void cp_gtk_button_init_jni (void);
@@ -254,6 +209,8 @@ void cp_gtk_textcomponent_connect_signals (GObject *ptr, jobject *gref);
/* Debugging */
void cp_gtk_print_current_thread (void);
+GdkPixmap *cp_gtk_get_pixmap( JNIEnv *env, jobject obj);
+
#define SYNCHRONIZE_GDK 0
#define DEBUG_LOCKING 0
diff --git a/native/jni/java-io/java_io_VMFile.c b/native/jni/java-io/java_io_VMFile.c
index 354df04ed..7a3fdaf43 100644
--- a/native/jni/java-io/java_io_VMFile.c
+++ b/native/jni/java-io/java_io_VMFile.c
@@ -1,5 +1,5 @@
/* java_io_VMFile.c - Native methods for java.io.File class
- Copyright (C) 1998, 2004 Free Software Foundation, Inc.
+ Copyright (C) 1998, 2004, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -730,3 +730,237 @@ Java_java_io_VMFile_list (JNIEnv * env, jobject obj
return (0);
#endif /* not WITHOUT_FILESYSTEM */
}
+
+/*************************************************************************/
+
+/*
+ * These two methods are used to maintain dynamically allocated
+ * buffers for getCanonicalPath without the overhead of calling
+ * realloc every time a buffer is modified. Buffers are sized
+ * at the smallest multiple of CHUNKSIZ that is greater than or
+ * equal to the desired length. The default CHUNKSIZ is 256,
+ * longer than most paths, so in most cases a getCanonicalPath
+ * will require only one malloc per buffer.
+ */
+
+#define CHUNKLOG 8
+#define CHUNKSIZ (1 << CHUNKLOG)
+
+static int
+nextChunkSize (int size)
+{
+ return ((size >> CHUNKLOG) + ((size & (CHUNKSIZ - 1)) ? 1 : 0)) << CHUNKLOG;
+}
+
+static char *
+maybeGrowBuf (JNIEnv *env, char *buf, int *size, int required)
+{
+ if (required > *size)
+ {
+ *size = nextChunkSize (required);
+ buf = JCL_realloc (env, buf, *size);
+ }
+ return buf;
+}
+
+/*************************************************************************/
+
+/*
+ * This method converts a path to canonical form on GNU/Posix systems.
+ * This involves the removal of redundant separators, references to
+ * "." and "..", and symbolic links.
+ *
+ * The conversion proceeds on a component-by-component basis: symbolic
+ * links and references to ".." are resolved as and when they occur.
+ * This means that if "/foo/bar" is a symbolic link to "/baz" then the
+ * canonical form of "/foo/bar/.." is "/" and not "/foo".
+ *
+ * In order to mimic the behaviour of proprietary JVMs, non-existant
+ * path components are allowed (a departure from the normal GNU system
+ * convention). This means that if "/foo/bar" is a symbolic link to
+ * "/baz", the canonical form of "/non-existant-directory/../foo/bar"
+ * is "/baz".
+ *
+ * Class: java_io_VMFile
+ * Method: toCanonicalForm
+ * Signature: (Ljava/lang/String)Ljava/lang/String
+ */
+
+JNIEXPORT jstring JNICALL
+Java_java_io_VMFile_toCanonicalForm (JNIEnv *env,
+ jclass class __attribute__ ((__unused__)),
+ jstring jpath)
+{
+#ifndef WITHOUT_FILESYSTEM
+ const char *path;
+ char *src, *dst;
+ int srci, dsti;
+ int srcl, dstl;
+ int len;
+ int fschecks;
+#if defined (HAVE_LSTAT) && defined (HAVE_READLINK)
+ struct stat sb;
+#endif /* HAVE_LSTAT && HAVE_READLINK */
+
+ path = JCL_jstring_to_cstring (env, jpath);
+ if (path == NULL)
+ return NULL;
+
+ /* It is the caller's responsibility to ensure the path is absolute. */
+ if (path[0] == 0 || path[0] != '/')
+ {
+ JCL_free_cstring (env, jpath, path);
+ JCL_ThrowException (env, "java/lang/RuntimeException", "Not absolute");
+ return NULL;
+ }
+
+ len = strlen (path);
+ srcl = nextChunkSize (len + 1);
+ src = JCL_malloc (env, srcl);
+ if (src == NULL)
+ {
+ JCL_free_cstring (env, jpath, path);
+ return NULL;
+ }
+ strcpy (src, path);
+ JCL_free_cstring (env, jpath, path);
+ srci = 1;
+
+ dstl = nextChunkSize (2);
+ dst = JCL_malloc (env, dstl);
+ if (dst == NULL)
+ {
+ JCL_free (env, src);
+ return NULL;
+ }
+ dst[0] = '/';
+ dsti = 1;
+
+ fschecks = JNI_TRUE;
+
+ while (src[srci] != '\0')
+ {
+ int tmpi, dsti_save;
+
+ /* Skip slashes. */
+ while (src[srci] == '/')
+ srci++;
+ tmpi = srci;
+ /* Find next slash. */
+ while (src[srci] != '/' && src[srci] != '\0')
+ srci++;
+ if (srci == tmpi)
+ /* We hit the end. */
+ break;
+ len = srci - tmpi;
+
+ /* Handle "." and "..". */
+ if (len == 1 && src[tmpi] == '.')
+ continue;
+ if (len == 2 && src[tmpi] == '.' && src[tmpi + 1] == '.')
+ {
+ while (dsti > 1 && dst[dsti - 1] != '/')
+ dsti--;
+ if (dsti != 1)
+ dsti--;
+ /* Reenable filesystem checking if disabled, as we might
+ * have reversed over whatever caused the problem before.
+ * At least one proprietary JVM has inconsistencies because
+ * it does not do this.
+ */
+ fschecks = JNI_TRUE;
+ continue;
+ }
+
+ /* Handle real path components. */
+ dst = maybeGrowBuf (env,
+ dst, &dstl, dsti + (dsti > 1 ? 1 : 0) + len + 1);
+ if (dst == NULL)
+ {
+ JCL_free (env, src);
+ return NULL;
+ }
+ dsti_save = dsti;
+ if (dsti > 1)
+ dst[dsti++] = '/';
+ strncpy (&dst[dsti], &src[tmpi], len);
+ dsti += len;
+ if (fschecks == JNI_FALSE)
+ continue;
+
+#if defined (HAVE_LSTAT) && defined (HAVE_READLINK)
+ dst[dsti] = '\0';
+ if (lstat (dst, &sb) == 0)
+ {
+ if (S_ISLNK (sb.st_mode))
+ {
+ int tmpl = CHUNKSIZ;
+ char *tmp = JCL_malloc (env, tmpl);
+ if (tmp == NULL)
+ {
+ JCL_free (env, src);
+ JCL_free (env, dst);
+ return NULL;
+ }
+
+ while (1)
+ {
+ tmpi = readlink (dst, tmp, tmpl);
+ if (tmpi < 1)
+ {
+ JCL_free (env, src);
+ JCL_free (env, dst);
+ JCL_free (env, tmp);
+ JCL_ThrowException (env, "java/io/IOException",
+ "readlink failed");
+ return NULL;
+ }
+ if (tmpi < tmpl)
+ break;
+ tmpl += CHUNKSIZ;
+ tmp = JCL_realloc (env, tmp, tmpl);
+ }
+
+ /* Prepend the link's path to src. */
+ tmp = maybeGrowBuf (env,
+ tmp, &tmpl, tmpi + strlen (&src[srci]) + 1);
+ if (tmp == NULL)
+ {
+ JCL_free (env, src);
+ JCL_free (env, dst);
+ return NULL;
+ }
+
+ strcpy (&tmp[tmpi], &src[srci]);
+ JCL_free (env, src);
+ src = tmp;
+ srcl = tmpl;
+ srci = 0;
+
+ /* Either replace or append dst depending on whether the
+ * link is relative or absolute.
+ */
+ dsti = src[0] == '/' ? 1 : dsti_save;
+ }
+ }
+ else
+ {
+ /* Something doesn't exist, or we don't have permission to
+ * read it, or a previous path component is a directory, or
+ * a symlink is looped. Whatever, we can't check the
+ * filesystem any more.
+ */
+ fschecks = JNI_FALSE;
+ }
+#endif /* HAVE_LSTAT && HAVE_READLINK */
+ }
+ dst[dsti] = '\0';
+
+ jpath = (*env)->NewStringUTF (env, dst);
+ JCL_free (env, src);
+ JCL_free (env, dst);
+ return jpath;
+#else /* not WITHOUT_FILESYSTEM */
+ return NULL;
+#endif /* not WITHOUT_FILESYSTEM */
+}
diff --git a/native/jni/midi-dssi/dssi_data.h b/native/jni/midi-dssi/dssi_data.h
index 8278f7b9e..27a4e2831 100644
--- a/native/jni/midi-dssi/dssi_data.h
+++ b/native/jni/midi-dssi/dssi_data.h
@@ -1,5 +1,5 @@
/* dssi_data.h - DSSI data
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -55,11 +55,6 @@ exception statement from your version. */
1/40th of a second). */
#define EVENT_BUFFER_SIZE 1024
-/* Helper macros for going between pointers and jlongs. */
-#define JLONG_TO_PTR(T,P) ((T *)(long)P)
-#define PTR_TO_JLONG(P) ((jlong)(long)P)
-
-
/* Every DSSI Synthesizer has one of these associated with it. The
Java class sees it as a "long" handle. */
diff --git a/native/jni/qt-peer/qtmenupeer.cpp b/native/jni/qt-peer/qtmenupeer.cpp
index 1ac17145c..6f35c89b9 100644
--- a/native/jni/qt-peer/qtmenupeer.cpp
+++ b/native/jni/qt-peer/qtmenupeer.cpp
@@ -44,9 +44,11 @@ exception statement from your version. */
#include "slotcallbacks.h"
#include "componentevent.h"
-#define ADDMENU 0
-#define ADDITEM 1
-#define ADDSEPA 2
+typedef enum ActionType {
+ ActionMenu,
+ ActionItem,
+ ActionSeparator
+} ActionType;
// Sets the title, but also tear-off.
class MenuTitleEvent : public AWTEvent {
@@ -81,18 +83,18 @@ class MenuAction : public AWTEvent {
private:
QMenu *menu;
QAction *action;
- int isMenu; // 0 to add a menu, 1 to add an item, 2 to add a seperator
+ ActionType actionType; // type of action to add
JavaVM *vm;
jobject menuPeer;
jobject itemPeer;
public:
MenuAction(JNIEnv *env, jobject mp, jobject ip, QMenu *m, QAction *a,
- bool ismenu) : AWTEvent()
+ ActionType actionType) : AWTEvent()
{
menu = m;
action = a;
- isMenu = ismenu;
+ this->actionType = actionType;
env->GetJavaVM( &vm );
menuPeer = env->NewGlobalRef( mp );
if( ip != NULL )
@@ -104,35 +106,22 @@ public:
void runEvent()
{
JNIEnv *env;
- QAction *newAction; // adding an action creates a new duplicate.
vm->GetEnv((void **)&env, JNI_VERSION_1_1);
-
- switch(isMenu)
- {
- case ADDMENU:
- newAction = menu->addMenu( (QMenu *)action );
- break;
- case ADDITEM:
- newAction = menu->addAction(action->text());
- newAction->setSeparator(action->isSeparator());
- newAction->setCheckable(action->isCheckable());
- // delete action;
- break;
- case ADDSEPA:
- newAction = menu->addSeparator();
- break;
- }
+ if (actionType == ActionMenu)
+ menu->addMenu ((QMenu *) action);
+ else
+ menu->addAction (action);
jclass menuCls = env->GetObjectClass( menuPeer );
jmethodID mid = env->GetMethodID(menuCls, "add", "(J)V");
env->DeleteLocalRef(menuCls);
- env->CallVoidMethod( menuPeer, mid, (jlong)newAction );
+ env->CallVoidMethod( menuPeer, mid, (jlong)action );
env->DeleteGlobalRef( menuPeer );
if( itemPeer != NULL )
{
- setNativeObject( env, itemPeer, newAction );
- connectAction(newAction, env, itemPeer);
+ setNativeObject( env, itemPeer, action );
+ connectAction(action, env, itemPeer);
env->DeleteGlobalRef( itemPeer );
}
}
@@ -190,7 +179,7 @@ JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtMenuPeer_insertSeperator
QMenu *menu = (QMenu *)getNativeObject( env, obj );
assert( menu );
mainThread->postEventToMain( new MenuAction( env, obj, NULL,
- menu, NULL, ADDSEPA ) );
+ menu, NULL, ActionSeparator ) );
}
/*
@@ -205,7 +194,7 @@ JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtMenuPeer_insertItem
QAction *action = (QAction *)getNativeObject( env, item );
assert( action );
- mainThread->postEventToMain( new MenuAction( env, obj, item, menu, action, ADDITEM ));
+ mainThread->postEventToMain( new MenuAction( env, obj, item, menu, action, ActionItem ));
}
/*
@@ -220,7 +209,7 @@ JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtMenuPeer_insertMenu
QMenu *insMenu = (QMenu *)getNativeObject(env, menu);
assert( insMenu );
- mainThread->postEventToMain( new MenuAction( env, obj, menu, thisMenu, (QAction *)insMenu, ADDMENU ) );
+ mainThread->postEventToMain( new MenuAction( env, obj, menu, thisMenu, (QAction *)insMenu, ActionMenu ) );
}
/*
diff --git a/native/plugin/Makefile.am b/native/plugin/Makefile.am
index 7358381eb..e1331fe45 100644
--- a/native/plugin/Makefile.am
+++ b/native/plugin/Makefile.am
@@ -4,15 +4,15 @@ libgcjwebplugin_la_SOURCES = gcjwebplugin.cc
libgcjwebplugin_la_CXXFLAGS = \
-Wall -DAPPLETVIEWER_EXECUTABLE="\"$(bindir)/appletviewer\"" \
- $(MOZILLA_CFLAGS) $(GLIB_CFLAGS)
+ $(MOZILLA_CFLAGS) $(GLIB_CFLAGS) $(GTK_CFLAGS)
libgcjwebplugin_la_LDFLAGS = -avoid-version \
- $(GLIB_LIBS) \
+ $(GLIB_LIBS) $(GTK_LIBS) \
-lstdc++
-install-libLTLIBRARIES: $(lib_LTLIBRARIES)
- $(INSTALL) -d -m0755 $(DESTDIR)@PLUGIN_DIR@
- $(INSTALL) .libs/libgcjwebplugin.so $(DESTDIR)@PLUGIN_DIR@
+install-plugin: $(lib_LTLIBRARIES)
+ $(INSTALL) -d -m0755 $(DESTDIR)$(PLUGIN_DIR)
+ $(INSTALL) .libs/libgcjwebplugin.so $(DESTDIR)$(PLUGIN_DIR)
-uninstall-libLTLIBRARIES:
- rm -f $(DESTDIR)@PLUGIN_DIR@/libgcjwebplugin.so
+uninstall-plugin:
+ rm -f $(DESTDIR)$(PLUGIN_DIR)/libgcjwebplugin.so
diff --git a/native/plugin/gcjwebplugin.cc b/native/plugin/gcjwebplugin.cc
index bbb9809be..ad65c7ef1 100644
--- a/native/plugin/gcjwebplugin.cc
+++ b/native/plugin/gcjwebplugin.cc
@@ -49,6 +49,10 @@ exception statement from your version. */
// GLib includes.
#include <glib.h>
+#include <glib/gstdio.h>
+
+// GTK includes.
+#include <gtk/gtk.h>
// gcjwebplugin includes.
#include "config.h"
@@ -75,6 +79,10 @@ exception statement from your version. */
g_printerr ("%s:%d: thread %p: Error: %s: %s\n", __FILE__, __LINE__, \
g_thread_self (), first, second)
+#define PLUGIN_ERROR_THREE(first, second, third) \
+ g_printerr ("%s:%d: thread %p: Error: %s: %s: %s\n", __FILE__, \
+ __LINE__, g_thread_self (), first, second, third)
+
// Plugin information passed to about:plugins.
#define PLUGIN_NAME "GCJ Web Browser Plugin"
#define PLUGIN_DESC "The " PLUGIN_NAME " executes Java applets."
@@ -113,8 +121,25 @@ exception statement from your version. */
#define PLUGIN_FILE_EXTS "class,jar,zip"
#define PLUGIN_MIME_COUNT 1
-// Directory in which named pipes are created.
-#define PIPE_DIRECTORY "/tmp"
+// Security dialog messages.
+#define RESPONSE_TRUST_APPLET "Trust Applet"
+#define RESPONSE_TRUST_APPLET_ADD_TO_LIST "Trust Applet and Add to Whitelist"
+#define SECURITY_WARNING \
+ "%s wants to load an applet.\n" \
+ "GNU Classpath's security implementation is not complete.\n" \
+ "HOSTILE APPLETS WILL STEAL AND/OR DESTROY YOUR DATA!\n"
+#define SECURITY_DESCRIPTION \
+ "Click \"Cancel\" if you do not trust the source of this applet.\n" \
+ "Click \"Trust Applet\" to load and run this applet now.\n" \
+ "Click \"Trust Applet and Add To Whitelist\" to always load" \
+ " and run this applet from now on, without asking.\n" \
+ "The whitelist is a list of the URLs from which you trust" \
+ " applets.\n" \
+ "Your whitelist file is \" %s \"."
+#define FAILURE_MESSAGE \
+ "This page wants to load an applet.\n" \
+ "The appletviewer is missing or not installed properly in \"" \
+ APPLETVIEWER_EXECUTABLE "\"."
// Documentbase retrieval required definition.
static NS_DEFINE_IID (kIPluginTagInfo2IID, NS_IPLUGINTAGINFO2_IID);
@@ -122,6 +147,16 @@ static NS_DEFINE_IID (kIPluginTagInfo2IID, NS_IPLUGINTAGINFO2_IID);
// Browser function table.
static NPNetscapeFuncs browserFunctions;
+// Data directory for plugin.
+static gchar* data_directory;
+
+// Whitelist filename
+static gchar* whitelist_filename;
+
+// Keeps track of initialization. NP_Initialize should only be
+// called once.
+gboolean initialized = false;
+
// GCJPluginData stores all the data associated with a single plugin
// instance. A separate plugin instance is created for each <APPLET>
// tag. For now, each plugin instance spawns its own applet viewer
@@ -173,6 +208,12 @@ typedef union
static void plugin_data_new (GCJPluginData** data);
// Documentbase retrieval.
static gchar* plugin_get_documentbase (NPP instance);
+// plugin failure handling.
+static bool plugin_failed ();
+// Whitelist handling.
+static bool plugin_user_trusts_documentbase (char* documentbase);
+static bool plugin_ask_user_about_documentbase (char* documentbase);
+static void plugin_add_documentbase_to_whitelist (char* documentbase);
// Callback used to monitor input pipe status.
static gboolean plugin_in_pipe_callback (GIOChannel* source,
GIOCondition condition,
@@ -181,7 +222,7 @@ static gboolean plugin_in_pipe_callback (GIOChannel* source,
static gboolean plugin_out_pipe_callback (GIOChannel* source,
GIOCondition condition,
gpointer plugin_data);
-static void plugin_start_appletviewer (GCJPluginData* data);
+static NPError plugin_start_appletviewer (GCJPluginData* data);
static gchar* plugin_create_applet_tag (int16 argc, char* argn[],
char* argv[]);
static void plugin_send_message_to_appletviewer (GCJPluginData* data,
@@ -195,6 +236,11 @@ static void plugin_data_destroy (GCJPluginData** data);
static GMutex* plugin_instance_mutex = NULL;
// A counter used to create uniquely named pipes.
static gulong plugin_instance_counter = 0;
+// The user's documentbase whitelist.
+static GIOChannel* whitelist_file = NULL;
+// A global variable for reporting GLib errors. This must be free'd
+// and set to NULL after each use.
+static GError* channel_error = NULL;
// Functions prefixed by GCJ_ are instance functions. They are called
// by the browser and operate on instances of GCJPluginData.
@@ -224,7 +270,7 @@ GCJ_New (NPMIMEType pluginType, NPP instance, uint16 mode,
NPError np_error = NPERR_NO_ERROR;
GCJPluginData* data = NULL;
- GError* channel_error = NULL;
+
gchar* documentbase = NULL;
gchar* read_message = NULL;
gchar* applet_tag = NULL;
@@ -278,13 +324,19 @@ GCJ_New (NPMIMEType pluginType, NPP instance, uint16 mode,
goto cleanup_appletviewer_mutex;
}
+ if (!plugin_user_trusts_documentbase (documentbase))
+ {
+ PLUGIN_ERROR ("User does not trust applet.");
+ np_error = NPERR_GENERIC_ERROR;
+ goto cleanup_appletviewer_mutex;
+ }
+
// Create appletviewer-to-plugin pipe which we refer to as the input
// pipe.
// data->in_pipe_name
- data->in_pipe_name = g_strdup_printf (PIPE_DIRECTORY
- "/gcj-%s-appletviewer-to-plugin",
- data->instance_string);
+ data->in_pipe_name = g_strdup_printf ("%s/gcj-%s-appletviewer-to-plugin",
+ data_directory, data->instance_string);
if (!data->in_pipe_name)
{
PLUGIN_ERROR ("Failed to create input pipe name.");
@@ -305,9 +357,8 @@ GCJ_New (NPMIMEType pluginType, NPP instance, uint16 mode,
// output pipe.
// data->out_pipe_name
- data->out_pipe_name = g_strdup_printf (PIPE_DIRECTORY
- "/gcj-%s-plugin-to-appletviewer",
- data->instance_string);
+ data->out_pipe_name = g_strdup_printf ("%s/gcj-%s-plugin-to-appletviewer",
+ data_directory, data->instance_string);
if (!data->out_pipe_name)
{
@@ -332,9 +383,17 @@ GCJ_New (NPMIMEType pluginType, NPP instance, uint16 mode,
// appletviewer, create the IO channels and install the channel
// watch callbacks.
g_mutex_lock (data->appletviewer_mutex);
-
- plugin_start_appletviewer (data);
-
+
+ np_error = plugin_start_appletviewer (data);
+
+ // If the appletviewer is not installed, then a dialog box will
+ // show up and the plugin will be killed.
+ if (np_error != NPERR_NO_ERROR)
+ {
+ if (plugin_failed ())
+ goto cleanup_applet_failure;
+ }
+
// Create plugin-to-appletviewer channel. The default encoding for
// the file is UTF-8.
// data->out_to_appletviewer
@@ -342,16 +401,19 @@ GCJ_New (NPMIMEType pluginType, NPP instance, uint16 mode,
"w", &channel_error);
if (!data->out_to_appletviewer)
{
- PLUGIN_ERROR_TWO ("Failed to create output channel",
- channel_error->message);
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Failed to create output channel",
+ channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Failed to create output channel");
+
np_error = NPERR_GENERIC_ERROR;
goto cleanup_out_to_appletviewer;
}
- if (channel_error)
- {
- g_error_free (channel_error);
- channel_error = NULL;
- }
// Watch for hangup and error signals on the output pipe.
data->out_watch_source =
@@ -366,16 +428,19 @@ GCJ_New (NPMIMEType pluginType, NPP instance, uint16 mode,
"r", &channel_error);
if (!data->in_from_appletviewer)
{
- PLUGIN_ERROR_TWO ("Failed to create input channel",
- channel_error->message);
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Failed to create input channel",
+ channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Failed to create input channel");
+
np_error = NPERR_GENERIC_ERROR;
goto cleanup_in_from_appletviewer;
}
- if (channel_error)
- {
- g_error_free (channel_error);
- channel_error = NULL;
- }
// Watch for hangup and error signals on the input pipe.
data->in_watch_source =
@@ -390,16 +455,19 @@ GCJ_New (NPMIMEType pluginType, NPP instance, uint16 mode,
&channel_error)
!= G_IO_STATUS_NORMAL)
{
- PLUGIN_ERROR_TWO ("Receiving confirmation from appletviewer failed",
- channel_error->message);
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Receiving confirmation from appletviewer failed",
+ channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Receiving confirmation from appletviewer failed");
+
np_error = NPERR_GENERIC_ERROR;
goto cleanup_in_watch_source;
}
- if (channel_error)
- {
- g_error_free (channel_error);
- channel_error = NULL;
- }
PLUGIN_DEBUG ("GCJ_New: got confirmation that appletviewer is running.");
data->appletviewer_alive = TRUE;
@@ -448,7 +516,8 @@ GCJ_New (NPMIMEType pluginType, NPP instance, uint16 mode,
// cleanup_out_pipe:
// Delete output pipe.
unlink (data->out_pipe_name);
-
+
+ cleanup_applet_failure:
cleanup_out_pipe_name:
g_free (data->out_pipe_name);
data->out_pipe_name = NULL;
@@ -480,7 +549,6 @@ GCJ_New (NPMIMEType pluginType, NPP instance, uint16 mode,
instance->pdata = NULL;
cleanup_done:
-
g_free (tag_message);
tag_message = NULL;
g_free (applet_tag);
@@ -602,6 +670,7 @@ GCJ_SetWindow (NPP instance, NPWindow* window)
window->width);
plugin_send_message_to_appletviewer (data, width_message);
g_free (width_message);
+ width_message = NULL;
// Store the new width.
data->window_width = window->width;
@@ -619,6 +688,7 @@ GCJ_SetWindow (NPP instance, NPWindow* window)
window->height);
plugin_send_message_to_appletviewer (data, height_message);
g_free (height_message);
+ height_message = NULL;
// Store the new height.
data->window_height = window->height;
@@ -651,6 +721,7 @@ GCJ_SetWindow (NPP instance, NPWindow* window)
(gulong) window->window);
plugin_send_message_to_appletviewer (data, window_message);
g_free (window_message);
+ window_message = NULL;
g_mutex_unlock (data->appletviewer_mutex);
@@ -833,6 +904,201 @@ plugin_get_documentbase (NPP instance)
return documentbase_copy;
}
+// This function shows a error message if the appletviewer has
+// not been installed. It returns true, if the user presses the
+// ok button.
+static bool
+plugin_failed ()
+{
+ GtkWidget* dialog = NULL;
+ GtkWidget* ok_button = NULL;
+
+ dialog = gtk_message_dialog_new (NULL,
+ GTK_DIALOG_MODAL,
+ GTK_MESSAGE_WARNING,
+ GTK_BUTTONS_NONE,
+ FAILURE_MESSAGE);
+ ok_button = gtk_dialog_add_button (GTK_DIALOG (dialog),
+ GTK_STOCK_OK,
+ GTK_RESPONSE_OK);
+ gtk_widget_show_all (dialog);
+ if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_OK)
+ {
+ gtk_widget_destroy (dialog);
+ return true;
+ }
+ return false;
+}
+
+// plugin_user_trusts_documentbase returns true if the given
+// documentbase is in the documentbase whitelist. Otherwise it asks
+// the user if he trusts the given documentbase by calling
+// plugin_ask_user_about_documentbase.
+static bool
+plugin_user_trusts_documentbase (char* documentbase)
+{
+ bool applet_in_whitelist = false;
+
+ // Check if documentbase is in whitelist.
+ while (true)
+ {
+ gchar* whitelist_entry = NULL;
+ gchar* newline_documentbase = NULL;
+
+ // If reading fails, break out of this loop with
+ // applet_in_whitelist still set to false.
+ if (g_io_channel_read_line (whitelist_file, &whitelist_entry,
+ NULL, NULL, &channel_error)
+ != G_IO_STATUS_NORMAL)
+ {
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Failed to read line from whitelist file",
+ channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Failed to open whitelist file.");
+ g_free (whitelist_entry);
+ whitelist_entry = NULL;
+ break;
+ }
+
+ newline_documentbase = g_strdup_printf ("%s\n", documentbase);
+ if (!strcmp (newline_documentbase, whitelist_entry))
+ {
+ applet_in_whitelist = true;
+ g_free (newline_documentbase);
+ newline_documentbase = NULL;
+ g_free (whitelist_entry);
+ whitelist_entry = NULL;
+ break;
+ }
+ g_free (whitelist_entry);
+ whitelist_entry = NULL;
+ g_free (newline_documentbase);
+ newline_documentbase = NULL;
+ }
+
+ return applet_in_whitelist ? true
+ : plugin_ask_user_about_documentbase (documentbase);
+}
+
+// plugin_add_documentbase_to_whitelist adds the given documentbase to
+// the user's documentbase whitelist.
+static void
+plugin_add_documentbase_to_whitelist (char* documentbase)
+{
+ gsize bytes_written = 0;
+ char* newline_documentbase = NULL;
+ GIOStatus status = G_IO_STATUS_NORMAL;
+
+ newline_documentbase = g_strdup_printf ("%s\n", documentbase);
+ status = g_io_channel_write_chars (whitelist_file,
+ newline_documentbase, -1, &bytes_written,
+ &channel_error);
+ g_free (newline_documentbase);
+ newline_documentbase = NULL;
+
+ if (status != G_IO_STATUS_NORMAL)
+ {
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Error writing to whitelist file",
+ channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Error writing to whitelist file.");
+ }
+
+ if (g_io_channel_flush (whitelist_file, &channel_error)
+ != G_IO_STATUS_NORMAL)
+ {
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Failed to write whitelist file",
+ channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Failed to write whitelist file.");
+ }
+
+ if (g_io_channel_shutdown (whitelist_file, TRUE, &channel_error)
+ != G_IO_STATUS_NORMAL)
+ {
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Failed to close whitelist file",
+ channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Failed to close whitelist file.");
+ }
+}
+
+// plugin_ask_user_about_documentbase puts up a dialog box that asks if the
+// user trusts applets from this documentbase. The user has three
+// options: "Cancel", "Trust Applet" and "Trust Applet and Add to
+// Whitelist". If the user selects Cancel (the default) then a
+// generic error code is returned from GCJ_New, telling the browser
+// that the applet failed to load. If the user selects "Trust Applet"
+// then plugin loading proceeds. If the user selects "Trust Applet
+// and Add to Whitelist" then this documentbase is added to the user's
+// applet whitelist and plugin loading proceeds.
+static bool
+plugin_ask_user_about_documentbase (char* documentbase)
+{
+ GtkWidget* dialog = NULL;
+ GtkWidget* ok_button = NULL;
+ GtkWidget* cancel_button = NULL;
+ GtkWidget* whitelist_button = NULL;
+ gint dialog_response = GTK_RESPONSE_NONE;
+
+ dialog = gtk_message_dialog_new (NULL,
+ GTK_DIALOG_MODAL,
+ GTK_MESSAGE_WARNING,
+ GTK_BUTTONS_NONE,
+ SECURITY_WARNING,
+ documentbase);
+ gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
+ SECURITY_DESCRIPTION, whitelist_filename);
+
+ cancel_button = gtk_dialog_add_button (GTK_DIALOG (dialog),
+ GTK_STOCK_CANCEL,
+ GTK_RESPONSE_CANCEL);
+ ok_button = gtk_dialog_add_button (GTK_DIALOG (dialog),
+ RESPONSE_TRUST_APPLET,
+ GTK_RESPONSE_OK);
+ whitelist_button = gtk_dialog_add_button (GTK_DIALOG (dialog),
+ RESPONSE_TRUST_APPLET_ADD_TO_LIST,
+ GTK_RESPONSE_APPLY);
+ gtk_widget_grab_focus (cancel_button);
+
+ gtk_widget_show_all (dialog);
+ dialog_response = gtk_dialog_run (GTK_DIALOG (dialog));
+ gtk_widget_destroy (dialog);
+ if (dialog_response == GTK_RESPONSE_CANCEL)
+ {
+ // The user does not trust this documentbase.
+ return false;
+ }
+ else if (dialog_response == GTK_RESPONSE_APPLY)
+ {
+ // The user wants this documentbase added to his documentbase
+ // whitelist.
+ plugin_add_documentbase_to_whitelist (documentbase);
+ }
+ // The user trusts this documentbase.
+ return true;
+}
+
// plugin_in_pipe_callback is called when data is available on the
// input pipe, or when the appletviewer crashes or is killed. It may
// be called after data has been destroyed in which case it simply
@@ -858,7 +1124,6 @@ plugin_in_pipe_callback (GIOChannel* source,
if (condition & G_IO_IN)
{
- GError* channel_error = NULL;
gchar* message = NULL;
if (g_io_channel_read_line (data->in_from_appletviewer,
@@ -866,8 +1131,15 @@ plugin_in_pipe_callback (GIOChannel* source,
&channel_error)
!= G_IO_STATUS_NORMAL)
{
- PLUGIN_ERROR_TWO ("Failed to read line from input channel",
- channel_error->message);
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Failed to read line from input channel",
+ channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Failed to read line from input channel");
}
else
{
@@ -899,12 +1171,6 @@ plugin_in_pipe_callback (GIOChannel* source,
g_print (" PIPE: plugin read %s\n", message);
}
- if (channel_error)
- {
- g_error_free (channel_error);
- channel_error = NULL;
- }
-
g_free (message);
message = NULL;
@@ -958,14 +1224,14 @@ plugin_out_pipe_callback (GIOChannel* source,
return FALSE;
}
-static void
+static NPError
plugin_start_appletviewer (GCJPluginData* data)
{
PLUGIN_DEBUG ("plugin_start_appletviewer");
-
+ NPError error = NPERR_NO_ERROR;
+
if (!data->appletviewer_alive)
{
- GError* spawn_error = NULL;
gchar* command_line[3] = { NULL, NULL, NULL };
command_line[0] = g_strdup (APPLETVIEWER_EXECUTABLE);
@@ -977,25 +1243,32 @@ plugin_start_appletviewer (GCJPluginData* data)
command_line[2] = NULL;
if (!g_spawn_async (NULL, command_line, NULL, (GSpawnFlags) 0,
- NULL, NULL, NULL, &spawn_error))
+ NULL, NULL, NULL, &channel_error))
{
- PLUGIN_ERROR_TWO ("Failed to spawn applet viewer",
- spawn_error->message);
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Failed to spawn applet viewer",
+ channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Failed to spawn applet viewer");
+ error = NPERR_GENERIC_ERROR;
goto cleanup;
}
cleanup:
g_free (command_line[0]);
+ command_line[0] = NULL;
g_free (command_line[1]);
+ command_line[1] = NULL;
g_free (command_line[2]);
- if (spawn_error)
- {
- g_error_free (spawn_error);
- spawn_error = NULL;
- }
+ command_line[2] = NULL;
}
PLUGIN_DEBUG ("plugin_start_appletviewer return");
+ return error;
}
// Build up the applet tag string that we'll send to the applet
@@ -1015,30 +1288,35 @@ plugin_create_applet_tag (int16 argc, char* argn[], char* argv[])
gchar* code = g_strdup_printf ("CODE=\"%s\" ", argv[i]);
applet_tag = g_strconcat (applet_tag, code, NULL);
g_free (code);
+ code = NULL;
}
else if (!g_ascii_strcasecmp (argn[i], "codebase"))
{
gchar* codebase = g_strdup_printf ("CODEBASE=\"%s\" ", argv[i]);
applet_tag = g_strconcat (applet_tag, codebase, NULL);
g_free (codebase);
+ codebase = NULL;
}
else if (!g_ascii_strcasecmp (argn[i], "archive"))
{
gchar* archive = g_strdup_printf ("ARCHIVE=\"%s\" ", argv[i]);
applet_tag = g_strconcat (applet_tag, archive, NULL);
g_free (archive);
+ archive = NULL;
}
else if (!g_ascii_strcasecmp (argn[i], "width"))
{
gchar* width = g_strdup_printf ("WIDTH=\"%s\" ", argv[i]);
applet_tag = g_strconcat (applet_tag, width, NULL);
g_free (width);
+ width = NULL;
}
else if (!g_ascii_strcasecmp (argn[i], "height"))
{
gchar* height = g_strdup_printf ("HEIGHT=\"%s\" ", argv[i]);
applet_tag = g_strconcat (applet_tag, height, NULL);
g_free (height);
+ height = NULL;
}
else
{
@@ -1046,10 +1324,14 @@ plugin_create_applet_tag (int16 argc, char* argn[], char* argv[])
// characters will pass through the pipe.
if (argv[i] != '\0')
{
- gchar* escaped = g_strescape (argv[i], NULL);
+ gchar* escaped = NULL;
+
+ escaped = g_strescape (argv[i], NULL);
parameters = g_strconcat (parameters, "<PARAM NAME=\"", argn[i],
"\" VALUE=\"", escaped, "\">", NULL);
+
g_free (escaped);
+ escaped = NULL;
}
}
}
@@ -1073,7 +1355,6 @@ plugin_send_message_to_appletviewer (GCJPluginData* data, gchar const* message)
if (data->appletviewer_alive)
{
- GError* channel_error = NULL;
gchar* newline_message = NULL;
gsize bytes_written = 0;
@@ -1086,27 +1367,34 @@ plugin_send_message_to_appletviewer (GCJPluginData* data, gchar const* message)
if (g_io_channel_write_chars (data->out_to_appletviewer,
newline_message, -1, &bytes_written,
&channel_error)
- != G_IO_STATUS_NORMAL)
- PLUGIN_ERROR_TWO ("Failed to write bytes to output channel",
- channel_error->message);
-
- if (channel_error)
+ != G_IO_STATUS_NORMAL)
{
- g_error_free (channel_error);
- channel_error = NULL;
- }
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Failed to write bytes to output channel",
+ channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Failed to write bytes to output channel");
+ }
if (g_io_channel_flush (data->out_to_appletviewer, &channel_error)
!= G_IO_STATUS_NORMAL)
- PLUGIN_ERROR_TWO ("Failed to flush bytes to output channel",
- channel_error->message);
-
- if (channel_error)
{
- g_error_free (channel_error);
- channel_error = NULL;
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Failed to flush bytes to output channel",
+ channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Failed to flush bytes to output channel");
}
g_free (newline_message);
+ newline_message = NULL;
g_print (" PIPE: plugin wrote %s\n", message);
}
@@ -1135,7 +1423,6 @@ plugin_stop_appletviewer (GCJPluginData* data)
if (data->appletviewer_alive)
{
// Shut down the appletviewer.
- GError* channel_error = NULL;
gsize bytes_written = 0;
if (data->out_to_appletviewer)
@@ -1143,36 +1430,45 @@ plugin_stop_appletviewer (GCJPluginData* data)
if (g_io_channel_write_chars (data->out_to_appletviewer, "shutdown",
-1, &bytes_written, &channel_error)
!= G_IO_STATUS_NORMAL)
- PLUGIN_ERROR_TWO ("Failed to write shutdown message to"
- " appletviewer", channel_error->message);
-
- if (channel_error)
{
- g_error_free (channel_error);
- channel_error = NULL;
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Failed to write shutdown message to"
+ " appletviewer", channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Failed to write shutdown message to");
}
if (g_io_channel_flush (data->out_to_appletviewer, &channel_error)
!= G_IO_STATUS_NORMAL)
- PLUGIN_ERROR_TWO ("Failed to write shutdown message to"
- " appletviewer", channel_error->message);
-
- if (channel_error)
{
- g_error_free (channel_error);
- channel_error = NULL;
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Failed to write shutdown message to"
+ " appletviewer", channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Failed to write shutdown message to");
}
if (g_io_channel_shutdown (data->out_to_appletviewer,
TRUE, &channel_error)
!= G_IO_STATUS_NORMAL)
- PLUGIN_ERROR_TWO ("Failed to shut down appletviewer"
- " output channel", channel_error->message);
-
- if (channel_error)
{
- g_error_free (channel_error);
- channel_error = NULL;
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Failed to shut down appletviewer"
+ " output channel", channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Failed to shut down appletviewer");
}
}
@@ -1181,13 +1477,16 @@ plugin_stop_appletviewer (GCJPluginData* data)
if (g_io_channel_shutdown (data->in_from_appletviewer,
TRUE, &channel_error)
!= G_IO_STATUS_NORMAL)
- PLUGIN_ERROR_TWO ("Failed to shut down appletviewer"
- " input channel", channel_error->message);
-
- if (channel_error)
{
- g_error_free (channel_error);
- channel_error = NULL;
+ if (channel_error)
+ {
+ PLUGIN_ERROR_TWO ("Failed to shut down appletviewer"
+ " input channel", channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR ("Failed to shut down appletviewer");
}
}
}
@@ -1267,18 +1566,25 @@ plugin_data_destroy (GCJPluginData** data)
// implement and initializes a local table with browser functions that
// we may wish to call. Called once, after browser startup and before
// the first plugin instance is created.
+// The field 'initialized' is set to true once this function has
+// finished. If 'initialized' is already true at the beginning of
+// this function, then it is evident that NP_Initialize has already
+// been called. There is no need to call this function more than once and
+// this workaround avoids any duplicate calls.
NPError
NP_Initialize (NPNetscapeFuncs* browserTable, NPPluginFuncs* pluginTable)
{
PLUGIN_DEBUG ("NP_Initialize");
-
- if ((browserTable == NULL) || (pluginTable == NULL))
+
+ if (initialized)
+ return NPERR_NO_ERROR;
+ else if ((browserTable == NULL) || (pluginTable == NULL))
{
PLUGIN_ERROR ("Browser or plugin function table is NULL.");
return NPERR_INVALID_FUNCTABLE_ERROR;
}
-
+
// Ensure that the major version of the plugin API that the browser
// expects is not more recent than the major version of the API that
// we've implemented.
@@ -1307,6 +1613,45 @@ NP_Initialize (NPNetscapeFuncs* browserTable, NPPluginFuncs* pluginTable)
return NPERR_INVALID_FUNCTABLE_ERROR;
}
+ data_directory = g_strconcat(getenv("HOME"), "/.gcjwebplugin", NULL);
+ whitelist_filename = g_strconcat (data_directory, "/whitelist.txt", NULL);
+ // Make sure the plugin data directory exists, creating it if
+ // necessary.
+ if (!g_file_test (data_directory,
+ (GFileTest) (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
+ {
+ int file_error = 0;
+
+ file_error = g_mkdir (data_directory, 0700);
+ if (file_error != 0)
+ {
+ PLUGIN_ERROR_THREE ("Failed to create data directory",
+ data_directory,
+ strerror (errno));
+ return NPERR_GENERIC_ERROR;
+ }
+ }
+
+ // Open the user's documentbase whitelist.
+ whitelist_file = g_io_channel_new_file (whitelist_filename,
+ "a+", &channel_error);
+ if (!whitelist_file)
+ {
+ if (channel_error)
+ {
+ PLUGIN_ERROR_THREE ("Failed to open whitelist file",
+ whitelist_filename,
+ channel_error->message);
+ g_error_free (channel_error);
+ channel_error = NULL;
+ }
+ else
+ PLUGIN_ERROR_TWO ("Failed to open whitelist file",
+ whitelist_filename);
+
+ return NPERR_GENERIC_ERROR;
+ }
+
// Store in a local table the browser functions that we may use.
browserFunctions.version = browserTable->version;
browserFunctions.size = browserTable->size;
@@ -1339,7 +1684,8 @@ NP_Initialize (NPNetscapeFuncs* browserTable, NPPluginFuncs* pluginTable)
pluginTable->print = NewNPP_PrintProc (GCJ_Print);
pluginTable->urlnotify = NewNPP_URLNotifyProc (GCJ_URLNotify);
pluginTable->getvalue = NewNPP_GetValueProc (GCJ_GetValue);
-
+
+ initialized = true;
plugin_instance_mutex = g_mutex_new ();
PLUGIN_DEBUG ("NP_Initialize: using " APPLETVIEWER_EXECUTABLE ".");
@@ -1402,9 +1748,32 @@ NP_Shutdown (void)
PLUGIN_DEBUG ("NP_Shutdown");
// Free mutex.
- g_mutex_free (plugin_instance_mutex);
- plugin_instance_mutex = NULL;
+ if (plugin_instance_mutex)
+ {
+ g_mutex_free (plugin_instance_mutex);
+ plugin_instance_mutex = NULL;
+ }
+ if (whitelist_file)
+ {
+ g_io_channel_close (whitelist_file);
+ whitelist_file = NULL;
+ }
+
+ if (data_directory)
+ {
+ g_free (data_directory);
+ data_directory = NULL;
+ }
+
+ if (whitelist_filename)
+ {
+ g_free (whitelist_filename);
+ whitelist_filename = NULL;
+ }
+
+ initialized = false;
+
PLUGIN_DEBUG ("NP_Shutdown return");
return NPERR_NO_ERROR;
diff --git a/resource/gnu/classpath/tools/keytool/messages.properties b/resource/gnu/classpath/tools/keytool/messages.properties
index 71b70a766..98f4e6842 100644
--- a/resource/gnu/classpath/tools/keytool/messages.properties
+++ b/resource/gnu/classpath/tools/keytool/messages.properties
@@ -40,6 +40,9 @@
Main.6=keytool: {0}
Main.8=keytool error: {0}
+Main.5=Import a CA's Trusted Certificate.\n\
+[-file FILE] [-storetype STORE_TYPE] [-keystore URL]\n\
+[-storepass PASSWORD] [-provider PROVIDER_CLASS_NAME] [-v].
Main.18=Unrecognized command: {0}
Main.19=Usage: keytool [COMMAND] [-- COMMAND]...\n\
Manage private keys and public certificates.
@@ -540,3 +543,28 @@ SelfCertCmd.33=Fully qualified class name of a Security Provider to add to the \
JVM in-use.
SelfCertCmd.34=PROVIDER_CLASS_NAME
SelfCertCmd.35=Emit more verbose messages.
+
+CACertCmd.0=Alias [{0}] is already present in key store
+CACertCmd.1=Certificate in file "{0}" was added to the key store under the alias "{1}"
+CACertCmd.2=Usage: keytool -cacert [OPTION]...\n\
+Import a trusted CA certificate.
+CACertCmd.3=Please report bugs at http://www.gnu.org/software/classpath/bugs.html
+CACertCmd.4=Command options
+CACertCmd.5=Location of the trusted CA certificate to import.
+CACertCmd.6=FILE
+CACertCmd.7=Type of the key store to use. If omitted, the default value is \
+that of the property "keystore.type" in the security properties file.
+CACertCmd.8=STORE_TYPE
+CACertCmd.9=Location of the key store to use. The default value is a \
+file-based scheme whose path is the file named ".keystore" in your home \
+directory.\n\
+If URL is malformed, the tool will use URL as a file-name of a key store; \
+i.e. as if the protocol was "file:".
+CACertCmd.10=URL
+CACertCmd.11=Password to unlock the key store. If omitted, you will be \
+prompted for one.
+CACertCmd.12=PASSWORD
+CACertCmd.13=Fully qualified class name of a Security Provider to add to the \
+JVM in-use.
+CACertCmd.14=PROVIDER_CLASS_NAME
+CACertCmd.15=Emit more verbose messages.
diff --git a/tools/.cvsignore b/tools/.cvsignore
index cf3688511..141547731 100644
--- a/tools/.cvsignore
+++ b/tools/.cvsignore
@@ -4,3 +4,4 @@ Makefile.in
Makefile
tools.zip
appletviewer
+.deps
diff --git a/tools/Makefile.am b/tools/Makefile.am
index 713c5827a..1be6c41e6 100755
--- a/tools/Makefile.am
+++ b/tools/Makefile.am
@@ -21,7 +21,7 @@ bin_PROGRAMS = appletviewer jarsigner keytool
#LIBJVM = -lgcj
#else
if FOUND_CACAO
-LIBJVM = -lcacaovm
+LIBJVM = -ljvm
else
LIBJVM =
endif
@@ -32,21 +32,21 @@ appletviewer_CFLAGS = -Wall \
-DDATA_DIR="\"$(datadir)\"" \
-DPACKAGE="\"$(PACKAGE)\"" \
-DTOOLNAME="\"appletviewer\""
-appletviewer_LDFLAGS = $(LIBJVM)
+appletviewer_LDFLAGS = -L$(libdir) $(LIBJVM)
jarsigner_SOURCES = toolwrapper.c
jarsigner_CFLAGS = -Wall \
-DDATA_DIR="\"$(datadir)\"" \
-DPACKAGE="\"$(PACKAGE)\"" \
-DTOOLNAME="\"jarsigner\""
-jarsigner_LDFLAGS = $(LIBJVM)
+jarsigner_LDFLAGS = -L$(libdir) $(LIBJVM)
keytool_SOURCES = toolwrapper.c
keytool_CFLAGS = -Wall \
-DDATA_DIR="\"$(datadir)\"" \
-DPACKAGE="\"$(PACKAGE)\"" \
-DTOOLNAME="\"keytool\""
-keytool_LDFLAGS = $(LIBJVM)
+keytool_LDFLAGS = -L$(libdir) $(LIBJVM)
else
bin_SCRIPTS = appletviewer jarsigner keytool
diff --git a/tools/gnu/classpath/tools/appletviewer/AppletTag.java b/tools/gnu/classpath/tools/appletviewer/AppletTag.java
index 4c3d01edb..80d572857 100644
--- a/tools/gnu/classpath/tools/appletviewer/AppletTag.java
+++ b/tools/gnu/classpath/tools/appletviewer/AppletTag.java
@@ -451,7 +451,7 @@ class AppletTag
else
{
String dirname = documentbase.getFile();
- if (!new File(dirname).isFile())
+ if (dirname.indexOf(".") < 0)
fullcodebase = new URL(documentbase + File.separator);
else
{
diff --git a/tools/gnu/classpath/tools/keytool/CACertCmd.java b/tools/gnu/classpath/tools/keytool/CACertCmd.java
new file mode 100644
index 000000000..912744713
--- /dev/null
+++ b/tools/gnu/classpath/tools/keytool/CACertCmd.java
@@ -0,0 +1,302 @@
+/* CACertCmd.java -- GNU specific cacert handler
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.classpath.tools.keytool;
+
+import gnu.classpath.tools.getopt.ClasspathToolParser;
+import gnu.classpath.tools.getopt.Option;
+import gnu.classpath.tools.getopt.OptionException;
+import gnu.classpath.tools.getopt.OptionGroup;
+import gnu.classpath.tools.getopt.Parser;
+
+import java.io.File;
+import java.io.IOException;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.util.logging.Logger;
+
+/**
+ * The <code>-cacert</code> keytol command handler is used to import a CA
+ * trusted X.509 certificate into a key store.
+ * <p>
+ * Possible options for this command are:
+ * <p>
+ * <dl>
+ * <dt>-file FILE_NAME</dt>
+ * <dd>The fully qualified path of the file containing the trusted CA
+ * certificate to import. If omitted, the tool will process STDIN.
+ * <p></dd>
+ *
+ * <dt>-storetype STORE_TYPE</dt>
+ * <dd>Use this option to specify the type of the key store to use. The
+ * default value, if this option is omitted, is that of the property
+ * <code>keystore.type</code> in the security properties file, which is
+ * obtained by invoking the {@link java.security.KeyStore#getDefaultType()}
+ * static method.
+ * <p></dd>
+ *
+ * <dt>-keystore URL</dt>
+ * <dd>Use this option to specify the location of the key store to use.
+ * The default value is a file {@link java.net.URL} referencing the file
+ * named <code>.keystore</code> located in the path returned by the call to
+ * {@link java.lang.System#getProperty(String)} using <code>user.home</code>
+ * as argument.
+ * <p>
+ * If a URL was specified, but was found to be malformed --e.g. missing
+ * protocol element-- the tool will attempt to use the URL value as a file-
+ * name (with absolute or relative path-name) of a key store --as if the
+ * protocol was <code>file:</code>.
+ * <p></dd>
+ *
+ * <dt>-storepass PASSWORD</dt>
+ * <dd>Use this option to specify the password protecting the key store. If
+ * this option is omitted from the command line, you will be prompted to
+ * provide a password.
+ * <p></dd>
+ *
+ * <dt>-provider PROVIDER_CLASS_NAME</dt>
+ * <dd>A fully qualified class name of a Security Provider to add to the
+ * current list of Security Providers already installed in the JVM in-use.
+ * If a provider class is specified with this option, and was successfully
+ * added to the runtime --i.e. it was not already installed-- then the tool
+ * will attempt to removed this Security Provider before exiting.
+ * <p></dd>
+ *
+ * <dt>-v</dt>
+ * <dd>Use this option to enable more verbose output.</dd>
+ * </dl>
+ */
+public class CACertCmd
+ extends Command
+{
+ private static final Logger log = Logger.getLogger(CACertCmd.class.getName());
+ /** Pathname of the file containing the CA certificate to import. */
+ protected String _certFileName;
+ /** Type of the key store to use. */
+ protected String _ksType;
+ /** The URL to the keystore where the trusted certificates will be added. */
+ protected String _ksURL;
+ /** The password protecting the keystore. */
+ protected String _ksPassword;
+ /** Class name of a security provider to use. */
+ protected String _providerClassName;
+ /** Reference to the X.509 factory. */
+ private CertificateFactory x509Factory;
+
+ // default 0-arguments constructor
+
+ // public setters -----------------------------------------------------------
+
+ /** @param pathName the fully qualified path name of the file to process. */
+ public void setFile(String pathName)
+ {
+ this._certFileName = pathName;
+ }
+
+ /** @param type the key-store type to use. */
+ public void setStoretype(String type)
+ {
+ this._ksType = type;
+ }
+
+ /** @param url the key-store URL to use. */
+ public void setKeystore(String url)
+ {
+ this._ksURL = url;
+ }
+
+ /** @param password the key-store password to use. */
+ public void setStorepass(String password)
+ {
+ this._ksPassword = password;
+ }
+
+ /** @param className a security provider fully qualified class name to use. */
+ public void setProvider(String className)
+ {
+ this._providerClassName = className;
+ }
+
+ // life-cycle methods -------------------------------------------------------
+
+ /* (non-Javadoc)
+ * @see gnu.classpath.tools.keytool.Command#setup()
+ */
+ void setup() throws Exception
+ {
+ setInputStreamParam(_certFileName);
+ setKeyStoreParams(_providerClassName, _ksType, _ksPassword, _ksURL);
+ log.finer("-cacert handler will use the following options:"); //$NON-NLS-1$
+ log.finer(" -file=" + _certFileName); //$NON-NLS-1$
+ log.finer(" -storetype=" + storeType); //$NON-NLS-1$
+ log.finer(" -keystore=" + storeURL); //$NON-NLS-1$
+ log.finer(" -provider=" + provider); //$NON-NLS-1$
+ log.finer(" -v=" + verbose); //$NON-NLS-1$
+ }
+
+ void start() throws CertificateException, KeyStoreException,
+ NoSuchAlgorithmException, IOException
+ {
+ log.entering(this.getClass().getName(), "start"); //$NON-NLS-1$
+ alias = getAliasFromFileName(_certFileName);
+ if (store.containsAlias(alias))
+ throw new IllegalArgumentException(Messages.getFormattedString("CACertCmd.0", //$NON-NLS-1$
+ alias));
+ x509Factory = CertificateFactory.getInstance("X.509"); //$NON-NLS-1$
+ Certificate certificate = x509Factory.generateCertificate(inStream);
+ log.finest("certificate = " + certificate); //$NON-NLS-1$
+ store.setCertificateEntry(alias, certificate);
+ saveKeyStore();
+ if (verbose)
+ System.out.println(Messages.getFormattedString("CACertCmd.1", //$NON-NLS-1$
+ new Object[] { _certFileName,
+ alias }));
+ log.exiting(this.getClass().getName(), "start"); //$NON-NLS-1$
+ }
+
+ // own methods --------------------------------------------------------------
+
+ /* (non-Javadoc)
+ * @see gnu.classpath.tools.keytool.Command#getParser()
+ */
+ Parser getParser()
+ {
+ log.entering(this.getClass().getName(), "getParser"); //$NON-NLS-1$
+ Parser result = new ClasspathToolParser(Main.CACERT_CMD, true);
+ result.setHeader(Messages.getString("CACertCmd.2")); //$NON-NLS-1$
+ result.setFooter(Messages.getString("CACertCmd.3")); //$NON-NLS-1$
+ OptionGroup options = new OptionGroup(Messages.getString("CACertCmd.4")); //$NON-NLS-1$
+ options.add(new Option(Main.FILE_OPT,
+ Messages.getString("CACertCmd.5"), //$NON-NLS-1$
+ Messages.getString("CACertCmd.6")) //$NON-NLS-1$
+ {
+ public void parsed(String argument) throws OptionException
+ {
+ _certFileName = argument;
+ }
+ });
+ options.add(new Option(Main.STORETYPE_OPT,
+ Messages.getString("CACertCmd.7"), //$NON-NLS-1$
+ Messages.getString("CACertCmd.8")) //$NON-NLS-1$
+ {
+ public void parsed(String argument) throws OptionException
+ {
+ _ksType = argument;
+ }
+ });
+ options.add(new Option(Main.KEYSTORE_OPT,
+ Messages.getString("CACertCmd.9"), //$NON-NLS-1$
+ Messages.getString("CACertCmd.10")) //$NON-NLS-1$
+ {
+ public void parsed(String argument) throws OptionException
+ {
+ _ksURL = argument;
+ }
+ });
+ options.add(new Option(Main.STOREPASS_OPT,
+ Messages.getString("CACertCmd.11"), //$NON-NLS-1$
+ Messages.getString("CACertCmd.12")) //$NON-NLS-1$
+ {
+ public void parsed(String argument) throws OptionException
+ {
+ _ksPassword = argument;
+ }
+ });
+ options.add(new Option(Main.PROVIDER_OPT,
+ Messages.getString("CACertCmd.13"), //$NON-NLS-1$
+ Messages.getString("CACertCmd.14")) //$NON-NLS-1$
+ {
+ public void parsed(String argument) throws OptionException
+ {
+ _providerClassName = argument;
+ }
+ });
+ options.add(new Option(Main.VERBOSE_OPT,
+ Messages.getString("CACertCmd.15")) //$NON-NLS-1$
+ {
+ public void parsed(String argument) throws OptionException
+ {
+ verbose = true;
+ }
+ });
+ result.add(options);
+ log.exiting(this.getClass().getName(), "getParser", result); //$NON-NLS-1$
+ return result;
+ }
+
+ /**
+ * Construct an Alias string from the name of the file containing the
+ * certificate to import. This method first removes the last dot (".")
+ * character and any subsequent characters from the input name, and then
+ * replaces any space and dot characters with underscores. For example the
+ * input string <code>brasil.gov.br.cert</code> will result in
+ * <code>brasil_gov_br</code> as its alias.
+ *
+ * @param fileName the name of the file containing the CA certificate
+ * @return a string which can, and will, be used as the Alias of this CA
+ * certificate.
+ */
+ private String getAliasFromFileName(String fileName)
+ {
+ log.entering(this.getClass().getName(), "getAliasFromFileName", fileName); //$NON-NLS-1$
+ // get the basename
+ fileName = new File(fileName).getName();
+ // remove '.' if at start
+ if (fileName.startsWith(".")) //$NON-NLS-1$
+ fileName = fileName.substring(1);
+
+ // remove last \..+
+ int ndx = fileName.lastIndexOf('.');
+ if (ndx > 0)
+ fileName = fileName.substring(0, ndx);
+ // replace spaces and dots with underscores
+ char[] chars = fileName.toCharArray();
+ for (int i = 0; i < chars.length; i++)
+ {
+ char c = chars[i];
+ if (c == ' ' || c == '.')
+ chars[i] = '_';
+ }
+ String result = new String(chars);
+ log.exiting(this.getClass().getName(), "getAliasFromFileName", result); //$NON-NLS-1$
+ return result;
+ }
+}
diff --git a/tools/gnu/classpath/tools/keytool/CertReqCmd.java b/tools/gnu/classpath/tools/keytool/CertReqCmd.java
index 3de97e589..fc85e6abd 100644
--- a/tools/gnu/classpath/tools/keytool/CertReqCmd.java
+++ b/tools/gnu/classpath/tools/keytool/CertReqCmd.java
@@ -128,7 +128,7 @@ import javax.security.auth.x500.X500Principal;
*
* <dt>-keypass PASSWORD</dt>
*
- * <dt>-storetype STORE_TYP}</dt>
+ * <dt>-storetype STORE_TYPE</dt>
* <dd>Use this option to specify the type of the key store to use. The
* default value, if this option is omitted, is that of the property
* <code>keystore.type</code> in the security properties file, which is
diff --git a/tools/gnu/classpath/tools/keytool/Command.java b/tools/gnu/classpath/tools/keytool/Command.java
index 0d8c56334..0811074b8 100644
--- a/tools/gnu/classpath/tools/keytool/Command.java
+++ b/tools/gnu/classpath/tools/keytool/Command.java
@@ -168,10 +168,17 @@ abstract class Command
private int providerNdx = -2;
/** The callback handler to use when needing to interact with user. */
private CallbackHandler handler;
+ /** The shutdown hook. */
+ private ShutdownHook shutdownThread;
// Constructor(s) -----------------------------------------------------------
- // default 0-arguments constructor
+ protected Command()
+ {
+ super();
+ shutdownThread = new ShutdownHook();
+ Runtime.getRuntime().addShutdownHook(shutdownThread);
+ }
// Methods ------------------------------------------------------------------
@@ -201,6 +208,8 @@ abstract class Command
finally
{
teardown();
+ if (shutdownThread != null)
+ Runtime.getRuntime().removeShutdownHook(shutdownThread);
}
}
@@ -1157,4 +1166,15 @@ abstract class Command
return handler;
}
+
+ // Inner class(es) ==========================================================
+
+ private class ShutdownHook
+ extends Thread
+ {
+ public void run()
+ {
+ teardown();
+ }
+ }
}
diff --git a/tools/gnu/classpath/tools/keytool/DeleteCmd.java b/tools/gnu/classpath/tools/keytool/DeleteCmd.java
index 9022f1c20..4c32ee1e6 100644
--- a/tools/gnu/classpath/tools/keytool/DeleteCmd.java
+++ b/tools/gnu/classpath/tools/keytool/DeleteCmd.java
@@ -70,7 +70,7 @@ import javax.security.auth.callback.UnsupportedCallbackException;
* omitted from the command line.
* <p></dd>
*
- * <dt>-storetype STORE_TYP}</dt>
+ * <dt>-storetype STORE_TYPE</dt>
* <dd>Use this option to specify the type of the key store to use. The
* default value, if this option is omitted, is that of the property
* <code>keystore.type</code> in the security properties file, which is
diff --git a/tools/gnu/classpath/tools/keytool/ExportCmd.java b/tools/gnu/classpath/tools/keytool/ExportCmd.java
index 49582a944..46f7acdf0 100644
--- a/tools/gnu/classpath/tools/keytool/ExportCmd.java
+++ b/tools/gnu/classpath/tools/keytool/ExportCmd.java
@@ -74,7 +74,7 @@ import java.util.logging.Logger;
* exported to. If omitted, STDOUT will be used instead.
* <p></dd>
*
- * <dt>-storetype STORE_TYP}</dt>
+ * <dt>-storetype STORE_TYPE</dt>
* <dd>Use this option to specify the type of the key store to use. The
* default value, if this option is omitted, is that of the property
* <code>keystore.type</code> in the security properties file, which is
diff --git a/tools/gnu/classpath/tools/keytool/GenKeyCmd.java b/tools/gnu/classpath/tools/keytool/GenKeyCmd.java
index 4d4ca7a74..6da0f58b6 100644
--- a/tools/gnu/classpath/tools/keytool/GenKeyCmd.java
+++ b/tools/gnu/classpath/tools/keytool/GenKeyCmd.java
@@ -158,7 +158,7 @@ import javax.security.auth.callback.UnsupportedCallbackException;
*
* <dt>-validity DAY_COUNT</dt>
*
- * <dt>-storetype STORE_TYP}</dt>
+ * <dt>-storetype STORE_TYPE</dt>
* <dd>Use this option to specify the type of the key store to use. The
* default value, if this option is omitted, is that of the property
* <code>keystore.type</code> in the security properties file, which is
diff --git a/tools/gnu/classpath/tools/keytool/IdentityDBCmd.java b/tools/gnu/classpath/tools/keytool/IdentityDBCmd.java
index 11d0f68da..46c5b9769 100644
--- a/tools/gnu/classpath/tools/keytool/IdentityDBCmd.java
+++ b/tools/gnu/classpath/tools/keytool/IdentityDBCmd.java
@@ -61,7 +61,7 @@ import java.util.logging.Logger;
* option is omitted, the tool will process STDIN.
* <p></dd>
*
- * <dt>-storetype STORE_TYP}</dt>
+ * <dt>-storetype STORE_TYPE</dt>
* <dd>Use this option to specify the type of the key store to use. The
* default value, if this option is omitted, is that of the property
* <code>keystore.type</code> in the security properties file, which is
diff --git a/tools/gnu/classpath/tools/keytool/ImportCmd.java b/tools/gnu/classpath/tools/keytool/ImportCmd.java
index 7a4b6dfb6..2e01bc0e4 100644
--- a/tools/gnu/classpath/tools/keytool/ImportCmd.java
+++ b/tools/gnu/classpath/tools/keytool/ImportCmd.java
@@ -148,7 +148,7 @@ import javax.security.auth.callback.UnsupportedCallbackException;
* should be considered when trying to establish chain-of-trusts.
* <p></dd>
*
- * <dt>-storetype STORE_TYP}</dt>
+ * <dt>-storetype STORE_TYPE</dt>
* <dd>Use this option to specify the type of the key store to use. The
* default value, if this option is omitted, is that of the property
* <code>keystore.type</code> in the security properties file, which is
diff --git a/tools/gnu/classpath/tools/keytool/KeyCloneCmd.java b/tools/gnu/classpath/tools/keytool/KeyCloneCmd.java
index a60fef936..61a8eb880 100644
--- a/tools/gnu/classpath/tools/keytool/KeyCloneCmd.java
+++ b/tools/gnu/classpath/tools/keytool/KeyCloneCmd.java
@@ -96,7 +96,7 @@ import javax.security.auth.callback.UnsupportedCallbackException;
* material of the newly cloned copy of the <i>Key Entry</i>.
* <p></dd>
*
- * <dt>-storetype STORE_TYP}</dt>
+ * <dt>-storetype STORE_TYPE</dt>
* <dd>Use this option to specify the type of the key store to use. The
* default value, if this option is omitted, is that of the property
* <code>keystore.type</code> in the security properties file, which is
diff --git a/tools/gnu/classpath/tools/keytool/KeyPasswdCmd.java b/tools/gnu/classpath/tools/keytool/KeyPasswdCmd.java
index 5cf25eb0f..83beb161b 100644
--- a/tools/gnu/classpath/tools/keytool/KeyPasswdCmd.java
+++ b/tools/gnu/classpath/tools/keytool/KeyPasswdCmd.java
@@ -91,7 +91,7 @@ import javax.security.auth.callback.UnsupportedCallbackException;
* private key material of the designated Key Entry.
* <p></dd>
*
- * <dt>-storetype STORE_TYP}</dt>
+ * <dt>-storetype STORE_TYPE</dt>
* <dd>Use this option to specify the type of the key store to use. The
* default value, if this option is omitted, is that of the property
* <code>keystore.type</code> in the security properties file, which is
diff --git a/tools/gnu/classpath/tools/keytool/ListCmd.java b/tools/gnu/classpath/tools/keytool/ListCmd.java
index 674099307..99fcfa2cf 100644
--- a/tools/gnu/classpath/tools/keytool/ListCmd.java
+++ b/tools/gnu/classpath/tools/keytool/ListCmd.java
@@ -69,7 +69,7 @@ import java.util.logging.Logger;
* omitted from the command line.
* <p></dd>
*
- * <dt>-storetype STORE_TYP}</dt>
+ * <dt>-storetype STORE_TYPE</dt>
* <dd>Use this option to specify the type of the key store to use. The
* default value, if this option is omitted, is that of the property
* <code>keystore.type</code> in the security properties file, which is
diff --git a/tools/gnu/classpath/tools/keytool/Main.java b/tools/gnu/classpath/tools/keytool/Main.java
index 582aba082..321934385 100644
--- a/tools/gnu/classpath/tools/keytool/Main.java
+++ b/tools/gnu/classpath/tools/keytool/Main.java
@@ -74,6 +74,7 @@ public class Main
static final String STOREPASSWD_CMD = "storepasswd"; //$NON-NLS-1$
static final String KEYPASSWD_CMD = "keypasswd"; //$NON-NLS-1$
static final String DELETE_CMD = "delete"; //$NON-NLS-1$
+ static final String CACERT_CMD = "cacert"; //$NON-NLS-1$
static final String _GENKEY = "-" + GENKEY_CMD; //$NON-NLS-1$
static final String _IMPORT = "-" + IMPORT_CMD; //$NON-NLS-1$
@@ -88,6 +89,7 @@ public class Main
static final String _KEYPASSWD = "-" + KEYPASSWD_CMD; //$NON-NLS-1$
static final String _DELETE = "-" + DELETE_CMD; //$NON-NLS-1$
static final String _HELP = "-help"; //$NON-NLS-1$
+ static final String _CACERT = "-" + CACERT_CMD; //$NON-NLS-1$
static final String ALIAS_OPT = "alias"; //$NON-NLS-1$
static final String SIGALG_OPT = "sigalg"; //$NON-NLS-1$
@@ -119,10 +121,14 @@ public class Main
private int gnuCallbacksNdx = -2;
/** The command line parser. */
private Parser cmdLineParser;
+ /** The shutdown hook. */
+ private ShutdownHook shutdownThread;
private Main()
{
super();
+ shutdownThread = new ShutdownHook();
+ Runtime.getRuntime().addShutdownHook(shutdownThread);
}
public static final void main(String[] args)
@@ -157,6 +163,8 @@ public class Main
finally
{
tool.teardown();
+ if (tool.shutdownThread != null)
+ Runtime.getRuntime().removeShutdownHook(tool.shutdownThread);
}
log.exiting(Main.class.getName(), "main", Integer.valueOf(result)); //$NON-NLS-1$
@@ -213,6 +221,8 @@ public class Main
cmd = new KeyPasswdCmd();
else if (_DELETE.equals(opt))
cmd = new DeleteCmd();
+ else if (_CACERT.equals(opt))
+ cmd = new CACertCmd();
else if (_HELP.equals(opt))
throw new OptionException(""); //$NON-NLS-1$
else
@@ -260,13 +270,15 @@ public class Main
Messages.getString("Main.32"))); //$NON-NLS-1$
cmdGroup.add(new NoParseOption(DELETE_CMD,
Messages.getString("Main.33"))); //$NON-NLS-1$
+ cmdGroup.add(new NoParseOption(CACERT_CMD,
+ Messages.getString("Main.5"))); //$NON-NLS-1$
result.add(cmdGroup);
log.exiting(this.getClass().getName(), "getParser", result); //$NON-NLS-1$
return result;
}
- private void teardown()
+ void teardown()
{
log.entering(this.getClass().getName(), "teardown"); //$NON-NLS-1$
@@ -309,4 +321,13 @@ public class Main
// do nothing
}
}
+
+ private class ShutdownHook
+ extends Thread
+ {
+ public void run()
+ {
+ teardown();
+ }
+ }
}
diff --git a/tools/gnu/classpath/tools/keytool/SelfCertCmd.java b/tools/gnu/classpath/tools/keytool/SelfCertCmd.java
index 418bce49f..db700a164 100644
--- a/tools/gnu/classpath/tools/keytool/SelfCertCmd.java
+++ b/tools/gnu/classpath/tools/keytool/SelfCertCmd.java
@@ -134,7 +134,7 @@ import javax.security.auth.x500.X500Principal;
*
* <dt>-keypass PASSWORD</dt>
*
- * <dt>-storetype STORE_TYP}</dt>
+ * <dt>-storetype STORE_TYPE</dt>
* <dd>Use this option to specify the type of the key store to use. The
* default value, if this option is omitted, is that of the property
* <code>keystore.type</code> in the security properties file, which is
diff --git a/tools/gnu/classpath/tools/keytool/StorePasswdCmd.java b/tools/gnu/classpath/tools/keytool/StorePasswdCmd.java
index e9262bd71..6c4dfddb9 100644
--- a/tools/gnu/classpath/tools/keytool/StorePasswdCmd.java
+++ b/tools/gnu/classpath/tools/keytool/StorePasswdCmd.java
@@ -70,7 +70,7 @@ import javax.security.auth.callback.UnsupportedCallbackException;
* designated key store.
* <p></dd>
*
- * <dt>-storetype STORE_TYP}</dt>
+ * <dt>-storetype STORE_TYPE</dt>
* <dd>Use this option to specify the type of the key store to use. The
* default value, if this option is omitted, is that of the property
* <code>keystore.type</code> in the security properties file, which is
diff --git a/tools/jarsigner.in b/tools/jarsigner.in
index cea95a288..537b7faf0 100644
--- a/tools/jarsigner.in
+++ b/tools/jarsigner.in
@@ -44,20 +44,4 @@ prefix=@prefix@
tools_dir=@datadir@/@PACKAGE@
tools_cp=${tools_dir}/tools.zip
-# find the java executable...
-if [ -z "${JAVA}" ] ; then
- if [ -n "${JAVA_HOME}" ] ; then
- if [ -x "${JAVA_HOME}/jre/sh/java" ] ; then
- JAVA="${JAVA_HOME}/jre/sh/java"
- else
- JAVA="${JAVA_HOME}/bin/java"
- fi
- else
- JAVA=`which java 2> /dev/null `
- if [ -z "${JAVA}" ] ; then
- JAVA=java
- fi
- fi
-fi
-
-exec "${JAVA}" -Xbootclasspath/p:"${tools_cp}" gnu.classpath.tools.jarsigner.Main $@
+exec @VM_BINARY@ -Xbootclasspath/p:"${tools_cp}" gnu.classpath.tools.jarsigner.Main $@
diff --git a/tools/keytool.in b/tools/keytool.in
index 6c11dc407..613baf7fd 100644
--- a/tools/keytool.in
+++ b/tools/keytool.in
@@ -44,20 +44,4 @@ prefix=@prefix@
tools_dir=@datadir@/@PACKAGE@
tools_cp=${tools_dir}/tools.zip
-# find the java executable...
-if [ -z "${JAVA}" ] ; then
- if [ -n "${JAVA_HOME}" ] ; then
- if [ -x "${JAVA_HOME}/jre/sh/java" ] ; then
- JAVA="${JAVA_HOME}/jre/sh/java"
- else
- JAVA="${JAVA_HOME}/bin/java"
- fi
- else
- JAVA=`which java 2> /dev/null `
- if [ -z "${JAVA}" ] ; then
- JAVA=java
- fi
- fi
-fi
-
-exec "${JAVA}" -Xbootclasspath/p:"${tools_cp}" gnu.classpath.tools.keytool.Main $@
+exec @VM_BINARY@ -Xbootclasspath/p:"${tools_cp}" gnu.classpath.tools.keytool.Main $@
diff --git a/vm/reference/java/io/VMFile.java b/vm/reference/java/io/VMFile.java
index 2931044c8..2f48aad71 100644
--- a/vm/reference/java/io/VMFile.java
+++ b/vm/reference/java/io/VMFile.java
@@ -1,5 +1,5 @@
/* VMFile.java -- Class for methods natively accessing files
- Copyright (C) 2004 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -210,10 +210,10 @@ final class VMFile
/**
* This method returns a canonical representation of the pathname of
- * the given path. The actual form of the canonical representation is
- * different. On the GNU system, the canonical form differs from the
- * absolute form in that all relative file references to "." and ".."
- * are resolved and removed.
+ * this file. The actual form of the canonical representation is
+ * system-dependent. On the GNU system, conversion to canonical
+ * form involves the removal of redundant separators, references to
+ * "." and "..", and symbolic links.
* <p>
* Note that this method, unlike the other methods which return path
* names, can throw an IOException. This is because native method
@@ -221,9 +221,5 @@ final class VMFile
*
* @exception IOException If an error occurs
*/
- public static String toCanonicalForm(String path) throws IOException
- {
- // FIXME: this only works on UNIX
- return PlatformHelper.toCanonicalForm(path);
- }
+ public static native String toCanonicalForm(String path) throws IOException;
}