JavaVM.st
author Claus Gittinger <cg@exept.de>
Thu, 24 Nov 2011 12:54:24 +0100
changeset 2290 cd61fd0b66ac
parent 2159 bab924a452d9
child 2353 fa7400d022a0
permissions -rw-r--r--
fixed: #version_SVN ($ to §)

"
 COPYRIGHT (c) 1996-2011 by Claus Gittinger
 COPYRIGHT (c) 2010-2011 by Jan Vrany, Jan Kurs and Marcel Hlopko
                            SWING Research Group, Czech Technical University in Prague

 Parts of the code written by Claus Gittinger are under following
 license:

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.

 Parts of the code written at SWING Reasearch Group [1] are MIT licensed:

 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the 'Software'), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.

 [1] Code written at SWING Research Group contain a signature
     of one of the above copright owners.
"
"{ Package: 'stx:libjava' }"

Object subclass:#JavaVM
	instanceVariableNames:''
	classVariableNames:'UnhandledJavaExceptionSignal JavaExceptionSignal
		UnimplementedInstructionSignal UnimplementedNativeMethodSignal
		BadMessageSignal InternalErrorSignal CallHandlerSignal
		FullExceptionTrace StackTrace TraceHistory LockTable
		LockTableAccess LibPath SimulatedLibs LoadedLibs
		SimulatedNativeLibs LoadedNativeLibs WaitTable WaitTableAccess
		JavaWindowGroup KnownWindows DrawOPTrace WindowOPTrace
		WindowCreationTrace EventTrace ThreadTrace MonitorTrace
		ExceptionTrace InsnCount InsnCounts FileOpenTrace FileAccessTrace
		FileOpenConfirmation SocketConnectConfirmation FileIOTrace
		OpenFileTable CachedNativeMethodTable ExceptionDebug ExitDebug
		JavaConsoleStream StandardThreadGroup EnteredMonitorsPerProcess
		JavaMethods DUMMY_LONG_HIGHWORD DUMMY_DOUBLE_HIGHWORD NoAudio
		FirstWindowCreationSemaphore PermittedDirectories
		PermittedHostConnects SimulatedOS O_WGgraphics_originX
		O_WGgraphics_originY O_WGgraphics_pData O_FramePeer_pNativeWidget
		O_FramePeer_pData ImageStretchCache LastGraphics LastGC
		EnteredMonitorObject EnteredMonitorObjectCount
		EnteredMonitorProcess LeftMonitorObject JavaEventThread
		JavaScreenUpdaterThread JavaEventQueueThread SystemProperties
		ExceptionDebugPatterns NullPointerExceptionDebug
		DivisionByZeroExceptionDebug IOExceptionDebug
		StdinReplacementFileQuerySignal AssertionsEnabled
		SimulatedNativeMemory Reflection ZipCache ZipEntryCache
		ZipLastModTimesCache ZipInflaters'
	poolDictionaries:''
	category:'Languages-Java-Support'
!

Object subclass:#Reflection
	instanceVariableNames:'vm constantPoolMapping javaClasses javaArrayClasses javaMethods
		returnNilIfMissing'
	classVariableNames:''
	poolDictionaries:''
	privateIn:JavaVM
!

!JavaVM class methodsFor:'documentation'!

copyright
"
 COPYRIGHT (c) 1996-2011 by Claus Gittinger
 COPYRIGHT (c) 2010-2011 by Jan Vrany, Jan Kurs and Marcel Hlopko
                            SWING Research Group, Czech Technical University in Prague

 Parts of the code written by Claus Gittinger are under following
 license:

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.

 Parts of the code written at SWING Reasearch Group [1] are MIT licensed:

 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the 'Software'), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.

 [1] Code written at SWING Research Group contain a signature
     of one of the above copright owners.

"
!

documentation
"Runtime support and environment for Java. 
You shouldn't communicate with JavaVM directly, 
use Java class instead. JavaVM is layer between
the native interpret and the rest of the system.
JavaVM implements native java virtual machine 
methods called by interpret, hides java primitive 
types handling, and gives the ST world ways to 
control class loading and reflection"
!

nativeMethods
"
    all native methods:

        JavaMethod allSubInstances select:[:m |
            m isNative 
        ]

    implemented methods:

        JavaMethod allSubInstances select:[:m |
            |sel|

            m isNative ifTrue:[
                sel := ('_' , m javaClass lastName , '_' , m name , ':') asSymbol.
                JavaVM class implements:sel.
            ] ifFalse:[
                false
            ]
        ]

    unimplemented methods:

        JavaMethod allSubInstances select:[:m |
            |sel|

            m isNative ifTrue:[
                sel := ('_' , m javaClass lastName , '_' , m name , ':') asSymbol.
                (JavaVM class implements:sel) not
            ] ifFalse:[
                false
            ]
        ]    


    list of all native methods as in jdk1.1.3:

      X - implemented
      * - implemented to be validated
      x - implemented with limited functionality
      o - implemented as dummy (no functionality)

    X (Math::double sin (double))
    X (Math::double cos (double))
    X (Math::double tan (double))
    X (Math::double asin (double))
    X (Math::double acos (double))
    X (Math::double atan (double))
    X (Math::double exp (double))
    X (Math::double log (double))
    X (Math::double sqrt (double))
      (Math::double IEEEremainder (double double))
    X (Math::double ceil (double))
    X (Math::double floor (double))
      (Math::double rint (double))
      (Math::double atan2 (double double))
    X (Math::double pow (double double))

    X (Class::java.lang.Class forName (java.lang.String))
    X (Class::java.lang.Object newInstance ())
    * (Class::boolean isInstance (java.lang.Object))
    X (Class::boolean isAssignableFrom (java.lang.Class))
    X (Class::boolean isInterface ())
      (Class::boolean isArray ())
    X (Class::boolean isPrimitive ())
    X (Class::java.lang.String getName ())
    X (Class::java.lang.ClassLoader getClassLoader ())
    X (Class::java.lang.Class getSuperclass ())
      (Class::java.lang.Class[] getInterfaces ())
      (Class::java.lang.Class getComponentType ())
      (Class::int getModifiers ())
      (Class::java.lang.Object[] getSigners ())
      (Class::void setSigners (java.lang.Object[]))
    X (Class::java.lang.Class getPrimitiveClass (java.lang.String))
      (Class::java.lang.reflect.Field getField0 (java.lang.String int))
      (Class::java.lang.reflect.Field[] getFields0 (int))
    X (Class::java.lang.reflect.Method getMethod0 (java.lang.String java.lang.Class[] int))
    X (Class::java.lang.reflect.Method[] getMethods0 (int))
      (Class::java.lang.reflect.Constructor[] getConstructors0 (int))
      (Class::java.lang.reflect.Constructor getConstructor0 (java.lang.Class[] int))

    X (InetAddressImpl::java.lang.String getLocalHostName ())
    X (InetAddressImpl::void makeAnyLocalAddress (java.net.InetAddress))
    X (InetAddressImpl::byte[][] lookupAllHostAddr (java.lang.String))
      (InetAddressImpl::java.lang.String getHostByAddr (int))
    X (InetAddressImpl::int getInetFamily ())

    X (ResourceBundle::java.lang.Class[] getClassContext ())

    X (System::void setIn0 (java.io.InputStream))
    X (System::void setOut0 (java.io.PrintStream))
    X (System::void setErr0 (java.io.PrintStream))
    X (System::long currentTimeMillis ())
    X (System::void arraycopy (java.lang.Object int java.lang.Object int int))
    X (System::int identityHashCode (java.lang.Object))
    X (System::java.util.Properties initProperties (java.util.Properties))

    X (Thread::java.lang.Thread currentThread ())
    X (Thread::void yield ())
    X (Thread::void sleep (long))
    X (Thread::void start ())
    X (Thread::boolean isInterrupted (boolean))
    X (Thread::boolean isAlive ())
      (Thread::int countStackFrames ())
    X (Thread::void setPriority0 (int))
    X (Thread::void stop0 (java.lang.Object))
    X (Thread::void suspend0 ())
    X (Thread::void resume0 ())
    * (Thread::void interrupt0 ())

      (String::java.lang.String intern ())

    X (Float::int floatToIntBits (float))
    X (Float::float intBitsToFloat (int))

      (ObjectStreamClass::int getClassAccess (java.lang.Class))
      (ObjectStreamClass::java.lang.String[] getMethodSignatures (java.lang.Class))
      (ObjectStreamClass::int getMethodAccess (java.lang.Class java.lang.String))
      (ObjectStreamClass::java.lang.String[] getFieldSignatures (java.lang.Class))
      (ObjectStreamClass::int getFieldAccess (java.lang.Class java.lang.String))
      (ObjectStreamClass::java.io.ObjectStreamField[] getFields0 (java.lang.Class))
      (ObjectStreamClass::long getSerialVersionUID (java.lang.Class))
      (ObjectStreamClass::boolean hasWriteObject (java.lang.Class))
      (ObjectInputStream::java.lang.Class loadClass0 (java.lang.Class java.lang.String))
      (ObjectInputStream::void inputClassFields (java.lang.Object java.lang.Class int[]))
      (ObjectInputStream::java.lang.Object allocateNewObject (java.lang.Class java.lang.Class))
      (ObjectInputStream::java.lang.Object allocateNewArray (java.lang.Class int))
      (ObjectInputStream::boolean invokeObjectReader (java.lang.Object java.lang.Class))

      (SecurityManager::java.lang.Class[] getClassContext ())
    X (SecurityManager::java.lang.ClassLoader currentClassLoader ())
      (SecurityManager::int classDepth (java.lang.String))
    X (SecurityManager::int classLoaderDepth ())
      (SecurityManager::java.lang.Class currentLoadedClass0 ())

    X (ClassLoader::void init ())
    X (ClassLoader::java.lang.Class defineClass0 (java.lang.String byte[] int int))
    X (ClassLoader::void resolveClass0 (java.lang.Class))
    X (ClassLoader::java.lang.Class findSystemClass0 (java.lang.String))
    X (ClassLoader::java.io.InputStream getSystemResourceAsStream0 (java.lang.String))
      (ClassLoader::java.lang.String getSystemResourceAsName0 (java.lang.String))

    X (FileDescriptor::boolean valid ())
      (FileDescriptor::void sync ())
    X (FileDescriptor::java.io.FileDescriptor initSystemFD (java.io.FileDescriptor int))

    X (Object::java.lang.Class getClass ())
    X (Object::int hashCode ())
    X (Object::java.lang.Object clone ())
    X (Object::void notify ())
    X (Object::void notifyAll ())
    X (Object::void wait (long))

    X (FileOutputStream::void open (java.lang.String))
    X (FileOutputStream::void openAppend (java.lang.String))
    X (FileOutputStream::void write (int))
    X (FileOutputStream::void writeBytes (byte[] int int))
    X (FileOutputStream::void close ())
    X (FileInputStream::void open (java.lang.String))
    X (FileInputStream::int read ())
    X (FileInputStream::int readBytes (byte[] int int))
      (FileInputStream::long skip (long))
    X (FileInputStream::int available ())
    X (FileInputStream::void close ())

      (VM::int getState ())
      (VM::boolean threadsSuspended ())
      (VM::void unsuspendThreads ())
      (VM::void unsuspendSomeThreads ())

    X (File::boolean exists0 ())
    X (File::boolean canWrite0 ())
    X (File::boolean canRead0 ())
    X (File::boolean isFile0 ())
    X (File::boolean isDirectory0 ())
    X (File::long lastModified0 ())
    X (File::long length0 ())
    X (File::boolean mkdir0 ())
    X (File::boolean renameTo0 (java.io.File))
    X (File::boolean delete0 ())
      (File::boolean rmdir0 ())
    X (File::java.lang.String[] list0 ())
      (File::java.lang.String canonPath (java.lang.String))
    X (File::boolean isAbsolute ())

      (ObjectOutputStream::void outputClassFields (java.lang.Object java.lang.Class int[]))
      (ObjectOutputStream::boolean invokeObjectWriter (java.lang.Object java.lang.Class))

    X (Throwable::void printStackTrace0 (java.lang.Object))
    X (Throwable::java.lang.Throwable fillInStackTrace ())

    X (Double::long doubleToLongBits (double))
    X (Double::double longBitsToDouble (long))
    X (Double::double valueOf0 (java.lang.String))

    X (Runtime::void exitInternal (int))
    o (Runtime::void runFinalizersOnExit0 (boolean))
    o (Runtime::java.lang.Process execInternal (java.lang.String[] java.lang.String[]))
    X (Runtime::long freeMemory ())
    X (Runtime::long totalMemory ())
    X (Runtime::void gc ())
      (Runtime::void runFinalization ())
      (Runtime::void traceInstructions (boolean))
      (Runtime::void traceMethodCalls (boolean))
    X (Runtime::java.lang.String initializeLinkerInternal ())
    X (Runtime::java.lang.String buildLibName (java.lang.String java.lang.String))
    X (Runtime::int loadFileInternal (java.lang.String))

      (WDrawingSurfaceInfo::int lock ())
      (WDrawingSurfaceInfo::void unlock ())
      (WDrawingSurfaceInfo::int getHWnd ())
      (WDrawingSurfaceInfo::int getHBitmap ())
      (WDrawingSurfaceInfo::int getPBits ())
      (WDrawingSurfaceInfo::int getHDC ())
      (WDrawingSurfaceInfo::int getDepth ())
      (WDrawingSurfaceInfo::int getHPalette ())

    X (WDefaultFontCharset::boolean canConvert (char))

      (ColorModel::void deletepData ())
    X (WToolkit::void init (java.lang.Thread))
    X (WToolkit::void eventLoop ())
      (WToolkit::java.awt.image.ColorModel makeColorModel ())
    X (WToolkit::int getScreenResolution ())
    X (WToolkit::int getScreenWidth ())
    X (WToolkit::int getScreenHeight ())
      (WToolkit::void sync ())
    * (WToolkit::void beep ())
    X (WToolkit::void loadSystemColors (int[]))

      (WPrintJob::void end ())

    X (WDialogPeer::void create (sun.awt.windows.WComponentPeer))
    X (WDialogPeer::void _show ())
    X (WDialogPeer::void _hide ())

    X (WWindowPeer::void toFront ())
    X (WWindowPeer::void toBack ())
    X (WWindowPeer::void _setTitle (java.lang.String))
    X (WWindowPeer::void _setResizable (boolean))
    X (WWindowPeer::void create (sun.awt.windows.WComponentPeer))
    o (WWindowPeer::void updateInsets (java.awt.Insets))
      (WWindowPeer::java.awt.Component getContainerElement (java.awt.Container int))

    X (WCanvasPeer::void create (sun.awt.windows.WComponentPeer))

    X (WTextAreaPeer::void create (sun.awt.windows.WComponentPeer))
    X (WTextAreaPeer::void insertText (java.lang.String int))
      (WTextAreaPeer::void replaceText (java.lang.String int int))

    X (WTextComponentPeer::java.lang.String getText ())
    X (WTextComponentPeer::void setText (java.lang.String))
    X (WTextComponentPeer::int getSelectionStart ())
    X (WTextComponentPeer::int getSelectionEnd ())
    X (WTextComponentPeer::void select (int int))
    X (WTextComponentPeer::void enableEditing (boolean))

    X (WComponentPeer::void show ())
    X (WComponentPeer::void hide ())
    X (WComponentPeer::void enable ())
    X (WComponentPeer::void disable ())
    X (WComponentPeer::java.awt.Point getLocationOnScreen ())
    X (WComponentPeer::void reshape (int int int int))
    o (WComponentPeer::void handleEvent (java.awt.AWTEvent))
    o (WComponentPeer::void _dispose ())
    X (WComponentPeer::void _setForeground (int))
    X (WComponentPeer::void _setBackground (int))
    o (WComponentPeer::void setFont (java.awt.Font))
    o (WComponentPeer::void requestFocus ())
    o (WComponentPeer::void setCursor (java.awt.Cursor))
    o (WComponentPeer::void start ())
      (WComponentPeer::void _beginValidate ())
      (WComponentPeer::void endValidate ())
    o (WComponentPeer::void setZOrderPosition (sun.awt.windows.WComponentPeer))

    X (WFramePeer::void setMenuBar0 (sun.awt.windows.WMenuBarPeer))
    X (WFramePeer::void create (sun.awt.windows.WComponentPeer))
    X (WFramePeer::void _setIconImage (sun.awt.image.ImageRepresentation))

    o (WFontMetrics::boolean needsConversion (java.awt.Font sun.awt.FontDescriptor))
    o (WFontMetrics::int getMFCharSegmentWidth (java.awt.Font sun.awt.FontDescriptor boolean char[] int int byte[] int))
      (WFontMetrics::int bytesWidth (byte[] int int))
      (WFontMetrics::void init ())

    o (WChoicePeer::void select (int))
    o (WChoicePeer::void remove (int))
    o (WChoicePeer::void addItem (java.lang.String int))
    X (WChoicePeer::void reshape (int int int int))
    X (WChoicePeer::void create (sun.awt.windows.WComponentPeer))

    X (WLabelPeer::void setText (java.lang.String))
    o (WLabelPeer::void setAlignment (int))
    X (WLabelPeer::void create (sun.awt.windows.WComponentPeer))

    X (WMenuItemPeer::void _setLabel (java.lang.String))
    X (WMenuItemPeer::void create (sun.awt.windows.WMenuPeer))
    X (WMenuItemPeer::void enable (boolean))
    o (WMenuItemPeer::void _dispose ())
      (WMenuPeer::void addSeparator ())
      (WMenuPeer::void delItem (int))
    X (WMenuPeer::void createMenu (sun.awt.windows.WMenuBarPeer))
      (WMenuPeer::void createSubMenu (sun.awt.windows.WMenuPeer))

      (WPopupMenuPeer::void createMenu (sun.awt.windows.WComponentPeer))
      (WPopupMenuPeer::void _show (java.awt.Event))
      (WMenuBarPeer::void addMenu (java.awt.Menu))
      (WMenuBarPeer::void delMenu (int))
    X (WMenuBarPeer::void create (sun.awt.windows.WFramePeer))

      (WCheckboxMenuItemPeer::void setState (boolean))

    X (WFileDialogPeer::void show ())

    X (WCheckboxPeer::void setState (boolean))
    X (WCheckboxPeer::void setCheckboxGroup (java.awt.CheckboxGroup))
      (WCheckboxPeer::void setLabel (java.lang.String))
    X (WCheckboxPeer::void create (sun.awt.windows.WComponentPeer))

    X (WClipboard::void init ())
      (WClipboard::void setClipboardText (java.awt.datatransfer.StringSelection))
      (WClipboard::java.lang.String getClipboardText ())

    X (WListPeer::void addItem (java.lang.String int))
    X (WListPeer::void delItems (int int))
    X (WListPeer::void select (int))
      (WListPeer::void deselect (int))
      (WListPeer::void makeVisible (int))
    X (WListPeer::void setMultipleSelections (boolean))
    X (WListPeer::void create (sun.awt.windows.WComponentPeer))
    X (WListPeer::boolean isSelected (int))

    x (WScrollbarPeer::void _setValues (int int int int))
    x (WScrollbarPeer::void setLineIncrement (int))
    x (WScrollbarPeer::void setPageIncrement (int))
    x (WScrollbarPeer::void create (sun.awt.windows.WComponentPeer))

    x (ImageRepresentation::void offscreenInit (java.awt.Color))
    x (ImageRepresentation::boolean setBytePixels (int int int int java.awt.image.ColorModel byte[] int int))
    x (ImageRepresentation::boolean setIntPixels (int int int int java.awt.image.ColorModel int[] int int))
    x (ImageRepresentation::boolean finish (boolean))
    X (ImageRepresentation::void imageDraw (java.awt.Graphics int int java.awt.Color))
    x (ImageRepresentation::void imageStretch (java.awt.Graphics int int int int int int int int java.awt.Color))
    x (ImageRepresentation::void disposeImage ())

    X (WTextFieldPeer::void create (sun.awt.windows.WComponentPeer))
    X (WTextFieldPeer::void setEchoCharacter (char))

    X (WScrollPanePeer::void create (sun.awt.windows.WComponentPeer))
    o (WScrollPanePeer::int getOffset (int))
      (WScrollPanePeer::void setInsets ())
      (WScrollPanePeer::void setScrollPosition (int int))
    x (WScrollPanePeer::int _getHScrollbarHeight ())
    x (WScrollPanePeer::int _getVScrollbarWidth ())
    o (WScrollPanePeer::void setSpans (int int int int))
      (WScrollPanePeer::java.awt.Component getScrollChild ())

      (WEmbeddedFramePeer::void create (sun.awt.windows.WComponentPeer))
    X (WButtonPeer::void setLabel (java.lang.String))
    X (WButtonPeer::void create (sun.awt.windows.WComponentPeer))

    x (WColor::java.awt.Color getDefaultColor (int))

    x (GifImageDecoder::boolean parseImage (int int int int boolean int byte[] byte[] java.awt.image.IndexColorModel))

    x (WGraphics::void createFromComponent (sun.awt.windows.WComponentPeer))
    x (WGraphics::void createFromGraphics (sun.awt.windows.WGraphics))
      (WGraphics::void createFromPrintJob (sun.awt.windows.WPrintJob))
      (WGraphics::void createFromHDC (int))
    x (WGraphics::void imageCreate (sun.awt.image.ImageRepresentation))
    x (WGraphics::void pSetFont (java.awt.Font))
    X (WGraphics::void pSetForeground (int))
      (WGraphics::void _dispose ())
    x (WGraphics::void dispose ())
    x (WGraphics::void setPaintMode ())
    x (WGraphics::void setXORMode (java.awt.Color))
    o (WGraphics::java.awt.Rectangle getClipBounds ())
    o (WGraphics::void changeClip (int int int int boolean))
      (WGraphics::void removeClip ())
    X (WGraphics::void clearRect (int int int int))
    X (WGraphics::void fillRect (int int int int))
    X (WGraphics::void drawRect (int int int int))
      (WGraphics::void drawSFChars (char[] int int int int))
    x (WGraphics::int drawMFCharsSegment (java.awt.Font sun.awt.FontDescriptor char[] int int int int))
      (WGraphics::int drawMFCharsConvertedSegment (java.awt.Font sun.awt.FontDescriptor byte[] int int int))
      (WGraphics::void drawBytes (byte[] int int int int))
    X (WGraphics::void drawLine (int int int int))
    X (WGraphics::void copyArea (int int int int int int))
    o (WGraphics::void drawRoundRect (int int int int int int))
    o (WGraphics::void fillRoundRect (int int int int int int))
    X (WGraphics::void drawPolygon (int[] int[] int))
      (WGraphics::void drawPolyline (int[] int[] int))
    X (WGraphics::void fillPolygon (int[] int[] int))
    x (WGraphics::void drawOval (int int int int))
    x (WGraphics::void fillOval (int int int int))
    x (WGraphics::void drawArc (int int int int int int))
    x (WGraphics::void fillArc (int int int int int int))
      (WGraphics::void print (sun.awt.windows.WComponentPeer))
      (WGraphics::void close (sun.awt.windows.WPrintJob))
      (JPEGImageDecoder::void readImage (java.io.InputStream byte[]))
    o (OffScreenImageSource::void sendPixels ())


    additional native methods added by microsoft (sigh):

    X (java.lang.String::boolean equals (java.lang.String))
    X (java.lang.String::int length (java.lang.String))
    o (java.lang.Runtime::void setInputStreamLocalised (java.io.DataInputStream))
    o (java.lang.Runtime::void setOutputStreamLocalised (java.io.DataOutputStream))

      (java.lang.String::int compareTo (java.lang.String))
      (java.lang.String::boolean equalsIgnoreCase (java.lang.String))
      (java.lang.String::int indexOf (java.lang.String int))
      (java.lang.String::boolean startsWith (java.lang.String int))
      (java.lang.String::boolean regionMatches (int java.lang.String int int))
      (java.lang.String::boolean regionMatches (boolean int java.lang.String int int))
      (java.lang.String::int lastIndexOf (java.lang.String int))
      (java.lang.ClassLoader::void resolveClass (java.lang.Class))

      (java.lang.ClassLoader::java.lang.Class createArrayClass (java.lang.String java.lang.Class))
      (java.io.PrintStream::boolean isOutputStreamLocalised (java.io.DataOutputStream))
      (java.lang.Runtime::boolean isOutputStreamLocalised (java.io.DataOutputStream))
      (java.lang.Runtime::boolean isInputStreamLocalised (java.io.DataInputStream))
      (java.lang.ThreadGroup::void initMainThreadGroup0 (java.lang.ThreadGroup))
      (java.lang.System::void validateSecurityManager (java.lang.SecurityManager))
      (java.lang.Class::java.lang.reflect.Method getMethod2 (int java.lang.String java.lang.String))
      (java.io.ObjectOutputStream::void invokeDefaultWriteObject (java.lang.Object java.lang.Class))
      (java.io.ObjectOutputStream::void invokeWriteObject (java.lang.Object java.lang.Class))
      (java.io.ObjectInputStream::void invokeDefaultReadObject (java.lang.Object java.lang.Class))
      (java.io.ObjectInputStream::void invokeReadObject (java.lang.Object java.lang.Class))
      (java.util.TimeZone::java.util.TimeZone getWin32TimeZone ())
      (java.net.InetAddress::java.lang.Object[] lookupHostByName (java.lang.String))
      (java.net.InetAddress::java.lang.Object[] lookupHostByAddr (int))
      (java.io.ObjectStreamClass::void doMismatchedRead (java.io.ObjectInputStream java.lang.Object))
      (java.io.ObjectStreamClass::long getClassDefinedUID (java.lang.Class))
      (java.io.ObjectStreamClass::boolean findObjectMethod0 (java.lang.Class int))
      (java.lang.reflect.Method::java.lang.String getDescriptor ())
      (java.lang.reflect.Array::void setShort (java.lang.Object int unsigned short))
      (java.lang.reflect.Array::char getChar (java.lang.Object int))
      (java.lang.reflect.Array::void setChar (java.lang.Object int char))
      (java.lang.reflect.Array::void setDouble (java.lang.Object int double))
      (java.lang.reflect.Array::java.lang.Object get (java.lang.Object int))
      (java.lang.reflect.Array::void set (java.lang.Object int java.lang.Object))
      (java.lang.reflect.Array::int getInt (java.lang.Object int))
      (java.lang.reflect.Array::void setInt (java.lang.Object int int))
      (java.lang.reflect.Array::java.lang.Object multiNewArray (java.lang.Class int[]))
      (java.lang.reflect.Array::boolean getBoolean (java.lang.Object int))
      (java.lang.reflect.Array::byte getByte (java.lang.Object int))
      (java.lang.reflect.Array::float getFloat (java.lang.Object int))
      (java.lang.reflect.Array::void setBoolean (java.lang.Object int boolean))
      (java.lang.reflect.Array::long getLong (java.lang.Object int))
      (java.lang.reflect.Array::void setByte (java.lang.Object int byte))
      (java.lang.reflect.Array::void setLong (java.lang.Object int long))
      (java.lang.reflect.Array::void setFloat (java.lang.Object int float))
      (java.lang.reflect.Array::java.lang.Object newArray (java.lang.Class int))
      (java.lang.reflect.Array::int getLength (java.lang.Object))
      (java.lang.reflect.Array::unsigned short getShort (java.lang.Object int))
      (java.lang.reflect.Array::double getDouble (java.lang.Object int))
      (java.lang.reflect.Field::void setShort (java.lang.Object unsigned short))
      (java.lang.reflect.Field::char getChar (java.lang.Object))
      (java.lang.reflect.Field::void setChar (java.lang.Object char))
      (java.lang.reflect.Field::void setDouble (java.lang.Object double))
      (java.lang.reflect.Field::java.lang.Object get (java.lang.Object))
      (java.lang.reflect.Field::void set (java.lang.Object java.lang.Object))
      (java.lang.reflect.Field::int getInt (java.lang.Object))
      (java.lang.reflect.Field::void setInt (java.lang.Object int))
      (java.lang.reflect.Field::boolean getBoolean (java.lang.Object))
      (java.lang.reflect.Field::byte getByte (java.lang.Object))
      (java.lang.reflect.Field::float getFloat (java.lang.Object))
      (java.lang.reflect.Field::long getLong (java.lang.Object))
      (java.lang.reflect.Field::void setBoolean (java.lang.Object boolean))
      (java.lang.reflect.Field::void setByte (java.lang.Object byte))
      (java.lang.reflect.Field::void setLong (java.lang.Object long))
      (java.lang.reflect.Field::void setFloat (java.lang.Object float))
      (java.lang.reflect.Field::int getModifiers ())
      (java.lang.reflect.Field::unsigned short getShort (java.lang.Object))
      (java.lang.reflect.Field::double getDouble (java.lang.Object))
      (java.lang.reflect.Constructor::java.lang.Object newInstance (java.lang.Object[]))
      (java.lang.reflect.Constructor::int getModifiers ())
      (java.util.zip.Inflater::void setDictionary0 (byte[] int int))
      (java.util.zip.Inflater::int getTotalIn0 ())
      (java.util.zip.Inflater::void reset0 ())
      (java.util.zip.Inflater::void end0 ())
      (java.util.zip.Inflater::int inflate0 (byte[] int int))
      (java.util.zip.Inflater::int getTotalOut0 ())
      (java.util.zip.Inflater::int getAdler0 ())
      (java.util.zip.CRC32::void update1 (int))
      (java.util.zip.CRC32::void update (byte[] int int))

      (com.ms.security.PolicyEngine::boolean isSystemClass (java.lang.String))
      (com.ms.security.PolicyEngine::void denyPermission (com.ms.security.PermissionID))
      (com.ms.security.PolicyEngine::void revertPermission (com.ms.security.PermissionID))
      (com.ms.security.PolicyEngine::void initPolicyEngine ())
      (com.ms.security.PolicyEngine::java.lang.Class _getClassOfCaller (java.lang.Class[]))
      (com.ms.security.PolicyEngine::void internalCheckClass (java.lang.Class com.ms.security.PermissionID java.lang.Object))
      (com.ms.security.PolicyEngine::com.ms.security.PermissionDataSet getPermissionsOfClass (java.lang.Class))
      (com.ms.security.PolicyEngine::void assertPermission (com.ms.security.PermissionID))
      (com.ms.security.PolicyEngine::void deepCheck (com.ms.security.PermissionID java.lang.Object))
      (com.ms.security.PolicyEngine::void shallowCheck (com.ms.security.PermissionID java.lang.Object java.lang.Class[] int))
      (com.ms.security.PolicyEngine::java.security.Principal getPrincipalOfClass (java.lang.Class))
      (com.ms.security.permissions.ThreadPermission::boolean pDecodeAsn (byte[]))
      (com.ms.security.permissions.ThreadPermission::byte[] pEncodeAsn ())
      (com.ms.security.permissions.RegistryPermission::boolean pDecodeAsn (byte[]))
      (com.ms.security.permissions.RegistryPermission::byte[] pEncodeAsn ())
      (com.ms.security.management.ZonePermissions::byte[] pEncodeAsn ())
      (com.ms.security.management.ZonePermissions::boolean pDecodeAsn (byte[]))
      (com.ms.security.permissions.UIPermission::byte[] pEncodeAsn ())
      (com.ms.security.permissions.UIPermission::boolean pDecodeAsn (byte[]))
      (com.ms.security.permissions.NetIOPermission::byte[] pEncodeAsn ())
      (com.ms.security.permissions.NetIOPermission::boolean pDecodeAsn (byte[]))
      (com.ms.security.permissions.ReflectionPermission::byte[] pEncodeAsn ())
      (com.ms.security.permissions.ReflectionPermission::boolean pDecodeAsn (byte[]))
      (com.ms.vm.WeakReference::void storeRef (int java.lang.Object))
      (com.ms.vm.WeakReference::int allocRef (java.lang.Object))
      (com.ms.vm.WeakReference::void freeRef (int))
      (com.ms.vm.WeakReference::java.lang.Object fetchRef (int))
      (com.ms.dll.DllLib::void CoTaskMemFree (int))
      (com.ms.dll.DllLib::void CopyWithDstOffset (int float[] int int))
      (com.ms.dll.DllLib::void CopyWithDstOffset (int double[] int int))
      (com.ms.dll.DllLib::int numParamBytes0 (java.lang.reflect.Method))
      (com.ms.dll.DllLib::void CopyWithDstOffset (int java.lang.Object int int))
      (com.ms.dll.DllLib::void write2 (java.lang.Object int unsigned short))
      (com.ms.dll.DllLib::void write2 (int int unsigned short))
      (com.ms.dll.DllLib::void write2 (java.lang.Object int char))
      (com.ms.dll.DllLib::void write2 (int int char))
      (com.ms.dll.DllLib::int GlobalAlloc (int int))
      (com.ms.dll.DllLib::void resize (java.lang.Object int))
      (com.ms.dll.DllLib::long read8 (java.lang.Object int))
      (com.ms.dll.DllLib::long read8 (int int))
      (com.ms.dll.DllLib::int lstrcpy (java.lang.StringBuffer int))
      (com.ms.dll.DllLib::int lstrlenA (int))
      (com.ms.dll.DllLib::int read4 (java.lang.Object int))
      (com.ms.dll.DllLib::int CoTaskMemAlloc (int))
      (com.ms.dll.DllLib::void write8 (java.lang.Object int long))
      (com.ms.dll.DllLib::int sizeOf0 (java.lang.Class))
      (com.ms.dll.DllLib::int getSystemDefaultCharSize ())
      (com.ms.dll.DllLib::void write8 (int int long))
      (com.ms.dll.DllLib::int read4 (int int))
      (com.ms.dll.DllLib::byte read1 (java.lang.Object int))
      (com.ms.dll.DllLib::byte read1 (int int))
      (com.ms.dll.DllLib::int lstrlen (int))
      (com.ms.dll.DllLib::void CopyMemoryAnsi (int java.lang.String int))
      (com.ms.dll.DllLib::void CopyMemoryAnsi (java.lang.StringBuffer int int))
      (com.ms.dll.DllLib::boolean isStruct (java.lang.reflect.Field))
      (com.ms.dll.DllLib::boolean GlobalFree (int))
      (com.ms.dll.DllLib::void internalAttemptCopyPtrToStruct (int java.lang.Object int int))
      (com.ms.dll.DllLib::int getLastError ())
      (com.ms.dll.DllLib::void write4 (java.lang.Object int int))
      (com.ms.dll.DllLib::void write4 (int int int))
      (com.ms.dll.DllLib::unsigned short read2 (java.lang.Object int))
      (com.ms.dll.DllLib::unsigned short read2 (int int))
      (com.ms.dll.DllLib::void release (java.lang.Object))
      (com.ms.dll.DllLib::void write1 (java.lang.Object int byte))
      (com.ms.dll.DllLib::void write1 (int int byte))
      (com.ms.dll.DllLib::boolean isStructCls (java.lang.Class))
      (com.ms.dll.DllLib::void prelink (java.lang.reflect.Method))
      (com.ms.dll.DllLib::void CopyMemoryUni (int java.lang.String int))
      (com.ms.dll.DllLib::void CopyMemoryUni (java.lang.StringBuffer int int))
      (com.ms.dll.DllLib::void internalAttemptCopyStructToPtr (java.lang.Object int int int))
      (com.ms.dll.DllLib::void CopyWithSrcOffset (int int int int))
      (com.ms.dll.DllLib::void CopyWithSrcOffset (byte[] int int int))
      (com.ms.dll.DllLib::void CopyWithSrcOffset (char[] int int int))
      (com.ms.dll.DllLib::void CopyWithSrcOffset (unsigned short[] int int int))
      (com.ms.dll.DllLib::void CopyWithSrcOffset (int[] int int int))
      (com.ms.dll.DllLib::void CopyWithSrcOffset (long[] int int int))
      (com.ms.dll.DllLib::void CopyWithSrcOffset (float[] int int int))
      (com.ms.dll.DllLib::void CopyWithSrcOffset (double[] int int int))
      (com.ms.dll.DllLib::void CopyWithSrcOffset (java.lang.Object int int int))
      (com.ms.dll.DllLib::void CopyWithDstOffset (int int int int))
      (com.ms.dll.DllLib::int lstrlenW (int))
      (com.ms.dll.DllLib::void CopyWithDstOffset (int byte[] int int))
      (com.ms.dll.DllLib::void CopyWithDstOffset (int char[] int int))
      (com.ms.dll.DllLib::void CopyWithDstOffset (int unsigned short[] int int))
      (com.ms.dll.DllLib::void CopyWithDstOffset (int int[] int int))
      (com.ms.dll.DllLib::void CopyWithDstOffset (int long[] int int))
      (com.ms.dll.DllLib::int internalGetStructAddr (java.lang.Object))
      (com.ms.dll.DllLib::int offsetOf (java.lang.reflect.Field))
      (com.ms.dll.DllLib::int lstrcpy (int java.lang.String))
      (com.ms.dll.DllLib::int sizeOf (java.lang.Object))
      (com.ms.lang.RegKey::com.ms.lang.RegKeyEnumValue pRegEnumValue (int))
      (com.ms.lang.RegKey::java.lang.String pRegQueryStringValue (java.lang.String))
      (com.ms.lang.RegKey::byte[] pRegQueryBinaryValue (java.lang.String))
      (com.ms.lang.RegKey::int pRegQueryIntValue (java.lang.String))
      (com.ms.lang.RegKey::void pRegSetStringValue (java.lang.String java.lang.String))
      (com.ms.lang.RegKey::void pRegSetIntValue (java.lang.String int))
      (com.ms.lang.RegKey::void pRegSetBinaryValue (java.lang.String byte[]))
      (com.ms.lang.RegKey::void pRegDeleteValue (java.lang.String))
      (com.ms.lang.RegKey::void pRegFlushKey ())
      (com.ms.lang.RegKey::void pRegDeleteKey (java.lang.String))
      (com.ms.lang.RegKey::void pRegOpenBaseKey (int))
      (com.ms.lang.RegKey::void pRegOpenKey (com.ms.lang.RegKey java.lang.String int))
      (com.ms.lang.RegKey::int pRegQueryInfoKey (com.ms.lang.RegQueryInfo))
      (com.ms.lang.RegKey::void pRegUnLoadKey (java.lang.String))
      (com.ms.lang.RegKey::void pRegCreateKey (com.ms.lang.RegKey java.lang.String))
      (com.ms.lang.RegKey::void pRegRestoreKey (java.lang.String boolean))
      (com.ms.lang.RegKey::void pRegLoadKey (java.lang.String java.lang.String))
      (com.ms.lang.RegKey::void pRegCloseKey ())
      (com.ms.lang.RegKey::java.lang.String pRegEnumKey (int))
      (com.ms.lang.RegKey::void pRegReplaceKey (java.lang.String java.lang.String java.lang.String))
      (com.ms.awt.peer.NativeServices::int pGetKeyboardLayouts (int[] int))
      (com.ms.awt.peer.NativeServices::void jpegReadByte (com.ms.awt.peer.IjpegDecoderCallback byte[] int com.ms.awt.peer.jpegInfoHeader byte[] int))
      (com.ms.awt.peer.NativeServices::int getColourDataDepth ())
      (com.ms.awt.peer.NativeServices::java.lang.String pGetFontEnumeratedFamily (int))
      (com.ms.awt.peer.NativeServices::int pNewFontEnumeration ())
      (com.ms.awt.peer.NativeServices::int getScreenClipRgn (int))
      (com.ms.awt.peer.NativeServices::int pSetKeyboardLayout (int int))
      (com.ms.awt.peer.NativeServices::void ClipboardInit (com.ms.awt.peer.IToolkit))
      (com.ms.awt.peer.NativeServices::void getDeviceCaps (int int[] int))
      (com.ms.awt.peer.NativeServices::void getAfcMetrics (int[]))
      (com.ms.awt.peer.NativeServices::void setUserLocale (int int))
      (com.ms.awt.peer.NativeServices::void getDCDI (com.ms.awt.peer.DirectColourDataInfo))
      (com.ms.awt.peer.NativeServices::int pGetNumKeyboardLayouts ())
      (com.ms.awt.peer.NativeServices::void getIndexedColours (byte[] byte[] byte[]))
      (com.ms.awt.peer.NativeServices::int getNativeFont (java.lang.String int int int))
      (com.ms.awt.peer.NativeServices::int pGetKeyboardLayout ())
      (com.ms.awt.peer.NativeServices::int getSystemLCID ())
      (com.ms.awt.peer.NativeServices::void caretSetPos (int int int))
      (com.ms.awt.peer.NativeServices::java.lang.String getLogFontFromIUnknown (com.ms.com.IUnknown com.ms.awt.peer.LogFontX))
      (com.ms.awt.peer.NativeServices::java.lang.String ClipboardGetText ())
      (com.ms.awt.peer.NativeServices::int systemMetric (int))
      (com.ms.awt.peer.NativeServices::void jpegInit (com.ms.awt.peer.IjpegDecoderCallback byte[] int com.ms.awt.peer.jpegInfoHeader))
      (com.ms.awt.peer.NativeServices::void caretHide (int))
      (com.ms.awt.peer.NativeServices::int chooseColor (int int))
      (com.ms.awt.peer.NativeServices::java.lang.String pGetKeyboardLayoutName (int))
      (com.ms.awt.peer.NativeServices::int matchFontAndLanguage (int int))
      (com.ms.awt.peer.NativeServices::java.lang.String chooseFont (com.ms.awt.peer.LogFontX java.lang.String int))
      (com.ms.awt.peer.NativeServices::java.lang.String getSystemFont (int com.ms.awt.peer.LogFontX))
      (com.ms.awt.peer.NativeServices::com.ms.com.IUnknown getIUnknownFromLogFont (java.lang.String com.ms.awt.peer.LogFontX))
      (com.ms.awt.peer.NativeServices::void caretDispose (int))
      (com.ms.awt.peer.NativeServices::void caretShow (int))
      (com.ms.awt.peer.NativeServices::void deleteObject (int))
      (com.ms.awt.peer.NativeServices::void setDebugOutput (com.ms.awt.peer.COMPrintCallback))
      (com.ms.awt.peer.NativeServices::void jpegReadInt (com.ms.awt.peer.IjpegDecoderCallback byte[] int com.ms.awt.peer.jpegInfoHeader int[] int))
      (com.ms.awt.peer.NativeServices::int getSystemColourValue (int))
      (com.ms.awt.peer.NativeServices::void caretCreate (int int int))
      (com.ms.awt.peer.NativeServices::void ClipboardSetText (java.lang.String))
      (com.ms.awt.peer.NativeServices::void println (java.lang.String))
      (com.ms.security.SecurityClassLoader::boolean getSecureState ())
      (com.ms.security.SecurityClassLoader::void setSecureState (java.lang.String java.lang.String))
      (com.ms.security.SecurityClassLoader::java.lang.Class internalDefineClass (java.lang.String byte[] int int))
      (com.ms.security.SecurityClassLoader::void markClass (java.lang.Class com.ms.security.PermissionSet java.security.Principal))
      (com.ms.security.SecurityClassLoader::java.util.Hashtable getHashTable ())
      (com.ms.security.auditing.SecurityAuditor::boolean isThreadAuditingEnabled ())
      (com.ms.security.auditing.SecurityAuditor::void disableThreadAuditing ())
      (com.ms.security.auditing.SecurityAuditor::void enableThreadAuditing ())
      (com.ms.security.auditing.SecurityAuditor::void initSecurityAuditor ())
      (com.ms.security.PermissionDataSet::byte[] pEncodeAsn ())
      (com.ms.security.PermissionDataSet::boolean pDecodeAsn (byte[]))
      (com.ms.lang.SystemX::int pAnsiToUnicode (byte[] char[] int int int))
      (com.ms.lang.SystemX::int pQueryUnicodeToAnsi (char[] int int int))
      (com.ms.lang.SystemX::void gc ())
      (com.ms.lang.SystemX::boolean arrayCompare (java.lang.Object[] int java.lang.Object[] int int))
      (com.ms.lang.SystemX::int pUnicodeToAnsi (char[] byte[] int int int))
      (com.ms.lang.SystemX::boolean isLocalCharDBCSLeadByte (byte))
      (com.ms.lang.SystemX::int pQueryAnsiToUnicode (byte[] int int int))
      (com.ms.lang.SystemX::boolean isBaseDBCS ())
      (com.ms.lang.SystemX::java.lang.reflect.Method getMethod2 (java.lang.Class int java.lang.String java.lang.String))
      (com.ms.packagemanager.JavaPackage::byte[] nativeGetSigner (java.lang.Object))
      (com.ms.packagemanager.JavaPackage::byte[] nativeGetCapabilities (java.lang.Object))
      (com.ms.com._Guid::void IIDFromString (java.lang.String com.ms.com._Guid))
      (com.ms.com._Guid::java.lang.String StringFromIID (com.ms.com._Guid))
      (com.ms.security.auditing.PrintStreamAuditor::int GetModuleHandle (java.lang.String))
      (com.ms.security.auditing.PrintStreamAuditor::int FormatMessage (int int int int java.lang.StringBuffer int int[]))
      (com.ms.security.permissions.CustomPermission::byte[] pEncodeAsn ())
      (com.ms.security.permissions.CustomPermission::boolean pDecodeAsn (byte[]))
      (com.ms.security.permissions.X509Signer::boolean pLoad (byte[]))
      (com.ms.packagemanager.PackageManager::java.lang.Class nativeFindClassInNamespace (java.lang.String java.lang.String java.lang.ClassLoader))
      (com.ms.packagemanager.PackageManager::java.lang.Object nativeGetPackage (java.lang.String java.lang.String))
      (com.ms.packagemanager.PackageManager::java.lang.String[] nativeGetBeansList ())
      (com.ms.packagemanager.PackageManager::com.ms.com.IStream nativeGetFileIStream (java.lang.String java.lang.String))
      (com.ms.packagemanager.PackageManager::java.lang.Class nativeFindClass (java.lang.String java.lang.String java.lang.ClassLoader))
      (com.ms.security.permissions.UserFileIOPermission::byte[] pEncodeAsn ())
      (com.ms.security.permissions.UserFileIOPermission::boolean pDecodeAsn (byte[]))
      (com.ms.security.permissions.PropertyPermission::byte[] pEncodeAsn ())
      (com.ms.security.permissions.PropertyPermission::boolean pDecodeAsn (byte[]))
      (com.ms.security.permissions.ClientStoragePermission::byte[] pEncodeAsn ())
      (com.ms.security.permissions.ClientStoragePermission::boolean pDecodeAsn (byte[]))
      (com.ms.security.permissions.ExecutionPermission::byte[] pEncodeAsn ())
      (com.ms.security.permissions.ExecutionPermission::boolean pDecodeAsn (byte[]))
      (com.ms.util.EventLog::boolean DeregisterEventSource (int))
      (com.ms.util.EventLog::void reportEvent0 (unsigned short unsigned short int java.lang.String[] byte[]))
      (com.ms.util.EventLog::int RegisterEventSource (java.lang.String java.lang.String))
      (com.ms.applet.BrowserAppletFrame::void signalViewChange (int))
      (com.ms.applet.BrowserAppletFrame::java.lang.Object newInstance (int java.lang.Class boolean com.ms.security.PermissionSet))
      (com.ms.applet.BrowserAppletFrame::void showSystemStatus (int int boolean java.lang.String))
      (com.ms.applet.BrowserAppletFrame::com.ms.security.management.SecurityPolicy getSecurityPolicy0 (int java.lang.String))
      (com.ms.applet.BrowserAppletFrame::void setDownloadState (int boolean))
      (com.ms.applet.BrowserAppletFrame::int GetSystemDefaultLCID ())
      (com.ms.applet.BrowserAppletFrame::void requestResize (int int int))
      (com.ms.applet.BrowserAppletFrame::void signalObjectLoadDone (int boolean))
      (com.ms.applet.BrowserAppletFrame::com.ms.applet.BrowserAppletFrame findOfflineContext ())
      (com.ms.applet.BrowserAppletFrame::void showStatus0 (int java.lang.String))
      (com.ms.applet.BrowserAppletFrame::boolean checkGlobalOfflineMode0 ())
      (com.ms.applet.BrowserAppletFrame::void showDocument0 (int java.lang.String java.lang.String))
      (com.ms.security.permissions.SystemStreamsPermission::byte[] pEncodeAsn ())
      (com.ms.security.permissions.SystemStreamsPermission::boolean pDecodeAsn (byte[]))
      (com.ms.security.permissions.FileIOPermission::byte[] pEncodeAsn ())
      (com.ms.security.permissions.FileIOPermission::boolean pDecodeAsn (byte[]))
      (com.ms.com.ComLib::int newGCHandle (java.lang.Object))
      (com.ms.com.ComLib::java.lang.Object derefGCHandle (int))
      (com.ms.com.ComLib::void dprinthelper (char[]))
      (com.ms.com.ComLib::void release (java.lang.Object))
      (com.ms.com.ComLib::int jcdwClassSizeOf (java.lang.Class))
      (com.ms.com.ComLib::int jcdwOffsetOf (java.lang.Object java.lang.String))
      (com.ms.com.ComLib::int jcdwClassOffsetOf (java.lang.Class java.lang.String))
      (com.ms.com.ComLib::boolean isJavaOwned (java.lang.Object))
      (com.ms.com.ComLib::void brk (java.lang.Object))
      (com.ms.com.ComLib::void setDataWrapperSize (java.lang.Object int))
      (com.ms.com.ComLib::void brk (int))
      (com.ms.com.ComLib::void setJCDWHomeThread (java.lang.Object java.lang.Object))
      (com.ms.com.ComLib::void propagateOwnership (java.lang.Object int))
      (com.ms.com.ComLib::void threadStartMTA (java.lang.Thread))
      (com.ms.com.ComLib::void IENVNextMarshalerJ2C (int))
      (com.ms.com.ComLib::boolean supportsInterface (java.lang.Object com.ms.com._Guid))
      (com.ms.com.ComLib::java.lang.Object ptrToStruct (java.lang.Class int))
      (com.ms.com.ComLib::int jcdwSizeOf (java.lang.Object))
      (com.ms.com.ComLib::void declareMessagePumpThread ())
      (com.ms.com.ComLib::void IENVNextMarshalerC2J (int))
      (com.ms.com.ComLib::void freeGCHandle (int))
      (com.ms.com.ComLib::boolean isEqualUnknown (java.lang.Object java.lang.Object))
      (com.ms.com.Dispatch::boolean NIsArray (java.lang.Object))
      (com.ms.com.Dispatch::java.lang.String NInvokeReal (java.lang.Object com.ms.com._Guid java.lang.String int int int int com.ms.com.Variant[] com.ms.com.Variant[] int[]))
      (com.ms.com.Dispatch::void NGetIDsOfNamesReal (java.lang.Object com.ms.com._Guid int java.lang.String[] int[]))
      (com.ms.com.ComException::int FormatMessage (int int int int java.lang.StringBuffer int int[]))
      (com.ms.com.Variant::int toInt ())
      (com.ms.com.Variant::double toDate ())
      (com.ms.com.Variant::boolean toBoolean ())
      (com.ms.com.Variant::double toDouble ())
      (com.ms.com.Variant::long toCurrency ())
      (com.ms.com.Variant::void putVariantArray (com.ms.com.Variant[]))
      (com.ms.com.Variant::com.ms.com.Variant[] getVariantArray ())
      (com.ms.com.Variant::void putByteArray (java.lang.Object))
      (com.ms.com.Variant::void putShortRef (unsigned short))
      (com.ms.com.Variant::void putIntRef (int))
      (com.ms.com.Variant::void putDoubleRef (double))
      (com.ms.com.Variant::void putDateRef (double))
      (com.ms.com.Variant::void putStringRef (java.lang.String))
      (com.ms.com.Variant::unsigned short getShortRef ())
      (com.ms.com.Variant::int getIntRef ())
      (com.ms.com.Variant::double getDoubleRef ())
      (com.ms.com.Variant::double getDateRef ())
      (com.ms.com.Variant::java.lang.String getStringRef ())
      (com.ms.com.Variant::java.lang.String internalToString ())
      (com.ms.com.Variant::void initSafeArrayByRef (com.ms.com.SafeArray int))
      (com.ms.com.Variant::java.lang.Object toCharArray ())
      (com.ms.com.Variant::java.lang.Object toDispatch ())
      (com.ms.com.Variant::byte toByte ())
      (com.ms.com.Variant::java.lang.Object getDispatch ())
      (com.ms.com.Variant::void putDispatch (java.lang.Object))
      (com.ms.com.Variant::boolean getBoolean ())
      (com.ms.com.Variant::int toError ())
      (com.ms.com.Variant::java.lang.Object toObject ())
      (com.ms.com.Variant::void initSafeArrayByVal (com.ms.com.SafeArray int))
      (com.ms.com.Variant::java.lang.Object getObject ())
      (com.ms.com.Variant::void putObject (java.lang.Object))
      (com.ms.com.Variant::com.ms.com.SafeArray toSafeArrayHelper (java.lang.Class))
      (com.ms.com.Variant::void putFloatRef (float))
      (com.ms.com.Variant::void putCurrencyRef (long))
      (com.ms.com.Variant::void putErrorRef (int))
      (com.ms.com.Variant::void putBooleanRef (boolean))
      (com.ms.com.Variant::void putObjectRef (java.lang.Object))
      (com.ms.com.Variant::void putByteRef (byte))
      (com.ms.com.Variant::java.lang.String getString ())
      (com.ms.com.Variant::void putString (java.lang.String))
      (com.ms.com.Variant::float getFloatRef ())
      (com.ms.com.Variant::long getCurrencyRef ())
      (com.ms.com.Variant::int getErrorRef ())
      (com.ms.com.Variant::boolean getBooleanRef ())
      (com.ms.com.Variant::java.lang.Object getObjectRef ())
      (com.ms.com.Variant::byte getByteRef ())
      (com.ms.com.Variant::float toFloat ())
      (com.ms.com.Variant::void putCharArray (java.lang.Object))
      (com.ms.com.Variant::void putDispatchRef (java.lang.Object))
      (com.ms.com.Variant::java.lang.Object getDispatchRef ())
      (com.ms.com.Variant::void putVariantArrayRef (com.ms.com.Variant[]))
      (com.ms.com.Variant::com.ms.com.Variant[] getVariantArrayRef ())
      (com.ms.com.Variant::void changeType (unsigned short))
      (com.ms.com.Variant::void ncloneIndirect (com.ms.com.Variant))
      (com.ms.com.Variant::void nFinalize (boolean))
      (com.ms.com.Variant::void nclone (com.ms.com.Variant))
      (com.ms.com.Variant::unsigned short toShort ())
      (com.ms.com.Variant::void putSafeArrayRefHelper (int))
      (com.ms.com.Variant::com.ms.com.Variant[] toVariantArray ())
      (com.ms.com.Variant::java.lang.Object toByteArray ())
      (com.ms.com.Variant::void TrueVariantClear ())
      (com.ms.awt.WToolkit::boolean MessageBeep (int))
      (com.ms.applet.AppletPanel::boolean StartCodeDownload (int java.lang.String java.lang.String java.lang.String))
      (com.ms.applet.AppletPanel::void securedCall0 (int java.lang.Object))
      (com.ms.applet.AppletPanel::com.ms.security.PermissionSet getDefaultPermissionsFromLoader (com.ms.vm.loader.URLClassLoader))
      (com.ms.dll.Win32Exception::int FormatMessage (int int int int java.lang.StringBuffer int int[]))
      (com.ms.awt.WGuiCallback::boolean SetEvent (int))
      (com.ms.awt.WGuiCallback::int CreateSemaphore (int int int int))
      (com.ms.awt.WGuiCallback::int ReleaseSemaphore (int int int))
      (com.ms.awt.WGuiCallback::void userYield (boolean))
      (com.ms.awt.WGuiCallback::int MsgWaitForMultipleObjects (int int[] boolean int int))
      (com.ms.awt.WGuiCallback::int CreateEvent (int boolean boolean int))
      (com.ms.activeX.ActiveXToolkit::int GetSysColor (int))
      (com.ms.awt.peer.NativeGraphics::void setPageDimension (int int))
      (com.ms.awt.peer.NativeGraphics::void setBkColour (int int))
      (com.ms.awt.peer.NativeGraphics::void getClipBounds (com.ms.awt.peer.NativeRect int int))
      (com.ms.awt.peer.NativeGraphics::void pGetCharOutline (int byte[]))
      (com.ms.awt.peer.NativeGraphics::void drawLine (int int int int))
      (com.ms.awt.peer.NativeGraphics::void setXORMode (int int int int))
      (com.ms.awt.peer.NativeGraphics::int drawString (java.lang.String int int int int int int int int[] int[]))
      (com.ms.awt.peer.NativeGraphics::int getCoClass ())
      (com.ms.awt.peer.NativeGraphics::void drawArc (int int int int int int int))
      (com.ms.awt.peer.NativeGraphics::void getInitialPageDimension (com.ms.awt.peer.NativeRect))
      (com.ms.awt.peer.NativeGraphics::void setVisRgn (int))
      (com.ms.awt.peer.NativeGraphics::void pSetForeground (int int))
      (com.ms.awt.peer.NativeGraphics::int pGetDC ())
      (com.ms.awt.peer.NativeGraphics::void drawPixels (int[] int int int))
      (com.ms.awt.peer.NativeGraphics::void drawPolygon (int[] int[] int int int int))
      (com.ms.awt.peer.NativeGraphics::void createFromImage (com.ms.awt.peer.INativeImage))
      (com.ms.awt.peer.NativeGraphics::void endPage ())
      (com.ms.awt.peer.NativeGraphics::int pGetCharOutlineSize (int))
      (com.ms.awt.peer.NativeGraphics::void pDrawBezier (int int int[] int))
      (com.ms.awt.peer.NativeGraphics::int drawBytes (byte[] int int int int int))
      (com.ms.awt.peer.NativeGraphics::void changeClip (int int int int boolean))
      (com.ms.awt.peer.NativeGraphics::int drawChars (char[] int int int int int int int int int int[] int[]))
      (com.ms.awt.peer.NativeGraphics::void drawT2Curve (float float float float float float int int))
      (com.ms.awt.peer.NativeGraphics::void createFromPrintJob (java.lang.String com.ms.awt.peer.SPJData))
      (com.ms.awt.peer.NativeGraphics::void endPrintJob ())
      (com.ms.awt.peer.NativeGraphics::void pSetOrigin (int int))
      (com.ms.awt.peer.NativeGraphics::void createFromHDC (int))
      (com.ms.awt.peer.NativeGraphics::void drawOval (int int int int int))
      (com.ms.awt.peer.NativeGraphics::int pSetFont (java.lang.String int int int))
      (com.ms.awt.peer.NativeGraphics::void setPaintMode (int int))
      (com.ms.awt.peer.NativeGraphics::void startPage ())
      (com.ms.awt.peer.NativeGraphics::void clearClip ())
      (com.ms.awt.peer.NativeGraphics::void createFromCopy (com.ms.awt.peer.INativeGraphics))
      (com.ms.awt.peer.NativeGraphics::void scanLines (int int[] int int int int))
      (com.ms.awt.peer.NativeGraphics::void drawRoundRect (int int int int int int int))
      (com.ms.awt.peer.NativeGraphics::void dispose ())
      (com.ms.awt.peer.NativeGraphics::void clearRect (int int int int int))
      (com.ms.awt.peer.NativeGraphics::void copyArea (int int int int int int))
      (com.ms.awt.peer.NativeGraphics::void createFromWindow (int))
      (com.ms.awt.peer.NativeGraphics::void drawPolyline (int[] int[] int int int))
      (com.ms.awt.peer.NativeGraphics::void drawRect (int int int int int))
      (com.ms.awt.peer.CToolkit::void callbackEventLoop (com.ms.awt.peer.IToolkitCallback))
      (com.ms.awt.peer.CToolkit::int getToolkitHwnd ())
      (com.ms.awt.peer.CToolkit::int createCompHwnd (int int))
      (com.ms.awt.peer.CNativeSystemIME::void setCompositionFont (int int))
      (com.ms.awt.peer.CNativeSystemIME::void setCompositionPos (int int int))
      (com.ms.awt.peer.CNativeSystemIME::void setOpenStatus (int int))
      (com.ms.awt.peer.CNativeSystemIME::int getOpenStatus (int))
      (com.ms.awt.peer.CNativeSystemIME::java.lang.String getCompositionString (int))
      (com.ms.awt.peer.CNativeSystemIME::java.lang.String getCompositionResultString (int))
      (com.ms.net.wininet.WininetStreamHandlerFactory::int initNative (java.lang.String))
      (com.ms.com.SafeArray::void rawGetVariantAs (int com.ms.com.Variant))
      (com.ms.com.SafeArray::void NSafeArrayInit (int))
      (com.ms.com.SafeArray::float rawGetDouble (int))
      (com.ms.com.SafeArray::void NRawBoolCopyToJavaArray (int int boolean[] int))
      (com.ms.com.SafeArray::void validateArray (int))
      (com.ms.com.SafeArray::void NSafeArrayCreateFromString (java.lang.String))
      (com.ms.com.SafeArray::void rawSetString (int java.lang.String))
      (com.ms.com.SafeArray::int getInt (int))
      (com.ms.com.SafeArray::void setInt (int int))
      (com.ms.com.SafeArray::boolean getBoolean (int))
      (com.ms.com.SafeArray::void setBoolean (int boolean))
      (com.ms.com.SafeArray::int computeOffset (int))
      (com.ms.com.SafeArray::void NSafeArrayNullInit ())
      (com.ms.com.SafeArray::void rawSetVariant (int com.ms.com.Variant))
      (com.ms.com.SafeArray::float rawGetFloat (int))
      (com.ms.com.SafeArray::float getFloat (int))
      (com.ms.com.SafeArray::void setFloat (int float))
      (com.ms.com.SafeArray::int computeOffset2 (int int))
      (com.ms.com.SafeArray::void rawSetDouble (int double))
      (com.ms.com.SafeArray::java.lang.String asString ())
      (com.ms.com.SafeArray::void NRawCopyToJavaArray (int int java.lang.Object int))
      (com.ms.com.SafeArray::void NSafeArrayCreate (int int int[] int[]))
      (com.ms.com.SafeArray::void NRawBoolCopyFromJavaArray (boolean[] int int int))
      (com.ms.com.SafeArray::void NSafeArrayDestroy (boolean boolean))
      (com.ms.com.SafeArray::int NSafeArrayCopy ())
      (com.ms.com.SafeArray::int rawGetInt (int))
      (com.ms.com.SafeArray::boolean rawGetBoolean (int))
      (com.ms.com.SafeArray::void rawSetFloat (int float))
      (com.ms.com.SafeArray::java.lang.String rawGetString (int))
      (com.ms.com.SafeArray::int NTotalNumElems ())
      (com.ms.com.SafeArray::double getDouble (int))
      (com.ms.com.SafeArray::void setDouble (int double))
      (com.ms.com.SafeArray::void Nreinit (com.ms.com.SafeArray))
      (com.ms.com.SafeArray::int getPhysicalSafeArray ())
      (com.ms.com.SafeArray::int NgetdwordAt (int))
      (com.ms.com.SafeArray::void NRawCopyFromJavaArray (java.lang.Object int int int))
      (com.ms.com.SafeArray::void rawSetBoolean (int boolean))
      (com.ms.com.SafeArray::void rawSetInt (int int))
      (com.ms.awt.peer.CNativeComponent::void invalidate (int int int int))
      (com.ms.awt.peer.CNativeComponent::void hideModal ())
      (com.ms.awt.peer.CNativeComponent::void hide ())
      (com.ms.awt.peer.CNativeComponent::void setOnTop (int))
      (com.ms.awt.peer.CNativeComponent::void registerDragDrop ())
      (com.ms.awt.peer.CNativeComponent::void endValidate ())
      (com.ms.awt.peer.CNativeComponent::void enable ())
      (com.ms.awt.peer.CNativeComponent::void disable ())
      (com.ms.awt.peer.CNativeComponent::void setTitle (java.lang.String))
      (com.ms.awt.peer.CNativeComponent::void getBounds (com.ms.awt.peer.NativeRect))
      (com.ms.awt.peer.CNativeComponent::int gethwnd ())
      (com.ms.awt.peer.CNativeComponent::void showModal ())
      (com.ms.awt.peer.CNativeComponent::void setCursor (int))
      (com.ms.awt.peer.CNativeComponent::void reshape (int int int int))
      (com.ms.awt.peer.CNativeComponent::void requestFocus ())
      (com.ms.awt.peer.CNativeComponent::void callDefWindowProc (int int int int))
      (com.ms.awt.peer.CNativeComponent::void registerCustomDropTarget (com.ms.com.IUnknown))
      (com.ms.awt.peer.CNativeComponent::void setNoActivate (boolean))
      (com.ms.awt.peer.CNativeComponent::void getPlaceOnScreen (com.ms.awt.peer.NativeRect))
      (com.ms.awt.peer.CNativeComponent::void beginValidate ())
      (com.ms.awt.peer.CNativeComponent::void clippedReshape (int int int int int))
      (com.ms.awt.peer.CNativeComponent::void setResizable (boolean))
      (com.ms.awt.peer.CNativeComponent::void setIcon (int))
      (com.ms.awt.peer.CNativeComponent::void toBack ())
      (com.ms.awt.peer.CNativeComponent::void setFrameHost (com.ms.awt.peer.IBrowserAppletFrameCallback))
      (com.ms.awt.peer.CNativeComponent::void toFront ())
      (com.ms.awt.peer.CNativeComponent::void show ())
      (com.ms.awt.peer.CNativeComponent::void updateInsets (com.ms.awt.peer.NativeInsets))
      (com.ms.awt.peer.CNativeComponent::void dispose ())
      (com.ms.awt.peer.CNativeComponent::void initFromJavaWindow (int com.ms.awt.peer.IComponentCallback com.ms.awt.peer.INativeComponent com.ms.awt.peer.IToolkit int))
      (com.ms.awt.peer.CNativeComponent::void init (int com.ms.awt.peer.IComponentCallback com.ms.awt.peer.INativeComponent com.ms.awt.peer.IToolkit))
      (com.ms.awt.peer.CNativeComponent::void beginDrag (com.ms.awt.peer.INativeDragCallback))
      (com.ms.fx.RegionConverter::int computeNativeRegion (int[]))
      (com.ms.fx.RegionConverter::int[] computeJavaRegion (int))
      (com.ms.net.wininet.URLUtils::java.lang.String canonicalizeURL (java.lang.String int))
      (com.ms.net.wininet.URLUtils::java.lang.String combineURL (java.lang.String java.lang.String int))
      (com.ms.awt.peer.NativeFontMetrics::int bytesWidth (byte[] int int))
      (com.ms.awt.peer.NativeFontMetrics::int stringWidth (java.lang.String int int[]))
      (com.ms.awt.peer.NativeFontMetrics::int charsWidth (char[] int int int int[]))
      (com.ms.awt.peer.NativeFontMetrics::java.lang.String init (com.ms.awt.peer.INativeGraphics int[] java.lang.String int int int))
      (com.ms.io.console.Console::int MessageBox (int java.lang.String java.lang.String int))
      (com.ms.awt.peer.NativeFileDialog::void show (com.ms.awt.peer.IFileDialogCallback java.lang.String java.lang.String java.lang.String int com.ms.awt.peer.INativeComponent int int))
      (com.ms.security.management.SecurityZone::byte[] pLoadCustomPermissions (int int java.lang.String))
      (com.ms.awt.peer.NativeImage::int setBytePixelsDirected (int int int int com.ms.awt.peer.DirectColourModelData byte[] int int com.ms.awt.peer.INativeImageBufferDone))
      (com.ms.awt.peer.NativeImage::void create (int int int int))
      (com.ms.awt.peer.NativeImage::int setIntPixelsIndexed (int int int int int[] int int[] int int com.ms.awt.peer.INativeImageBufferDone))
      (com.ms.awt.peer.NativeImage::int getCoClass ())
      (com.ms.awt.peer.NativeImage::int getIcon (int int int))
      (com.ms.awt.peer.NativeImage::int setBytePixelsIndexed (int int int int int[] int byte[] int int com.ms.awt.peer.INativeImageBufferDone))
      (com.ms.awt.peer.NativeImage::void sendPixels (com.ms.awt.peer.SPData))
      (com.ms.awt.peer.NativeImage::void fillPixels (com.ms.awt.peer.SPData byte[]))
      (com.ms.awt.peer.NativeImage::void dispose ())
      (com.ms.awt.peer.NativeImage::void init (int int int int int))
      (com.ms.awt.peer.NativeImage::int setIntPixelsDirected (int int int int com.ms.awt.peer.DirectColourModelData int[] int int com.ms.awt.peer.INativeImageBufferDone))
      (com.ms.awt.peer.NativeImage::void imageDrawStretched (com.ms.awt.peer.INativeGraphics int int int int int int int int int int))
      (com.ms.awt.peer.NativeImage::int finish (int))
      (com.ms.awt.peer.NativeImage::void imageDraw (int int int int int))
      (com.ms.awt.peer.NativeResource::java.lang.String loadString (int))
      (com.ms.awt.peer.NativeResource::int openDialogFromID (int))
      (com.ms.awt.peer.NativeResource::boolean attach (java.lang.String))
      (com.ms.awt.peer.NativeResource::void loadBytes (int int java.lang.String byte[] int))
      (com.ms.awt.peer.NativeResource::int getSize (int int java.lang.String))
      (com.ms.awt.peer.NativeResource::void detach ())
      (com.ms.awt.peer.NativeResource::int openDialogFromName (java.lang.String))
      (com.ms.net.wininet.WininetURLConnection::com.ms.applet.BrowserAppletFrame findOfflineContext ())
      (com.ms.com.DispatchProxy::void finalize ())
      (com.ms.com.DispatchProxy::void init (com.ms.com._Guid java.lang.reflect.Method[] int[]))
      (com.ms.net.wininet.WininetInputStream::void close ())
      (com.ms.net.wininet.WininetInputStream::int read (byte[] int int))
      (com.ms.net.wininet.WininetInputStream::int available ())
      (com.ms.net.wininet.WininetInputStream::long skip (long))
      (com.ms.net.wininet.WininetInputStream::void connect (java.lang.String boolean boolean java.lang.SecurityManager))
      (com.ms.vm.loader.CabSignatureInfo::com.ms.vm.loader.CabSignatureInfo extractFromFile0 (java.lang.String com.ms.security.management.SecurityPolicy))
      (com.ms.net.wininet.http.HttpInputStream::byte[] getResponseHeaders ())
      (com.ms.net.wininet.http.HttpInputStream::void close0 ())
      (com.ms.net.wininet.http.HttpInputStream::void connect (java.lang.String int java.lang.String boolean boolean boolean boolean byte[] byte[] java.lang.SecurityManager))
      (com.ms.vm.loader.CabCracker::int GetTempFileName (java.lang.StringBuffer java.lang.String int java.lang.StringBuffer))
      (com.ms.vm.loader.CabCracker::void getBytes0 (int int byte[]))
      (com.ms.vm.loader.CabCracker::void cleanup ())
      (com.ms.vm.loader.CabCracker::int GetTempPath (int java.lang.StringBuffer))
      (com.ms.vm.loader.CabCracker::void load0 ())


"
!

performance
    "
     JAVA::BenchMark new loopmark        
     JAVA::BenchMark new logicmark  
     JAVA::BenchMark new sievemark       
     JAVA::BenchMark new methodmark      
     JAVA::BenchMark new stringmark  
     JAVA::BenchMark new newstringmark                
     JAVA::BenchMark new neweststringmark               


    "
"
		    caffmark  loopmark  logicmark  sievemark  methodmark  stringmark  float  image  graphic dialog newstringmark  neweststringmark
 linux:
   P6/233 No JIT                 84         87        90          40          22                                       17              10
		      103       133        142       137          28          73       109    167     18    140

   P6/233 JIT                   479       2459       393         649          28                                       21              12
   P6/233 JIT         473      1805       3046       439         986          28                                       21              12
		      533      1808       3382       613        1003          25       105    143      1
		      668      3330       3644       740
		      793      4116       3731      1243        1365         120       103     79      2
		      914      4480       4061                  2290          68       106    158     19     34
		      941      4607       4149      1238        2434          75       101    152     18     32
									     591              164
		     1087                           1836                     800       110                   35
		     1102      4592       4270      1844        2381         841       109    169     21     35
		     1177      4608       4309      1810        2432         895       532    182     20     35


 w95
   P5/200 JIT          90        95         90        95         686          18        60     54      7
		      428      1657       2385       684         957          21        61     62      9
		      541      2886       2589       823         976          18        62     55      7
		      583      3062       2635       842         861         223        65     57      8
		      616      3075       2438      1081        1324         218        64     54      8
		      718      3138       2755      1085        1200         816        63     48      9      7

		    caffmark  loopmark  logicmark  sievemark  methodmark  stringmark  float  image  graphic dialog newstringmark  neweststringmark
"

!

performance2
    "
     symantec benchmarks


    "
"
		BubbleSort    BidirBubbleSort  QuickSort  Sieve   Hanoi   Dhry   Fib   Array   Tree   Total

   ST/X+J Linux         
   233Mhz P6
   No JIT          352767         354597         69585    43048  101638  28961 108839  48815

   ST/X+J Linux                  
   233Mhz P6
   JIT             128724         116810         20259    39733   83160  27613  52093  33166  43996  545554
		   124744         101428         17239    10052    8264  14004  38821  23252  33709  374660
   +IINC           120324                                  7265
   +IADD op2       100173          90737         18128     6996    7423  17093  48559  44209  57056  390374
   +ISUB op2                       90460         17547             5921                       57056  390461
   +ICMPEQ/NE       99785          90147                           5792                43482  56486  388255
   +ICMP            87398          78214         15784     7574    5628  12812  38481  24654  32252  302797
   +IFICMPLE        84198          74928         13814     5650          11674         23241         293118
   +IFICMPxx        76867          69738         12208                          37505  21973  32104  273569
   +IFICMPEQ/NE                                                    5580  11202         21723
   const IFICMPxx                                11856             5463  11032  37372                272726
   +lea for add/sub
   +BALOAD                                       11700     4600    5015   9431
   +BASTORE                                                3279
   +CALOAD/CASTORE                                                        8907
   regSave change   66119          60365          9997             4917  15386  37851  38202  50027  286497
		    64858          58360          9476             4889  15001  37211  36288  48313  278478
		    63146          55949          9302                   14899
		    62970          56085          9352     3226    4837   8779  37573  22815  33899  241297
   -O               43662          40292          7181     2530    4696   8170  34555  22116  32337  195539

   +IALOAD          39162          36347
   +IASTORE         32461          30663          4299             3667                19556  30563  166868

   -IALOAD/IASTORE
										34167  19347
										       19232  29726  
										       18821
   +AALOAD/BALOAD
		    41490          39527          6776     3315    4077   8443  33895  19152  28018  184693
		    41291          37034          6593                          32682
   +ATHROW                                                                6449                       180079
   +IASTORE         38848          35601          6219             3796   6122         17869  30085  175106
   IINC delayed code
   +ANEWARRAY                                              3263
   +LADD/LSUB const 38719          35256                                  6062  27071                172859

							   2837                 22835
   +ISTORE into arg
									  3080
   quick L2I for ints                                                     2774  21184
   +*ASTORE / *ALOAD
    again                                                  1621    3654   1525
   +CHECKCAST                                                      3574                       25810
                                                                
------------------------------------------------------------------------------------------------------------
		BubbleSort    BidirBubbleSort  QuickSort  Sieve   Hanoi   Dhry   Fib   Array   Tree   Total
   ST/X+J Win95         
   200Mhz P5
   JIT              78490          77060         15220     4840    6370   9180  73160  36080         351700
				   76900         13560             5500   9010         35200         348600
										66080         69920  370750
   +IADD non consts 76620          73210         13180     3790                 63550         58880  356900
											      51740
		    77390          72450         12520     3900    6040   8950  62450  34330  57780  335810    
		    77220          71950                           5270   8840                       338650
		    72390          70690                                                      48010  327370
		    74910          66740         11420                    8620  61730  33340  47350  313940
   +xALOAD/JMP_ZERO
		    71740                                  2800             
		    71460          65250         11540     2750                 62180  33840  50750  311660
   +LCMP                                                                        59100
   better abs(I)
   +xALOAD/IF_ICMPx 66130          61520         12080     3300    5280   8190  56510  33830  50310  297150
   elim dummy static                                               5210                       48270
   methods                                                                                    44160
		   119020         112440         19330     3070    4560   2640  56960  37730  52790  408540
------------------------------------------------------------------------------------------------------------
		BubbleSort    BidirBubbleSort  QuickSort  Sieve   Hanoi   Dhry   Fib   Array   Tree   Total


   Sun JDK         274625         244461         52676    50653   65183  26668  78133  28572  61608  882583
   (90Mhz P5)   

   Microsoft J++     9684           8452          2874     1733    3535   3665   3836   4746  25717   64242
   (90Mhz P5)   

   Symantec Cafe    14541          12198          3686     1922    4527   3325   3425  12969  26829   83422
   JIT 1.02
   (90Mhz P5)   

   Symantec Cafe     8292           6970          2714     1613    3345   3235   2013   4516  13180   45878
   JIT 1.2
   (90Mhz P5)
"

"
   |b|

   b := JAVA::BubbleSortAlgorithm new.
   b perform:#'setData(JJ)V' with:10000 with:0 with:0 with:0.
   Time millisecondsToRun:[
       b performTest.
   ]
"
"
   |b|

   b := JAVA::QSortAlgorithm new.
   b perform:#'setData(JJ)V' with:500000 with:0 with:0 with:0.
   Time millisecondsToRun:[
       b performTest.
   ]
"
"
   |t|

   t := JAVA::Tree new.
   t perform:#'setData(JJ)V' with:1000000 with:0 with:0 with:0.
   Time millisecondsToRun:[
       t performTest.
   ]
"
"
   |t|

   t := JAVA::Array new.
   t perform:#'setData(JJ)V' with:1000000 with:0 with:0 with:0.
   Time millisecondsToRun:[
       t performTest.
   ]
"

! !

!JavaVM class methodsFor:'initialization'!

compile:source selector:smalltalkSelector asJavaMethod:javaSelector fakedSource:fakedSource in:aClass
    "install additional java protocol in smalltalk classes, req'd for java programs"

    |cloneCode|

    (aClass implements:javaSelector) ifFalse:[
        Class packageQuerySignal answer:'__temporary__'
        do:[
            aClass
                compile:source
                classified:'java support'
                logged:false.
        ].

        cloneCode := aClass compiledMethodAt:smalltalkSelector.
        cloneCode source:fakedSource.

        Class withoutUpdatingChangesDo:[
            aClass removeSelector:smalltalkSelector.
            aClass addSelector:javaSelector withMethod:cloneCode.
        ]
    ].

    "Created: / 5.11.1998 / 19:30:22 / cg"
    "Modified: / 5.11.1998 / 19:37:57 / cg"
!

deinitialize
    |table|

    StandardThreadGroup := nil.
    self releaseAllMonitors.
    KnownWindows notNil ifTrue:[
        KnownWindows do:[:v | 
            v isTopView ifTrue:[
                v destroy
            ]
        ]
    ].
    JavaWindowGroup := nil.
    KnownWindows := nil.
    OpenFileTable := nil.          
    JavaMethods := nil.

    "
     JavaVM deinitialize"

    "Created: / 03-01-1998 / 21:28:14 / cg"
    "Modified: / 03-12-1998 / 20:33:21 / cg"
    "Modified: / 28-01-2011 / 14:11:35 / Marcel Hlopko <hlopik@gmail.com>"
!

deinitializeAdditionalJavaProtocol
    "deinstall additional java protocol in smalltalk classes, req'd for java programs"

    #(
        #'clone()Ljava/lang/Object;'
        #'equals(Ljava/lang/Object;)Z'
        #'toString()Ljava/lang/String;'
        #'getClass()Ljava/lang/Class;'
     ) do:[:sel |
        (Object implements:sel) ifTrue:[
            Class withoutUpdatingChangesDo:[
                Object removeSelector:sel.
            ]
        ].
    ].

    "
     self deinitializeAdditionalJavaProtocol
    "

    "Created: / 4.2.1998 / 21:37:10 / cg"
    "Modified: / 5.12.1998 / 15:27:39 / cg"
!

initialize
    DUMMY_LONG_HIGHWORD := 1.
    DUMMY_DOUBLE_HIGHWORD := 2.
    StandardThreadGroup := nil.
    NoAudio := true.
    
    "/ NoAudio := false.
    
    JavaConsoleStream := Transcript.
    FullExceptionTrace := StackTrace := false.
    WindowOPTrace := DrawOPTrace := EventTrace := ThreadTrace := false.
    MonitorTrace := ExceptionTrace := FileOpenTrace := FileIOTrace := false.
    ExceptionDebug := ExitDebug := false.
    ExceptionDebugPatterns := Set new.
    WindowCreationTrace := false.
    FileOpenConfirmation := true.
    SocketConnectConfirmation := true.
    WindowOPTrace := false.
    MonitorTrace := false.
    ThreadTrace := false.
    UnhandledJavaExceptionSignal := (Signal new) mayProceed: true.
    UnhandledJavaExceptionSignal nameClass: self
        message: #unhandledJavaExceptionSignal.
    UnhandledJavaExceptionSignal notifierString: 'unhandled java exception'.
    JavaExceptionSignal := (Signal new) mayProceed: false.
    JavaExceptionSignal nameClass: self message: #javaExceptionSignal.
    JavaExceptionSignal notifierString: 'java exception'.
    UnimplementedInstructionSignal := (Signal new) mayProceed: false.
    UnimplementedInstructionSignal nameClass: self
        message: #unimplementedInstructionSignal.
    UnimplementedInstructionSignal notifierString: 'unimplemented instruction'.
    UnimplementedNativeMethodSignal := (Signal new) mayProceed: false.
    UnimplementedNativeMethodSignal nameClass: self
        message: #unimplementedNativeMethodSignal.
    UnimplementedNativeMethodSignal 
        notifierString: 'unimplemented native method'.
    BadMessageSignal := (Signal new) mayProceed: false.
    BadMessageSignal nameClass: self message: #badMessageSignal.
    BadMessageSignal notifierString: 'invalid message to JAVA object'.
    InternalErrorSignal := (Signal new) mayProceed: false.
    InternalErrorSignal nameClass: self message: #internalErrorSignal.
    InternalErrorSignal notifierString: 'internal error'.
    CallHandlerSignal := (Signal new) mayProceed: false.
    CallHandlerSignal nameClass: self message: #callHandlerSignal.
    CallHandlerSignal notifierString: 'internal signal'.
    StdinReplacementFileQuerySignal := QuerySignal new.
    StdinReplacementFileQuerySignal nameClass: self
        message: #stdinReplacementFileQuerySignal.
    StdinReplacementFileQuerySignal notifierString: 'asking for stdin stream'.
    AssertionsEnabled := true.

    "
     JavaVM initialize"

    "Created: / 02-01-1998 / 18:02:34 / cg"
    "Modified: / 02-12-1998 / 23:02:22 / cg"
    "Modified: / 25-02-2011 / 08:05:26 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 01-04-2011 / 12:33:37 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

initializeAdditionalJavaProtocol
    "install additional java protocol in smalltalk classes, req'd for java programs"

    "/ since we use smalltalk Arrays for JavaArray, some
    "/ additional (java-) protocol is required.
    "/ This is also useful, when Smalltalk objects are passed to
    "/ java ...
    "/ We should implement all of the java.lang.Object protocol in
    "/ Object, to be on the bright side of life; more of this later ...

    self
        compile:'__clone
    "this is smalltalk code with a java selector ...
     (This source cannot be accepted in the browser, 
      since it has a funny selector.)
     Has been added by JavaVM>>initializeAdditionalJavaProtocol"

    ^ self shallowCopy'
        selector:#'__clone' 
        asJavaMethod:#'clone()Ljava/lang/Object;' 
        fakedSource:'#''clone()Ljava/lang/Object;''
    "this is smalltalk code with a java selector ...
     (This source cannot be accepted in the browser, 
      since it has a funny selector.)
     Has been added by JavaVM>>initializeAdditionalJavaProtocol"

    ^ self shallowCopy'
        in:Object.

    "/ ------------------------------------------------------------

    self
        compile:'__equals:arg
    "this is smalltalk code with a java selector ...
     (This source cannot be accepted in the browser, 
      since it has a funny selector.)
     Has been added by JavaVM>>initializeAdditionalJavaProtocol"

    ^ (arg = self) ifTrue:[1] ifFalse:[0]'
        selector:#'__equals:' 
        asJavaMethod:#'equals(Ljava/lang/Object;)Z' 
        fakedSource:'#''equals(Ljava/lang/Object;)Z''
    "this is smalltalk code with a java selector ...
     (This source cannot be accepted in the browser, 
      since it has a funny selector.)
     Has been added by JavaVM>>initializeAdditionalJavaProtocol"

    ^ (arg = self) ifTrue:[1] ifFalse:[0]'
        in:Object.

    "/ ------------------------------------------------------------

    self
        compile:'__toString
    "this is smalltalk code with a java selector ...
     (This source cannot be accepted in the browser, 
      since it has a funny selector.)
     Has been added by JavaVM>>initializeAdditionalJavaProtocol"

    ^ Java as_String:(self displayString)'
        selector:#'__toString' 
        asJavaMethod:#'toString()Ljava/lang/String;' 
        fakedSource:'#''toString()Ljava/lang/String;''
    "this is smalltalk code with a java selector ...
     (This source cannot be accepted in the browser, 
      since it has a funny selector.)
     Has been added by JavaVM>>initializeAdditionalJavaProtocol"

    ^ Java as_String:(self displayString)'
        in:Object.

    "/ ------------------------------------------------------------

    self
        compile:'__getClass
    "this is smalltalk code with a java selector ...
     (This source cannot be accepted in the browser, 
      since it has a funny selector.)
     Has been added by JavaVM>>initializeAdditionalJavaProtocol"

    ^ JavaVM javaClassObjectForClass:self class'
        selector:#'__getClass' 
        asJavaMethod:#'getClass()Ljava/lang/Class;' 
        fakedSource:'#''getClass()Ljava/lang/Class;''
    "this is smalltalk code with a java selector ...
     (This source cannot be accepted in the browser, 
      since it has a funny selector.)
     Has been added by JavaVM>>initializeAdditionalJavaProtocol"

    ^ JavaVM javaClassObjectForClass:self class'
        in:Object.

    "/ ------------------------------------------------------------

    self
        compile:'__hashCode
    "this is smalltalk code with a java selector ...
     (This source cannot be accepted in the browser, 
      since it has a funny selector.)
     Has been added by JavaVM>>initializeAdditionalJavaProtocol"

    ^ self identityHash'
        selector:#'__hashCode' 
        asJavaMethod:#'hashCode()I' 
        fakedSource:'#''hashCode()I''
    "this is smalltalk code with a java selector ...
     (This source cannot be accepted in the browser, 
      since it has a funny selector.)
     Has been added by JavaVM>>initializeAdditionalJavaProtocol"

    ^ self identityHash'
        in:Object.


    "
     self initializeAdditionalJavaProtocol
    "

    "Modified: / 28-01-1997 / 19:38:58 / stefan"
    "Modified: / 22-01-1998 / 21:23:40 / av"
    "Created: / 04-02-1998 / 21:35:46 / cg"
    "Modified: / 30-12-1998 / 21:07:55 / cg"
    "Modified: / 25-10-2010 / 16:26:54 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

initializeBaseClasses
    "load req'd base classes"

    #(
        'java.lang.Object'
        'java.lang.Class'
        'java.lang.String'      
        'java.lang.System'
    ) do:[:cName |
        (Java classForName:cName) isNil ifTrue:[
            self warn:('JavaVM: could not find required class: ' 
                        , cName asText allBold
                        , '\\Please check the Java settings (javaHome)') withCRs.
            AbortSignal raise.
            ^ self
        ]
    ].

    "
     self initializeBaseClasses
    "

    "Created: / 3.1.1998 / 21:13:28 / cg"
    "Modified: / 23.12.1999 / 19:27:42 / cg"
!

initializeOpenFileTable
    OpenFileTable := OrderedCollection 
			with:Stdin 
			with:(JavaConsoleStream ? Stdout)
			with:(JavaConsoleStream ? Stderr).

    "
     JavaVM initializeOpenFileTable
    "

    "Modified: / 6.8.1997 / 00:40:19 / cg"
    "Created: / 2.1.1998 / 18:04:32 / cg"
!

initializePrimitiveClasses
    

    "/    #(
    "/        (#byte    'B' 1)
    "/        (#short   'S' 2)
    "/        (#int     'I' 4)
    "/        (#long    'J' 8)
    "/        (#boolean 'Z' 1)
    "/        (#char    'C' 2)
    "/        (#float   'F' 4)
    "/        (#double  'D' 8)
    "/        (#void    'V' 0)
    "/    ) triplesDo:[:nm :sig :len |
    "/        |jClass classInst|
    "/
    "/        "/
    "/        "/ create a javaClass for it.
    "/        "/
    "/        jClass := Java at:'java.lang.Class'.
    "/        jClass notNil ifTrue:[
    "/            classInst := jClass new.
    "/            JavaClasses at:nm put:classInst.
    "/            JavaClasses at:classInst put:nm.
    "/        ]
    "/    ].
    "
     self initializePrimitiveClasses"

    "Modified: / 22-10-1998 / 01:56:02 / cg"
    "Modified: / 20-12-2010 / 23:39:56 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-01-2011 / 14:57:38 / Marcel Hlopko <hlopik@gmail.com>"
!

initializeReflection

    Reflection := JavaVM::Reflection for: self.

    "Created: / 21-12-2010 / 19:48:10 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

initializeSimulatedLibs
    "return a collection of native libs which are considered 
     being already loaded. (used with jdk < 1.2)"

    LibPath := #(
                        '__builtIn__' 
                        '/usr/local/lib' 
                        '/usr/local/lib/java'
                ).

    SimulatedLibs := #(
                        '__builtIn__/net' 
                        '__builtIn__/awt' 
                        '__builtIn__/tawt' 
                        '__builtIn__/winawt' 
                        '__builtIn__/jpeg'
                        '__builtIn__/mmedia'
                        '__builtIn__/zip'
                        '__builtIn__/math'
                        '__builtIn__/sysresource'

                        "/ KAVA ... 
                        '__builtIn__/agent'

                        "/ MS-java ... 
                        '__builtIn__/msawt'
                        '__builtIn__/javart'

                        "/ 1.1.8
                        '__builtIn__/jpeg_sun' 
                      ).

    "
     self initializeSimulatedLibs
    "

    "Created: / 4.1.1998 / 19:05:03 / cg"
    "Modified: / 17.11.1998 / 23:53:02 / cg"
!

initializeSimulatedNativeLibs
    "return a collection of native libs which are considered 
     being already loaded (used with jdk >= 1.2)"

    OperatingSystem isUNIXlike ifTrue:[
        SimulatedNativeLibs := #(
                                 'libawt.so' 
                                 'libnet.so' 
                                 'libcmm.so' 
                                 'libzip.so'
                                ).
        ^self.
    ].
    OperatingSystem isMSWINDOWSlike ifTrue:[
        SimulatedNativeLibs := #(
                                 'awt.dll' 
                                 'net.dll' 
                                 'cmm.dll' 
                                 'zip.dll'
                                ).
        ^self.
    ].
    SimulatedNativeLibs := #().
    

    "
     self initializeSimulatedNativeLibs
    "

    "Modified: / 27-01-1998 / 18:43:10 / cg"
    "Modified: / 01-04-2011 / 23:02:21 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

initializeSimulatedNativeMemory

    SimulatedNativeMemory := JavaNativeMemory new.

    "Created: / 07-12-2010 / 21:07:31 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 07-12-2010 / 23:45:31 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

initializeSystemPropertiesInto:props
    |cpu os jHome|

    "/ use JAVA compatible cpu-name
    cpu := OperatingSystem getCPUType.
    cpu = 'i386' ifTrue:[
        cpu := 'ix86'
    ].
    SimulatedOS notNil ifTrue:[
        os := SimulatedOS
    ] ifFalse:[
        os := OperatingSystem getOSType.
        os := os asUppercaseFirst.
    ].

    props at:'java.version'       put:'1'.
    props at:'java.vendor'        put:'eXept Software AG & SWING Reseach Group'.
    props at:'java.vendor.url'    put:'http://www.exept.de & http://swing.fit.cvut.cz'.
    props at:'java.vm.name'       put:'Smalltalk/X'.
    (jHome := self defaultJAVAHome) notNil ifTrue:[
        props at:'java.home'          put:(jHome asFilename pathName).
    ].
    props at:'java.class.version' put:'1'.
    props at:'java.class.path'    put:(self defaultCLASSPATH).
    props at:'os.name'            put:os.
    props at:'os.arch'            put:cpu.
    props at:'os.version'         put:'1'.
    props at:'file.separator'     put:(Filename separator asString).

    props at:'path.separator'     put: OperatingSystem pathSeparator asString. 
    props at:'line.separator'     put:(Character cr asString).
    props at:'user.name'          put:(OperatingSystem getLoginName).
    props at:'user.home'          put:(OperatingSystem getHomeDirectory ? Filename currentDirectory name).
    props at:'user.dir'          put:(OperatingSystem getHomeDirectory ? Filename currentDirectory name).
    "/ props at:'user.dir'           put:(Filename currentDirectory pathName).

    "/props at:'awt.toolkit'        put:(self defaultWindowingToolKit).

    props at: 'user.country'    put: 'US'.

    props at:'hotjava.home'       put:(self defaultHotJavaHome).

    "/ new with jdk 1.1.8
    "/ undocumented ?
    props at:'file.encoding.pkg'    put:'sun.io'.
    props at:'file.encoding'        put:'UTF-8'.

    "/ suppress copyright view in appletViewer ...
    props at:'appletviewer.version' put:'1.1'.

    "/ new with jdk 1.2
    props at:'java.awt.graphicsenv' put:'sun.awt.X11GraphicsEnvironment'.
    props at:'java.awt.fonts'       put:'/usr/lib/X11/fonts'.

    "/ jws
    "/props at:'jws.home'             put:(self defaultJWSHome).
    "/ new with jws 2.0 ...
    "/props at:'jws.startcmd'         put:'jws.showwin.mainide'.

    props at: 'java.library.path'   put: self defaultJavaLibraryPath.
    props at: 'sun.boot.library.path' put: self defaultSunBootLibraryPath. 

"/    props at: 'sun.misc.URLClassPath.debug' put: 'true'. 

    ^ props

    "
     self initializeSystemPropertiesInto:(Dictionary new)
    "

    "Created: / 03-01-1998 / 14:26:39 / cg"
    "Modified: / 27-01-2000 / 02:20:18 / cg"
    "Modified: / 12-08-2011 / 19:51:25 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

initializeVM
    "Force off JIT compiler for Java code - it hasn't been
     updated to reflect changes in jinterpret.c.
     Following >>make it working, make it fast<< rule"
    
    ObjectMemory
        javaJustInTimeCompilation: false;
        javaNativeCodeOptimization: false.
    JavaObject autoload.
    JavaContext autoload.
    MonitorTrace ifNil: [ self initialize ].
    self initializeAdditionalJavaProtocol.
    self releaseAllJavaResources.
    JavaConsoleStream := Transcript.
    Java initAllStaticFields.
    Java markAllClassesUninitialized.

    ZipCache := OrderedCollection new.
    ZipEntryCache := OrderedCollection new.
    ZipInflaters := OrderedCollection new.
    
    "/ force re-resolving;
    "/ otherwise, class-inits would not be called
    "/ by resolver ... (sigh)
    
    JavaNativeMethod flushAllCachedNativeMethods.
    JavaMethod allSubInstancesDo: 
            [:m | 
            m checked: false.
            m code: nil. ].
    ObjectMemory flushCaches.
    
    "/ sigh - must flush inline caches.
    
    JavaClass startRememberingOrderOfClassInits.
    self initializeSimulatedLibs.
    
    "/ < jdk 1.2
    
    self initializeSimulatedNativeLibs.
    
    "/ >= jdk 1.2
    
    self initializeSimulatedNativeMemory.
    
    "/>  jdk 6
    
    self initializeOpenFileTable.
    self initializeReflection.
    self initializeBaseClasses.
    self initializePrimitiveClasses.
    Java initSystemClass.
    ObjectMemory addDependent: self.

    "
     JavaVM initialize.
     JavaVM initializeVM."

    "Created: / 03-01-1998 / 21:29:09 / cg"
    "Modified: / 14-12-1999 / 18:58:56 / cg"
    "Modified: / 15-10-2010 / 15:27:45 / Jan Kurs <kurs.jan@post.cz>"
    "Modified: / 01-04-2011 / 15:33:39 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
    "Modified: / 11-08-2011 / 00:57:20 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

initializeVMIfNoEventThreadRunning
    |uClass updater p|

    uClass := JAVA::sun::awt::ScreenUpdater.
    uClass notNil ifTrue:[
        updater := uClass instVarNamed:'updater'.
        updater notNil ifTrue:[
            p := self stProcessForJavaThread:updater
        ].
        (updater isNil or:[p isNil or:[p isDead]]) isNil ifTrue:[
            self initializeVM.
            ^ self.
        ]
    ].

    (JavaEventThread isNil or:[JavaEventThread isDead]) ifTrue:[
        self initializeVM
    ].

    "
     JavaVM initializeVMIfNoEventThreadRunning
    "

    "Created: / 15.1.1998 / 17:32:27 / cg"
    "Modified: / 24.12.1999 / 02:18:25 / cg"
!

reinitializeVM
    |classesToInit|

    self releaseAllJavaResources.

    JavaConsoleStream := Transcript.

    Java initAllStaticFields.
    Java markAllClassesUninitialized.

    self initializeOpenFileTable.

    classesToInit := JavaClass orderOfClassInits.
    JavaClass startRememberingOrderOfClassInits.

    self initializePrimitiveClasses.
"/    Java initSystemClass.

    classesToInit do:[:jClass |
Transcript showCR:'classInit: ' , jClass name.
	jClass classInit
    ].
    Java initSystemClass.

    "Created: / 12.11.1998 / 15:37:52 / cg"
    "Modified: / 17.11.1998 / 16:10:11 / cg"
!

reinitializeVMIfNoEventThreadRunning
    (JavaEventThread isNil or:[JavaEventThread isDead]) ifTrue:[
        ^ self reinitializeVM
    ].
    (JavaEventQueueThread isNil or:[JavaEventQueueThread isDead]) ifTrue:[
        ^ self reinitializeVM
    ].

    "
     JavaVM reinitializeVMIfNoEventThreadRunning
    "

    "Created: / 24.11.1998 / 15:45:49 / cg"
    "Modified: / 24.12.1999 / 02:36:41 / cg"
!

releaseAllJavaResources
    self deinitialize.

    FirstWindowCreationSemaphore := Semaphore new.
    JavaScreenUpdaterThread := JavaEventQueueThread := nil.

    LoadedLibs := nil.             "/ gc will reclaim them ...
    LoadedNativeLibs := nil.       "/ gc will reclaim them ...
    
    ImageStretchCache := nil.
    LastGraphics := LastGC := nil.

    SimulatedNativeMemory := nil.

    self initializePrimitiveClasses.

    self terminateAllThreads.

    self releaseAllWindows.
    self releaseAllStreams.

    "
     JavaVM releaseAllJavaResources
    "

    "Created: / 07-01-1998 / 22:49:42 / cg"
    "Modified: / 24-12-1999 / 02:33:11 / cg"
    "Modified: / 17-12-2010 / 17:51:35 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

releaseAllMonitors
    LockTable := WeakIdentityDictionary new.
    LockTableAccess := Semaphore"RecursionLock" forMutualExclusion.
    LockTableAccess name: 'JavaVM lock table access mutex'.
    WaitTable := IdentityDictionary new.
    WaitTableAccess := Semaphore"RecursionLock" forMutualExclusion.
    WaitTableAccess name: 'JavaVM wait table access mutex'.

    EnteredMonitorsPerProcess := IdentityDictionary new.

    "
     JavaVM releaseAllMonitors
    "

    "Created: / 02-01-1998 / 18:04:05 / cg"
    "Modified: / 07-01-1998 / 22:58:10 / cg"
    "Modified: / 25-10-2010 / 19:14:51 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

releaseAllStreams
    OpenFileTable notNil ifTrue:[
	OpenFileTable do:[:aStream |
	    aStream notNil ifTrue:[
		aStream ~~ Stdin ifTrue:[
		    aStream ~~ Stdout ifTrue:[
			aStream ~~ Stderr ifTrue:[
			    aStream ~~ JavaConsoleStream ifTrue:[
				aStream isExternalStream ifTrue:[
				    aStream shutDown
				]
			    ]
			]
		    ]
		]
	    ]
	]
    ].
    self initializeOpenFileTable.

    "
     JavaVM releaseAllStreams
    "

    "Created: / 7.1.1998 / 22:57:04 / cg"
    "Modified: / 4.2.1998 / 19:53:11 / cg"
!

releaseAllWindows
    KnownWindows notNil ifTrue:[
	KnownWindows do:[:aView |
	    aView destroy
	].
	KnownWindows := nil.
    ]

    "
     self releaseAllWindows
    "

    "Created: / 7.1.1998 / 22:58:32 / cg"
!

releaseLeftOverMonitors
    "release monitors held by dead processes"

    |deadProcesses|

    deadProcesses := IdentitySet new.

    EnteredMonitorsPerProcess keysAndValuesDo:[:p :monitors |
	p isDead ifTrue:[
	    monitors do:[:mon |
		Transcript showCR:'release leftover monitor ...'.
		mon release
	    ].
	    deadProcesses add:p.
	]
    ].
    deadProcesses do:[:p |
	EnteredMonitorsPerProcess removeKey:p
    ].

    "
     JavaVM releaseLeftOverMonitors
    "

    "Created: / 8.1.1998 / 17:29:26 / cg"
    "Modified: / 8.1.1998 / 17:38:33 / cg"
!

systemProperties
    |props|

    props := Dictionary new.
    self initializeSystemPropertiesInto:props.
    ^ props

    "Created: / 3.1.1998 / 14:25:58 / cg"
    "Modified: / 3.1.1998 / 14:32:38 / cg"
!

terminateAllThreads
    Java terminateAllThreads.
    JavaEventThread := nil.
    JavaScreenUpdaterThread := JavaEventQueueThread := nil.

    "Created: / 8.1.1998 / 17:43:54 / cg"
    "Modified: / 24.12.1999 / 02:33:16 / cg"
!

update:something with:aParameter from:changedObject
    something == #returnFromSnapshot ifTrue:[
"/         self initializeVM
    ].

    "
     JavaVM initializeVM
    "

    "Created: / 9.1.1998 / 10:30:13 / cg"
    "Modified: / 6.11.1998 / 00:40:53 / cg"
! !

!JavaVM class methodsFor:'Signal constants'!

badMessageSignal
    ^ BadMessageSignal

    "Created: / 2.1.1998 / 18:06:52 / cg"
!

callHandlerSignal
    ^ CallHandlerSignal

    "Created: / 2.1.1998 / 18:07:16 / cg"
!

internalErrorSignal
    ^ InternalErrorSignal

    "Created: / 2.1.1998 / 18:07:05 / cg"
!

javaExceptionSignal
    "^ JavaExceptionSignal"
    ^JavaError

    "Created: / 02-01-1998 / 18:05:58 / cg"
    "Modified: / 01-03-2011 / 21:50:40 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

stdinReplacementFileQuerySignal
    ^ StdinReplacementFileQuerySignal

    "Created: / 2.1.1998 / 18:06:52 / cg"
!

unhandledJavaExceptionSignal
    ^ UnhandledJavaExceptionSignal

    "Created: / 2.1.1998 / 18:05:19 / cg"
!

unimplementedInstructionSignal
    ^ UnimplementedInstructionSignal

    "Created: / 2.1.1998 / 18:06:15 / cg"
!

unimplementedNativeMethodSignal
    ^ UnimplementedNativeMethodSignal

    "Created: / 2.1.1998 / 18:06:40 / cg"
! !

!JavaVM class methodsFor:'accessing'!

addSelector:newSelector withMethod:newMethod 
    super addSelector:newSelector withMethod:newMethod.
    
    "/JavaNativeMethod may not be loaded..."
    
    (Smalltalk at:#JavaNativeMethod) 
        ifNotNil:[JavaNativeMethod flushAllCachedNativeMethods].

    "Created: / 24-12-1999 / 03:12:05 / cg"
    "Modified: / 02-02-2011 / 04:38:23 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 02-02-2011 / 23:38:08 / Marcel Hlopko <hlopik@gmail.com>"
!

assertionsEnabled: aBoolean

    AssertionsEnabled := aBoolean

    "
        JavaVM assertionsEnabled: true.
        JavaVM assertionsEnabled: false.
    "

    "Created: / 24-11-2010 / 09:02:05 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

classForName:aString 

    ^ Java classForName:aString.

    "Created: / 21-12-2010 / 19:50:58 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 02-02-2011 / 23:48:57 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 03-02-2011 / 21:45:11 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

javaEventQueueThread
     ^ JavaEventQueueThread

    "Created: / 24.12.1999 / 02:34:35 / cg"
!

javaEventThread
     ^ JavaEventThread

    "Created: / 8.1.1999 / 17:05:02 / cg"
!

javaScreenUpdaterThread
     ^ JavaScreenUpdaterThread

    "Created: / 8.1.1999 / 17:06:52 / cg"
!

reflection
    ^ Reflection.

    "Created: / 28-01-2011 / 15:09:19 / Marcel Hlopko <hlopik@gmail.com>"
!

useSmalltalkInterpreter

    JavaMethod makeMetaMethod

    "Created: / 23-02-2011 / 12:59:44 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

useVMInterpreter

    JavaMethod makeJavaMethod

    "Created: / 23-02-2011 / 12:59:37 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!JavaVM class methodsFor:'debugging support'!

exceptionDebug
    ^ ExceptionDebug

    "Created: / 27.1.1999 / 20:14:51 / cg"
!

exceptionDebug:aBoolean
    ExceptionDebug := aBoolean

    "Created: / 27.1.1999 / 20:15:00 / cg"
!

exceptionDebugPatterns

    ^ ExceptionDebugPatterns
    "
    ExceptionDebugPatterns add: 'java/lang/ArrayIndex*'
    "

    "Created: / 25-02-2011 / 08:08:46 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!JavaVM class methodsFor:'defaults'!

audioEnabled
    ^ NoAudio not

    "Created: / 18.7.1998 / 22:31:36 / cg"
!

audioEnabled:aBoolean
    NoAudio := aBoolean not

    "Created: / 18.7.1998 / 22:31:20 / cg"
!

defaultCLASSPATH
    |s|

    s := '' writeStream.
    Java effectiveClassPath do:[:p |
        s size == 0 ifFalse:[
            s nextPut:$:
        ].
        s nextPutAll:p.
    ].

    ^ s contents

    "
     self defaultCLASSPATH  
    "

    "Created: / 03-01-1998 / 14:27:21 / cg"
    "Modified: / 22-11-2010 / 13:44:42 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

defaultHotJavaHome
    ^ '/usr/local/java/hotjava'.

    "Modified: / 5.8.1997 / 04:13:36 / cg"
    "Created: / 3.1.1998 / 14:27:34 / cg"
!

defaultJAVAHome
    ^ Java javaHome

    "Modified: / 6.8.1997 / 00:54:44 / cg"
    "Created: / 3.1.1998 / 14:27:01 / cg"
!

defaultJWSHome
    '/phys/idefix/home2/java/JWS2_0/Java-WorkShop2.0/JWS' asFilename exists ifTrue:[
	^ '/phys/idefix/home2/java/JWS2_0/Java-WorkShop2.0/JWS'
    ].

    ^ '/usr/local/java/JWS'.

    "Created: / 3.1.1998 / 14:27:42 / cg"
    "Modified: / 3.12.1998 / 14:54:08 / cg"
!

defaultJavaLibraryPath

    | dirs |
    dirs := OrderedCollection new
            add: Java release javaHome asFilename / 'lib';
            add: Java release javaHome asFilename / 'lib' / 'amd64';
            add: Java release javaHome asFilename / 'lib' / 'i386';
            add: Java release javaHome asFilename / 'jre' / 'lib' ;
            add: Java release javaHome asFilename / 'jre' / 'lib' / 'amd64'  ;
            add: Java release javaHome asFilename / 'jre' / 'lib' / 'i386' ;
            add: Java release javaHome asFilename / 'jre' / 'bin' ;
            yourself.
    OperatingSystem isMSWINDOWSlike ifTrue:[
        dirs
            add: Java release javaHome asFilename / 'bin'.
    ].

    ^String streamContents:
        [:path|
        (dirs select:[:d|d exists])
            do:[:d|path nextPutAll:d pathName]
            separatedBy:[path nextPut: OperatingSystem pathSeparator]]

    "
        JavaVM defaultJavaLibraryPath
    "

    "Created: / 10-12-2010 / 14:09:50 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 01-04-2011 / 18:21:35 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

defaultSunBootLibraryPath

    | dirs |
    dirs := OrderedCollection new
            add: Java release javaHome asFilename / 'lib';
            add: Java release javaHome asFilename / 'lib' / 'amd64';
            add: Java release javaHome asFilename / 'lib' / 'i386';
            add: Java release javaHome asFilename / 'jre' / 'lib' ;
            add: Java release javaHome asFilename / 'jre' / 'lib' / 'amd64'  ;
            add: Java release javaHome asFilename / 'jre' / 'lib' / 'i386' ;
            yourself.
    OperatingSystem isMSWINDOWSlike ifTrue:[
        dirs
            add: Java release javaHome asFilename / 'bin'.
    ].


    ^String streamContents:
        [:path|
        (dirs select:[:d|d exists])
            do:[:d|path nextPutAll:d pathName]
            separatedBy:[path nextPut: OperatingSystem pathSeparator]]

    "
        JavaVM defaultJavaLibraryPath
    "

    "Created: / 10-12-2010 / 14:37:36 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

defaultWindowingToolKit
    "/ prefer the windows toolkit ...

    (Java classForName:'sun.awt.windows.WToolkit') notNil ifTrue:[
        ^ 'sun.awt.windows.WToolkit'.
    ].
    (Java classForName:'sun.awt.motif.MToolkit') notNil ifTrue:[
        self halt:'MotifToolKit: this is untested code'.
        ^ 'sun.awt.motif.MToolkit'.
    ].

    self halt:'TinyToolKit: this is untested code'.
    ^ 'sun.awt.tiny.TinyToolkit'.


"/    ^ 'sun.awt.win32.MToolkit'.
"/    ^ 'sun.awt.motif.MToolkit'.

    "
     self defaultWindowingToolKit
    "

    "Created: / 3.1.1998 / 14:27:49 / cg"
    "Modified: / 27.1.1998 / 21:52:52 / cg"
!

fileAccessTrace
    ^ FileAccessTrace

    "Created: / 27.1.1999 / 18:55:40 / cg"
!

fileAccessTrace:aBoolean
    FileAccessTrace := aBoolean

    "Created: / 19.10.1998 / 16:01:44 / cg"
    "Modified: / 27.1.1999 / 18:55:52 / cg"
!

fileOpenConfirmation
    ^ FileOpenConfirmation

    "Created: / 19.10.1998 / 16:01:44 / cg"
!

fileOpenConfirmation:aBoolean
    FileOpenConfirmation := aBoolean

    "Created: / 19.10.1998 / 16:01:56 / cg"
!

javaConsole:aStream
    JavaConsoleStream := aStream

    "
     JavaVM javaConsole:Transcript
    "

    "Modified: / 6.8.1997 / 00:34:13 / cg"
    "Created: / 3.1.1998 / 14:27:58 / cg"
!

javaConsoleStream
    ^ JavaConsoleStream

    "Created: / 3.1.1998 / 14:32:16 / cg"
!

nullPointerExceptionDebug
    ^ NullPointerExceptionDebug

    "Created: / 27.1.1999 / 20:14:51 / cg"
!

nullPointerExceptionDebug:aBoolean
    NullPointerExceptionDebug := aBoolean

    "Created: / 27.1.1999 / 20:15:00 / cg"
!

socketConnectConfirmation
    ^ SocketConnectConfirmation

    "Created: / 19.10.1998 / 16:02:15 / cg"
!

socketConnectConfirmation:aBoolean
    SocketConnectConfirmation := aBoolean

    "Created: / 19.10.1998 / 16:02:06 / cg"
! !

!JavaVM class methodsFor:'fileIO'!

addOpenFile:aStream
    OpenFileTable add:aStream.
    ^ OpenFileTable size - 1.

    "Created: / 2.1.1998 / 18:32:59 / cg"
!

getOpenFileAt:idx
    ^ OpenFileTable at:idx+1 ifAbsent:nil.

    "Created: / 2.1.1998 / 18:28:01 / cg"
    "Modified: / 2.1.1998 / 18:33:06 / cg"
!

setOpenFile:aStream at:idx
    OpenFileTable size < (idx+1) ifTrue:[
	OpenFileTable grow:idx+1.
    ].
    OpenFileTable at:idx+1 put:aStream.

    "Modified: / 2.1.1998 / 18:33:21 / cg"
! !

!JavaVM class methodsFor:'helpers'!

canCast: s to: t
    "Helper for _CHECKCAST:_:"
    | sc tc |

    "Not specified in JVM spec, sigh"
    s isJavaPrimitiveType ifTrue:[
        "FIXME"
        ^s == t
    ].
    "
    Java VM Spec, 3rd edition, p 280:

    The following rules are used to determine whether an objectref that is not
    null can be cast to the resolved type: if S is the class of the object
    referred to by objectref and T is the resolved class, array, or interface type,
    checkcast determines whether objectref can be cast to type T as follows:

    - If S is an ordinary (nonarray) class, then:
      - If T is a class type, then S must be the same class as T, or a subclass
        of T.
      - If T is an interface type, then S must implement interface T.
    "
    (s isJavaArrayClass not and:[s isInterface not]) ifTrue:
        [^s includesBehavior: t].

    "
    - If S is an interface type, then:
      - If T is a class type, then T must be Object.
      - If T is an interface type, then T must be the same interface as S or a
        superinterface of S.    
    "
    s isInterface ifTrue:
        [^t isInterface not 
            ifTrue: [t == (self classForName:'java.lang.Object')]
            ifFalse:[s includesBehavior: t]].
    "
    - If S is a class representing the array type SC[], that is, an array of com-
      ponents of type SC , then:
    "
    self assert: s isJavaArrayClass description: 'S should be array type'.
    sc := s javaComponentClass.
    "
      - If T is a class type, then T must be Object.
    "
      t isJavaClassType ifTrue:
        [^t == (self classForName: 'java.lang.Object')].
    "
      - If T is an array type TC[], that is, an array of components of type TC ,
        then one of the following must be true:
        - TC and SC are the same primitive type.
        - TC and SC are reference types, and type SC can be cast to TC by
          recursive application of these rules.
    "        
      t isJavaArrayClass ifTrue:
        [tc := t javaComponentClass.
        ^tc isJavaPrimitiveType
            ifTrue:[tc == sc]
            ifFalse:[self canCast: sc to: tc]].
    "
      - If T is an interface type, T must be one of the interfaces implemented
        by arrays (JLS3 4.10.3).
    "
    ((t name == #'java/lang/Cloneable') or:
        [t name == #'java/lang/Serializable'])
            ifTrue:[^true].

    ^false

    "Modified: / 09-01-1999 / 00:45:21 / cg"
    "Created: / 11-02-2011 / 08:21:36 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 14-08-2011 / 23:14:26 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

javaArrayClassFor:aClass 
    ^ self reflection javaArrayClassObjectForClass:aClass
        ifAbsentPut:[JavaArray javaArrayClassFor:aClass]

    "Created: / 17-12-2010 / 13:46:36 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-01-2011 / 14:59:16 / Marcel Hlopko <hlopik@gmail.com>"
!

javaStringObjectForString:string 
    self breakPoint:#mh info:'refactor my sender to use reflection directly'.
    ^ self reflection javaStringObjectForString:string interned:false

    "Created: / 22-11-2010 / 16:31:27 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 09-02-2011 / 00:47:49 / Marcel Hlopko <hlopik@gmail.com>"
!

javaStringObjectForString:string interned:intern 
    self breakPoint:#mh info:'refactor my sender to use reflection directly'.
    ^self reflection javaStringObjectForString:string interned:intern.

    "Created: / 22-11-2010 / 16:28:09 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 22-11-2010 / 17:57:43 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 09-02-2011 / 01:04:21 / Marcel Hlopko <hlopik@gmail.com>"
!

javaThreadForSTProcess:stProcess
    |t|

    t := Java threads keyAtValue:stProcess ifAbsent:nil.
    t == 0 ifTrue:[
	^ nil
    ].
    ^ t

    "Modified: / 26.8.1997 / 19:56:31 / cg"
    "Created: / 3.1.1998 / 01:53:41 / cg"
!

newThread:name
    |thread threadClass i|

    threadClass := Java at:'java.lang.Thread'.

    thread := (Java at:'java.lang.Thread') basicNew.
    thread instVarNamed:'name'        put:(Java as_String:name).
    thread instVarNamed:'priority'    put:(threadClass instVarNamed:'NORM_PRIORITY').
    thread instVarNamed:'single_step' put:0.
    thread instVarNamed:'daemon'      put:0.
    thread instVarNamed:'stillborn'   put:0.
    thread instVarNamed:'target'      put:nil.
    "/
    "/ that on was only temporarily present in JDK1.1.3 (sigh)
    "/
    (i := thread class instVarOffsetOf:'initial_stack_memory') notNil ifTrue:[
	thread instVarAt:i put:0.
    ].
    thread instVarNamed:'group'       put:(self standardThreadGroup).
    ^ thread

    "Created: / 3.1.1998 / 01:47:30 / cg"
    "Modified: / 27.1.1998 / 00:54:33 / cg"
!

stProcessForJavaThread:jThread
    |p|

    p := Java threads at:jThread ifAbsent:nil.
    p == 0 ifTrue:[
	^ nil
    ].
    ^ p

    "Created: / 2.1.1998 / 21:48:27 / cg"
    "Modified: / 3.1.1998 / 01:53:55 / cg"
!

standardThreadGroup
    |standardGroup threadClass|

    StandardThreadGroup isNil ifTrue:[
        threadClass := Java at:'java.lang.Thread'.

        standardGroup := (self classForName:'java.lang.ThreadGroup') new.
        standardGroup instVarNamed:'parent'      put:nil.
        standardGroup instVarNamed:'name'        put:(Java as_String:'main').
        standardGroup instVarNamed:'maxPriority' put:(threadClass instVarNamed:'MAX_PRIORITY').
        standardGroup instVarNamed:'destroyed'   put:0.
        standardGroup instVarNamed:'daemon'      put:nil.
        (standardGroup class instVarOffsetOf:'vmAllowSuspension') notNil ifTrue:[
            standardGroup instVarNamed:'vmAllowSuspension' put:0.
        ].
        standardGroup instVarNamed:'nthreads'    put:0.
        standardGroup instVarNamed:'ngroups'     put:0.
        standardGroup instVarNamed:'groups'      put:nil.
        StandardThreadGroup := standardGroup.
    ].
    ^ StandardThreadGroup

    "Created: / 03-01-1998 / 01:41:54 / cg"
    "Modified: / 17-11-1998 / 22:55:30 / cg"
    "Modified: / 25-04-2011 / 20:27:26 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

threadStart:nativeContext
    "start the thread"

    |jThread jName name stProcess helper |

    jThread := nativeContext receiver.
    (jThread instVarNamed:'priority') < 1 ifTrue:[
        self halt.
        jThread instVarNamed:'priority' put:1.
    ].

    
    stProcess := JavaProcess 
                    for: (helper := JavaProcess newHelper)
                    priority:(Processor activePriority).
    helper javaThreadObject: jThread.
    helper javaProcess: stProcess.

    jName := jThread instVarNamed:'name'.
    jName isString ifFalse:[
        name := Java as_ST_String:jName.
    ] ifTrue:[
        name := jName
    ].

    "/ kludge - remember the ScreenUpdater ...
    name = 'Screen Updater' ifTrue:[
        JavaScreenUpdaterThread := stProcess.
    ] ifFalse:[
        name = 'AWT-Windows' ifTrue:[
            JavaEventThread := stProcess.
        ] ifFalse:[
            (name startsWith:'AWT-EventQueue') ifTrue:[
                JavaEventQueueThread := stProcess.
            ].
        ]
    ].

"/name = 'UserDialogShowThread' ifTrue:[
"/self halt
"/].
    "/ when that process terminates, wakup any waiters
    "/stProcess addExitAction:[self wakeup:jThread].

    stProcess name:'JAVA-' , name.
    stProcess restartable:true.
    stProcess resume.

    Java threads at:jThread put:stProcess.

    ^ nil

    "Modified: / 24-12-1999 / 03:14:33 / cg"
    "Created: / 14-12-2010 / 21:31:02 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 15-12-2010 / 11:19:50 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

wakeup:anObject
    JavaVM releaseAndSignalSemaphoreFor:anObject.

    "Created: / 3.1.1998 / 02:29:27 / cg"
    "Modified: / 3.1.1998 / 03:08:05 / cg"
!

wakeupAll:anObject
    JavaVM releaseAndSignalForAllSemaphoreFor:anObject.

    "Created: / 3.1.1998 / 03:07:48 / cg"
    "Modified: / 3.1.1998 / 03:08:15 / cg"
! !

!JavaVM class methodsFor:'helpers - awt'!

commonReshapeComponent:nativeContext
    |view x y width height ext menu|

    view := self viewForWPeer:nativeContext.

    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    width := nativeContext argAt:3.
    height := nativeContext argAt:4.
    ext := width@height.

"/    'pReshape ' print. view print. 
"/    ' ' print. x print. '/' print. y print.
"/    ' extent: ' print. ext printNL.
    view isPopUpView ifTrue:[
	view origin:x@y extent:ext.
    ] ifFalse:[
	(view isTopView 
	or:[view isMemberOf:JavaEmbeddedFrameView]) ifTrue:[
	    "/
	    "/ dont allow setting the origin
	    "/
	    menu := self topViewsMenu:view.
	    menu notNil ifTrue:[
		"/ must add the menus height
		height := height + menu height.
		ext := width@height.
	    ].

	    "/ to prevent a view from not being visible/closable
	    "/ in case Java goes mad ..

	    (width < 30
	    or:[height < 10]) ifTrue:[
		"/ self halt.
		width := 30.
		height := 20.
		ext := width@height.
	    ].

	    view extent:ext.
	    (view isKindOf:ModalBox) ifTrue:[
		view preferredExtent:ext
	    ].

	    "/ adjust non-resizable views min/max

	    view isTopView ifTrue:[
		view minExtent notNil ifTrue:[
		    view minExtent:ext.
		    view maxExtent:ext
		].
	    ]
	] ifFalse:[
	    (view superView notNil
	    and:[view superView isTopView]) ifTrue:[
		menu := self topViewsMenu:view superView.
		menu notNil ifTrue:[
		    "/ must add menus height to yPos
		    y := y + menu height.
		]
	    ] ifFalse:[
		"/ post a configuration event
		EventTrace == true ifTrue:[
		    'JAVA: configure: need event' printCR.
		]
	    ].
	    (x isNil or:[y isNil]) ifTrue:[
		Transcript showCR:'bad args to reshape'.
	    ] ifFalse:[
		view origin:x@y extent:ext.
	    ]
	].
    ].

    view isJavaView ifTrue:[
	view invalidate.
    ].

    ^ nil

    "Created: / 4.1.1998 / 18:00:52 / cg"
    "Modified: / 5.12.1998 / 13:34:20 / cg"
!

createdWindowsView:aView for:aJavaPeer
    "this is only sent with the sun.awt.windows toolkit"

    aJavaPeer instVarNamed:'pData' put:aView.

    JavaWindowGroup isNil ifTrue:[
	JavaWindowGroup := WindowGroup new.
	JavaWindowGroup isForModalSubview:true.
    ].
    aView windowGroup:JavaWindowGroup.
    JavaWindowGroup addView:aView.

    KnownWindows isNil ifTrue:[
	KnownWindows := IdentityDictionary new.
    ].
    KnownWindows at:aJavaPeer put:aView.

    FirstWindowCreationSemaphore signalIf.

"/'*** ' print. aJavaPeer print. ' -> ' print. aView printCR.
"/(aView isKindOf:ModalBox) ifTrue:[
"/    self halt.
"/].

    "Created: / 4.1.1998 / 17:57:16 / cg"
    "Modified: / 28.1.1998 / 22:40:19 / cg"
!

gcForWGraphics:nativeContext
    |jGraphics gc orgX orgY trans tX tY|

    jGraphics := nativeContext receiver.
    O_WGgraphics_pData isNil ifTrue:[
	O_WGgraphics_pData := (jGraphics class instVarOffsetOf:'pData').
    ].
    O_WGgraphics_originX isNil ifTrue:[
	O_WGgraphics_originX := (jGraphics class instVarOffsetOf:'originX').
    ].
    O_WGgraphics_originY isNil ifTrue:[
	O_WGgraphics_originY := (jGraphics class instVarOffsetOf:'originY').
    ].
    gc := jGraphics instVarAt:O_WGgraphics_pData.

    trans := gc translation.
    tX := trans x.
    tY := trans y.
"/    tX := gc translationX.
"/    tY := gc translationY.

    orgX := jGraphics instVarAt:O_WGgraphics_originX.
    orgY := jGraphics instVarAt:O_WGgraphics_originY.
    ((orgX ~~ tX) or:[orgY ~~ tY]) ifTrue:[
	gc translation:orgX@orgY
    ].
    ^ gc

    "Created: / 8.1.1998 / 00:16:38 / cg"
    "Modified: / 23.12.1998 / 20:27:35 / cg"
!

jPeerForView:aView
    ^ KnownWindows keyAtValue:aView ifAbsent:nil

    "Created: / 15.1.1998 / 13:48:01 / cg"
    "Modified: / 15.1.1998 / 13:48:43 / cg"
!

pReshape:nativeContext
    |jFramePeer view x y width height menu|

    jFramePeer := nativeContext receiver.
    view := jFramePeer instVarNamed:'pData'.

    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    width := nativeContext argAt:3.
    height := nativeContext argAt:4.

"/    'pReshape ' print. view print. 
"/    ' ' print. x print. '/' print. y print.
"/    ' extent: ' print. width print. '/' print. height printNL.

    view isPopUpView ifTrue:[
	self halt.
    ].

    (view isTopView 
    or:[view isMemberOf:JavaEmbeddedFrameView]) ifTrue:[
	"/
	"/ dont allow setting the origin
	"/
	menu := self topViewsMenu:view.
	menu notNil ifTrue:[
	    "/ must add the menus height
	    height := height + menu height
	].
	view extent:width@height.
    ] ifFalse:[
	(view superView notNil
	and:[view superView isTopView]) ifTrue:[
	    menu := self topViewsMenu:view superView.
	    menu notNil ifTrue:[
		"/ must add menus height to yPos
		y := y + menu height.
	    ]
	].
	view origin:x@y extent:width@height.
    ].

    ^ nil

    "Created: / 7.1.1998 / 21:47:11 / cg"
    "Modified: / 5.12.1998 / 13:47:52 / cg"
!

replacementFontFor:name style:styleNr size:size
    |font family style|

    style := 'roman'.
    styleNr = 0 ifTrue:[
        style := 'roman'
    ].

    font := Font family:name style:style size:size.
    font notNil ifTrue:[^ font].

    name = 'Dialog' ifTrue:[
        family := 'helvetica'
    ] ifFalse:[
        family := 'courier'
    ].

    ^ Font family:name style:style size:size.
!

topViewsMenu:view
    |idx|

    view isTopView ifTrue:[
	view subViews size > 0 ifTrue:[
	    (idx := view subViews findFirst:[:v | v isMemberOf:MenuPanel]) ~~ 0 ifTrue:[
		"/ must add the menus height
		^ view subViews at:idx
	    ]
	].
    ].
    ^ nil

    "Modified: / 4.8.1997 / 01:23:06 / cg"
    "Created: / 4.1.1998 / 18:01:42 / cg"
!

viewForWPeer:nativeContext
    |jPeer|

    jPeer := nativeContext receiver.

    "/ sigh; pData was renamed to pNativeWidget in jdk1.2 ...
    O_FramePeer_pNativeWidget isNil ifTrue:[
	O_FramePeer_pNativeWidget := (jPeer class instVarOffsetOf:'pNativeWidget').
	O_FramePeer_pNativeWidget isNil ifTrue:[
	    O_FramePeer_pNativeWidget := 0.
	    O_FramePeer_pData isNil ifTrue:[
		O_FramePeer_pData := (jPeer class instVarOffsetOf:'pData').
	    ].
	]
    ].
    O_FramePeer_pNativeWidget > 0 ifTrue:[
	"/ ok, we are < 1.2
	^ jPeer instVarAt:O_FramePeer_pNativeWidget.
    ].
    ^ jPeer instVarAt:O_FramePeer_pData.

    "Modified: / 19.11.1998 / 01:43:20 / cg"
! !

!JavaVM class methodsFor:'helpers - exceptions'!

throwAbstractMethodError
    ^ self throwExceptionClassName: 'java.lang.AbstractMethodError'
        withMessage: 'resolving a method ref failed'.

    "Created: / 11-04-2011 / 20:32:53 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

throwArrayIndexOutOfBoundsException:badIndex
    |exClass ex|

    exClass := Java classForName:'java.lang.ArrayIndexOutOfBoundsException'.
    ex := exClass newWith_int:badIndex.
    ^ self throwException:ex

    "Created: / 14.1.1998 / 21:36:05 / cg"
    "Modified: / 20.11.1998 / 13:27:14 / cg"
!

throwArrayIndexOutOfBoundsException:theArray _:badIndex
    |exClass ex|

    exClass := Java classForName:'java.lang.ArrayIndexOutOfBoundsException'.
    ex := exClass newWith_int:badIndex.
    ^ self throwException:ex

    "Modified: / 20.11.1998 / 13:27:14 / cg"
    "Created: / 8.1.1999 / 15:03:59 / cg"
!

throwArrayStoreException:badArray
    ^ self
        throwExceptionClassName:'java.lang.ArrayStoreException'
         withMessage:('bad array store: ' , badArray class printString)

    "Modified: / 23-06-2011 / 09:19:01 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

throwClassCastException
    ^ self 
	throwExceptionClassName:'java.lang.ClassCastException' 
	withMessage:'cast failed'

    "Modified: / 7.1.1998 / 15:25:35 / cg"
    "Created: / 8.1.1999 / 18:55:31 / cg"
!

throwClassFormatError
    ^ self 
        throwExceptionClassName:'java.lang.ClassFormatError' 
        withMessage:'Invalid class format'

    "Created: / 04-01-1998 / 22:26:09 / cg"
    "Modified: / 10-11-1998 / 13:20:31 / cg"
    "Created: / 08-08-2011 / 17:57:08 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

throwClassNotFoundException
    ^ self 
	throwExceptionClassName:'java.lang.ClassNotFoundException' 
	withMessage:'no such class'

    "Created: / 4.1.1998 / 22:25:26 / cg"
    "Modified: / 7.1.1998 / 15:25:35 / cg"
!

throwClassNotFoundException:className
    ^ self 
	throwExceptionClassName:'java.lang.ClassNotFoundException' 
	withMessage:'no such class: ' , className

    "Created: / 4.1.1998 / 22:26:09 / cg"
    "Modified: / 10.11.1998 / 13:20:31 / cg"
!

throwDivisionByZeroException
    DivisionByZeroExceptionDebug == true ifTrue:[
	self halt:'division by zero'.
    ].
    ^ self
	throwExceptionClassName:'java.lang.ArithmeticException'
	withMessage:'division by zero'

    "Created: / 8.1.1999 / 14:28:15 / cg"
!

throwException:aJavaException

    <resource: #skipInDebuggersWalkBack>

    |con jMsg msg exClass srchCon handlerContext handlerPC method pc hPC
     monitorObject|



    ExceptionTrace ifTrue:[
        'JAVA: exception: ' print. aJavaException class fullName print.
        msg := aJavaException instVarNamed:'detailMessage'.
        msg notNil ifTrue:[
            ' (' print.
            (Java as_ST_String:msg) print.
            ')' print.
        ].
        '' printCR.
    ].
    ExceptionDebug ifTrue:[
"/        self internalError:('JAVA: exception: ' , aJavaException class fullName).        
        (ExceptionDebugPatterns isNilOrEmptyCollection or:
            [ExceptionDebugPatterns anySatisfy: [:pattern|pattern match:aJavaException class fullName]])
            ifTrue:
                [self halt:('JAVA: exceptionDebug: ' , aJavaException class fullName)]
    ].

    "/
    "/ search stack for a javaContext which handles that exception
    "/
    srchCon := thisContext sender.
    [handlerContext isNil and:[srchCon notNil]] whileTrue:[
        (srchCon isJavaContext) ifTrue:[
            method := srchCon method.
            pc := srchCon pc.
            (hPC := method handlerFor:aJavaException at:pc) notNil ifTrue:[
                "JV@2011-02-25: Another crap in JVM and Java VM Spec?
                 Or theri proxu generator? Assume that if athrow's pc
                 is same as the handler's pc it means rethrow to
                 handling context - so DO NOT HANDLE IT!!"
                "Hack disabled for now"
                "pc ~~ hPC"true ifTrue:[
                    handlerPC := hPC.
                    handlerContext := srchCon
                ].
            ] ifFalse:[
                "/ on the fly, release any monitor
                method isSynchronized ifTrue:[
                    method isStatic ifTrue:[
                        self assert: srchCon receiver == method javaClass.
                        monitorObject := method javaClass.
                    ] ifFalse:[
                        monitorObject := srchCon receiver
                    ].
                    self _MONITOREXIT:monitorObject
                ]
            ]
        ].
        srchCon := srchCon sender.
    ].

    handlerContext isNil ifTrue:[
        "/
        "/ no JavaHandler ... let smalltalk handle it
        "/
        exClass := aJavaException class.
        msg := 'Java ' , exClass name.
        jMsg := aJavaException instVarNamed:'detailMessage'.
        jMsg notNil ifTrue:[
            msg := msg , ': ' , (Java as_ST_String:jMsg).
        ].

        "/ for our convenience: skip ST contexts 
        "/ (i.e. the handler or debugger will see the javaContext first )

        con := thisContext sender.
        [con isNil or:[con isJavaContext]] whileFalse:[
            con := con sender
        ].
        con isNil ifTrue:[con := thisContext sender].
        JavaUnhandledExceptionError
                raiseWith:aJavaException
                errorString:msg
                in:con.
    ] ifFalse:[
        "/
        "/ found a java exceptionHandler
        "/
        handlerContext setPC:handlerPC.
        handlerContext exceptionArg:aJavaException pc:handlerPC.
        handlerContext markForException.
        handlerContext unwindAndRestart.
        self halt:'should not be reached'.
    ].
Processor activeProcess == JavaScreenUpdaterThread ifTrue:[self halt].
Processor activeProcess == JavaEventQueueThread ifTrue:[self halt].
    Processor activeProcess terminate.

    "Created: / 07-01-1998 / 15:28:22 / cg"
    "Modified: / 24-12-1999 / 02:33:25 / cg"
    "Modified: / 10-08-2011 / 20:23:03 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

throwExceptionClassName:aJavaExceptionClassName withMessage:someMessage
    |exClass ex|

    exClass := Java classForName:aJavaExceptionClassName.
    ex := exClass newWith_String:someMessage.
    ^ self throwException:ex

    "Created: / 7.1.1998 / 15:25:09 / cg"
    "Modified: / 14.1.1998 / 23:38:30 / cg"
!

throwExceptionInInitializerError:className
    ^ self 
        throwExceptionClassName:'java.lang.ExceptionInInitializerError' 
        withMessage:'error when initializing class: ' , className

    "Created: / 24-11-2010 / 09:23:45 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

throwFileNotFoundException: message
    ^ self 
        throwExceptionClassName:'java.io.FileNotFoundException' 
        withMessage: message

    "Created: / 04-01-1998 / 22:26:09 / cg"
    "Modified: / 10-11-1998 / 13:20:31 / cg"
    "Created: / 10-08-2011 / 14:19:10 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

throwIOExceptionWithMessage:message
    IOExceptionDebug == true ifTrue:[
	self halt:'IO Exception'.
    ].
    ^ self 
	throwExceptionClassName:'java.io.IOException' 
	withMessage:message

    "Created: / 7.1.1998 / 10:34:24 / cg"
    "Modified: / 7.1.1998 / 15:26:25 / cg"
!

throwIllegalAccessError
    ^ self throwExceptionClassName: 'java.lang.IllegalAccessError'
        withMessage: 'illegal access'

    "Created: / 13-04-2011 / 23:07:54 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

throwIllegalAccessException
    ^ self 
	throwExceptionClassName:'java.lang.IllegalAccessException' 
	withMessage:'illegal access'

    "Modified: / 7.1.1998 / 15:25:35 / cg"
    "Created: / 14.1.1998 / 23:13:44 / cg"
!

throwIncompatibleClassChangeError
        ^ self throwExceptionClassName: 'java.lang.IncompatibleClassChangeError'
                withMessage: 'illegal change'.

    "Created: / 11-04-2011 / 20:03:21 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

throwInstantiationException
    ^ self 
	throwExceptionClassName:'java.lang.InstantiationException' 
	withMessage:'cannot instantiate'

    "Modified: / 7.1.1998 / 15:25:35 / cg"
    "Created: / 14.1.1998 / 23:15:01 / cg"
!

throwInstantiationExceptionFor:aJavaClass
    ^ self 
        throwExceptionClassName:'java.lang.InstantiationException' 
        withMessage:('cannot instantiate: ' , aJavaClass javaName)

    "Modified: / 7.1.1998 / 15:25:35 / cg"
    "Created: / 14.1.1998 / 23:17:02 / cg"
!

throwLinkageError: message
    ^ self 
        throwExceptionClassName:'java.lang.LinkageError' 
        withMessage: message

    "Modified: / 10-11-1998 / 13:20:31 / cg"
    "Created: / 26-11-2010 / 11:26:02 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

throwNoSuchFieldException
  ^ self throwExceptionClassName: 'java.lang.NoSuchFieldError'
        withMessage: 'looking up a field failed'.

    "Created: / 13-04-2011 / 12:16:36 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

throwNoSuchMethodError
      ^ self throwExceptionClassName: 'java.lang.NoSuchMethodError'
              withMessage: 'looking up a method failed'.

    "Created: / 11-04-2011 / 20:33:19 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

throwNullPointerException
    NullPointerExceptionDebug == true ifTrue:[
        self halt:'Null Pointer exception'.
    ].

    ^ self 
        throwExceptionClassName:'java.lang.NullPointerException' 
        withMessage:'null pointer'

    "Created: / 09-01-1998 / 02:26:08 / cg"
    "Modified: / 28-01-1998 / 02:30:09 / cg"
    "Modified: / 13-08-2011 / 01:10:42 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

throwNumberFormatException 
    ^ self 
	throwExceptionClassName:'java.lang.NumberFormatException' 
	withMessage:'bad number format'

    "Modified: / 7.1.1998 / 15:25:35 / cg"
    "Created: / 11.1.1998 / 16:08:22 / cg"
!

throwZipException
    ^ self throwExceptionClassName: 'java.util.zip.ZipException'
        withMessage: 'error in opening zip file'.

    "Created: / 27-03-2011 / 16:25:43 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
! !

!JavaVM class methodsFor:'helpers - io'!

anyStream_close:nativeContext
    |jStream fileNo file|

    jStream := nativeContext receiver.

    fileNo := self validateFileNo:jStream.
    fileNo == 0 ifTrue:[
	'JAVA: file is already closed' errorPrintCR.
	^ self    "/ already closed
    ].
    file := self getOpenFileAt:fileNo.
    file isNil ifTrue:[
	self halt:'invalid fileNo in close'.
	self internalError:'invalid fileNo in close'.
	^ self
    ].

    file == Stdin ifTrue:[
	file := StdinReplacementFileQuerySignal raiseRequest.
	file isNil ifTrue:[
	    file := Stdin
	]
    ].

    "/ should always be bytes

    (file ~~ Stdin
    and:[file ~~ Stdout
    and:[file ~~ Stderr
    and:[file ~~ Transcript]]]) ifTrue:[
	file close.
    ].
    self setOpenFile:nil at:fileNo.

    fileNo := jStream instVarNamed:'fd'.
    fileNo isInteger ifFalse:[
	"/ JDK 1.1.3
	fileNo instVarNamed:'fd' put:0.
    ] ifTrue:[
	"/ JDK 1.0
	jStream instVarNamed:'fd' put:0
    ].

    "Created: / 4.2.1998 / 15:22:03 / cg"
    "Modified: / 14.10.1998 / 15:10:07 / cg"
!

anyStream_readBytes:nativeContext
    |bytes offset count stream nRead|

    bytes := nativeContext argAt:1.
    offset := nativeContext argAt:2.
    count := nativeContext argAt:3.

    stream := self validateFile:(nativeContext receiver).

    "/ should always be bytes
    bytes class isBytes ifFalse:[
        self halt.
    ].
    stream == Stdin ifTrue:[
        stream := StdinReplacementFileQuerySignal raiseRequest.
        stream isNil ifTrue:[
            ^ -1 "/ 0  EOF
        ]
    ].

    FileIOTrace ifTrue:[
        ('JAVA: read ' , count printString , ' bytes from ' , stream pathName) infoPrintCR.
    ].

    stream isPositionable ifFalse:[
        "/ mhmh - some kind of socket or pipe

        stream readWait.
    ].

    count == 0 ifTrue:[^0].

    Stream readErrorSignal handle:[:ex |
        nRead := -1
    ] do:[
        nRead := stream nextAvailableBytes:count into:bytes startingAt:offset+1.
    ].
    nRead == 0 ifTrue:[
        stream atEnd ifTrue:[
            FileIOTrace ifTrue:[
                ('JAVA: at EOF ' , nRead printString) infoPrintCR.
            ].
            ^ -1
        ].
    ].
    count ~~ nRead ifTrue:[
        FileIOTrace ifTrue:[
            ('JAVA: only got ' , nRead printString) infoPrintCR.
        ]
    ].
    ^ nRead

    "Created: / 04-02-1998 / 15:20:00 / cg"
    "Modified: / 10-11-1998 / 19:56:47 / cg"
    "Modified: / 10-08-2011 / 21:35:00 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

anyStream_writeBytes:nativeContext
    |bytes offset count stream|

    bytes := nativeContext argAt:1.
    offset := nativeContext argAt:2.
    count := nativeContext argAt:3.

    stream := self validateFile:(nativeContext receiver).

    FileIOTrace ifTrue:[
        stream isFileStream ifTrue:[
            ('JAVA: write ' , count printString , ' bytes to ' , stream pathName) infoPrintCR.
        ] ifFalse:[
            stream ~~ Stdout ifTrue:[
                stream ~~ Stderr ifTrue:[
                    ('JAVA: write ' , count printString , ' bytes to ' , stream displayString) infoPrintCR.
                ]
            ]
        ]
    ].

    "/ should always be bytes
    Stream writeErrorSignal handle:[:ex |
        ex return
    ] do:[
        Socket brokenConnectionSignal handle:[:ex |
            ex return
        ] do:[
            stream isBinary ifTrue:[
                stream nextPutBytes:count from:bytes startingAt:offset+1
            ] ifFalse:[
                stream nextPutAll: (bytes asString copyFrom: offset + 1 to: offset + count).
            ]
            
        ].
        stream == Transcript ifTrue:[
            Transcript endEntry
        ]
    ].

    "Created: / 04-02-1998 / 15:23:58 / cg"
    "Modified: / 16-02-1999 / 11:32:45 / cg"
    "Modified: / 11-12-2010 / 20:02:36 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

checkWritePermissionOfDirectory:dir message:msg
    |answer|

    (PermittedDirectories notNil
    and:[PermittedDirectories includes:dir]) ifFalse:[
	FileOpenConfirmation ifTrue:[
	    answer := Dialog 
		    confirmWithCancel:msg withCRs
			       labels:#('no' 'grant')
			       values:#(false true)
			      default:2.
	    answer == false ifTrue:[
		^ false
	    ].

	    (self confirm:('JAVA Security check\\Always permit writes in this directory (''' , dir pathName , ''') ?') withCRs)
	    ifTrue:[
		PermittedDirectories isNil ifTrue:[
		    PermittedDirectories := Set new
		].
		PermittedDirectories add:dir.
	    ]
	]
    ].
    ^ true

    "Created: / 3.12.1998 / 15:07:56 / cg"
    "Modified: / 3.12.1998 / 15:16:55 / cg"
!

commonClose:nativeContext

    | fdobj fd stream |
    fdobj := (nativeContext receiver instVarNamed: #fd).
    fd    := fdobj instVarNamed: #fd.
    stream := self getOpenFileAt:fd.
    stream notNil ifTrue:[
        stream close.
    ] ifFalse:[
        self breakPoint: #jv.
    ].
    self setOpenFile: nil at: fd.
    fdobj instVarNamed:#fd put: -1.

    "Created: / 10-08-2011 / 14:02:47 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

commonOpen:nativeContext forAppend:forAppend
    |fs fd fn name dir stream fileNo answer readonly|

    fs := nativeContext receiver.
    fd := fs instVarNamed:'fd'.
    (fd instVarNamed:'fd') ~~ -1 ifTrue:[
        "/self halt:'file already open'.
        self internalError:'file already open'.
        ^ self.
    ].

    name := nativeContext argAt:1.
    name := Java as_ST_String:name.

    FileOpenTrace ifTrue:[
        ('JAVA: opening ' , name) infoPrintCR.
    ].

    fn := name utf8Decoded asFilename.
    dir := fn directory pathName.

    readonly := false.
"/    (PermittedDirectories notNil
"/    and:[PermittedDirectories includes:dir]) ifFalse:[
"/        FileOpenConfirmation ifTrue:[
"/            answer := Dialog 
"/                    confirmWithCancel:('JAVA Security check\\Opening ''' , name , ''' for read/write.\Grant permission ?') withCRs
"/                               labels:#('no' 'grant' 'readonly')
"/                               values:#(false true #readonly)
"/                              default:3.
"/            answer == false ifTrue:[
"/                self throwIOExceptionWithMessage:('no permission to open ' , name , ' for writing').
"/                ^ self
"/            ].
"/            readonly := (answer == #readonly).
"/
"/            readonly ifFalse:[
"/                (self confirm:('JAVA Security check\\Always permit writes in this directory (''' , dir , ''') ?') withCRs)
"/                ifTrue:[
"/                    PermittedDirectories isNil ifTrue:[
"/                        PermittedDirectories := Set new
"/                    ].
"/                    PermittedDirectories add:dir.
"/                ]
"/            ]
"/        ]
"/    ].

    readonly ifTrue:[
        (fn exists and:[fn isReadable not]) ifTrue:[
            ^self throwFileNotFoundException: 'File is not readable'    
        ].
        stream := fn readStream.
    ] ifFalse:[    
        fn exists ifFalse:[
            ^self throwFileNotFoundException: 'File does not exist'
        ].
        fn isDirectory ifTrue:[
             ^self throwFileNotFoundException: 'File is directory'
        ].
        fn isWritable ifFalse:[
            ^self throwFileNotFoundException: 'File does not writable'    
        ].
        forAppend ifTrue:[
            stream := fn appendingWriteStream.
        ] ifFalse:[
            stream := fn writeStream.
        ]
    ].
    stream isNil ifTrue:[
        self throwIOExceptionWithMessage:('cannot open ' , name , ' for writing').
    ].

    fileNo := self addOpenFile:stream.

    FileOpenTrace ifTrue:[
        ('JAVA: opened ' , name , ' as FD ' , fileNo printString , ' for writing') infoPrintCR.
    ].

    fd instVarNamed:'fd' put:fileNo.

    "Created: / 07-04-1998 / 19:14:09 / cg"
    "Modified: / 04-01-1999 / 14:34:42 / cg"
    "Modified: / 10-08-2011 / 23:49:25 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

fileStreamForReading:name
    |fn stream tryAlongClassPath|

    FileOpenTrace ifTrue:[
        ('JAVA: opening for read:' , name) infoPrintCR.
    ].
    fn := name asFilename.
    fn exists  ifFalse:[
        ^self throwFileNotFoundException: 'File does not exists'
    ].
    fn isDirectory ifTrue:[
        ^self throwFileNotFoundException: 'File is directory'
    ].
    fn isReadable  ifFalse:[
        ^self throwFileNotFoundException: 'File is not readable'
    ].

    stream := fn readStream.
    stream notNil ifTrue:[^ stream].

    fn isAbsolute ifFalse:[
        "/ if not absolute, try along classPath
        "/ This allows classes to open local files (JEdit)
        "/ even if they have NOT been loaded by a Java classLoader.
        "/ Only do this for image files 
        "/ (and maybe some other config files in the future),
        "/ to avoid security holes.
        tryAlongClassPath := true.
"/        tryAlongClassPath := false.
"/        (fn hasSuffix:'gif') ifTrue:[
"/            tryAlongClassPath := true.
"/        ].
"/        (fn hasSuffix:'jpg') ifTrue:[
"/            tryAlongClassPath := true.
"/        ].

        tryAlongClassPath ifTrue:[
            Java effectiveClassPath do:[:dirName |
                |fn|

                (fn := dirName asFilename construct:name) exists ifTrue:[
                    fn isReadable ifFalse:[
                        self throwFileNotFoundException: 'File is not readable'.
                        ^nil
                    ].
                    stream := fn readStream.
                    stream notNil ifTrue:[^ stream].
                ]
            ]
        ]
    ].
    ^ nil.

    "Modified: / 27-01-1999 / 18:54:46 / cg"
    "Modified: / 10-08-2011 / 19:22:43 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

fixFilename:path
    OperatingSystem isMSDOSlike ifTrue:[
	(#($/ $\) includes:(path at:1)) ifTrue:[
	    (path at:3) == $: ifTrue:[
		^ path copyFrom:2
	    ]
	]
    ].
    ^ path

    "Created: / 20.10.1998 / 20:58:45 / cg"
    "Modified: / 20.10.1998 / 21:06:49 / cg"
!

validateFile:javaStream
    |fileNo file descriptor|

    fileNo := self validateFileNo:javaStream.
    fileNo isNil ifTrue:[
"/        self halt:'invalid fileNo in read'.
"/        self internalError:'invalid fileNo in read'.
	self throwIOExceptionWithMessage:'invalid fileNo in read'.
	^ nil
    ].

    file := self getOpenFileAt:fileNo.

    file isNil ifTrue:[
"/        self halt:'invalid fileNo in read'.
"/        self internalError:'invalid fileNo in read'.
	self throwIOExceptionWithMessage:'invalid fileNo in read'.
	^ nil
    ].

    ^ file

    "Created: / 4.1.1998 / 16:50:38 / cg"
    "Modified: / 4.1.1998 / 17:50:00 / cg"
!

validateFileNo:javaStream
    |fileNo file descriptor|

    "/ JDK 1.1.3 has fileDescriptor wrapped
    "/ JDK 1.0 has it directly as integer

    fileNo := javaStream instVarNamed:'fd'.
    fileNo isInteger ifFalse:[
        descriptor := fileNo.
        descriptor notNil ifTrue:[
            fileNo := descriptor instVarNamed:'fd'.
            ((fileNo == -1) and:[OperatingSystem isMSWINDOWSlike]) ifTrue:[
                fileNo := descriptor instVarNamed:'handle'.
            ]
        ]
    ].

    fileNo isInteger ifFalse:[
"/        self halt:'invalid fileNo in read'.
"/        self internalError:'invalid fileNo in read'.
        self throwIOExceptionWithMessage:'invalid fileNo in read'.
        ^ nil
    ].

    ^ fileNo.

    "Created: / 04-01-1998 / 17:49:08 / cg"
    "Modified: / 13-01-1998 / 14:07:47 / cg"
    "Modified: / 18-08-2011 / 20:03:37 / jv"
! !

!JavaVM class methodsFor:'helpers - reflection'!

classForJavaClassObject:aJavaClassObject 
    "given java.lang.class instance, return the real class for it."
    
    ^ self reflection classForJavaClassObject:aJavaClassObject

    "Created: / 23-01-1998 / 17:44:09 / cg"
    "Modified: / 03-02-2011 / 21:33:14 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 09-02-2011 / 01:02:17 / Marcel Hlopko <hlopik@gmail.com>"
!

javaClassObjectForClass:aClass 
    "given a real class, return the corresponding java.lang.class
     instance for it."
    
    |class|

    "find reflection of StClass in the Java World"
    (JavaObjectDictionary new hasReflection:aClass name) ifTrue:[
        class := JavaObjectDictionary new reflectionOf:aClass name
    ] ifFalse:[
        class := aClass.
    ].
    ^self reflection javaClassObjectForClass:class.

    "Created: / 23-01-1998 / 17:43:38 / cg"
    "Modified: / 05-12-1998 / 15:29:32 / cg"
    "Modified: / 17-01-2011 / 19:24:22 / kursjan <kursjan@fit.cvut.cz>"
    "Modified: / 28-01-2011 / 14:31:25 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 03-02-2011 / 21:31:32 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

javaConstructorObjectForMethod:method 
    "given a real method, return the corresponding java.lang.reflect.Constructor
     instance for it."
    self breakPoint:#mh info:'refactor my sender to call reflection directly'.
    ^ self reflection javaConstructorObjectForMethod: method.

    "Modified: / 09-02-2011 / 00:58:09 / Marcel Hlopko <hlopik@gmail.com>"
!

javaFieldObjectForField: aJavaField in: aJavaLangClass 
    "given a java field, return the corresponding java.lang.Field
     instance for it."
    "
        See OpenJDK7 source:
        jdk7/hotspot/src/share/vm/runtime/reflection.cpp,
        oop Reflection::new_field"
    
    | field  clazz  name  slot  type  modifiers |

    clazz := aJavaLangClass.
    name := self reflection javaStringObjectForString: aJavaField name
                interned: true.
    slot := aJavaField index.
    type := self javaClassObjectForClass: aJavaField typeClass.
    modifiers := aJavaField accessFlags.
    field := (Java classForName: 'java.lang.reflect.Field') new.
    field
        instVarNamed: #clazz put: clazz;
        instVarNamed: #name put: name;
        instVarNamed: #slot put: slot;
        instVarNamed: #type put: type;
        instVarNamed: #modifiers put: modifiers;        
        yourself.
    aJavaField annotations ifNotNil: [field instVarNamed: #annotations
            put: aJavaField annotations runtimeVisible rawAnnotations].
    ^ field.

    "Modified: / 05-12-1998 / 15:29:32 / cg"
    "Created: / 22-11-2010 / 17:01:33 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 09-02-2011 / 01:06:20 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 01-04-2011 / 12:11:11 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
    "Modified: / 25-04-2011 / 20:23:16 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

javaMethodObjectForMethod:method 
    "given a real method, return the corresponding java.lang.reflect.Constructor
     instance for it."

    ^ self reflection javaMethodObjectForMethod:method.

    "Modified: / 28-02-2011 / 17:08:36 / Marcel Hlopko <hlopik@gmail.com>"
!

methodForJavaConstructorObject:constructor 
    "given a java.lang.reflect.Constructor, return the corresponding method
     it."
    self breakPoint:#mh info: 'refactor my sender to call reflection directly'.
    ^ self reflection methodForJavaConstructorObject: constructor.

    "Modified: / 09-02-2011 / 00:59:43 / Marcel Hlopko <hlopik@gmail.com>"
!

methodForJavaMethodObject:aJavaMethodObject 
    "
        Given an instance of java.lang.reflect.Method, answers
        real method associated with it."
   ^ self reflection methodForJavaMethodObject:aJavaMethodObject.

    "Modified: / 07-02-2011 / 09:50:05 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-02-2011 / 16:58:05 / Marcel Hlopko <hlopik@gmail.com>"
! !

!JavaVM class methodsFor:'native - java.awt'!

_java_awt_AWTEvent_initIDs: nativeContext

    <javanative: 'java/awt/AWTEvent' name: 'initIDs'>

    "Intentionally left blank"

    "Modified: / 12-08-2011 / 19:08:25 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_awt_Component_initIDs: nativeContext

    <javanative: 'java/awt/Component' name: 'initIDs'>

        "/ introduced with jdk1.2 ... (sigh)

    "Created: / 27.1.1998 / 19:53:29 / cg"
!

_java_awt_Container_initIDs: nativeContext

    <javanative: 'java/awt/Container' name: 'initIDs'>

    "Intentionally left blank"

    "Modified: / 12-08-2011 / 19:09:05 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_awt_Dimension_initIDs: nativeContext

    <javanative: 'java/awt/Dimension' name: 'initIDs'>

    "Intentionally left blank"

    "Modified: / 12-08-2011 / 19:08:43 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_awt_Toolkit_initIDs: nativeContext

    <javanative: 'java/awt/Toolkit' name: 'initIDs'>

        "/ introduced with jdk1.2 ... (sigh)

    "Created: / 27.1.1998 / 19:53:50 / cg"
! !

!JavaVM class methodsFor:'native - java.io'!

_java_io_FileDescriptor_initIDs: nativeContext

    <javanative: 'java/io/FileDescriptor' name: 'initIDs'>

        "/ introduced with jdk1.2 ... (sigh)

    "Created: / 27.1.1998 / 18:16:29 / cg"
!

_java_io_FileDescriptor_set: nativeContext

    <javanative: 'java/io/FileDescriptor' name: 'set(I)J'>

    "SunJDK Speciofic method, we don't need handles, so return
     FD instead"

    ^nativeContext argAt:1

    "Modified: / 18-08-2011 / 19:54:36 / jv"
!

_java_io_FileDescriptor_sync: nativeContext

    <javanative: 'java/io/FileDescriptor' name: 'sync'>
    "
    /**
    * Force all system buffers to synchronize with the underlying
    * device.  This method returns after all modified data and
    * attributes of this FileDescriptor have been written to the
    * relevant device(s).  In particular, if this FileDescriptor
    * refers to a physical storage medium, such as a file in a file
    * system, sync will not return until all in-memory modified copies
    * of buffers associated with this FileDescriptor have been
    * written to the physical medium.
    *
    * sync is meant to be used by code that requires physical
    * storage (such as a file) to be in a known state  For
    * example, a class that provided a simple transaction facility
    * might use sync to ensure that all changes to a file caused
    * by a given transaction were recorded on a storage medium.
    *
    * sync only affects buffers downstream of this FileDescriptor.  If
    * any in-memory buffering is being done by the application (for
    * example, by a BufferedOutputStream object), those buffers must
    * be flushed into the FileDescriptor (for example, by invoking
    * OutputStream.flush) before that data will be affected by sync.
    *
    * @exception SyncFailedException
    *        Thrown when the buffers cannot be flushed,
    *        or because the system cannot guarantee that all the
    *        buffers have been synchronized with physical media.
    * @since     JDK1.1
    */
    public native void sync() throws SyncFailedException;
    "

    OpenFileTable do:[:stream|
        stream notNil ifTrue:[stream flush].
    ].

    "Created: / 12-11-1998 / 19:26:25 / cg"
    "Modified (format): / 10-08-2011 / 19:04:24 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_FileInputStream_available: nativeContext

    <javanative: 'java/io/FileInputStream' name: 'available'>

        |file|

    file := self validateFile:(nativeContext receiver).
    file isNil ifTrue:[
	self throwIOExceptionWithMessage:'invalid fileNo in available'.
	^ self
    ].
    file == Stdin ifTrue:[
	file := StdinReplacementFileQuerySignal raiseRequest.
	file isNil ifTrue:[
	    ^ 1
	]
    ].
    file isFileStream ifTrue:[
	^ file size - file position + 1
    ].
    file atEnd ifTrue:[
	^ 0.
    ].
    self halt.
    ^ 1

    "Modified: / 14.1.1998 / 15:12:52 / cg"
!

_java_io_FileInputStream_close0: nativeContext

    <javanative: 'java/io/FileInputStream' name: 'close0'>

    ^self commonClose: nativeContext

    "Modified: / 10-08-2011 / 14:03:06 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_FileInputStream_initIDs: nativeContext

    <javanative: 'java/io/FileInputStream' name: 'initIDs'>

        "/ introduced with jdk1.2 ... (sigh)

    "Created: / 27.1.1998 / 18:15:51 / cg"
!

_java_io_FileInputStream_open: nativeContext

    <javanative: 'java/io/FileInputStream' name: 'open'>

        |fs fd fn name stream fileNo|

    fs := nativeContext receiver.
    fd := fs instVarNamed:'fd'.
    (fileNo := fd instVarNamed:'fd') ~~ 0 ifTrue:[
        fileNo ~~ -1 ifTrue:[
            self halt:'file already open'.
            self internalError:'file already open'.
            ^ self.
        ]
    ].

    name := nativeContext argAt:1.
    name := Java as_ST_String:name.

    name := self fixFilename:name.

    FileOpenTrace ifTrue:[
        ('JAVA: opening ' , name) infoPrintCR.
    ].

    stream := self fileStreamForReading:name.
    stream isNil ifTrue:[
        ^ self.
    ].
    stream buffered:false.

"/    FileOpenConfirmation ifTrue:[
"/        (self confirm:('JAVA Security check\\Opening ''' , name , ''' for reading.\Grant permission ?') withCRs)
"/        ifFalse:[
"/            self throwIOExceptionWithMessage:('no permission to open ' , name , ' for reading').
"/            ^ self
"/        ]
"/    ].

    fileNo := self addOpenFile:stream.

    FileOpenTrace ifTrue:[
        ('JAVA: opened ' , name , ' as FD ' , fileNo printString) infoPrintCR.
    ].

    fd instVarNamed:'fd' put:fileNo.

    "Created: / 04-01-1998 / 16:47:12 / cg"
    "Modified: / 28-01-1999 / 17:24:07 / cg"
    "Modified: / 10-08-2011 / 19:21:05 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_FileInputStream_readBytes: nativeContext

    <javanative: 'java/io/FileInputStream' name: 'readBytes'>

    ^ self anyStream_readBytes:nativeContext

    "Modified: / 04-02-1998 / 15:23:08 / cg"
    "Modified (format): / 10-08-2011 / 21:32:37 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_FileOutputStream_close0: nativeContext

    <javanative: 'java/io/FileOutputStream' name: 'close0'>

    ^self commonClose: nativeContext

    "Modified: / 10-08-2011 / 14:03:13 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_FileOutputStream_initIDs: nativeContext

    <javanative: 'java/io/FileOutputStream' name: 'initIDs'>

        "/ introduced with jdk1.2 ... (sigh)

    "Created: / 27.1.1998 / 18:16:40 / cg"
!

_java_io_FileOutputStream_open: nativeContext

    <javanative: 'java/io/FileOutputStream' name: 'open'>

    ^ self commonOpen:nativeContext forAppend:false

    "Modified: / 07-04-1998 / 19:14:31 / cg"
    "Modified (format): / 10-08-2011 / 14:25:50 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_FileOutputStream_openAppend: nativeContext

    <javanative: 'java/io/FileOutputStream' name: 'openAppend'>

    ^ self commonOpen:nativeContext forAppend:true

    "Modified: / 07-04-1998 / 19:13:42 / cg"
    "Modified (format): / 10-08-2011 / 23:48:34 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_FileOutputStream_write: nativeContext

    <javanative: 'java/io/FileOutputStream' name: 'write'>
    "
     /**
     * Writes the specified byte to this file output stream. Implements
     * the <code>write</code> method of <code>OutputStream</code>.
     *
     * @param      b   the byte to be written.
     * @exception  IOException  if an I/O error occurs.
     */
     public native void write(int b) throws IOException;
    "

    | fdobj fd stream b |
    b := nativeContext argAt:1.
    fdobj := (nativeContext receiver instVarNamed: #fd).
    fd    := fdobj instVarNamed: #fd.
    stream := self getOpenFileAt:fd.
    [
        stream nextPut: b asCharacter
    ] on: Error do:[:ex|
        self throwIOExceptionWithMessage: ex description
    ]

    "Modified: / 10-08-2011 / 14:15:22 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_FileOutputStream_writeBytes: nativeContext

    <javanative: 'java/io/FileOutputStream' name: 'writeBytes'>

        ^ self anyStream_writeBytes:nativeContext

    "Modified: / 4.2.1998 / 15:24:20 / cg"
!

_java_io_FileSystem_getFileSystem: aJavaContext

    <javanative: 'java/io/FileSystem' name: 'getFileSystem'>

    
    OperatingSystem isUNIXlike ifTrue:
        [^(Java classForName:'java.io.UnixFileSystem') new].

    OperatingSystem isMSWINDOWSlike ifTrue:
        [^(Java classForName:'java.io.WinNTFileSystem') new].

    self error:'Unknown/Unsupported platform'

    "Created: / 09-12-2010 / 17:58:22 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 01-04-2011 / 18:09:32 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_ObjectInputStream_latestUserDefinedLoader: nativeContext

    <javanative: 'java/io/ObjectInputStream' name: 'latestUserDefinedLoader'>

    "
    /**
    * Returns the first non-null class loader (not counting class loaders of
    * generated reflection implementation classes) up the execution stack, or
    * null if only code from the null class loader is on the stack.  This
    * method is also called via reflection by the following RMI-IIOP class:
    *
    *     com.sun.corba.se.internal.util.JDKClassLoader
    *
    * This method should not be removed or its signature changed without
    * corresponding modifications to the above class.
    */
    // REMIND: change name to something more accurate?
    private static native ClassLoader latestUserDefinedLoader();
    "

    | ctx cl |
    ctx := nativeContext.
    [ ctx notNil ] whileTrue:[
        ctx receiver isJavaObject ifTrue:[
            (cl := ctx receiver class classLoader) notNil ifTrue:[
                self breakPoint: #jv info: 'Should not count class loaders of generated reflection implementation classes'.
                "/Please check"
                ^cl.
            ]                    
        ].
        ctx := ctx sender.
    ].
    ^nil

    "Modified: / 10-08-2011 / 01:38:14 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_ObjectStreamClass_hasStaticInitializer: nativeContext

    <javanative: 'java/io/ObjectStreamClass' name: 'hasStaticInitializer'>

    | cls |
    cls := self reflection classForJavaClassObject: (nativeContext argAt:1).
    ^(cls includesSelector: #'<clinit>()V') ifTrue:[1] ifFalse:[0]

    "Modified: / 10-08-2011 / 01:13:21 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_ObjectStreamClass_initNative: aJavaContext

    <javanative: 'java/io/ObjectStreamClass' name: 'initNative'>

    
    "
    /**
     * Initializes native code.
     */
    "
    "Nothing to do"

    "Created: / 20-12-2010 / 17:43:55 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_RandomAccessFile_initIDs: nativeContext

    <javanative: 'java/io/RandomAccessFile' name: 'initIDs'>

    "Nothing to do"

    "Modified: / 10-08-2011 / 21:49:17 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_RandomAccessFile_open: nativeContext

    <javanative: 'java/io/RandomAccessFile' name: 'open'>

        |fs fd name dir stream fileNo answer readonly|

    readonly := false.

    fs := nativeContext receiver.
    fd := fs instVarNamed:'fd'.
    (fd instVarNamed:'fd') ~~ 0 ifTrue:[
	self halt:'file already open'.
	self internalError:'file already open'.
	^ self.
    ].

    name := nativeContext argAt:1.
    name := Java as_ST_String:name.
    name := self fixFilename:name.

    FileOpenTrace ifTrue:[
	('JAVA: opening ' , name) infoPrintCR.
    ].

    dir := name asFilename directory pathName.

    (PermittedDirectories notNil
    and:[PermittedDirectories includes:dir]) ifFalse:[
	FileOpenConfirmation ifTrue:[
	    answer := Dialog 
		    confirmWithCancel:('JAVA Security check\\Opening ''' , name , ''' for read/write.\Grant permission ?') withCRs
			       labels:#('no' 'grant' 'readonly')
			       values:#(false true #readonly)
			      default:3.
	    answer == false ifTrue:[
		self throwIOExceptionWithMessage:('no permission to open ' , name , ' for writing').
		^ self
	    ].
	    readonly := (answer == #readonly).

	    readonly ifFalse:[
		(self confirm:('JAVA Security check\\Always permit writes in this directory (''' , dir , ''') ?') withCRs)
		ifTrue:[
		    PermittedDirectories isNil ifTrue:[
			PermittedDirectories := Set new
		    ].
		    PermittedDirectories add:dir.
		]
	    ]
	]
    ].

    readonly ifTrue:[
	stream := name asFilename readStream.
    ] ifFalse:[
	stream := name asFilename readWriteStream.
    ].
    stream isNil ifTrue:[
	self throwIOExceptionWithMessage:('cannot open ' , name , ' for writing').
    ].

    fileNo := self addOpenFile:stream.

    FileOpenTrace ifTrue:[
	('JAVA: opened ' , name , ' as FD ' , fileNo printString , ' for writing') infoPrintCR.
    ].

    fd instVarNamed:'fd' put:fileNo.

    "Created: / 4.2.1998 / 00:14:48 / cg"
    "Modified: / 12.11.1998 / 21:29:46 / cg"
!

_java_io_UnixFileSystem_canonicalize0: aJavaContext

    <javanative: 'java/io/UnixFileSystem' name: 'canonicalize0'>

    |  path |

    path := Java as_ST_String: (aJavaContext argAt: 1).
    ^(Java as_String: path utf8Encoded asFilename asAbsoluteFilename pathName utf8Decoded)

    "Created: / 10-12-2010 / 14:40:49 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_UnixFileSystem_checkAccess: nativeContext

    <javanative: 'java/io/UnixFileSystem' name: 'checkAccess'>

    "
     public static final int ACCESS_READ    = 0x04;
     public static final int ACCESS_WRITE   = 0x02;
     public static final int ACCESS_EXECUTE = 0x01;
    "

    | fileobj file access result |
    fileobj := nativeContext argAt:1.
    file := (Java as_ST_String:(fileobj instVarNamed:#path)) asFilename.
    access := nativeContext argAt:2.
    [
        access == 16r01 ifTrue:[result := file isExecutable].
        access == 16r02 ifTrue:[result := file isWritable].
        access == 16r04 ifTrue:[result := file isReadable].
    ] on: Error do:[
        result := false.
    ].
    ^result ifTrue:[1] ifFalse:[0].

    "Modified: / 09-08-2011 / 17:09:56 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_UnixFileSystem_createDirectory: nativeContext

    <javanative: 'java/io/UnixFileSystem' name: 'createDirectory'>

    | fileobj file |
    fileobj := (nativeContext argAt:1).
    file := Java as_ST_String: (fileobj instVarNamed:#path).
    file := file asFilename.
    file exists ifFalse:[
        [
            file makeDirectory.
            ^1.
        ] on: Error do:[:ex|
            self throwIOExceptionWithMessage:ex description.
        ].
    ].
    ^0

    "Modified: / 10-08-2011 / 13:42:01 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_UnixFileSystem_createFileExclusively: nativeContext

    <javanative: 'java/io/UnixFileSystem' name: 'createFileExclusively'>

    | file |
    file := Java as_ST_String: (nativeContext argAt:1).
    file := file asFilename.
    file exists ifFalse:[
        [
            file createAsEmptyFile
        ] on: Error do:[:ex|
            self throwIOExceptionWithMessage:ex description.
        ].
        ^1
    ].
    ^0

    "Modified: / 10-08-2011 / 13:42:38 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_UnixFileSystem_delete0: nativeContext

    <javanative: 'java/io/UnixFileSystem' name: 'delete0'>
    "
      /**
      * Delete the file or directory denoted by the given abstract pathname,
      * returning <code>true</code> if and only if the operation succeeds.
      */
      public abstract boolean delete(File f);
    "
    | file |

    file := (Java as_ST_String: ((nativeContext argAt:1) instVarNamed: #path)) asFilename.
    file exists ifFalse:[^0].
    ^[
        file remove.
        true
    ] on: Error do:[
        false
    ]

    "Modified: / 09-08-2011 / 17:09:05 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_UnixFileSystem_getBooleanAttributes0: aJavaContext

    <javanative: 'java/io/UnixFileSystem' name: 'getBooleanAttributes0'>

        |file path retval fileSystemClass|

    retval := 0.
    file := aJavaContext argAt:1.
    path := Java as_ST_String:(file instVarNamed:#path).
    fileSystemClass := (Java classForName:'java.io.FileSystem').
    path asFilename exists ifTrue:[
        retval := retval bitOr:(fileSystemClass instVarNamed:#'BA_EXISTS')
    ] ifFalse:[ ^ 0. ].
    path asFilename isDirectory ifTrue:[
        retval := retval bitOr:(fileSystemClass instVarNamed:#'BA_DIRECTORY')
    ].
    path asFilename isRegularFile ifTrue:[
        retval := retval bitOr:(fileSystemClass instVarNamed:#'BA_REGULAR')
    ].
    path asFilename isHidden ifTrue:[
        retval := retval bitOr:(fileSystemClass instVarNamed:#'BA_HIDDEN')
    ].
    ^ retval

    "Modified: / 10-12-2010 / 14:43:31 / Jan Kurs <kurs.jan@post.cz>"
    "Created: / 10-12-2010 / 14:46:28 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 11-12-2010 / 19:44:19 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_UnixFileSystem_getLastModifiedTime: aJavaContext

    <javanative: 'java/io/UnixFileSystem' name: 'getLastModifiedTime'>

        | file  path  retval |

    retval := 0.
    file := aJavaContext argAt: 1.
    path := Java as_ST_String: (file instVarNamed: #path).
    retval := path asFilename modificationTime asMilliseconds.
    ^ retval

    "Modified: / 10-12-2010 / 14:43:31 / Jan Kurs <kurs.jan@post.cz>"
    "Modified: / 11-12-2010 / 19:44:19 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Created: / 27-03-2011 / 15:32:59 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

_java_io_UnixFileSystem_getLength: nativeContext

    <javanative: 'java/io/UnixFileSystem' name: 'getLength'>

    | file |

    file := (Java as_ST_String: ((nativeContext argAt:1) instVarNamed: #path)) asFilename.
    file exists ifFalse:[^0].
    ^file fileSize

    "Modified: / 09-08-2011 / 15:38:30 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_UnixFileSystem_initIDs: aJavaContext

    <javanative: 'java/io/UnixFileSystem' name: 'initIDs'>

    
    self breakPoint: #libjava

    "Created: / 10-12-2010 / 14:47:25 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 10-12-2010 / 20:58:11 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_UnixFileSystem_list: nativeContext

    <javanative: 'java/io/UnixFileSystem' name: 'list'>
    "
    /**
    * Returns an array of strings naming the files and directories in the
    * directory denoted by this abstract pathname.
    *
    * <p> If this abstract pathname does not denote a directory, then this
    * method returns {@code null}.  Otherwise an array of strings is
    * returned, one for each file or directory in the directory.  Names
    * denoting the directory itself and the directory's parent directory are
    * not included in the result.  Each string is a file name rather than a
    * complete path.
    *
    * <p> There is no guarantee that the name strings in the resulting array
    * will appear in any specific order; they are not, in particular,
    * guaranteed to appear in alphabetical order.
    *
    * @return  An array of strings naming the files and directories in the
    *          directory denoted by this abstract pathname.  The array will be
    *          empty if the directory is empty.  Returns {@code null} if
    *          this abstract pathname does not denote a directory, or if an
    *          I/O error occurs.
    */
   "
    | fileobj file names jnames |
    fileobj := (nativeContext argAt:1).
    file := Java as_ST_String: (fileobj instVarNamed:#path).
    file := file asFilename.
    file exists ifFalse:[^nil].
    file isDirectory ifFalse:[^nil].

    names := file directoryContents.
    jnames := String javaArrayClass new: names size.
    1 to: names size do:[:i|
        jnames at: i put: (Java as_String:(names at: i))
    ].
    ^jnames

    "Modified: / 10-08-2011 / 13:28:21 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_UnixFileSystem_setPermission: nativeContext

    <javanative: 'java/io/UnixFileSystem' name: 'setPermission'>
    "
    /**
     * Set on or off the access permission (to owner only or to all) to the file
     * or directory denoted by the given abstract pathname, based on the parameters
     * enable, access and oweronly.
     */
    public abstract boolean setPermission(File f, int access, boolean enable, boolean owneronly);
    "
    | f access enable owneronly file perms |
    f := nativeContext argAt: 1.
    access := nativeContext argAt: 2.
    enable := (nativeContext argAt: 3) == 1.
    owneronly := (nativeContext argAt: 4) == 1.
    file := (Java as_ST_String: (f instVarNamed: #path)) asFilename.
    "
    public static final int ACCESS_READ    = 0x04;
    public static final int ACCESS_WRITE   = 0x02;
    public static final int ACCESS_EXECUTE = 0x01;
    "

    access == 16r04 ifTrue:[
        perms := owneronly ifFalse:[#(readUser readGroup readOthers)] ifTrue:[#(readUser)].
    ].
    access == 16r02 ifTrue:[
        perms := owneronly ifFalse:[#(writeUser writeGroup writeOthers)] ifTrue:[#(writeUser)].
    ].
    access == 16r01 ifTrue:[
        perms := owneronly ifFalse:[#(executeUser executeGroup executeOthers)] ifTrue:[#(executeUser)].
    ].
    [
        enable ifTrue:[
            file addAccessRights: perms
        ] ifFalse:[
            file removeAccessRights: perms
        ].
        ^ 1.
    ] on: Error do:[
        ^ 0
    ].
    ^0

    "Modified: / 09-08-2011 / 17:18:42 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_UnixFileSystem_setReadOnly: nativeContext

    <javanative: 'java/io/UnixFileSystem' name: 'setReadOnly'>

    | fileobj file |
    fileobj := (nativeContext argAt:1).
    file := Java as_ST_String: (fileobj instVarNamed:#path).
    file := file asFilename.
    file exists ifFalse:[^0].
    [
        file  removeAccessRights: #(writeUser writeGroup writeOthers).
        ^1
    ] on: Error do:[
        ^0
    ].
    ^0

    "Modified: / 10-08-2011 / 13:40:20 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_Win32FileSystem_initIDs: nativeContext

    <javanative: 'java/io/Win32FileSystem' name: 'initIDs()V'>

    "Intentionally left blank"
!

_java_io_WinNTFileSystem_canonicalize0: aJavaContext

    <javanative: 'java/io/WinNTFileSystem' name: 'canonicalize0(Ljava/lang/String;)Ljava/lang/String;'>

    
    |  path |

    path := Java as_ST_String: (aJavaContext argAt: 1).
    ^(Java as_String: path asFilename asAbsoluteFilename pathName)

    "Created: / 01-04-2011 / 23:00:06 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_WinNTFileSystem_createFileExclusively: nativeContext

    <javanative: 'java/io/WinNTFileSystem' name: 'createFileExclusively(Ljava/lang/String;)Z'>

    ^ self _java_io_UnixFileSystem_createFileExclusively: nativeContext

    "Modified: / 18-08-2011 / 17:26:11 / jv"
!

_java_io_WinNTFileSystem_getBooleanAttributes: aJavaContext

    <javanative: 'java/io/WinNTFileSystem' name: 'getBooleanAttributes(Ljava/io/File;)I'>

    ^ self _java_io_UnixFileSystem_getBooleanAttributes0:aJavaContext

    "Created: / 01-04-2011 / 18:10:46 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_io_WinNTFileSystem_getLastModifiedTime: nativeContext

    <javanative: 'java/io/WinNTFileSystem' name: 'getLastModifiedTime(Ljava/io/File;)J'>

    ^ self _java_io_UnixFileSystem_getLastModifiedTime: nativeContext

    "Modified: / 18-08-2011 / 14:12:07 / jv"
!

_java_io_WinNTFileSystem_getLength: nativeContext

    <javanative: 'java/io/WinNTFileSystem' name: 'getLength(Ljava/io/File;)J'>

    ^ self _java_io_UnixFileSystem_getLength: nativeContext

    "Modified: / 18-08-2011 / 14:15:36 / jv"
! !

!JavaVM class methodsFor:'native - java.lang'!

_java_lang_ClassLoader_NativeLibrary_load: nativeContext

    <javanative: 'java/lang/ClassLoader$NativeLibrary' name: 'load'>

        "/ introduced with jdk1.2 ... (sigh)

    |nativeLoader jLibName libName libHandle index|

    nativeLoader := nativeContext receiver.
    jLibName := nativeContext argAt:1.
    libName := (Java as_ST_String:jLibName) asFilename baseName.

    (index := SimulatedNativeLibs indexOf:libName) ~~ 0 ifTrue:[
"/        ('JAVA: builtIn nativeLibLoad simulated: ' , libName) printNL.
        nativeLoader instVarNamed:'handle' put:index.
        ^ self "/ void
    ].
    (LoadedNativeLibs notNil 
    and:[LoadedNativeLibs includesKey:libName]) ifTrue:[
"/        ('JAVA: native library already loaded: ' , libName) printNL.
        nativeLoader instVarNamed:'handle' put:(LoadedNativeLibs at:libName).
        ^ self "/ void
    ].

    (self confirm:'permission to load native library: ' , libName , ' ?') ifFalse:[
        ^ self
    ].
self halt.

    libName asFilename exists ifFalse:[
        ('JAVA: no file to load nativeLib: ' , libName) printNL.
        ^ self "/ void
    ].

    libHandle := ObjectFileLoader loadLibrary:libName.
    libHandle isNil ifTrue:[
        ('JAVA: failed to load nativeLib: ' , libName) printNL.
        ^ self "/ void
    ].

    LoadedNativeLibs isNil ifTrue:[
        LoadedNativeLibs := Dictionary new.
    ].

    LoadedNativeLibs at:libName put:libHandle.
    nativeLoader instVarNamed:'handle' put:(LoadedNativeLibs at:libName).
    ^ self "/ void

    "Modified: / 06-02-1998 / 03:12:17 / cg"
    "Created: / 10-12-2010 / 15:11:33 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_ClassLoader_defineClass1: nativeContext

    <javanative: 'java/lang/ClassLoader' name: 'defineClass1'>
    "
    private native Class defineClass1(String name, byte[] b, int off, int len,
                                      ProtectionDomain pd, String source);
    "
    | name b off len pd source bs cls |
    name :=  Java as_ST_String: (nativeContext argAt:1).
    b := nativeContext argAt:2.
    off := nativeContext argAt:3.
    len := nativeContext argAt:4.
    pd := nativeContext argAt:5.
    source := Java as_ST_String: (nativeContext argAt:6).

    bs := (off = 0 and: [len = b size]) 
            ifTrue:[b readStream]
            ifFalse:[(b copyFrom: off + 1 to: off + len) readStream].
    [
        cls := JavaClassReader readStream: bs.
    ] on: JavaClassReader invalidClassFormatSignal do:[
        self throwClassFormatError.
        ^self.
    ].
    cls classLoader: nativeContext receiver.
    "FIXME: What to do with source?"

    ^self reflection javaClassObjectForClass: cls.

    "Modified: / 08-08-2011 / 17:57:29 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_ClassLoader_findBootstrapClass: nativeContext

    <javanative: 'java/lang/ClassLoader' name: 'findBootstrapClass'>

    | nm class |
    nm := Java as_ST_String: (nativeContext argAt:1).
    class := JavaClassReader loadSystemClass: nm classpath: Java release classPath .
    ^class notNil ifTrue:[
        self reflection javaClassObjectForClass:class
    ] ifFalse:[
        self throwClassNotFoundException: nm
    ]

    "Modified: / 12-08-2011 / 09:07:06 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_ClassLoader_findLoadedClass0: nativeContext

    <javanative: 'java/lang/ClassLoader' name: 'findLoadedClass0'>

    "
    The <tt>Class</tt> object, or <tt>null</tt> if the class has not been loaded
    "        
    |  class |
    class := Java at: (Java as_ST_String: (nativeContext argAt:1)).
    ^(class notNil and:[class classLoader == nativeContext receiver]) ifTrue:[
        self reflection javaClassObjectForClass:class
    ] ifFalse:[
        nil
    ]

    "Modified: / 12-08-2011 / 21:32:31 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_ClassLoader_registerNatives: aJavaContext

    <javanative: 'java/lang/ClassLoader' name: 'registerNatives'>

    
    "Nothing to do"

    "Created: / 09-11-2010 / 20:55:45 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_ClassLoader_resolveClass0: nativeContext

    <javanative: 'java/lang/ClassLoader' name: 'resolveClass0'>

        "resolve a new class as previously created by defineClass0"
    
    |jClassLoader jCls cls anyUnresolved|

    jClassLoader := nativeContext receiver.
    jCls := nativeContext argAt:1.
    jCls isNil ifTrue:[
        self halt.
        ^ nil
    ].
    cls := self reflection classForJavaClassObject:jCls.
    cls isNil ifTrue:[
        self halt.
        ^ nil
    ].
    ('JavaVM [info]: resolving class ' , cls fullName , ' ...') infoPrintCR.
    JavaClassReader classLoaderQuerySignal answer:jClassLoader
        do:[
            JavaClassReader resolveClass:cls.
            
"/        JavaClassReader postLoadActions:true.
            
            anyUnresolved := false.
            cls constantPool do:[:entry | 
                (entry isMemberOf:JavaUnresolvedClassConstant) ifTrue:[
                    self halt:'debugHalt'.
                    entry preResolve.
                    self halt:'debugHalt'.
                    anyUnresolved := true.
                ]
            ]
        ].
    anyUnresolved ifTrue:[
        jClassLoader notNil ifTrue:[
            "/ any unresolved left -> try resolving with standard loader
            JavaClassReader classLoaderQuerySignal answer:nil
                do:[
                    JavaClassReader postLoadActions:true.
                    cls constantPool do:[:entry | 
                        (entry isMemberOf:JavaUnresolvedClassConstant) ifTrue:[
                            self halt:'debugHalt'.
                            entry preResolve.
                            self halt:'debugHalt'.
                        ]
                    ]
                ]
        ].
    ].

    "Created: / 07-01-1998 / 13:12:27 / cg"
    "Modified: / 20-10-1998 / 19:01:57 / cg"
    "Modified: / 28-01-2011 / 15:28:18 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 14-08-2011 / 10:36:40 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_desiredAssertionStatus0: aJavaContext

    <javanative: 'java/lang/Class' name: 'desiredAssertionStatus0'>

    
    ^AssertionsEnabled == true

    "Created: / 24-11-2010 / 08:58:40 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_forName0: aJavaContext

    <javanative: 'java/lang/Class' name: 'forName0'>

    
    | name initialize loader class |
    name := Java as_ST_String: (aJavaContext argAt: 1).
    initialize := aJavaContext argAt: 2.
    loader := aJavaContext argAt: 3.   
    JavaClassReader classLoaderQuerySignal answer: loader do:
        [class := Java classForName: name].
    class isNil ifTrue:
        [^self throwClassNotFoundException: name].
    initialize ~~ 0 ifTrue:
        [[class classInit] on: Error do:[self throwExceptionInInitializerError:name]].
    ^JavaVM javaClassObjectForClass: class.

    "Created: / 24-11-2010 / 09:03:13 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 01-05-2011 / 13:27:15 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_getClassLoader0: aJavaContext

    <javanative: 'java/lang/Class' name: 'getClassLoader0'>

        "get a classes loader"
    
    |jClass cls clc loader |

    jClass := aJavaContext receiver.
    cls := self reflection classForJavaClassObject:jClass.
    cls isJavaPrimitiveType ifTrue:[^nil].
    [ cls isJavaArrayClass ] whileTrue:[cls := cls javaComponentClass].
    loader := cls classLoader.
"/    loader isNil ifTrue:[
"/        cls := (Java at:'java/lang/ClassLoader').
"/        clc notNil ifTrue:[loader := clc instVarNamed: #scl].
"/    ].
    ^ loader

    "Created: / 25-10-2010 / 22:49:45 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-01-2011 / 15:18:54 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 14-08-2011 / 23:17:16 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_getComponentType: nativeContext

    <javanative: 'java/lang/Class' name: 'getComponentType'>

        |cls|

    cls := self reflection classForJavaClassObject:(nativeContext receiver).
    cls isJavaPrimitiveType ifTrue:[
        self breakPoint:#jv.
        ^ nil
    ].
    ^ self javaClassObjectForClass:cls javaComponentClass

    "Created: / 12-11-1998 / 18:54:46 / cg"
    "Modified: / 20-12-2010 / 22:56:00 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-01-2011 / 15:18:59 / Marcel Hlopko <hlopik@gmail.com>"
!

_java_lang_Class_getConstantPool: aJavaContext

    <javanative: 'java/lang/Class' name: 'getConstantPool'>

        | class |

    class := self reflection classForJavaClassObject:aJavaContext receiver.
    ^ self reflection javaConstantPoolObjectFor:class constantPool.

    "Created: / 21-12-2010 / 20:00:02 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-02-2011 / 18:05:13 / Marcel Hlopko <hlopik@gmail.com>"
!

_java_lang_Class_getDeclaredClasses0: nativeContext

    <javanative: 'java/lang/Class' name: 'getDeclaredClasses0'>

    ^ UnimplementedNativeMethodSignal raise
!

_java_lang_Class_getDeclaredConstructors0:aJavaContext 
    <javanative: 'java/lang/Class' name: 'getDeclaredConstructors0'>
    |class publicOnly constructors|

    class := self reflection classForJavaClassObject:(aJavaContext receiver).
    publicOnly := (aJavaContext argAt:1) == 1.
    constructors := OrderedCollection new.
    class selectorsAndMethodsDo:
            [:selector :method | 
            (method isJavaMethod and:
                    [ (selector at:1) == $< and:
                            [ (selector startsWith:'<init>(') 
                                and:[ publicOnly not or:[ method isPublic ] ] ] ]) 
                ifTrue:
                    [ constructors add:(self reflection javaConstructorObjectForMethod:method) ] ].
    ^ (self classForName:'java.lang.reflect.Constructor') javaArrayClass 
        withAll:constructors

    "Created: / 24-11-2010 / 09:25:32 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 09-02-2011 / 01:24:03 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 11-02-2011 / 08:55:39 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_getDeclaredFields0:aJavaContext 
    <javanative: 'java/lang/Class' name: 'getDeclaredFields0'>
    |javaClassObject class fields publicOnly|

    class := self reflection 
                classForJavaClassObject:(javaClassObject := aJavaContext argAt:0).
    (class isJavaPrimitiveType or:[class isJavaArrayClass]) ifTrue:[
        ^(self classForName:'java.lang.reflect.Field') javaArrayClass new:0.
    ].
    
    publicOnly := (aJavaContext argAt:1) == 1.
    fields := class fields , class staticFields.
    publicOnly ifTrue:[ fields := fields select:[:f | f isPublic ] ].
    fields := fields 
                collect:[:f | self javaFieldObjectForField:f in:javaClassObject ].
    ^ (self classForName:'java.lang.reflect.Field') javaArrayClass 
        withAll:fields

    "Created: / 10-11-2010 / 16:22:46 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-01-2011 / 15:19:06 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 17-08-2011 / 09:06:30 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_getDeclaredMethods0:aJavaContext 
    <javanative: 'java/lang/Class' name: 'getDeclaredMethods0'>
    |class publicOnly methods|

    class := self reflection classForJavaClassObject:(aJavaContext receiver).
    publicOnly := (aJavaContext argAt:1) == 1.
    methods := OrderedCollection new.
    class selectorsAndMethodsDo:
            [:selector :method | 
            (method isJavaMethod and:
                    [ (selector at:1) ~~ $< and:
                            [ (selector startsWith:'<init>(') not 
                                and:[ publicOnly not or:[ method isPublic ] ] ] ]) 
                ifTrue:[ methods add:(self javaMethodObjectForMethod:method) ] ].
    ^ (self classForName:'java.lang.reflect.Method') javaArrayClass 
        withAll:methods asArray

    "Created: / 21-12-2010 / 22:39:25 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-01-2011 / 15:19:09 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 11-02-2011 / 08:35:19 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 04-06-2011 / 17:07:04 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

_java_lang_Class_getDeclaringClass: nativeContext

    <javanative: 'java/lang/Class' name: 'getDeclaringClass'>
    "
     /**
     * If the class or interface represented by this {@code Class} object
     * is a member of another class, returns the {@code Class} object
     * representing the class in which it was declared.  This method returns
     * null if this class or interface is not a member of any other class.  If
     * this {@code Class} object represents an array class, a primitive
     * type, or void,then this method returns null.
     *
     * @return the declaring class for this class
     * @since JDK1.1
     */
    "

    | cls enclosingClsName enclosingCls |

    cls := self reflection classForJavaClassObject:(nativeContext receiver).
    (cls isJavaPrimitiveType or:[cls isJavaArrayClass]) ifTrue:[^nil].
    (cls name includes: $$) ifFalse:[^nil].
    enclosingClsName := cls name copyTo: (cls name lastIndexOf: $$) - 1.
    enclosingCls := Java classForName: enclosingClsName.
    enclosingCls isNil ifTrue:[self error:'Cannot fins declaring class'].
    ^self reflection javaClassObjectForClass: enclosingCls

    "Modified: / 13-08-2011 / 02:01:19 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_getEnclosingMethod0: nativeContext

    <javanative: 'java/lang/Class' name: 'getEnclosingMethod0'>

    ^nil "/Not true"

    "Modified: / 14-08-2011 / 20:05:05 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_getGenericSignature: nativeContext

    <javanative: 'java/lang/Class' name: 'getGenericSignature'>

    |cls sig |

    cls := self reflection classForJavaClassObject:(nativeContext receiver).
    (cls isJavaPrimitiveType or:[cls isJavaArrayClass]) ifTrue:[^nil].
    sig := cls signatureJ.
    ^sig notNil ifTrue:[
        Java as_String: sig
    ] ifFalse:[
        nil
    ]

    "Modified: / 13-08-2011 / 02:19:21 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_getInterfaces:nativeContext 
    <javanative: 'java/lang/Class' name: 'getInterfaces'>
    |jClass cls interfaces jInterfaces|

    jClass := nativeContext receiver.
    cls := self reflection classForJavaClassObject:jClass.
    (cls isJavaPrimitiveType or:[cls isJavaArrayClass])
        ifTrue:[ ^ (self classForName:'java.lang.Class') javaArrayClass new ].
    interfaces := cls interfaces.
    interfaces 
        ifNil:[ ^ (self classForName:'java.lang.Class') javaArrayClass new ].
    jInterfaces := (self classForName:'java.lang.Class') javaArrayClass 
                new:interfaces size.
    interfaces 
        withIndexDo:[:iface :idx | jInterfaces at:idx put:(self javaClassObjectForClass:iface) ].
    ^ jInterfaces

    "Modified: / 28-01-2011 / 15:19:11 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 12-08-2011 / 22:27:13 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_getModifiers: aJavaContext

    <javanative: 'java/lang/Class' name: 'getModifiers'>

    | cls |

    cls := (self reflection classForJavaClassObject:aJavaContext receiver).
    ^(cls isJavaPrimitiveType or:[cls isJavaArrayClass]) ifTrue:[
        1041"FIXME: make it symbolic"
    ] ifFalse:[
        cls accessFlags
    ]

    "Created: / 12-11-1998 / 18:54:53 / cg"
    "Modified: / 28-01-2011 / 15:19:14 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 12-08-2011 / 22:34:21 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_getName0: aJavaContext

    <javanative: 'java/lang/Class' name: 'getName0'>

        |class|

    class := aJavaContext receiver.
    class := self reflection classForJavaClassObject:aJavaContext receiver.
    ^ self reflection 
        javaStringObjectForString:class javaName
        interned:true.

    "Created: / 22-11-2010 / 17:50:31 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 09-02-2011 / 01:06:53 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 25-02-2011 / 19:00:27 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_getPrimitiveClass: nativeContext

    <javanative: 'java/lang/Class' name: 'getPrimitiveClass'>

        "get a primitive class by name"
    
    |jClassName className|

    jClassName := nativeContext argAt:1.
    className := Java as_ST_String:jClassName.
    (JavaDescriptor baseTypesByTypeName keys includes: className)
        ifFalse:[self throwClassNotFoundException:className].
    ^self reflection javaClassObjectForClassNamed: className

    "Created: / 04-01-1998 / 00:46:03 / cg"
    "Modified: / 28-01-2011 / 15:30:45 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 03-02-2011 / 21:43:34 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_getProtectionDomain0: nativeContext

    <javanative: 'java/lang/Class' name: 'getProtectionDomain0'>

    ^(self reflection classForJavaClassObject: nativeContext receiver)
        protectionDomain

    "Modified: / 10-08-2011 / 15:19:23 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_getRawAnnotations: aJavaContext

    <javanative: 'java/lang/Class' name: 'getRawAnnotations'>

        |class |

    class := self reflection classForJavaClassObject:aJavaContext receiver.
    ^ class runtimeVisibleAnnotationsAsBytesOrNil

    "Created: / 21-12-2010 / 19:35:27 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-01-2011 / 15:19:20 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 25-02-2011 / 16:48:30 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_getSuperclass: nativeContext

    <javanative: 'java/lang/Class' name: 'getSuperclass'>

        "return a classes superclass"
    
    |jClass cls superCls|

    jClass := nativeContext receiver.
    cls := self reflection classForJavaClassObject:jClass.
    cls isJavaPrimitiveType ifTrue:[^nil].
    cls isJavaArrayClass ifTrue:[^self javaClassObjectForClass:(Java at:'java.lang.Object')].
    cls isInterface ifTrue:[^nil].

    superCls := cls superclass.
    superCls == JavaObject ifTrue:[
        ^ nil.
    ].
    ^ self javaClassObjectForClass:superCls

    "Created: / 12-01-1998 / 12:38:36 / cg"
    "Modified: / 04-02-1998 / 14:51:22 / cg"
    "Modified: / 28-01-2011 / 14:12:47 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 15-08-2011 / 09:09:39 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_isArray: nativeContext

    <javanative: 'java/lang/Class' name: 'isArray'>

        ^ (self reflection classForJavaClassObject:nativeContext receiver) isJavaArrayClass 
        ifTrue:[1]
        ifFalse:[0]

    "Created: / 12-11-1998 / 18:54:24 / cg"
    "Modified: / 20-12-2010 / 23:20:03 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-01-2011 / 15:19:24 / Marcel Hlopko <hlopik@gmail.com>"
!

_java_lang_Class_isAssignableFrom: nativeContext

    <javanative: 'java/lang/Class' name: 'isAssignableFrom'>

        "
    /**
     * Determines if the class or interface represented by this
     * {@code Class} object is either the same as, or is a superclass or
     * superinterface of, the class or interface represented by the specified
     * {@code Class} parameter. It returns {@code true} if so;
     * otherwise it returns {@code false}. If this {@code Class}
     * object represents a primitive type, this method returns
     * {@code true} if the specified {@code Class} parameter is
     * exactly this {@code Class} object; otherwise it returns
     * {@code false}.
     *
     * <p> Specifically, this method tests whether the type represented by the
     * specified {@code Class} parameter can be converted to the type
     * represented by this {@code Class} object via an identity conversion
     * or via a widening reference conversion. See <em>The Java Language
     * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
     *
     * @param cls the {@code Class} object to be checked
     * @return the {@code boolean} value indicating whether objects of the
     * type {@code cls} can be assigned to objects of this class
     * @exception NullPointerException if the specified Class parameter is
     *            null.
     * @since JDK1.1
     */
    "
    | clsObj me other |
    clsObj := nativeContext argAt: 1.
    clsObj ifNil:[^self throwNullPointerException].
    me := self reflection classForJavaClassObject: nativeContext receiver.
    other := self reflection classForJavaClassObject: clsObj.

    "/    Determines if the class or interface represented by this
    "/    @code Class} object is either the same as, or is a superclass or
    "/    superinterface of, the class or interface represented by the specified
    "/    {@code Class} parameter.

    ^(other includesBehavior: me)
        ifTrue:[1]
        ifFalse:[0]

    "Created: / 12-11-1998 / 18:54:16 / cg"
    "Modified: / 05-02-2011 / 23:38:15 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_isInstance: nativeContext

    <javanative: 'java/lang/Class' name: 'isInstance'>

        "
    /**
     * Determines if the specified {@code Object} is assignment-compatible
     * with the object represented by this {@code Class}.  This method is
     * the dynamic equivalent of the Java language {@code instanceof}
     * operator. The method returns {@code true} if the specified
     * {@code Object} argument is non-null and can be cast to the
     * reference type represented by this {@code Class} object without
     * raising a {@code ClassCastException.} It returns {@code false}
     * otherwise.
     *
     * <p> Specifically, if this {@code Class} object represents a
     * declared class, this method returns {@code true} if the specified
     * {@code Object} argument is an instance of the represented class (or
     * of any of its subclasses); it returns {@code false} otherwise. If
     * this {@code Class} object represents an array class, this method
     * returns {@code true} if the specified {@code Object} argument
     * can be converted to an object of the array class by an identity
     * conversion or by a widening reference conversion; it returns
     * {@code false} otherwise. If this {@code Class} object
     * represents an interface, this method returns {@code true} if the
     * class or any superclass of the specified {@code Object} argument
     * implements this interface; it returns {@code false} otherwise. If
     * this {@code Class} object represents a primitive type, this method
     * returns {@code false}.
     *
     * @param   obj the object to check
     * @return  true if {@code obj} is an instance of this class
     *
     * @since JDK1.1
     */
    public native boolean isInstance(Object obj);
    "
    
    |jClass cls obj|

    obj := nativeContext argAt:1.
    obj isNil ifTrue:[^ 0].
    jClass := nativeContext receiver.
    cls := self reflection classForJavaClassObject:jClass.
    ^self _INSTANCEOF:obj _:cls

    "Modified: / 09-02-1998 / 14:56:23 / cg"
    "Modified: / 28-01-2011 / 14:12:42 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 25-02-2011 / 18:37:07 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_isInterface: nativeContext

    <javanative: 'java/lang/Class' name: 'isInterface'>

        "return true, if this class is an interface"
    
    |jClass cls|

    jClass := nativeContext receiver.
    cls := self reflection classForJavaClassObject:jClass. 
    cls isJavaClass ifFalse:[
        ^ 0
    ].
    cls isInterface ifTrue:[
        ^ 1 "TRUE"
    ].
    ^ 0 "FALSE"

    "Created: / 12-01-1998 / 12:37:02 / cg"
    "Modified: / 28-01-2011 / 14:12:35 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 03-02-2011 / 21:50:19 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_isPrimitive: nativeContext

    <javanative: 'java/lang/Class' name: 'isPrimitive'>

        "return true, if this class is builtin primitive class
     (i.e. byteArray, array, string etc."
    
    |jClass cls|

    jClass := nativeContext receiver.
    cls := self reflection classForJavaClassObject:jClass. 
    ^cls isJavaPrimitiveType 
        ifTrue:[1"true"]
        ifFalse:[0"false"].

    "Created: / 09-02-1998 / 14:46:07 / cg"
    "Modified: / 28-01-2011 / 14:12:30 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 04-02-2011 / 11:56:40 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_registerNatives: aJavaContext

    <javanative: 'java/lang/Class' name: 'registerNatives'>

    
     "Nothing to do, native method are bound lazily"

    "Created: / 20-10-2010 / 11:13:23 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Class_setProtectionDomain0: nativeContext

    <javanative: 'java/lang/Class' name: 'getProtectionDomain0'>

    (self reflection classForJavaClassObject: nativeContext receiver)
        protectionDomain: (nativeContext argAt:1)

    "Created: / 10-08-2011 / 15:20:10 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Double_doubleToRawLongBits: aJavaContext

    <javanative: 'java/lang/Double' name: 'doubleToRawLongBits'>

        "
    /**
     * Returns a representation of the specified floating-point value
     * according to the IEEE 754 floating-point 'double
     * format' bit layout, preserving Not-a-Number (NaN) values.
     *
     * <p>Bit 63 (the bit that is selected by the mask
     * {@code 0x8000000000000000L}) represents the sign of the
     * floating-point number. Bits
     * 62-52 (the bits that are selected by the mask
     * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0
     * (the bits that are selected by the mask
     * {@code 0x000fffffffffffffL}) represent the significand
     * (sometimes called the mantissa) of the floating-point number.
     *
     * <p>If the argument is positive infinity, the result is
     * {@code 0x7ff0000000000000L}.
     *
     * <p>If the argument is negative infinity, the result is
     * {@code 0xfff0000000000000L}.
     *
     * <p>If the argument is NaN, the result is the {@code long}
     * integer representing the actual NaN value.  Unlike the
     * {@code doubleToLongBits} method,
     * {@code doubleToRawLongBits} does not collapse all the bit
     * patterns encoding a NaN to a single 'canonical' NaN
     * value.
     *
     * <p>In all cases, the result is a {@code long} integer that,
     * when given to the {@link #longBitsToDouble(long)} method, will
     * produce a floating-point value the same as the argument to
     * {@code doubleToRawLongBits}.
     *
     * @param   value   a {@code double} precision floating-point number.
     * @return the bits that represent the floating-point number.
     * @since 1.3
     */
    "
    | f b |
    f := aJavaContext argAt:1.
    (f =  0.0) ifTrue:[^0].
    (f = -0.0) ifTrue:[^(1 bitShift: 63)].

    b := ByteArray streamContents:[:s|Float storeBinaryIEEEDouble:f on:s].
    ^ LargeInteger digitBytes: b MSB: UninterpretedBytes isBigEndian not.

    "Created: / 10-11-2010 / 14:48:46 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 07-08-2011 / 21:43:49 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Double_longBitsToDouble: nativeContext

    <javanative: 'java/lang/Double' name: 'longBitsToDouble'>

        |i aFloat|

    i := nativeContext argAt:1.

    aFloat := Float new.
    UninterpretedBytes isBigEndian ifTrue:[
	aFloat basicAt:1 put:((i bitShift:-56) bitAnd:16rFF).
	aFloat basicAt:2 put:((i bitShift:-48) bitAnd:16rFF).
	aFloat basicAt:3 put:((i bitShift:-40) bitAnd:16rFF).
	aFloat basicAt:4 put:((i bitShift:-32) bitAnd:16rFF).
	aFloat basicAt:5 put:((i bitShift:-24) bitAnd:16rFF).
	aFloat basicAt:6 put:((i bitShift:-16) bitAnd:16rFF).
	aFloat basicAt:7 put:((i bitShift:-8) bitAnd:16rFF).
	aFloat basicAt:8 put:(i bitAnd:16rFF).
    ] ifFalse:[
	aFloat basicAt:1 put:(i bitAnd:16rFF).
	aFloat basicAt:2 put:((i bitShift:-8) bitAnd:16rFF).
	aFloat basicAt:3 put:((i bitShift:-16) bitAnd:16rFF).
	aFloat basicAt:4 put:((i bitShift:-24) bitAnd:16rFF).
	aFloat basicAt:5 put:((i bitShift:-32) bitAnd:16rFF).
	aFloat basicAt:6 put:((i bitShift:-40) bitAnd:16rFF).
	aFloat basicAt:7 put:((i bitShift:-48) bitAnd:16rFF).
	aFloat basicAt:8 put:((i bitShift:-56) bitAnd:16rFF).
    ].

    ^ aFloat.

    "Created: / 4.1.1998 / 01:45:00 / cg"
!

_java_lang_Float_floatToRawIntBits: aJavaContext

    <javanative: 'java/lang/Float' name: 'floatToRawIntBits'>

        "
    /**
     * Returns a representation of the specified floating-point value
     * according to the IEEE 754 floating-point 'single format' bit
     * layout, preserving Not-a-Number (NaN) values.
     *
     * <p>Bit 31 (the bit that is selected by the mask
     * {@code 0x80000000}) represents the sign of the floating-point
     * number.
     * Bits 30-23 (the bits that are selected by the mask
     * {@code 0x7f800000}) represent the exponent.
     * Bits 22-0 (the bits that are selected by the mask
     * {@code 0x007fffff}) represent the significand (sometimes called
     * the mantissa) of the floating-point number.
     *
     * <p>If the argument is positive infinity, the result is
     * {@code 0x7f800000}.
     *
     * <p>If the argument is negative infinity, the result is
     * {@code 0xff800000}.
     *
     * <p>If the argument is NaN, the result is the integer representing
     * the actual NaN value.  Unlike the {@code floatToIntBits}
     * method, {@code floatToRawIntBits} does not collapse all the
     * bit patterns encoding a NaN to a single 'canonical'
     * NaN value.
     *
     * <p>In all cases, the result is an integer that, when given to the
     * {@link #intBitsToFloat(int)} method, will produce a
     * floating-point value the same as the argument to
     * {@code floatToRawIntBits}.
     *
     * @param   value   a floating-point number.
     * @return the bits that represent the floating-point number.
     * @since 1.3
     */
    "
    | f b |
    f := aJavaContext argAt:1.
    (f =  0.0) ifTrue:[^0].
    (f = -0.0) ifTrue:[^(1 bitShift: 31) ].

    b := ByteArray streamContents:[:s|ShortFloat storeBinaryIEEESingle:f on:s].
    ^ (LargeInteger digitBytes: b MSB: UninterpretedBytes isBigEndian not) compressed

    "Created: / 09-11-2010 / 20:59:20 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 07-08-2011 / 21:45:23 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Object_clone: nativeContext

    <javanative: 'java/lang/Object' name: 'clone'>

        "clone an object"

    |o rslt|

    o := nativeContext receiver.
    rslt := o shallowCopy.
    ^ rslt

    "Created: / 4.1.1998 / 19:39:26 / cg"
!

_java_lang_Object_getClass: nativeContext

    <javanative: 'java/lang/Object' name: 'getClass'>

        "return an objects class"

    |o cls jClass|

    o := nativeContext receiver.
    cls := o class.

    jClass := self javaClassObjectForClass:cls.
    ^ jClass

    "Created: / 6.1.1998 / 18:28:27 / cg"
    "Modified: / 23.1.1998 / 17:48:22 / cg"
!

_java_lang_Object_hashCode: nativeContext

    <javanative: 'java/lang/Object' name: 'hashCode'>

        "identityHash"

    |o rslt|

    o := nativeContext receiver.
    rslt := o identityHash.
    ^ rslt

    "Created: / 4.1.1998 / 19:40:26 / cg"
!

_java_lang_Object_notify: nativeContext

    <javanative: 'java/lang/Object' name: 'notify'>

        "wakeup"

    self wakeup:(nativeContext receiver).

    "Created: / 6.1.1998 / 21:09:26 / cg"
!

_java_lang_Object_notifyAll: nativeContext

    <javanative: 'java/lang/Object' name: 'notifyAll'>

        self wakeupAll:(nativeContext receiver).

    "Created: / 3.1.1998 / 03:06:56 / cg"
!

_java_lang_Object_registerNatives: aJavaContext

    <javanative: 'java/lang/Object' name: 'registerNatives'>

    
    "Nothing to do, native method are bound lazily"

    "Created: / 19-10-2010 / 12:42:50 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 20-10-2010 / 10:57:44 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Object_wait: nativeContext

    <javanative: 'java/lang/Object' name: 'wait'>

    |tmo handle sema|

    handle := nativeContext receiver.
    tmo := nativeContext argAt:1.

    sema := JavaVM semaphoreFor:handle.

    [
        self waitFor:sema state:#javaWait timeOut:tmo.
    ] valueOnUnwindDo:[
        JavaVM releaseSemaphoreFor:handle.
    ].

    ThreadTrace ifTrue:[
        '====> thread continues ...' printCR.
    ]

    "Modified: / 30-12-1998 / 19:20:43 / cg"
    "Modified: / 01-05-2011 / 13:26:26 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Package_getSystemPackage0: nativeContext

    <javanative: 'java/lang/Package' name: 'getSystemPackage0'>

    "Based on code on OpenJDK, it is ok to return nil here:"

    ^nil

    "Modified: / 12-08-2011 / 16:00:44 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_ProcessEnvironment_environ: nativeContext

    <javanative: 'java/lang/ProcessEnvironment' name: 'environ'>

    | env jenv i|
    env := OperatingSystem getEnvironment.
    jenv :=  ByteArray javaArrayClass new: env size * 2.
    i := 1.
    env keysAndValuesDo:
        [:name :value|
        jenv 
            at: i   put: name  asByteArray;
            at: i+1 put: value asByteArray.
        i := i + 2].
    ^jenv

    "Modified: / 25-06-2011 / 08:57:47 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Runtime_gc: nativeContext

    <javanative: 'java/lang/Runtime' name: 'gc'>

        "Runs the garbage collector.
     Ignored, since the ST-gc runs all the time."

    ^ self

    "Modified: / 12.1.1998 / 12:58:32 / cg"
!

_java_lang_Runtime_runFinalization0: nativeContext

    <javanative: 'java/lang/Runtime' name: 'runFinalization0'>

    Smalltalk garbageCollect

    "Modified: / 08-08-2011 / 17:48:57 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_SecurityManager_getClassContext: nativeContext

    <javanative: 'java/lang/SecurityManager' name: 'getClassContext'>

        UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 18:52:07 / cg"
    "Created: / 12.11.1998 / 18:56:06 / cg"
!

_java_lang_Shutdown_halt0: nativeContext

    <javanative: 'java/lang/Shutdown' name: 'halt0'>

    "Intentionally left empty!!!!!!"

    "Modified: / 10-08-2011 / 22:20:53 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_StrictMath_cbrt: nativeContext

    <javanative: 'java/lang/StrictMath' name: 'cbrt'>

    ^ UnimplementedNativeMethodSignal raise
!

_java_lang_StrictMath_cos: nativeContext

    <javanative: 'java/lang/StrictMath' name: 'cos'>

    | f |
    f := nativeContext argAt: 1.
    ^f cos

    "Modified: / 08-08-2011 / 23:44:13 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_StrictMath_cosh: nativeContext

    <javanative: 'java/lang/StrictMath' name: 'cos'>

    | f |
    f := nativeContext argAt: 1.
    ^f cosh

    "Modified: / 08-08-2011 / 23:44:24 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_StrictMath_expm1: nativeContext

    <javanative: 'java/lang/StrictMath' name: 'expm1'>

    ^ UnimplementedNativeMethodSignal raise
!

_java_lang_StrictMath_floor: nativeContext

    <javanative: 'java/lang/StrictMath' name: 'floor'>

    | f |
    f := nativeContext argAt:1.
    ^f floor

    "Modified: / 10-08-2011 / 01:14:46 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_StrictMath_floot: nativeContext

    <javanative: 'java/lang/StrictMath' name: 'cos'>

    | f |
    f := nativeContext argAt: 1.
    ^f floor

    "Created: / 08-08-2011 / 23:46:14 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_StrictMath_sin: nativeContext

    <javanative: 'java/lang/StrictMath' name: 'cos'>

    | f |
    f := nativeContext argAt: 1.
    ^f sin

    "Modified: / 08-08-2011 / 23:44:36 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_StrictMath_sinh: nativeContext

    <javanative: 'java/lang/StrictMath' name: 'cos'>

    | f |
    f := nativeContext argAt: 1.
    ^f sinh

    "Modified: / 08-08-2011 / 23:44:42 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_StrictMath_tanh: nativeContext

    <javanative: 'java/lang/StrictMath' name: 'cos'>

    | f |
    f := nativeContext argAt: 1.
    ^f tanh

    "Modified: / 08-08-2011 / 23:44:56 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_String_intern: nativeContext

    <javanative: 'java/lang/String' name: 'intern'>

        |jString|

    jString := nativeContext receiver.
    ^ Java intern:jString
!

_java_lang_System_arraycopy: nativeContext

    <javanative: 'java/lang/System' name: 'arraycopy'>

    |srcArray srcIdx dstArray dstIdx srcArrayCC dstArrayCC count dstEndIdx|

    srcArray := nativeContext argAt:1.
    srcArray isNil ifTrue:[
        ^ self throwNullPointerException
    ].
    srcArray isJavaArray ifFalse:[
        ^ self throwArrayStoreException:srcArray
    ].
    srcIdx := nativeContext argAt:2.
    dstArray := nativeContext argAt:3.
    dstArray isNil ifTrue:[
        ^ self throwNullPointerException
    ].
    dstArray isJavaArray ifFalse:[
        ^ self throwArrayStoreException:dstArray
    ].

    srcArrayCC := srcArray class javaComponentClass.
    dstArrayCC := dstArray class javaComponentClass.

    srcArrayCC isJavaPrimitiveType == dstArrayCC isJavaPrimitiveType 
        ifTrue:
            [srcArrayCC isJavaPrimitiveType
                ifTrue:
                    [srcArrayCC ~~ dstArrayCC ifTrue:
                        [^ self throwArrayStoreException:dstArray]].
            ]
        ifFalse:
            [^ self throwArrayStoreException:dstArray].

    dstIdx := nativeContext argAt:4.
    count := nativeContext argAt:5.

    ((srcIdx < 0) or:[srcIdx + count > srcArray size]) ifTrue:[
        srcArray size == 0 ifTrue:[
            srcArray isVariable ifFalse:[
                ^ self throwArrayStoreException:srcArray
            ]
        ].
        ^ self throwArrayIndexOutOfBoundsException:(srcIdx + count - 1)
    ].
    ((dstIdx < 0) or:[dstIdx + count > dstArray size]) ifTrue:[
        dstArray size == 0 ifTrue:[
            dstArray isVariable ifFalse:[
                ^ self throwArrayStoreException:dstArray
            ]
        ].
        ^ self throwArrayIndexOutOfBoundsException:(dstIdx + count - 1)
    ].

    dstEndIdx := dstIdx + count.
    dstIdx := dstIdx + 1.       "/ ST uses 1-based indexing
    srcIdx := srcIdx + 1.       "/ ST uses 1-based indexing

    (srcArray class isBytes and:[dstArray class isBytes]) ifTrue:[
        dstArray replaceBytesFrom:dstIdx to:dstEndIdx with:srcArray startingAt:srcIdx.
    ] ifFalse:[
        dstArray replaceFrom:dstIdx to:dstEndIdx with:srcArray startingAt:srcIdx.
    ].
    ^ nil.

    "Modified: / 23-06-2011 / 09:17:54 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_System_currentTimeMillis: nativeContext

    <javanative: 'java/lang/System' name: 'currentTimeMillis'>

        "return the milliseconds since 1.jan.1970"

    |delta|

    "/ workaround win32 bug (use 01:01:01 as base)
    delta := Timestamp now millisecondDeltaFrom:(AbsoluteTime day:1 month:1 year:1970 hour:1 minutes:1 seconds:1).
    delta := delta - 3600 - 60 - 1.
"/    "/ make certain, it fits 64 signed bits
"/    delta := delta bitAnd:16r7FFFFFFFFFFFFFFF.
"/    ^ delta max:0
    ^ delta

    "
     JavaVM _System_currentTimeMillis:nil
    "

    "Modified: / 23.12.1998 / 21:54:50 / cg"
!

_java_lang_System_identityHashCode: nativeContext

    <javanative: 'java/lang/System' name: 'identityHashCode'>

        |obj|

    obj := nativeContext argAt:1.
    ^ obj identityHash

    "Modified: / 12.11.1998 / 18:52:07 / cg"
    "Created: / 12.11.1998 / 18:54:00 / cg"
!

_java_lang_System_initProperties: nativeContext

    <javanative: 'java/lang/System' name: 'initProperties'>

        |props stProps|

    props := nativeContext argAt:1.
    stProps := self systemProperties.

    "/ recursively invoke myself on the Java HashTable.
    "/ calling 'put' to stuff in the values ...

    stProps keysAndValuesDo:[:key :value |
	|keyObj valueObj|

	keyObj := Java as_String:key.
	valueObj := Java as_String:value.

	props 
	    perform:#'put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;'
	    with:keyObj 
	    with:valueObj.
    ].
    ^ props

    "Created: / 3.1.1998 / 14:25:22 / cg"
    "Modified: / 4.1.1998 / 14:23:18 / cg"
!

_java_lang_System_mapLibraryName: aJavaContext

    <javanative: 'java/lang/System' name: 'mapLibraryName'>

    
    | name |
    name := Java as_ST_String: (aJavaContext argAt: 1).

    OperatingSystem isUNIXlike ifTrue:[
        ^Java as_String: ('lib' , name , '.so').
    ].

    OperatingSystem isMSWINDOWSlike ifTrue:[
        ^Java as_String: ( name , '.dll').
    ].

    self error:'Unknown/Unsupported platform'

    "Created: / 09-12-2010 / 18:16:12 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 01-04-2011 / 18:14:02 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_System_nanoTime: nativeContext

    <javanative: 'java/lang/System' name: 'nanoTime'>

    ^ OperatingSystem getMicrosecondTime * 1000

    "Modified: / 07-08-2011 / 21:47:58 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_System_registerNatives: aJavaContext

    <javanative: 'java/lang/System' name: 'registerNatives'>

    
    "Nothing to do, native method are bound lazily"

    "Created: / 20-10-2010 / 10:56:35 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_System_setErr0: nativeContext

    <javanative: 'java/lang/System' name: 'setErr0'>

        |stream|

    stream := nativeContext argAt:1.

    self setOpenFile:(self javaConsoleStream ? Stderr) at:2.

    nativeContext receiver instVarNamed:'err' put:stream.

    "Created: / 18.3.1997 / 15:02:05 / cg"
    "Modified: / 4.1.1998 / 16:21:15 / cg"
!

_java_lang_System_setIn0: nativeContext

    <javanative: 'java/lang/System' name: 'setIn0'>

        |stream|

    stream := nativeContext argAt:1.

    self setOpenFile:Stdin at:0.

    nativeContext receiver instVarNamed:'in' put:stream.

    "Created: / 4.1.1998 / 16:16:38 / cg"
    "Modified: / 4.1.1998 / 16:20:44 / cg"
!

_java_lang_System_setOut0: nativeContext

    <javanative: 'java/lang/System' name: 'setOut0'>

        |stream|

    stream := nativeContext argAt:1.

    self setOpenFile:(self javaConsoleStream ? Stdout) at:1.

    nativeContext receiver instVarNamed:'out' put:stream.

    "Created: / 4.1.1998 / 16:18:26 / cg"
    "Modified: / 4.1.1998 / 16:20:23 / cg"
!

_java_lang_Thread_currentThread: nativeContext

    <javanative: 'java/lang/Thread' name: 'currentThread'>

    |t p|

    p := Processor activeProcess.
    t := self javaThreadForSTProcess:p.
    t notNil ifTrue:[
        ^ t
    ].
    t := self newThread:'main'.
    Java threads at:t put:p.
    ^ t

    "Modified: / 01-05-2011 / 13:24:33 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Thread_holdsLock: aJavaContext

    <javanative: 'java/lang/Thread' name: 'holdsLock'>

    
    | obj |
    obj := aJavaContext argAt: 1.

    ^(self enteredMonitorsOfProcess:Processor activeProcess)
        includes: obj.

    "Created: / 30-04-2011 / 22:06:29 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Thread_isAlive: nativeContext

    <javanative: 'java/lang/Thread' name: 'isAlive'>

        "is it alive ?"

    |jThread stProcess|

    jThread := nativeContext receiver.
    stProcess := JavaVM stProcessForJavaThread:jThread.
    stProcess isNil ifTrue:[
	ThreadTrace == true ifTrue:[
	    ('JAVA: no stProcess for javaThread: ' , jThread displayString) printNL.
	].
	^ 0 "FALSE"
    ].
    stProcess isDead ifTrue:[^ 0 "FALSE"].
    ^ 1 "TRUE"

    "Created: / 5.1.1998 / 02:03:51 / cg"
    "Modified: / 6.2.1998 / 02:15:01 / cg"
!

_java_lang_Thread_isInterrupted: nativeContext

    <javanative: 'java/lang/Thread' name: 'isInterrupted'>

        "ask if a thread is interrupted (clear interruptState if arg is true)"

    |jThread stProcess clearInterrupt rslt|

    jThread := nativeContext receiver.
    stProcess := self stProcessForJavaThread:jThread.
    stProcess isNil ifTrue:[
        self halt.
        ^ 0
    ].

    clearInterrupt := nativeContext argAt:1.
    rslt := "stProcess isInterrupted"false ifTrue:[1] ifFalse:[0].
    "clearInterrupt ~~ 0 ifTrue:[stProcess clearInterruptActions]."
    ^ rslt

    "Modified: / 02-01-1998 / 21:49:06 / cg"
    "Created: / 07-01-1998 / 18:50:26 / cg"
    "Modified: / 05-08-2011 / 22:21:41 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Thread_registerNatives: aJavaContext

    <javanative: 'java/lang/Thread' name: 'registerNatives'>

    
    "Nothing to do, native method are bound lazily"

    "Created: / 20-10-2010 / 11:12:39 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Thread_setPriority0: nativeContext

    <javanative: 'java/lang/Thread' name: 'setPriority0'>

   |t p prio|

    t := nativeContext receiver.
    p := JavaVM stProcessForJavaThread:t.
    prio := nativeContext argAt:1.

    p isNil ifTrue:[
        ThreadTrace == true ifTrue:[
            'JAVA [info]: no process yet (in setPriority)' infoPrintCR.
        ].
        ^ nil
    ].

    "Modified: / 01-05-2011 / 13:25:23 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Thread_sleep: nativeContext

    <javanative: 'java/lang/Thread' name: 'sleep'>

        "sleep for some milliseconds "

    |millis|

    millis := nativeContext argAt:1.
    self waitFor:nil state:nil timeOut:(millis max:50)

    "Modified: / 8.1.1999 / 16:42:52 / cg"
!

_java_lang_Thread_start0: nativeContext

    <javanative: 'java/lang/Thread' name: 'start0'>

    
    ^self threadStart: nativeContext

    "Modified: / 24-12-1999 / 03:14:33 / cg"
    "Created: / 22-11-2010 / 17:48:46 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 14-12-2010 / 21:31:37 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Throwable_fillInStackTrace: nativeContext

    <javanative: 'java/lang/Throwable' name: 'fillInStackTrace'>

        |exClass exceptionObject list con|

    exClass := Java classNamed:'java.lang.Throwable'.

    exceptionObject := nativeContext receiver.

    "/
    "/ debugging only
    "/
    (exceptionObject isKindOf:(Java classNamed:'java.lang.Throwable')) ifFalse:[
	self halt
    ].

    con := thisContext sender.

    "/
    "/ we are not interrested in all intermediate Exception frames ...
    "/
    FullExceptionTrace ifFalse:[
	"/ first, skip any JavaVM contexts
	[con receiver == exceptionObject] whileFalse:[
	    con := con sender
	].
	"/ then, all exception-init contexts
	[con receiver == exceptionObject] whileTrue:[
	    con := con sender
	].
    ].

    list := OrderedCollection new.
    [con notNil] whileTrue:[
	(con isJavaContext) ifTrue:[
	    "/ add a copy, in case the context continues with some
	    "/ cleanup ...
	    list add:con shallowCopy
	].
	con := con sender
    ].

    exceptionObject instVarNamed:'backtrace' put:(list asArray).

    ^ nil.

    "Created: / 4.1.1998 / 14:27:40 / cg"
    "Modified: / 8.5.1998 / 21:29:53 / cg"
!

_java_lang_Throwable_getStackTraceDepth: nativeContext

    <javanative: 'java/lang/Throwable' name: 'getStackTraceDepth'>


    ^(nativeContext receiver instVarNamed: #backtrace) size

    "Modified: / 01-05-2011 / 20:25:36 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_Throwable_getStackTraceElement: nativeContext

    <javanative: 'java/lang/Throwable' name: 'getStackTraceElement'>

    | throwable index ctx stackTraceElement |
    throwable := nativeContext receiver.
    index :=  nativeContext argAt: 1.
    ctx := (throwable instVarNamed:#backtrace) at: index + 1.

    stackTraceElement := (self classForName: 'java.lang.StackTraceElement') new.

    stackTraceElement 
        instVarNamed: #declaringClass 
        put: (Java as_String:(ctx method javaClass javaName));

        instVarNamed: #methodName 
        put: (Java as_String:(ctx method printStringForBrowserWithSelector:ctx method selector inClass: ctx method javaClass));

        instVarNamed: #lineNumber 
        put: ctx lineNumber.

    ctx method javaClass sourceFile notNil ifTrue:[                
        stackTraceElement        
            instVarNamed: #fileName 
            put: (Java as_String:(ctx method javaClass sourceFile))
    ].
    ^ stackTraceElement

    "Modified: / 07-08-2011 / 13:30:09 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_UNIXProcess_forkAndExec: nativeContext

    <javanative: 'java/lang/UNIXProcess' name: 'forkAndExec'>

    ^ UnimplementedNativeMethodSignal raise
!

_java_lang_UNIXProcess_initIDs: nativeContext

    <javanative: 'java/lang/UNIXProcess' name: 'initIDs'>

    "Nothing to do"

    "Modified: / 25-06-2011 / 10:05:24 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!JavaVM class methodsFor:'native - java.lang.reflect'!

_java_lang_reflect_Array_getLength: nativeContext

    <javanative: 'java/lang/reflect/Array' name: 'getLength(Ljava/lang/Object;)I'>

    ^(nativeContext argAt: 1) size

    "Modified: / 17-08-2011 / 09:02:18 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_lang_reflect_Array_newArray:aJavaContext 
    <javanative: 'java/lang/reflect/Array' name: 'newArray'>
    |componentClass size|

    componentClass := self reflection 
                classForJavaClassObject:(aJavaContext argAt:1).
    size := aJavaContext argAt:2.
    ^ componentClass javaArrayClass new:size

    "Created: / 17-12-2010 / 14:49:02 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 19-12-2010 / 17:54:51 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-01-2011 / 15:18:50 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 04-06-2011 / 17:06:41 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

_java_lang_reflect_Array_set: nativeContext

    <javanative: 'java/lang/reflect/Array' name: 'set'>

    ^ UnimplementedNativeMethodSignal raise
!

_java_lang_reflect_Proxy_defineClass0: nativeContext

    <javanative: 'java/lang/reflect/Proxy' name: 'defineClass0'>

        "
    private static native Class defineClass0(ClassLoader loader, String name,
                                             byte[] b, int off, int len);
    "
    | loader name b off len  bs cls |
    loader := nativeContext argAt: 1.
    name := nativeContext argAt: 2.
    b := nativeContext argAt: 3.
    off := nativeContext argAt: 4.
    len := nativeContext argAt: 5.

    bs := (off = 0 and: [len = b size]) 
            ifTrue:[b readStream]
            ifFalse:[(b copyFrom: off + 1 to: off + len) readStream].

    cls := JavaClassReader readStream: bs.
    cls classLoader: loader.

    ^self reflection javaClassObjectForClass: cls.

    "Created: / 06-02-2011 / 16:55:31 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!JavaVM class methodsFor:'native - java.net'!

_java_net_DatagramPacket_init: nativeContext

    <javanative: 'java/net/DatagramPacket' name: 'init'>

    ^ UnimplementedNativeMethodSignal raise
!

_java_net_InetAddressImplFactory_isIPv6Supported: nativeContext

    <javanative: 'java/net/InetAddressImplFactory' name: 'isIPv6Supported'>

    ^ UnimplementedNativeMethodSignal raise
!

_java_net_InetAddress_init: nativeContext

    <javanative: 'java/net/InetAddress' name: 'init'>

        "/ introduced with jdk1.2 ... (sigh)

    "Created: / 27.1.1998 / 18:16:40 / cg"


!

_java_net_NetworkInterface_init: nativeContext

    <javanative: 'java/net/NetworkInterface' name: 'init'>

    ^ UnimplementedNativeMethodSignal raise
!

_java_net_PlainDatagramSocketImpl_init: nativeContext

    <javanative: 'java/net/PlainDatagramSocketImpl' name: 'init'>

    ^ UnimplementedNativeMethodSignal raise
!

_java_net_PlainSocketImpl_initProto: nativeContext

    <javanative: 'java/net/PlainSocketImpl' name: 'initProto'>

    
    "Created: / 12.1.1998 / 12:56:52 / cg"
! !

!JavaVM class methodsFor:'native - java.security'!

_java_security_AccessController_doPrivileged: aJavaContext

    <javanative: 'java/security/AccessController' name: 'doPrivileged'>

    
    "Don't care about permissions :-)"

    ^(aJavaContext argAt:1) perform: #'run()Ljava/lang/Object;'

    "Created: / 20-10-2010 / 12:31:59 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_security_AccessController_getStackAccessControlContext: nativeContext

    <javanative: 'java/security/AccessController' name: 'getStackAccessControlContext'>

        "/ introduced with jdk1.2

    "/ supposed to do more here ...

    ^ nil

    "Created: / 27.1.1998 / 18:22:15 / cg"
! !

!JavaVM class methodsFor:'native - java.util'!

_java_util_ResourceBundle_getClassContext: nativeContext

    <javanative: 'java/util/ResourceBundle' name: 'getClassContext'>

        "returns an array filled with the contextChain receivers classes.
     What an ugly, messy interface."
    
    |chain con cls jClass|

    chain := OrderedCollection new.
    con := thisContext sender.
    [
        con notNil 
            and:[con receiver isMethod not or:[con receiver isJavaMethod not]]
    ] whileTrue:[con := con sender.].
    con := con sender.
    [con notNil] whileTrue:[
        (true) "con isJavaContext" ifTrue:[
            cls := con receiver class.
            cls isMeta ifTrue:[
                "/ t'was a static method
                cls := cls soleInstance
            ].
            cls isJavaClass ifTrue:[
                jClass := self reflection javaClassObjectForClass:cls.
                chain add:jClass.
            ]
        ].
        con := con sender.
    ].
    ^ chain asArray

    "Created: / 05-01-1998 / 02:47:00 / cg"
    "Modified: / 24-12-1998 / 00:34:57 / cg"
    "Modified: / 28-01-2011 / 15:31:28 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 03-02-2011 / 21:31:49 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_util_TimeZone_getSystemTimeZoneID: nativeContext

    <javanative: 'java/util/TimeZone' name: 'getSystemTimeZoneID'>

    "JV@2011-06-25: TODO: finish, returning nil here means GMT"

    ^ nil

    "Modified: / 25-06-2011 / 08:26:06 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!JavaVM class methodsFor:'native - java.util.concurrent.atomic'!

_java_util_concurrent_atomic_AtomicLong_VMSupportsCS8: nativeContext

    <javanative: 'java/util/concurrent/atomic/AtomicLong' name: 'VMSupportsCS8'>

    "Should be safe - say we don't support lockless updates"        

    ^ 0

    "Modified: / 07-08-2011 / 20:53:11 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!JavaVM class methodsFor:'native - java.util.jar'!

_java_util_jar_JarFile_getMetaInfEntryNames: nativeContext

    <javanative: 'java/util/jar/JarFile' name: 'getMetaInfEntryNames'>
    "
    private native String[] getMetaInfEntryNames();
    "
    | zipArchive entries jentries |

    zipArchive := ZipCache at: (nativeContext receiver instVarNamed: #jzfile).
    entries := zipArchive entries select:[:entry|entry size > 9 and:[entry startsWith: 'META-INF/']].    
    jentries := Java java_lang_String javaArrayClass new: entries size.
    1 to: entries size do:[:i|
        jentries at: i put: (Java as_String: (entries at: i))
    ].
    ^jentries

    "Modified: / 05-08-2011 / 20:18:06 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!JavaVM class methodsFor:'native - java.util.zip'!

_java_util_zip_Adler32_updateBytes: nativeContext

    <javanative: 'java/util/zip/Adler32' name: 'updateBytes'>

    ^ UnimplementedNativeMethodSignal raise
!

_java_util_zip_Deflater_initIDs: nativeContext

    <javanative: 'java/util/zip/Deflater' name: 'initIDs'>

    ^ UnimplementedNativeMethodSignal raise
!

_java_util_zip_Inflater_getBytesWritten: nativeContext

    <javanative: 'java/util/zip/Inflater' name: 'getBytesWritten'>

    ^ UnimplementedNativeMethodSignal raise
!

_java_util_zip_Inflater_inflateBytes: nativeContext

    <javanative: 'java/util/zip/Inflater' name: 'inflateBytes'>
    "
    private native int inflateBytes(long addr, byte[] b, int off, int len)
    "

    | addr inputBuf outputBuf b off len inflater |
    addr := nativeContext argAt: 1.
    inflater := ZipInflaters at: addr.
    inputBuf := nativeContext receiver instVarNamed: #buf.
    inputBuf size == 0 ifTrue:[^0].

    b := nativeContext argAt: 3.
    off := nativeContext argAt: 4.
    len := nativeContext argAt: 5.

    outputBuf := ByteArray new: (b size + 1000"save").

    ZipArchive basicNew inflate:inputBuf to:outputBuf.

    b replaceFrom:off + 1 to: off + len with: outputBuf startingAt:1.

    ^len

    "Created: / 30-04-2011 / 23:02:11 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 12-08-2011 / 18:37:52 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_util_zip_Inflater_init: nativeContext

    <javanative: 'java/util/zip/Inflater' name: 'init'>

    
    | index |
    index := ZipInflaters indexOf: nativeContext receiver.
    index == 0 ifTrue:
        [ZipInflaters add: JavaInflater new.
        index := ZipInflaters size].
    ^index

    "Created: / 01-02-1998 / 20:14:01 / cg"
    "Modified: / 12-08-2011 / 18:19:40 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_util_zip_Inflater_initIDs: aJavaContext

    <javanative: 'java/util/zip/Inflater' name: 'initIDs'>

    
    "Nothing to do, used only to register natives"

    "Created: / 30-04-2011 / 21:55:37 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_util_zip_Inflater_reset: nativeContext

    <javanative: 'java/util/zip/Inflater' name: 'reset'>
    "
    private native static void reset(long addr);
    "
    | addr |
    addr := nativeContext argAt: 1.
    ZipInflaters at: addr put: nil.

    "Created: / 01-02-1998 / 20:14:13 / cg"
    "Modified: / 12-08-2011 / 18:21:18 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_util_zip_ZipEntry_initFields: aJavaContext

    <javanative: 'java/util/zip/ZipEntry' name: 'initFields'>

        | entry jzentry zmember |

    entry := aJavaContext receiver.
    jzentry := aJavaContext argAt: 1.
    zmember := ZipEntryCache at: jzentry.

    entry 
        instVarNamed: #time     put: zmember lastModFileTime;
        instVarNamed: #crc      put: zmember crc32;
        instVarNamed: #size     put: zmember uncompressedSize;
        instVarNamed: #csize    put: zmember compressedSize;
        instVarNamed: #method   put: zmember compressionMethod;
        instVarNamed: #extra    put: zmember extraField;
        instVarNamed: #comment  put: (zmember fileComment ifNotNil:[Java as_String: zmember fileComment]).
        
        

    "Created: / 01-04-2011 / 13:04:24 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
    "Modified: / 29-04-2011 / 20:01:00 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_util_zip_ZipEntry_initIDs: aJavaContext

    <javanative: 'java/util/zip/ZipEntry' name: 'initIDs'>

        "hopefully nothing to do"

    "Created: / 01-04-2011 / 13:02:06 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

_java_util_zip_ZipFile_freeEntry: nativeContext

    <javanative: 'java/util/zip/ZipFile' name: 'freeEntry'>

    | zipArchiveIndex  zipEntryIndex |


    zipArchiveIndex := nativeContext at: 1.
    zipEntryIndex := nativeContext at: 3.
    zipEntryIndex = 0 ifFalse: [ ZipEntryCache at: zipEntryIndex put: nil ].

    "Modified: / 01-05-2011 / 13:33:00 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_util_zip_ZipFile_getCSize: aJavaContext

    <javanative: 'java/util/zip/ZipFile' name: 'getCSize'>

    
    | jzentry zmember |
    jzentry := aJavaContext argAt: 1.
    zmember := ZipEntryCache at: jzentry.

    ^zmember compressedSize

    "Created: / 30-04-2011 / 21:50:23 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_util_zip_ZipFile_getEntry: nativeContext

    <javanative: 'java/util/zip/ZipFile' name: 'getEntry'>

    | zipArchive  filename  member |

    zipArchive := ZipCache at: (nativeContext at: 1).
    filename := Java as_ST_String: (nativeContext at: 3).
    member := (zipArchive findMember: filename).
    member isNil 
        ifTrue: [ ^ 0 ]
        ifFalse: [ ^ ZipEntryCache indexOf: (ZipEntryCache add: member) ].

    "Created: / 27-03-2011 / 16:59:03 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
    "Modified: / 01-04-2011 / 16:03:01 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
    "Modified: / 01-05-2011 / 15:12:35 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 18-08-2011 / 19:44:56 / jv"
!

_java_util_zip_ZipFile_getMethod: aJavaContext

    <javanative: 'java/util/zip/ZipFile' name: 'getMethod'>

    
    | jzentry zmember |
    jzentry := aJavaContext argAt: 1.
    zmember := ZipEntryCache at: jzentry.

    ^zmember compressionMethod

    "Created: / 30-04-2011 / 21:53:33 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_util_zip_ZipFile_getSize: aJavaContext

    <javanative: 'java/util/zip/ZipFile' name: 'getSize'>

    
    | jzentry zmember |
    jzentry := aJavaContext argAt: 1.
    zmember := ZipEntryCache at: jzentry.

    ^zmember uncompressedSize

    "Created: / 30-04-2011 / 21:53:33 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_util_zip_ZipFile_getTotal: nativeContext

    <javanative: 'java/util/zip/ZipFile' name: 'getTotal'>

    | zar |
    zar := ZipCache at: (nativeContext at: 1).
    ^ zar entries size.

    "Modified: / 01-05-2011 / 13:31:05 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_util_zip_ZipFile_initIDs: aJavaContext

    <javanative: 'java/util/zip/ZipFile' name: 'initIDs'>

    
    "Nothing to do"

    "Created: / 23-03-2011 / 19:37:21 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_util_zip_ZipFile_open: nativeContext

    <javanative: 'java/util/zip/ZipFile' name: 'open'>

    | path  mode  lastModTime  result |

    path := Java as_ST_String: (nativeContext at: 1).
    mode := nativeContext at: 2.
    lastModTime := nativeContext at: 3.
    result := path asFilename.
    result ifNil: [ JavaVM throwZipException ].
    ^ ZipCache 
        indexOf: ( ZipCache add: (ZipArchive readingFrom: result readStream) ).

    "Modified: / 01-04-2011 / 15:35:21 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
    "Modified: / 01-05-2011 / 13:29:42 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_java_util_zip_ZipFile_read: aJavaContext

    <javanative: 'java/util/zip/ZipFile' name: 'read'>

    
    | jzfile jzentry pos b off len zar zmember bytesToRead |
    jzfile := aJavaContext argAt: 1.
    jzentry := aJavaContext argAt: 3. "first arg is long!!!!!!"
    pos := aJavaContext argAt: 5. "jzentry arg is long!!!!!!"
    b := aJavaContext argAt: 7.
    off := aJavaContext argAt: 8.
    len := aJavaContext argAt: 9.

    zar := ZipCache at: jzfile.
    zmember := ZipEntryCache at: jzentry.

    bytesToRead := len min: (zmember compressedSize - pos).

    ^zar nextBytes: bytesToRead of: zmember startingAt: pos into: b startingAt: off + 1.

    "Created: / 30-04-2011 / 22:15:06 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 01-05-2011 / 16:22:03 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!JavaVM class methodsFor:'native - old-style'!

_AccessController_beginPrivileged:nativeContext
    "/ introduced with jdk1.2

    "Created: / 27.1.1998 / 18:18:11 / cg"
!

_AccessController_endPrivileged:nativeContext
    "/ introduced with jdk1.2

    "Created: / 27.1.1998 / 18:18:32 / cg"
!

_AudioDevice_audioClose:nativeContext
    |device fd stream|

    device := nativeContext receiver.
    device notNil ifTrue:[
	fd := device instVarNamed:'dev'.
	(fd notNil and:[fd > 0]) ifTrue:[
	    stream := self getOpenFileAt:fd.
	    stream notNil ifTrue:[
		stream close.
		device instVarNamed:'dev' put:0.
	    ]
	]
    ]

    "Created: / 10.1.1998 / 15:45:16 / cg"
    "Modified: / 13.1.1998 / 18:08:20 / cg"
!

_AudioDevice_audioOpen:nativeContext
    |f stream fileNo|

    NoAudio ifTrue:[
	Transcript showCR:'JAVA: audio disabled'.
	^ -1
    ].

    Stream streamErrorSignal handle:[:ex |
	Stream streamErrorSignal handle:[:ex |
	    stream := nil.
	    ex return.
	] do:[
	    stream := SoundStream writing.
	].
    ] do:[
	stream := SoundStream writing.
	stream notNil ifTrue:[
	    stream setSampleRate:8000.
	]
    ].
    stream isNil ifTrue:[
"/        ^ -1.

	f := '/dev/audio' asFilename.
	f exists ifFalse:[
	    Transcript showCR:'JAVA: neither SoundStream nor /dev/audio available'.
	    ^ -1
	].
	stream := f readWriteStream.
	stream isNil ifTrue:[
	    Transcript showCR:'JAVA: /dev/audio exists, but cannot be opened'.
	    ^ -1
	].
	fileNo := self addOpenFile:stream.
    ].

    fileNo := self addOpenFile:stream.

    FileOpenTrace ifTrue:[
	('JAVA: opened audioDevice as FD ' , fileNo printString) infoPrintCR.
    ].

    ^ fileNo

    "Created: / 10.1.1998 / 15:45:30 / cg"
    "Modified: / 14.10.1998 / 15:20:52 / cg"
!

_AudioDevice_audioWrite:nativeContext
    |device fd stream bytes count|

    device := nativeContext receiver.
    device notNil ifTrue:[
	fd := device instVarNamed:'dev'.
	(fd notNil and:[fd > 0]) ifTrue:[
	    stream := self getOpenFileAt:fd.
	    stream notNil ifTrue:[
		bytes := nativeContext argAt:1.
		count := nativeContext argAt:2.
		stream nextPutBytes:count from:bytes startingAt:1
	    ]
	]
    ]

    "Created: / 10.1.1998 / 15:45:16 / cg"
    "Modified: / 13.1.1998 / 18:07:20 / cg"
!

_BigInteger_plumbInit:nativeContext
    UnimplementedNativeMethodSignal raiseRequest

    "Modified: / 12.11.1998 / 19:23:00 / cg"
!

_CMM_cmmGetTagSize:nativeContext
    "/ public static native synchronized int cmmGetTagSize (long arg1, int arg2, int[] arg3)
    "/ new with jdk1.2 ...

    UnimplementedNativeMethodSignal raiseRequest.
    ^ -1.

    "Created: / 27.1.1998 / 21:43:25 / cg"
!

_CMM_cmmInit:nativeContext
    "/ new with jdk1.2 ...

    "Created: / 27.1.1998 / 21:43:25 / cg"
!

_CMM_cmmLoadProfile:nativeContext
    "/ public static native synchronized int cmmLoadProfile (byte[] arg1, long[] arg2)
    "/ new with jdk1.2 ...

    UnimplementedNativeMethodSignal raiseRequest.
    ^ -1.

    "Created: / 27.1.1998 / 21:43:25 / cg"
!

_CRC32_update1:nativeContext
    "/ void update1 (int)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 03:08:47 / cg"
!

_CRC32_update:nativeContext
    "/ void update (byte[] int int)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 03:08:47 / cg"
    "Created: / 27.1.2000 / 03:09:20 / cg"
!

_ClassLoader_createArrayClass:nativeContext
    "java.lang.Class createArrayClass (java.lang.String java.lang.Class)"

    "resolve a new class as previously created by defineClass0"

    |jClassLoader name elCls|

    jClassLoader := nativeContext receiver.
    name := nativeContext argAt:1.
    elCls := nativeContext argAt:2.
    elCls isNil ifTrue:[
        self halt.
        ^ nil
    ].
UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:36:01 / cg"
    "Created: / 27.1.2000 / 02:56:37 / cg"
!

_ClassLoader_defineClass0:nativeContext
    "create a new class from a given byteArray.
     Here, construct a stream on it and pass the work to the
     JavaClassReader."

    |jClassLoader jName name data offset length inStream newClass
     loaderStub jClass|

    jClassLoader := nativeContext receiver.
    jName := nativeContext argAt:1.

    "/ className is now optional ...
"/    jName isNil ifTrue:[
"/        self internalError:'nil name in defineClass'.
"/        ^ nil
"/    ] ifFalse:[
"/        name := Java as_ST_String:jName.
"/    ].

    data := nativeContext argAt:2.
    offset := nativeContext argAt:3.
    length := nativeContext argAt:4.

    inStream := data readStream.
    inStream position:offset + 1.
    inStream readLimit:(offset + length).

"/    loaderStub := Plug new.
"/    loaderStub respondTo:#loadClass: with:[:clsName |
"/                                                |jName|
"/
"/self halt.
"/                                                jName := Java as_String:clsName.
"/                                                "/ jClassLoader loadClass:jName
"/                                                jClassLoader 
"/                                                    perform:#'loadClass(Ljava/lang/String;)Ljava/lang/Class;'
"/                                                    with:jName.
"/                                          ].

"/    ('JAVA [info]: defining class ...') infoPrintCR.

"/    self internalError:'break'.

    newClass := JavaClassReader 
                    readStream:inStream 
                    loader:jClassLoader "loaderStub"
                    loadUnresolved:false.

    newClass isNil ifTrue:[
        ('JAVA [info]: defineClass failed') infoPrintCR.
        ^ nil.
    ].
"/    Transcript showCR:('defined class ' , newClass fullName , '.').
    newClass classLoader:jClassLoader.

"/    ('Java [info]: defined new class: ' , newClass fullName) infoPrintCR.

    jClass := self javaClassObjectForClass:newClass.
    ^ jClass

    "Created: / 7.1.1998 / 12:35:10 / cg"
    "Modified: / 24.1.1998 / 15:26:21 / cg"
!

_ClassLoader_findSystemClass0:nativeContext
    |loader name class jClass|

    loader := nativeContext receiver.
    name := nativeContext argAt:1.
    name := Java as_ST_String:name.

    class := Java at:name.
    class isNil ifTrue:[ 
"/    ('JAVA: findSystemClass0 for ' , name , ' loader is ' , loader displayString) infoPrintCR.
	loader class == (Java classForName:'java.util.SystemClassLoader') ifTrue:[
"/            Java classForName:name.
"/            class := Java at:name.
	    class := JavaClassReader loadSystemClass:name.
	] ifFalse:[
	    "/ load using default (ST/X) loader
	    class := JavaClassReader loadSystemClass:name.
"/            JavaClassReader classLoaderQuerySignal answer:nil do:[
"/                Java classForName:name.
"/            ]
	].
    ].

"/    JavaClassReader classLoaderQuerySignal answer:nil "loader"
"/    do:[
"/        class := Java classForName:name.
"/        JavaClassReader postLoadActions:true.
"/    ].

    (class isNil 
    "or:[class classLoader notNil]") ifTrue:[
"/        self halt:'class: ' , name , ' not found.'.
"/        self internalError:'class: ' , name , ' not found.'.

	self 
	    throwExceptionClassName:'java.lang.ClassNotFoundException'
	    withMessage:('class: ' , name , ' not found.').
	^ nil
    ].

"/    'JAVA: findSystemClass0 - loaded: ' infoPrint. class fullName infoPrintCR.
    jClass := self javaClassObjectForClass:class.
    ^ jClass

    "Created: / 5.1.1998 / 02:53:04 / cg"
    "Modified: / 20.10.1998 / 17:28:34 / cg"
!

_ClassLoader_findSystemClass:nativeContext
    ^ self _ClassLoader_findSystemClass0:nativeContext

    "Created: / 18.11.1998 / 00:00:14 / cg"
!

_ClassLoader_getSystemResource:nativeContext asStream0:returnAsStream
    "common code for
        getSystemResourceAsStream0
        getSystemResourceAsName0"

    |jString rString dir file text inStream url|

    jString := nativeContext argAt:1.
    rString := Java as_ST_String:jString.
    Java effectiveClassPath keysAndValuesDo:[:classPathIndex :aPath |
        |f zipFile zar data |

        f := aPath asFilename.
        ((zipFile := f withSuffix:'jar') exists 
        or:[(zipFile := f withSuffix:'zip') exists]) ifTrue:[
            zar := ZipArchive oldFileNamed:zipFile.
            (Array 
                with:rString
                with:rString asLowercase
                with:rString asUppercase) 
            do:[:tryName |
                |entry|

                entry := zar findMember:tryName.
                entry notNil ifTrue:[
                    returnAsStream ifTrue:[
                        data := zar extract:tryName.
                        inStream := (Java classForName:'java.io.ByteArrayInputStream') newCleared.
                        inStream perform:#'<init>([B)V' with:data.
                        ^ inStream.
                    ].
                    url := 'systemResource:/ZIP' , (classPathIndex-1) printString , '/+/' , tryName.
                    ^ Java as_String:url.
                ]
            ]
        ] ifFalse:[
            f exists ifTrue:[
                (file := f construct:rString) exists ifTrue:[
                    (Java isExcludedFromClassPath:file) ifFalse:[

                        "/ Copy data from returned buffer into Java byte array. 

"/ self halt.
                        returnAsStream ifTrue:[
                            text := file contents asString.
                            data := text asByteArray.

                            "/ Create input stream using byte array 

                            inStream := (Java classForName:'java.io.ByteArrayInputStream') newCleared.
                            inStream perform:#'<init>([B)V' with:data.
                            ^ inStream.
                        ].
                        url := 'systemResource:/FILE/' , file pathName.
self halt.
                        ^ Java as_String:url
                    ]
                ]
            ]
        ]
    ].
    ^ nil

    "Created: / 08-01-1998 / 16:06:56 / cg"
    "Modified: / 26-12-1998 / 17:14:52 / cg"
    "Modified: / 22-11-2010 / 13:44:07 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_ClassLoader_getSystemResourceAsName0:nativeContext
    "/ java.lang.String getSystemResourceAsName0 (java.lang.String)

    ^ self
	_ClassLoader_getSystemResource:nativeContext 
	asStream0:false.
!

_ClassLoader_getSystemResourceAsStream0:nativeContext
    "/ java.lang.InputStream getSystemResourceAsStream0 (java.lang.String)

    ^ self
	_ClassLoader_getSystemResource:nativeContext 
	asStream0:true.
!

_ClassLoader_init:nativeContext
     ^ nil

    "Created: / 5.1.1998 / 02:04:43 / cg"
!

_ClassLoader_initIDs:nativeContext
    "/ introduced with jdk1.2 ... (sigh)

    "Created: / 27.1.1998 / 18:37:08 / cg"
!

_ClassLoader_resolveClass0:nativeContext 
    "resolve a new class as previously created by defineClass0"
    
    |jClassLoader jCls cls loaderStub anyUnresolved|

    jClassLoader := nativeContext receiver.
    jCls := nativeContext argAt:1.
    jCls isNil ifTrue:[
        self halt.
        ^ nil
    ].
    cls := self reflection javaClassObjectForClass:jCls.
    cls isNil ifTrue:[
        self halt.
        ^ nil
    ].
    ('JavaVM [info]: resolving class ' , cls fullName , ' ...') infoPrintCR.
    JavaClassReader classLoaderQuerySignal answer:jClassLoader
        do:[
            JavaClassReader resolveClass:cls.
            
"/        JavaClassReader postLoadActions:true.
            
            anyUnresolved := false.
            cls constantPool do:[:entry | 
                (entry isMemberOf:JavaUnresolvedClassConstant) ifTrue:[
                    self halt:'debugHalt'.
                    entry preResolve.
                    self halt:'debugHalt'.
                    anyUnresolved := true.
                ]
            ]
        ].
    anyUnresolved ifTrue:[
        jClassLoader notNil ifTrue:[
            "/ any unresolved left -> try resolving with standard loader
            JavaClassReader classLoaderQuerySignal answer:nil
                do:[
                    JavaClassReader postLoadActions:true.
                    cls constantPool do:[:entry | 
                        (entry isMemberOf:JavaUnresolvedClassConstant) ifTrue:[
                            self halt:'debugHalt'.
                            entry preResolve.
                            self halt:'debugHalt'.
                        ]
                    ]
                ]
        ].
    ].

    "Created: / 07-01-1998 / 13:12:27 / cg"
    "Modified: / 20-10-1998 / 19:01:57 / cg"
    "Modified: / 28-01-2011 / 15:28:18 / Marcel Hlopko <hlopik@gmail.com>"
!

_ClassLoader_resolveClass:nativeContext
    "void resolveClass (java.lang.Class)"

    "resolve a new class as previously created by defineClass0"

    |jClassLoader jCls cls loaderStub anyUnresolved|

    jClassLoader := nativeContext receiver.
    jCls := nativeContext argAt:1.
    jCls isNil ifTrue:[
        self halt.
        ^ nil
    ].
UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:36:01 / cg"
!

_Class_forName:nativeContext
    "get a java.lang.Class by name"

    |jClassName className cls jClass s m c loader|

    jClassName := nativeContext argAt:1.
    className := Java as_ST_String:jClassName.

    (s := nativeContext sender) notNil ifTrue:[
	(s isJavaContext) ifTrue:[
	    c := s method javaClass.
	    loader := c classLoader.
	    loader isNil ifTrue:[
"/ self halt.
	    ]
	]
    ].

    JavaClassReader classLoaderQuerySignal answer:loader
    do:[
	cls := Java classForName:className.
    ].

"/(className startsWith:'sun.awt') ifTrue:[self halt].
"/('classForName: ' , className , ' -> ') print.
"/cls notNil ifTrue:[cls fullName printCR] ifFalse:['nil' printCR].

    cls isNil ifTrue:[
	ExceptionTrace ifTrue:[
	    ('throwing exception: no such class:' , className) infoPrintCR.
	].
	ExceptionDebug ifTrue:[
	    self halt:'no such class:' , className.
	].
	self throwClassNotFoundException:className.
	"/ not proceedable
	AbortSignal raise.
	"/ not reached
	^ self
    ].

    ^ self javaClassObjectForClass:cls.

    "Modified: / 30.12.1998 / 20:12:53 / cg"
!

_Class_getClassLoader:nativeContext 
    "get a classes loader"
    
    |jClass cls loader|

    jClass := nativeContext receiver.
    cls := self reflection classForJavaClassObject:jClass.
    loader := cls classLoader.
    cls isNil ifTrue:[
        loader := JavaClassReader classLoaderQuerySignal query.
        
"/    ('JAVA: getClassLoader - ' , loader printString) infoPrintCR.
    ].
    ^ loader

    "Created: / 05-01-1998 / 02:51:59 / cg"
    "Modified: / 04-01-1999 / 17:50:15 / cg"
    "Modified: / 28-01-2011 / 15:18:57 / Marcel Hlopko <hlopik@gmail.com>"
!

_Class_getConstructor0:nativeContext
    UnimplementedNativeMethodSignal raiseRequest

    "Modified: / 12.11.1998 / 18:52:07 / cg"
    "Created: / 12.11.1998 / 18:55:42 / cg"
!

_Class_getConstructors0:nativeContext
    UnimplementedNativeMethodSignal raiseRequest

    "Modified: / 12.11.1998 / 18:52:07 / cg"
    "Created: / 12.11.1998 / 18:55:26 / cg"
!

_Class_getField0:nativeContext
    UnimplementedNativeMethodSignal raiseRequest

    "Modified: / 12.11.1998 / 18:52:07 / cg"
    "Created: / 12.11.1998 / 18:55:37 / cg"
!

_Class_getFields0:nativeContext
    UnimplementedNativeMethodSignal raiseRequest

    "Modified: / 12.11.1998 / 18:52:07 / cg"
    "Created: / 12.11.1998 / 18:55:18 / cg"
!

_Class_getMethod0:nativeContext 
    "get a method, given a name and type spec"
    
    |jClass cls jmName mName mTypes whichAccess argSig sel|

    jClass := nativeContext receiver.
    cls := self reflection javaClassObjectForClass:jClass.
    jmName := nativeContext argAt:1.
    mName := Java as_ST_String:jmName.
    mTypes := nativeContext argAt:2.
    whichAccess := nativeContext argAt:3.
    argSig := JavaMethod argSignatureFromArgTypeArray:mTypes.
    cls methodDictionary 
        keysAndValuesDo:[:sel :mthd | 
            |i1 i2 jMethod retTypeClass argTypes|

            JavaMethods notNil ifTrue:[
                (jMethod := JavaMethods at:mthd ifAbsent:nil) notNil ifTrue:[
                    ^ jMethod
                ]
            ].
            mthd name printCR.
            mName printCR.
            mthd name = mName ifTrue:[
                i1 := mthd signature indexOf:$(.
                i2 := mthd signature indexOf:$) startingAt:(i1 + 1).
                (mthd signature copyFrom:i1 + 1 to:i2 - 1) = argSig ifTrue:[
                    "/ found it - create a java.lang.reflect.Method for it.
                    jMethod := (Java at:'java.lang.reflect.Method') new.
                    jMethod instVarNamed:'clazz' put:jClass.
                    jMethod instVarNamed:'slot' put:sel.
                    jMethod instVarNamed:'name' put:jmName.
                    retTypeClass := mthd returnTypeClass.
                    retTypeClass isNil ifTrue:[
                        retTypeClass := #void
                    ].
                    argTypes := mthd argSignature.
                    argTypes := argTypes 
                                collect:[:s | 
                                    |c|

                                    c := Java at:s.
                                    self javaClassObjectForClass:(c ? s asSymbol)
                                ].
                    jMethod instVarNamed:'returnType'
                        put:(self javaClassObjectForClass:retTypeClass).
                    jMethod instVarNamed:'parameterTypes' put:argTypes.
                    JavaMethods isNil ifTrue:[
                        JavaMethods := IdentityDictionary new
                    ].
                    JavaMethods at:jMethod put:mthd.
                    JavaMethods at:mthd put:jMethod.
                    ^ jMethod.
                ].
            ].
        ].
    self halt.
    self throwExceptionClassName:'java.lang.NoSuchMethodException'
        withMessage:'not yet implemented'.
    ^ nil.

    "Modified: / 22-10-1998 / 01:54:38 / cg"
    "Modified: / 28-01-2011 / 14:36:26 / Marcel Hlopko <hlopik@gmail.com>"
!

_Class_getMethods0:nativeContext 
    "get a method, given a name and type spec"
    
    |jClass cls jmName mTypes whichAccess argSig sel methods|

    jClass := nativeContext receiver.
    cls := self reflection javaClassObjectForClass:jClass.
    
    "/ 0 = PUBLIC (i.e. includes inherited) / 1 = DECLARED here
    
    whichAccess := nativeContext argAt:1.
    methods := OrderedCollection new.
    [cls isJavaClass] whileTrue:[
        cls methodDictionary 
            keysAndValuesDo:[:sel :mthd | 
                |i1 i2 jMethod argTypes retTypeClass|

                mthd name printCR.
                i1 := mthd signature indexOf:$(.
                i2 := mthd signature indexOf:$) startingAt:(i1 + 1).
                
                "/ create a java.lang.reflect.Method for it.
                
                jMethod := (Java at:'java.lang.reflect.Method') new.
                jMethod instVarNamed:'clazz' put:jClass.
                jMethod instVarNamed:'slot' put:sel.
                jMethod instVarNamed:'name' put:(Java as_String:mthd name).
                retTypeClass := mthd returnTypeClass.
                retTypeClass isNil ifTrue:[
                    retTypeClass := #void
                ].
                argTypes := mthd argSignature.
                argTypes := argTypes 
                            collect:[:s | 
                                |c|

                                c := Java at:s.
                                self javaClassObjectForClass:(c ? s asSymbol)
                            ].
                jMethod instVarNamed:'returnType'
                    put:(self javaClassObjectForClass:retTypeClass).
                jMethod instVarNamed:'parameterTypes' put:argTypes.
                
"/ (mthd name includesString:'setName') ifTrue:[self halt].
                
                JavaMethods isNil ifTrue:[
                    JavaMethods := IdentityDictionary new
                ].
                JavaMethods at:jMethod put:mthd.
                JavaMethods at:mthd put:jMethod.
                methods add:jMethod.
            ].
        whichAccess == 1 ifTrue:[
            "/ local methods only
            cls := nil
        ] ifFalse:[
            cls := cls superclass.
        ]
    ].
    methods := methods asArray.
    ^ methods.

    "Modified: / 22-10-1998 / 01:53:58 / cg"
    "Modified: / 28-01-2011 / 14:36:58 / Marcel Hlopko <hlopik@gmail.com>"
!

_Class_getName:nativeContext 
    "get a classes name"
    
    |jClass cls nm|

    jClass := nativeContext receiver.
    cls := self reflection javaClassObjectForClass:jClass.
    cls isNil ifTrue:[
        self halt.
    ].
    cls isJavaClass ifTrue:[
        nm := (cls fullName copyReplaceAll:$/ with:$.)
    ] ifFalse:[
        cls isSymbol ifTrue:[
            nm := cls
        ] ifFalse:[
            nm := cls name
        ]
    ].
    ^ Java as_String:nm.

    "Modified: / 30-12-1998 / 21:13:50 / cg"
    "Modified: / 28-01-2011 / 15:30:34 / Marcel Hlopko <hlopik@gmail.com>"
!

_Class_getSigners:nativeContext
    UnimplementedNativeMethodSignal raiseRequest

    "Modified: / 12.11.1998 / 18:52:07 / cg"
    "Created: / 12.11.1998 / 18:55:01 / cg"
!

_Class_newInstance:nativeContext 
    "get an instance for a java.lang.Class"
    
    |jClass cls newInst|

    jClass := nativeContext receiver.
    cls := self reflection javaClassObjectForClass:jClass.
    cls classInit.
    newInst := cls newCleared.
    newInst perform:#'<init>()V'.
    ^ newInst

    "Created: / 02-01-1998 / 22:41:38 / cg"
    "Modified: / 15-01-1998 / 00:57:37 / cg"
    "Modified: / 28-01-2011 / 14:12:25 / Marcel Hlopko <hlopik@gmail.com>"
!

_Class_setSigners:nativeContext
    UnimplementedNativeMethodSignal raiseRequest

    "Modified: / 12.11.1998 / 18:52:07 / cg"
    "Created: / 12.11.1998 / 18:55:08 / cg"
!

_ColorModel_deletepData:nativeContext
    "/ void deletepData ()
    UnimplementedNativeMethodSignal raiseRequest

    "Created: / 12.11.1998 / 19:22:05 / cg"
!

_ColorModel_initIDs:nativeContext
    "/ new with jdk1.2 ...

    "Created: / 28.1.1998 / 22:19:23 / cg"
!

_Color_initIDs:nativeContext
    "/ new with jdk1.2 ...

    "Created: / 28.1.1998 / 22:19:23 / cg"
!

_Constructor_getModifiers:nativeContext
    "/ int getModifiers ()

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 02:54:38 / cg"
!

_Constructor_newInstance:nativeContext
    "/ java.lang.Object newInstance (java.lang.Object[])

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
!

_Double_doubleToLongBits:nativeContext
    |f i|

    f := nativeContext argAt:1.

    UninterpretedBytes isBigEndian ifTrue:[
	i := f basicAt:8. 
	i := i bitOr:((f basicAt:7) bitShift:8).
	i := i bitOr:((f basicAt:6) bitShift:16).
	i := i bitOr:((f basicAt:5) bitShift:24).
	i := i bitOr:((f basicAt:4) bitShift:32).
	i := i bitOr:((f basicAt:3) bitShift:40).
	i := i bitOr:((f basicAt:2) bitShift:48).
	i := i bitOr:((f basicAt:1) bitShift:56).
    ] ifFalse:[
	i := f basicAt:1. 
	i := i bitOr:((f basicAt:2) bitShift:8).
	i := i bitOr:((f basicAt:3) bitShift:16).
	i := i bitOr:((f basicAt:4) bitShift:24).
	i := i bitOr:((f basicAt:5) bitShift:32).
	i := i bitOr:((f basicAt:6) bitShift:40).
	i := i bitOr:((f basicAt:7) bitShift:48).
	i := i bitOr:((f basicAt:8) bitShift:56).
    ].

    ^ i.

    "Created: / 4.1.1998 / 01:39:12 / cg"
!

_Double_valueOf0:nativeContext
    |s d|

    s := nativeContext argAt:1.
    s notNil ifTrue:[
	s := Java as_ST_String:s.
	d := Float readFrom:s onError:nil.
    ].
    d isNil ifTrue:[
	self throwNumberFormatException.
	"/ not reached
    ].

    ^ d

    "Modified: / 8.8.1997 / 12:03:55 / cg"
    "Created: / 7.1.1998 / 11:09:43 / cg"
!

_Field_get:nativeContext
    "/ java.lang.Object get (java.lang.Object)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:04:18 / cg"
!

_Field_getBoolean:nativeContext
    "/ boolean getBoolean (java.lang.Object)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:05:16 / cg"
!

_Field_getByte:nativeContext
    "/ byte getByte (java.lang.Object)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:05:30 / cg"
!

_Field_getChar:nativeContext
    "/ char getChar (java.lang.Object)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:03:37 / cg"
!

_Field_getDouble:nativeContext
    "/ double getDouble (java.lang.Object)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:07:49 / cg"
!

_Field_getFloat:nativeContext
    "/ float getFloat (java.lang.Object)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:05:41 / cg"
!

_Field_getInt:nativeContext
    "/ int getInt (java.lang.Object)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:04:47 / cg"
!

_Field_getLong:nativeContext
    "/ long getLong (java.lang.Object)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:05:54 / cg"
!

_Field_getModifiers:nativeContext
    "/ int getModifiers ()

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:07:03 / cg"
!

_Field_getShort:nativeContext
    "/ unsigned short getShort (java.lang.Object)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:07:35 / cg"
!

_Field_set:nativeContext
    "/ void set (java.lang.Object java.lang.Object)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:04:33 / cg"
!

_Field_setBoolean:nativeContext
    "/ void setBoolean (java.lang.Object boolean)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:06:06 / cg"
!

_Field_setByte:nativeContext
    "/ void setByte (java.lang.Object byte)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:06:20 / cg"
!

_Field_setChar:nativeContext
    "/ void setChar (java.lang.Object char)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:03:48 / cg"
!

_Field_setDouble:nativeContext
    "/ void setDouble (java.lang.Object double)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:04:02 / cg"
!

_Field_setFloat:nativeContext
    "/ void setFloat (java.lang.Object float)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:06:48 / cg"
!

_Field_setInt:nativeContext
    "/ void setInt (java.lang.Object int)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:05:04 / cg"
!

_Field_setLong:nativeContext
    "/ void setLong (java.lang.Object long)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:06:37 / cg"
!

_Field_setShort:nativeContext
    "/ void setShort (java.lang.Object unsigned short)

UnimplementedNativeMethodSignal raiseRequest.

    "Modified: / 27.1.2000 / 02:53:55 / cg"
    "Created: / 27.1.2000 / 03:03:23 / cg"
!

_FileDescriptor_initSystemFD:nativeContext
    |descriptor fileNo idx myStream|

    descriptor := nativeContext argAt:1.
    fileNo := nativeContext argAt:2.

    fileNo == 0 ifTrue:[
	myStream := Stdin
    ] ifFalse:[
	fileNo == 1 ifTrue:[
	   myStream := JavaConsoleStream ? Stdout
	] ifFalse:[
	    fileNo == 2 ifTrue:[
		myStream := JavaConsoleStream ? Stderr
	    ] ifFalse:[
		self halt:'invalid fileNo given'.
		self internalError:'invalid fileNo given'.
	    ]
	]
    ].

    self setOpenFile:myStream at:fileNo.

    descriptor instVarNamed:'fd' put:fileNo.
    ^ descriptor

    "Modified: / 27.1.1998 / 18:15:28 / cg"
!

_FileDescriptor_valid:nativeContext
    "/ boolean valid ()
    |descriptor fileNo stream|

    descriptor := nativeContext receiver.
    fileNo := descriptor instVarNamed:'fd'.
    stream := self getOpenFileAt:fileNo.
    stream isNil ifTrue:[^ 0]. "/ FALSE 
    stream isOpen ifFalse:[^ 0].  "/ FALSE 

    ^ 1 "/ TRUE

    "Modified: / 11.12.1998 / 13:02:47 / cg"
!

_FileInputStream_close:nativeContext
    ^ self anyStream_close:nativeContext

    "Created: / 4.1.1998 / 17:45:23 / cg"
    "Modified: / 4.2.1998 / 15:20:46 / cg"
!

_FileInputStream_read:nativeContext
    |file byte|

    file := self validateFile:(nativeContext receiver).

    file == Stdin ifTrue:[
	file := StdinReplacementFileQuerySignal raiseRequest.
	file isNil ifTrue:[
	    ^ -1
	]
    ].

    FileIOTrace ifTrue:[
	('JAVA: read 1 byte from ' , file pathName) infoPrintCR.
    ].

    byte := file nextByte.
    byte isNil ifTrue:[
	^ -1
    ].
    ^ byte

    "Created: / 5.1.1998 / 02:17:08 / cg"
    "Modified: / 5.1.1998 / 02:17:25 / cg"
!

_FileInputStream_skip:nativeContext
    "/ long skip (long)
    |file nSkip nSkipped|

    file := self validateFile:(nativeContext receiver).
    nSkip := nativeContext argAt:1.

    file == Stdin ifTrue:[
	file := StdinReplacementFileQuerySignal raiseRequest.
	file isNil ifTrue:[
	    ^ -1
	]
    ].

    FileIOTrace ifTrue:[
	(('JAVA: skip %1 byte(s) from ' bindWith:nSkip printString) , file pathName) infoPrintCR.
    ].

    file skip:nSkip.
    ^ nSkip

    "Modified: / 27.1.1999 / 20:36:11 / cg"
!

_FileOutputStream_close:nativeContext
    ^ self anyStream_close:nativeContext

    "Created: / 13.1.1998 / 09:33:16 / cg"
    "Modified: / 4.2.1998 / 15:20:53 / cg"
!

_File_canRead0:nativeContext
    |file path f|

    file := nativeContext receiver.
    path := file instVarNamed:'path'.
    path notNil ifTrue:[
	path := Java as_ST_String:path.

	FileAccessTrace == true ifTrue:[
	    path storeString print. ' ' print. thisContext printCR
	].

	path := self fixFilename:path.
	(f := path asFilename) isReadable ifTrue:[
	    ^ 1 "/ TRUE
	]
    ].
    ^ 0 "/ FALSE

    "Created: / 4.1.1998 / 18:09:55 / cg"
    "Modified: / 27.1.1999 / 18:57:55 / cg"
!

_File_canWrite0:nativeContext
    |file path f|

    file := nativeContext receiver.
    path := file instVarNamed:'path'.
    path notNil ifTrue:[
	FileAccessTrace == true ifTrue:[
	    path storeString print. ' ' print. thisContext printCR
	].
	path := Java as_ST_String:path.
	path := self fixFilename:path.
	(f := path asFilename) isWritable ifTrue:[
	    ^ 1 "/ TRUE
	]
    ].
    ^ 0 "/ FALSE

    "Created: / 4.2.1998 / 00:19:55 / cg"
    "Modified: / 27.1.1999 / 18:57:52 / cg"
!

_File_canonPath:nativeContext
    "/ introduced with jdk1.2 ... (sigh)

    |jPath path realPath|

    jPath := nativeContext argAt:1.
    jPath isNil ifTrue:[^ jPath].

    path := Java as_ST_String:jPath.
    realPath := path asFilename pathName.

    ^ Java as_String:realPath

    "Created: / 27.1.1998 / 18:35:58 / cg"
    "Modified: / 27.1.1998 / 21:36:03 / cg"
!

_File_delete0:nativeContext
    "/ boolean delete0 ()
    |oldFile oldPath oldF|

    oldFile := nativeContext receiver.
    oldPath := oldFile instVarNamed:'path'.
    oldPath isNil ifTrue:[^ 0].    "/ FALSE

    oldPath := Java as_ST_String:oldPath.
    oldF := oldPath asFilename.

    oldF exists ifFalse:[
	^ 1 "/ TRUE
    ].

    (self checkWritePermissionOfDirectory:oldF directory message:('JAVA Security check\\Delete of ''' , oldPath , '''.\Grant permission ?'))
    ifFalse:[
	^ 0 "/ FALSE
    ].

    OperatingSystem accessDeniedErrorSignal handle:[:ex |
	^ 0 "/ FALSE
    ] do:[
	oldF delete.
	^ 1 "/ TRUE
    ].
    ^ 0 "/ FALSE

    "Modified: / 30.12.1998 / 20:15:06 / cg"
!

_File_exists0:nativeContext
    |file path f|

    file := nativeContext receiver.
    path := file instVarNamed:'path'.
    path notNil ifTrue:[
	path := Java as_ST_String:path.
	path := self fixFilename:path.
	FileAccessTrace == true ifTrue:[
	    path storeString print. ' ' print. thisContext printCR
	].
	(f := path asFilename) exists ifTrue:[
	    ^ 1 "TRUE"
	]
    ].
    ^ 0 "FALSE"

    "Created: / 5.1.1998 / 02:07:48 / cg"
    "Modified: / 27.1.1999 / 18:57:46 / cg"
!

_File_initIDs:nativeContext
    "/ introduced with jdk1.2 ... (sigh)

    "Created: / 27.1.1998 / 18:25:19 / cg"
!

_File_isAbsolute:nativeContext
    |file path f|

    file := nativeContext receiver.
    path := file instVarNamed:'path'.
    path notNil ifTrue:[
	path := Java as_ST_String:path.
	path := self fixFilename:path.
	(f := path asFilename) isAbsolute ifTrue:[
	    ^ 1 "/ TRUE
	]
    ].
    ^ 0 "/ FALSE

    "Created: / 11.1.1998 / 09:54:38 / cg"
    "Modified: / 20.10.1998 / 20:59:53 / cg"
!

_File_isDirectory0:nativeContext
    |file path f|

    file := nativeContext receiver.
    path := file instVarNamed:'path'.
    path notNil ifTrue:[
	FileAccessTrace == true ifTrue:[
	    path storeString print. ' ' print. thisContext printCR
	].
	path := Java as_ST_String:path.
	path := self fixFilename:path.
	(f := path asFilename) exists ifTrue:[
	    f isDirectory ifTrue:[^ 1 "TRUE"]
	]
    ].
    ^ 0 "FALSE"

    "Created: / 7.1.1998 / 10:31:37 / cg"
    "Modified: / 27.1.1999 / 18:58:01 / cg"
!

_File_isFile0:nativeContext
    |file path f|

    file := nativeContext receiver.
    path := file instVarNamed:'path'.
    path notNil ifTrue:[
	FileAccessTrace == true ifTrue:[
	    path storeString print. ' ' print. thisContext printCR
	].
	path := Java as_ST_String:path.
	path := self fixFilename:path.
	(f := path asFilename) exists ifTrue:[
	    f isDirectory ifFalse:[^ 1 "TRUE"]
	]
    ].
    ^ 0 "/ FALSE

    "Created: / 11.1.1998 / 11:40:22 / cg"
    "Modified: / 27.1.1999 / 18:58:04 / cg"
!

_File_lastModified0:nativeContext
    |file path f|

    file := nativeContext receiver.
    path := file instVarNamed:'path'.
    path notNil ifTrue:[
	path := Java as_ST_String:path.
	path := self fixFilename:path.
	(f := path asFilename) exists ifTrue:[
	    ^ f modificationTime getMilliseconds.
	]
    ].
    ^ 0

    "Created: / 4.2.1998 / 16:50:30 / cg"
    "Modified: / 20.10.1998 / 21:00:05 / cg"
!

_File_length0:nativeContext
    |file path f|

    file := nativeContext receiver.
    path := file instVarNamed:'path'.
    path notNil ifTrue:[
	FileAccessTrace == true ifTrue:[
	    thisContext printCR
	].
	path := Java as_ST_String:path.
	path := self fixFilename:path.
	(f := path asFilename) exists ifTrue:[
	    ^ f fileSize
	]
    ].
    ^ -1

    "Created: / 7.1.1998 / 12:18:57 / cg"
    "Modified: / 27.1.1999 / 18:57:06 / cg"
!

_File_list0:nativeContext
    |file path f files|

    file := nativeContext receiver.
    path := file instVarNamed:'path'.
    path notNil ifTrue:[
	path := Java as_ST_String:path.
	path := self fixFilename:path.
	(f := path asFilename) exists ifTrue:[
	    f isDirectory ifTrue:[
		files := f directoryContents asArray.
		files := files collect:[:nm | Java as_String:nm].
		^ files
	    ]
	]
    ].
    ^ nil

    "Created: / 14.1.1998 / 21:30:22 / cg"
    "Modified: / 20.10.1998 / 21:00:21 / cg"
!

_File_mkdir0:nativeContext
    |file path f|

    file := nativeContext receiver.
    path := file instVarNamed:'path'.
    path notNil ifTrue:[
	path := Java as_ST_String:path.
	path := self fixFilename:path.
	f := path asFilename.
	(f exists and:[f isDirectory]) ifTrue:[
	    ^ 0 "/ FALSE
	].

	FileOpenConfirmation ifTrue:[
	    (self confirm:('JAVA Security check\\Create directory ''' , path , '''.\Grant permission ?') withCRs)
	    ifFalse:[
		^ 0 "/ FALSE
	    ]
	].
	OperatingSystem accessDeniedErrorSignal handle:[:ex |
	    ^ 0 "/ FALSE
	] do:[
	    f makeDirectory.
	].
	f  exists ifTrue:[
	    f isDirectory ifTrue:[^ 1 "TRUE"]
	]
    ].
    ^ 0 "FALSE"

    "Created: / 4.2.1998 / 00:19:05 / cg"
    "Modified: / 4.12.1998 / 14:04:03 / cg"
!

_File_renameTo0:nativeContext
    "/ void renameTo0 (java.io.File)

    |oldFile newFile oldPath newPath oldF newF|

    oldFile := nativeContext receiver.
    oldPath := oldFile instVarNamed:'path'.
    oldPath isNil ifTrue:[^ 0].    "/ FALSE

    oldPath := Java as_ST_String:oldPath.
    oldF := oldPath asFilename.

    newFile := nativeContext argAt:1.
    newPath := newFile instVarNamed:'path'.
    newPath isNil ifTrue:[^ 0].    "/ FALSE
    newPath := Java as_ST_String:newPath.

    newF := newPath asFilename.

    (self checkWritePermissionOfDirectory:oldF directory message:('JAVA Security check\\Rename of ''' , oldPath , ''' to ''' , newPath , '''.\Grant permission ?'))
    ifFalse:[
	^ 0 "/ FALSE
    ].
    oldF directory pathName ~= newF directory pathName ifTrue:[
	(self checkWritePermissionOfDirectory:newF directory message:('JAVA Security check\\Rename of ''' , oldPath , ''' to ''' , newPath , '''.\Grant permission ?'))
	ifFalse:[
	    ^ 0 "/ FALSE
	].
    ].

    OperatingSystem accessDeniedErrorSignal handle:[:ex |
	^ 0 "/ FALSE
    ] do:[
	oldF renameTo:newF.
	^ 1 "/ TRUE
    ].
    ^ 0 "/ FALSE

    "Modified: / 3.12.1998 / 21:01:08 / cg"
!

_File_rmdir0:nativeContext
    "/ boolean rmdir0 ()
    UnimplementedNativeMethodSignal raiseRequest

    "Modified: / 12.11.1998 / 19:01:48 / cg"
    "Created: / 12.11.1998 / 19:03:52 / cg"
!

_Float_floatToIntBits:nativeContext
    |f i|

    f := nativeContext argAt:1.

    UninterpretedBytes isBigEndian ifTrue:[
	i := f basicAt:4. 
	i := i bitOr:((f basicAt:3) bitShift:8).
	i := i bitOr:((f basicAt:2) bitShift:16).
	i := i bitOr:((f basicAt:1) bitShift:24).
    ] ifFalse:[
	i := f basicAt:1. 
	i := i bitOr:((f basicAt:2) bitShift:8).
	i := i bitOr:((f basicAt:3) bitShift:16).
	i := i bitOr:((f basicAt:4) bitShift:24).
    ].

    ^ i.

    "Created: / 4.1.1998 / 01:25:50 / cg"
!

_Float_intBitsToFloat:nativeContet
    |i aFloat|

    i := nativeContet argAt:1.

    aFloat := ShortFloat basicNew.
    UninterpretedBytes isBigEndian ifTrue:[
	aFloat basicAt:1 put:((i bitShift:-24) bitAnd:16rFF).
	aFloat basicAt:2 put:((i bitShift:-16) bitAnd:16rFF).
	aFloat basicAt:3 put:((i bitShift:-8) bitAnd:16rFF).
	aFloat basicAt:4 put:(i bitAnd:16rFF).
    ] ifFalse:[
	aFloat basicAt:1 put:(i bitAnd:16rFF).
	aFloat basicAt:2 put:((i bitShift:-8) bitAnd:16rFF).
	aFloat basicAt:3 put:((i bitShift:-16) bitAnd:16rFF).
	aFloat basicAt:4 put:((i bitShift:-24) bitAnd:16rFF).
    ].

    ^ aFloat.

    "Created: / 13.1.1998 / 23:03:36 / cg"
    "Modified: / 13.1.1998 / 23:05:01 / cg"
!

_FontDescriptor_initIDs:nativeContext
    "/ new with jdk1.2 ...

    "Created: / 28.1.1998 / 22:30:52 / cg"
!

_Font_initIDs:nativeContext
    "/ new with jdk1.2 ...

    "Created: / 27.1.1998 / 21:43:25 / cg"
!

_GifImageDecoder_parseImage:nativeContext
    |decoder width height bool1 depth subHdrBytes dstBytes i1 i2 colorModel
     stream byte compressedData compressedSize index count data 
     leftOffs topOffs codeLen flags pixelStore clrModel t buffSize 
     countGot countGot2|

    decoder := nativeContext receiver.

    i1 := nativeContext argAt:1.
    i2 := nativeContext argAt:2.
    width := nativeContext argAt:3.
    height := nativeContext argAt:4.
    bool1 := nativeContext argAt:5.
    depth := nativeContext argAt:6.
    subHdrBytes := nativeContext argAt:7.
    dstBytes := nativeContext argAt:8.
    colorModel := nativeContext argAt:9.

    leftOffs := subHdrBytes wordAt:1 MSB:false.
    topOffs := subHdrBytes wordAt:3 MSB:false.
    width := subHdrBytes wordAt:5 MSB:false.
    height := subHdrBytes wordAt:7 MSB:false.
    flags := subHdrBytes at:9.
    codeLen := subHdrBytes at:10.

    stream := decoder instVarNamed:'input'.
    pixelStore := decoder instVarNamed:'store'.
    pixelStore isNil ifTrue:[
	^ 0
    ].

    buffSize := (width * height // 2) max:4096.
    compressedData := ByteArray uninitializedNew:buffSize.
    "get compressed data"
    index := 1.
    count := stream perform:#'read()I'.

    [count notNil and:[count > 0]] whileTrue:[
	(index + count) > buffSize ifTrue:[
	    t := ByteArray uninitializedNew:(buffSize * 2).
	    t replaceFrom:1 to:buffSize with:compressedData startingAt:1.
	    compressedData := t.
	    buffSize := buffSize * 2.
	].
	[count ~~ 0] whileTrue:[
	    countGot := stream 
			perform:#'read([BII)I' 
			with:compressedData
			with:index-1
			with:count.

	    countGot > 0 ifTrue:[
		count := count - countGot.
		index := index + countGot.
	    ] ifFalse:[
		count := -1.
	    ]
	].

	count >= 0 ifTrue:[
	    count := stream perform:#read.
	]
    ].
    compressedSize := index - 1.

    data := pixelStore perform:#'allocateLines(I)Ljava/lang/Object;' with:height.
    (data isMemberOf:ByteArray) ifFalse:[
	self halt.
	^ 0.
    ].
"/    'GIFReader: decompressing ...' infoPrintCR.


    GIFReader 
	decompressGIFFrom:compressedData
	count:compressedSize
	into:data
	startingAt:1
	codeLen:(codeLen + 1).

    clrModel := pixelStore instVarNamed:'colormodel'.

    pixelStore 
	perform:#'setPixels(IIII[BII)Z'
	withArguments:
	    (Array 
		with:0        "/ x
		with:0        "/ y
		with:width    "/ w
		with:height   "/ h
		with:data
		with:0        "/ offs
		with:width).   "/ scanSize

    pixelStore  perform:#'imageComplete()V'.
"/        perform:#'imageComplete(I)V' 
"/        with:((Java at:'java.awt.image.ImageConsumer') instVarNamed:'STATICIMAGEDONE').

"/ self internalError:'breakPoint'.
    ^ 1 "/ true

    "Modified: / 10.4.1998 / 14:31:59 / cg"
!

_ImageRepresentation_disposeImage:nativeContext
    |imgRep img|

    imgRep := nativeContext receiver.

    img := imgRep instVarNamed:'pData'.
    (img notNil and:[img ~~ 0]) ifTrue:[
	ImageStretchCache notNil ifTrue:[
	    ImageStretchCache removeKey:img ifAbsent:nil.
	]
    ].

    imgRep instVarNamed:'pData' put:0.
"/    self halt.

    "Created: / 7.1.1998 / 22:31:46 / cg"
    "Modified: / 17.1.1998 / 13:26:55 / cg"
!

_ImageRepresentation_finish:nativeContext
    |imgRep bool|

    imgRep := nativeContext receiver.
    bool := nativeContext argAt:1.
"/ self halt.
"/    'JAVA: ImageRepresentation_finish ignored for now' infoPrintCR.

    ^ 1 "/ true

    "Created: / 8.1.1998 / 00:11:40 / cg"
    "Modified: / 6.2.1998 / 02:12:54 / cg"
!

_ImageRepresentation_imageDraw:nativeContext
    |imgRep x y img deviceImage jGraphics gc clr|

    imgRep := nativeContext receiver.
    img := imgRep instVarNamed:'pData'.
    (img isNil or:[img == 0]) ifTrue:[
	"/ self halt.
	^ self.
    ].
    jGraphics := nativeContext argAt:1.
    gc := jGraphics instVarNamed:'pData'.
    gc realized ifFalse:[^ self].

    x := nativeContext argAt:2.
    y := nativeContext argAt:3.
    clr := nativeContext argAt:4.

    deviceImage := img onDevice:gc device.
    deviceImage ~~ img ifTrue:[
	imgRep instVarNamed:'pData' put:deviceImage.
    ].
    gc realized ifFalse:[^ self].
    deviceImage displayOn:gc x:x y:y.
    ^ 1.

    "Created: / 13.1.1998 / 13:32:28 / cg"
    "Modified: / 25.11.1998 / 15:36:38 / cg"
!

_ImageRepresentation_imageStretch:nativeContext
    |imgRep x1 y1 x2 y2 srcX1 srcY1 w h 
     img deviceImage jGraphics gc clr stretchWidth stretchHeight|

    imgRep := nativeContext receiver.
    img := imgRep instVarNamed:'pData'.
    (img isNil or:[img == 0]) ifTrue:[
	"/ self halt.
	^ self.
    ].

    jGraphics := nativeContext argAt:1.
    gc := jGraphics instVarNamed:'pData'.
    gc realized ifFalse:[^ self].

    x1 := nativeContext argAt:2.
    y1 := nativeContext argAt:3.
    x2 := nativeContext argAt:4.
    y2:= nativeContext argAt:5.
    srcX1 := nativeContext argAt:6.
    srcY1 := nativeContext argAt:7.
    w := nativeContext argAt:8.
    h := nativeContext argAt:9.
    clr := nativeContext argAt:10.

    (srcX1 ~~ 0 or:[srcY1 ~~ 0]) ifTrue:[
	self halt.
	^ self.
    ].
    (w ~~ img width or:[h ~~ img height]) ifTrue:[
	self halt.
	^ self
    ].

    "/ TODO: remember magnified images somewhere for a while,
    "/ to avoid repeated action ...

    stretchWidth := (x2-x1).
    stretchHeight := (y2-y1).

    (stretchWidth == img width
    and:[stretchHeight == img height]) ifTrue:[
	deviceImage := img onDevice:gc device.
	deviceImage ~~ img ifTrue:[
	    imgRep instVarNamed:'pData' put:deviceImage.
	].
    ] ifFalse:[
	ImageStretchCache notNil ifTrue:[
	    deviceImage := ImageStretchCache at:img ifAbsent:nil.
	].
	(deviceImage isNil 
	or:[deviceImage width ~~ stretchWidth
	or:[deviceImage height ~~ stretchHeight]]) ifTrue:[
	    deviceImage := (img magnifiedTo:stretchWidth@stretchHeight) onDevice:gc device.
	    ImageStretchCache isNil ifTrue:[
		ImageStretchCache := WeakIdentityDictionary new.
	    ].
	    ImageStretchCache at:img put:deviceImage
	].
    ].
    deviceImage displayOn:gc x:x1 y:y1

    "Created: / 13.1.1998 / 13:32:28 / cg"
    "Modified: / 15.1.1998 / 13:14:47 / cg"
!

_ImageRepresentation_offscreenInit:nativeContext
    |imgRep jclr w h form screenDevice|

    imgRep := nativeContext receiver.
    jclr := nativeContext argAt:1.

    w := imgRep instVarNamed:'width'.
    h := imgRep instVarNamed:'height'.

    screenDevice := Screen current.
    form := Form width:w height:h depth:(screenDevice depth) on:screenDevice.

    imgRep instVarNamed:'pData' put:form.
    "/ self halt.

    "Created: / 7.1.1998 / 22:31:46 / cg"
    "Modified: / 17.1.1998 / 12:36:43 / cg"
!

_ImageRepresentation_setBytePixels:nativeContext
    |imgRep x y w h clrModel bytes offs i2
     img depth cmap rgbMap opaque transparentColorIndex
     scanLineWidth nBytes srcIdx dstIdx|

    imgRep := nativeContext receiver.
    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    w := nativeContext argAt:3.
    h := nativeContext argAt:4.
    clrModel := nativeContext argAt:5.
    bytes := nativeContext argAt:6.
    offs := nativeContext argAt:7.  "/ offset ??
    scanLineWidth := nativeContext argAt:8.

    depth := clrModel instVarNamed:'pixel_bits'.
    (clrModel instVarNamed:'map_size') ~~ 0 ifTrue:[
	rgbMap := clrModel instVarNamed:'rgb'.
	cmap := Array new:rgbMap size.
	rgbMap 
	    keysAndValuesDo:[:idx :rgb |
		cmap at:idx put:(Color rgbValue:(rgb bitAnd:16rFFFFFF))
	    ].        
    ].

    opaque := (clrModel instVarNamed:'opaque') ~~ 0.
    opaque ifFalse:[
	transparentColorIndex := clrModel instVarNamed:'transparent_index'
    ].

    img := imgRep instVarNamed:'pData'.
    (img isNil or:[img == 0]) ifFalse:[
"/        self halt
    ].

    (offs ~~ 0 or:[scanLineWidth ~~ w]) ifTrue:[
	nBytes := ByteArray new:w*h.
	srcIdx := offs+1.
	dstIdx := 1.
	1 to:h do:[:y |
	    nBytes replaceFrom:dstIdx to:(dstIdx+w-1) with:bytes startingAt:srcIdx.
	    srcIdx := srcIdx + scanLineWidth.
	    dstIdx := dstIdx + w.
	].
	bytes := nBytes.
    ].
    img := Image width:w height:h depth:depth fromArray:bytes.
    cmap notNil ifTrue:[
	img colorMap:cmap.
	img photometric:#palette
    ].
    opaque ifFalse:[
	img mask:(ImageReader 
		    buildMaskFromColor:transparentColorIndex 
		    for:bytes
		    width:w
		    height:h)
    ].

    imgRep instVarNamed:'pData' put:img.
    ^ 1.

    "Created: / 7.1.1998 / 22:31:46 / cg"
    "Modified: / 21.10.1998 / 00:35:45 / cg"
!

_ImageRepresentation_setIntPixels:nativeContext
    |imgRep x y w h clrModel ints offs scanLineWidth
     img depth cmap rgbMap opaque transparentColorIndex
     bytes srcIdx dstIdx val red green blue
     redMask greenMask blueMask redShift greenShift blueShift|

    imgRep := nativeContext receiver.
    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    w := nativeContext argAt:3.
    h := nativeContext argAt:4.
    clrModel := nativeContext argAt:5.
    ints := nativeContext argAt:6.
    offs := nativeContext argAt:7.  "/ offset ??
    scanLineWidth := nativeContext argAt:8.  "/ scanLineWidth ??
    opaque := false.
offs ~~ 0 ifTrue:[
 self halt
].

    depth := clrModel instVarNamed:'pixel_bits'.
    clrModel class == (Java at:'java.awt.image.DirectColorModel') ifTrue:[
    ] ifFalse:[
	(clrModel instVarNamed:'map_size') ~~ 0 ifTrue:[
	    rgbMap := clrModel instVarNamed:'rgb'.
	    cmap := Array new:rgbMap size.
	    rgbMap 
		keysAndValuesDo:[:idx :rgb |
		    cmap at:idx put:(Color rgbValue:(rgb bitAnd:16rFFFFFF))
		].        
	].
	opaque := (clrModel instVarNamed:'opaque') ~~ 0.
	opaque ifFalse:[
	    transparentColorIndex := clrModel instVarNamed:'transparent_index'
	].
    ].

    img := imgRep instVarNamed:'pData'.
    (img isNil or:[img == 0]) ifFalse:[
"/        self halt.
    ].

    depth == 32 ifTrue:[
	"/ temporary kludge - ony use 24 bits/pixel
	bytes := ByteArray new:w*h*3.
	srcIdx := 1.
	dstIdx := 1.
	redMask := clrModel instVarNamed:'red_mask'.
	greenMask := clrModel instVarNamed:'green_mask'.
	blueMask := clrModel instVarNamed:'blue_mask'.
	redShift := (clrModel instVarNamed:'red_offset') negated.
	greenShift := (clrModel instVarNamed:'green_offset') negated.
	blueShift := (clrModel instVarNamed:'blue_offset') negated.

	1 to:h do:[:y |
	    1 to:w do:[:x |
		val := ints at:srcIdx.
		red := (val bitAnd:redMask) bitShift:redShift.
		green := (val bitAnd:greenMask) bitShift:greenShift.
		blue := (val bitAnd:blueMask) bitShift:blueShift.
		bytes at:dstIdx put:red.
		bytes at:dstIdx+1 put:green.
		bytes at:dstIdx+2 put:blue.
		dstIdx := dstIdx + 3.
		srcIdx := srcIdx + 1.
	    ].
	    srcIdx := srcIdx + (scanLineWidth - w).
	].
	img := Depth24Image width:w height:h depth:24 fromArray:bytes.
	img photometric:#rgb.
    ] ifFalse:[
	scanLineWidth ~~ w ifTrue:[
	    self halt
	].
	img := Image width:w height:h depth:depth fromArray:ints.
	cmap notNil ifTrue:[
	    img colorMap:cmap.
	    img photometric:#palette
	] ifFalse:[
	    img photometric:#rgb
	].
    ].
    opaque ifFalse:[
	img mask:(ImageReader 
		    buildMaskFromColor:transparentColorIndex 
		    for:ints
		    width:w
		    height:h)
    ].

    imgRep instVarNamed:'pData' put:img.
    ^ 1.

    "Created: / 1.2.1998 / 17:38:47 / cg"
    "Modified: / 21.10.1998 / 00:35:37 / cg"
!

_InetAddressImpl_getHostByAddr:nativeContext
    "/ java.lang.String getHostByAddr (int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:08:04 / cg"
!

_InetAddressImpl_getInetFamily:nativeContext
    "/ self unimplementedNativeMethod.
    ^ 0

    "Modified: / 15.8.1997 / 17:04:43 / cg"
    "Created: / 5.1.1998 / 02:05:48 / cg"
!

_InetAddressImpl_getLocalHostName:nativeContext
    ""

    |hostName|

    hostName := OperatingSystem getHostName.

    ^ (Java as_String:hostName).

    "Modified: / 7.8.1997 / 21:16:55 / cg"
    "Created: / 5.1.1998 / 02:07:03 / cg"
!

_InetAddressImpl_lookupAllHostAddr:nativeContext
    ""

    |jAddrImpl jHostName hostName addrBytes|

    jAddrImpl := nativeContext receiver.
    jHostName := nativeContext argAt:1.

    hostName := Java as_ST_String:jHostName.
    addrBytes := Socket ipAddressOfHost:hostName.
    addrBytes isNil ifTrue:[
	addrBytes := #[0 0 0 0] copy
    ].
    ^ Array with:addrBytes

    "Modified: / 8.8.1997 / 12:04:25 / cg"
    "Created: / 7.1.1998 / 18:51:31 / cg"
!

_InetAddressImpl_makeAnyLocalAddress:nativeContext
    ""

    |jAddrImpl jAddr hostName addrBytes address|

    jAddrImpl := nativeContext receiver.
    jAddr := nativeContext argAt:1.

    hostName := OperatingSystem getHostName.
    addrBytes := Socket ipAddressOfHost:hostName.
    addrBytes isNil ifTrue:[
	addrBytes := #[127 0 0 0].
    ].
    "/ MSB first into an integer.
    address := (addrBytes at:1).
    address := (address bitShift:8) bitOr:(addrBytes at:2).
    address := (address bitShift:8) bitOr:(addrBytes at:3).
    address := (address bitShift:8) bitOr:(addrBytes at:4).

    jAddr instVarNamed:'hostName' put:(Java as_String:hostName).
    jAddr instVarNamed:'address' put:address.
    jAddr instVarNamed:'family' put:0.

    ^ nil

    "Created: / 5.1.1998 / 02:06:27 / cg"
    "Modified: / 21.10.1998 / 03:30:29 / cg"
!

_InetAddress_getInetFamily:nativeContext
    "/ self unimplementedNativeMethod.
    ^ 0

    "Modified: / 15.8.1997 / 17:04:43 / cg"
    "Created: / 17.11.1998 / 23:54:38 / cg"
!

_InetAddress_getLocalHostName:nativeContext
    ""

    |hostName|

    hostName := OperatingSystem getHostName.

    ^ Java as_String:hostName.

    "Modified: / 7.8.1997 / 21:16:55 / cg"
    "Created: / 17.11.1998 / 23:54:54 / cg"
!

_InetAddress_lookupAllHostAddr:nativeContext
    ""

    |jAddrImpl jHostName hostName addrBytes|

    jAddrImpl := nativeContext receiver.
    jHostName := nativeContext argAt:1.

    hostName := Java as_ST_String:jHostName.
    addrBytes := Socket ipAddressOfHost:hostName.
    addrBytes isNil ifTrue:[
	addrBytes := #[0 0 0 0] copy
    ].
    ^ Array with:addrBytes

    "Modified: / 8.8.1997 / 12:04:25 / cg"
    "Created: / 17.11.1998 / 23:56:10 / cg"
!

_InetAddress_lookupHostByAddr:nativeContext
    "java.lang.Object[] lookupHostByAddr (int)"

UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 02:59:22 / cg"
!

_InetAddress_lookupHostByName:nativeContext
    "java.lang.Object[] lookupHostByName (java.lang.String)"

UnimplementedNativeMethodSignal raise.

    "Modified: / 27.1.2000 / 02:58:53 / cg"
!

_InetAddress_makeAnyLocalAddress:nativeContext
    ""

    |jAddrImpl jAddr hostName addrBytes address|

    jAddrImpl := nativeContext receiver.
    jAddr := nativeContext argAt:1.

    hostName := OperatingSystem getHostName.
    addrBytes := Socket ipAddressOfHost:hostName.
    addrBytes isNil ifTrue:[
	addrBytes := #[127 0 0 0].
    ].
    "/ MSB first into an integer.
    address := (addrBytes at:1).
    address := (address bitShift:8) bitOr:(addrBytes at:2).
    address := (address bitShift:8) bitOr:(addrBytes at:3).
    address := (address bitShift:8) bitOr:(addrBytes at:4).

    jAddr instVarNamed:'hostName' put:(Java as_String:hostName).
    jAddr instVarNamed:'address' put:address.
    jAddr instVarNamed:'family' put:0.

    ^ nil

    "Modified: / 21.10.1998 / 03:30:29 / cg"
    "Created: / 17.11.1998 / 23:54:00 / cg"
!

_Inflater_end0:nativeContext
    "/ void end0 ()

UnimplementedNativeMethodSignal raise.

    "Modified: / 27.1.2000 / 03:08:47 / cg"
    "Created: / 27.1.2000 / 03:11:21 / cg"
!

_Inflater_getAdler0:nativeContext
    "/ int getAdler0 ()

UnimplementedNativeMethodSignal raise.

    "Modified: / 27.1.2000 / 03:08:47 / cg"
    "Created: / 27.1.2000 / 03:12:15 / cg"
!

_Inflater_getTotalIn0:nativeContext
    "/ int getTotalIn0 ()

UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 03:10:50 / cg"
    "Modified: / 27.1.2000 / 03:11:08 / cg"
!

_Inflater_getTotalOut0:nativeContext
    "/ int getTotalOut0 ()

UnimplementedNativeMethodSignal raise.

    "Modified: / 27.1.2000 / 03:08:47 / cg"
    "Created: / 27.1.2000 / 03:12:01 / cg"
!

_Inflater_inflate0:nativeContext
    "/ int inflate0 (byte[] int int)

UnimplementedNativeMethodSignal raise.

    "Modified: / 27.1.2000 / 03:08:47 / cg"
    "Created: / 27.1.2000 / 03:11:39 / cg"
!

_Inflater_reset0:nativeContext
    "/ void reset0 ()

UnimplementedNativeMethodSignal raise.

    "Modified: / 27.1.2000 / 03:08:47 / cg"
    "Created: / 27.1.2000 / 03:11:02 / cg"
!

_Inflater_setDictionary0:nativeContext
    "/ void setDictionary0 (byte[] int int)

UnimplementedNativeMethodSignal raise.

    "Modified: / 27.1.2000 / 03:08:47 / cg"
    "Created: / 27.1.2000 / 03:10:33 / cg"
!

_InputThread_run:nativeContext
    self _WToolkit_eventLoop:nativeContext.

    "Created: / 28.1.1998 / 22:34:47 / cg"
    "Modified: / 28.1.1998 / 22:35:16 / cg"
!

_Introspector_getMethodDescriptor:nativeContext
    "java.lang.String getMethodDescriptor (java.lang.reflect.Method)"

UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 02:47:43 / cg"
!

_Introspector_getMethodParameterCount:nativeContext
    "int getMethodParameterCount (java.lang.reflect.Method)"

UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 02:49:15 / cg"
!

_Introspector_getPublicDeclaredMethods0:nativeContext
    "java.lang.reflect.Method[] getPublicDeclaredMethods0 (java.lang.Class)"

UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 02:48:49 / cg"
!

_JPEGImageDecoder_readImage:nativeContext
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 18:53:30 / cg"
    "Modified: / 12.11.1998 / 18:53:40 / cg"
!

_MButtonPeer_create:nativeContext
    ^ self _WButtonPeer_create:nativeContext
!

_MCanvasPeer_create:nativeContext
    |jCanvasPeer jFrame frame subView|

    jCanvasPeer := nativeContext receiver.

    jFrame := nativeContext argAt:1.
    jFrame isNil ifTrue:[
	self halt:'no frame in canvasPeer create'.
	self internalError:'no frame in canvasPeer create'.     
	^ self.
    ].
    frame := jFrame instVarNamed:'pData'.

    subView := JavaView in:frame.
    subView delegate:self.
    subView javaPeer:jCanvasPeer.

    self createdWindowsView:subView for:jCanvasPeer.

    WindowCreationTrace == true ifTrue:[
	'WCanvasPeer_create: ' print. frame print. ' -> ' print. subView printNL.
    ].

    "Modified: / 16.1.1998 / 13:40:00 / cg"
    "Created: / 18.11.1998 / 00:14:44 / cg"
!

_MComponentPeer_cacheInit:nativeContext

    "Created: / 28.1.1998 / 22:22:30 / cg"
!

_MComponentPeer_handleEvent:nativeContext
    ^ self _WComponentPeer_handleEvent:nativeContext

    "Created: / 18.11.1998 / 00:21:17 / cg"
!

_MComponentPeer_nativeHandleEvent:nativeContext
    ^ self _WComponentPeer_nativeHandleEvent:nativeContext
!

_MComponentPeer_pHide:nativeContext
    ^ self _WComponentPeer_hide:nativeContext

    "Created: / 18.11.1998 / 00:15:18 / cg"
!

_MComponentPeer_pInitialize:nativeContext

    "Created: / 28.1.1998 / 22:27:25 / cg"
!

_MComponentPeer_pReshape:nativeContext
    self commonReshapeComponent:nativeContext

    "Created: / 18.11.1998 / 00:18:17 / cg"
!

_MComponentPeer_pSetBackground:nativeContext
    |view jClr rgb clr|

    view := self viewForWPeer:nativeContext.
    jClr := nativeContext argAt:1.
    rgb := jClr instVarNamed:'value'.

    clr := Color rgbValue:rgb.

    clr := clr on:(view device).
    (view isKindOf:ScrollableView) ifTrue:[
        view := view scrolledView
    ].
    view viewBackground:clr.
    view backgroundPaint:clr.
!

_MComponentPeer_pSetFont:nativeContext
    |view jFont stFont name style size|

    view := self viewForWPeer:nativeContext.
    jFont := nativeContext argAt:1.

    stFont := jFont instVarNamed:'pData'.
    (stFont isNil or:[stFont == 0]) ifTrue:[
        name := jFont instVarNamed:'name'.
        style := jFont instVarNamed:'style'.
        size := jFont instVarNamed:'size'.

        stFont := self replacementFontFor:(Java as_ST_String:name) style:style size:size.
        jFont instVarNamed:'pData' put:stFont.
    ].
    view font:stFont.

    ^ nil
!

_MComponentPeer_pSetForeground:nativeContext
    |view jClr rgb clr|

    view := self viewForWPeer:nativeContext.
    jClr := nativeContext argAt:1.
    rgb := jClr instVarNamed:'value'.

    clr := Color rgbValue:rgb.

    clr := clr on:(view device).

    (view isKindOf:ScrollableView) ifTrue:[
        view := view scrolledView
    ].
    view foregroundColor:clr.
!

_MComponentPeer_pShow:nativeContext
    |view|

    view := self viewForWPeer:nativeContext.

    "/ frame views are under my browsers own control
    (view isMemberOf:JavaEmbeddedFrameView) ifFalse:[
	view beVisible.
	view realize.
    ].

"/    view windowGroup notNil ifTrue:[
"/        windowServer addGroup:(view windowGroup)
"/    ].

    ^ nil

"/ self halt.

    "Modified: / 25.1.1998 / 09:54:07 / cg"
    "Created: / 18.11.1998 / 00:21:51 / cg"
!

_MComponentPeer_setBackground:nativeContext
    |jClr rgb clr view|

    view := self viewForWPeer:nativeContext.

    jClr := nativeContext argAt:1.
    rgb := jClr instVarNamed:'value'.
"/ self halt.
    clr := Color rgbValue:rgb.


    clr := clr on:(view device).

    (view isKindOf:ScrollableView) ifTrue:[
	view := view scrolledView
    ].
    view viewBackground:clr.
    view backgroundPaint:clr.

    "Created: / 17.11.1998 / 23:49:41 / cg"
!

_MComponentPeer_setCursor:nativeContext

    "Created: / 28.1.1998 / 22:27:35 / cg"
!

_MComponentPeer_setFont:nativeContext
    |view|

    view := self viewForWPeer:nativeContext.
"/ self halt.

    "Modified: / 25.1.1998 / 01:22:19 / cg"
    "Created: / 17.11.1998 / 23:43:48 / cg"
!

_MComponentPeer_setForeground:nativeContext
    |jClr rgb clr view|

    view := self viewForWPeer:nativeContext.

    jClr := nativeContext argAt:1.
    rgb := jClr instVarNamed:'value'.
"/ self halt.
    clr := Color rgbValue:rgb.

    clr := clr on:(view device).

    view paint:clr.

    "Created: / 17.11.1998 / 23:50:31 / cg"
    "Modified: / 17.11.1998 / 23:57:29 / cg"
!

_MFramePeer_create:nativeContext
    ^ self _WFramePeer_create:nativeContext

    "Created: / 28.1.1998 / 22:25:44 / cg"
!

_MFramePeer_getWindowBackgroundColor:nativeContext
    ^ View defaultViewBackgroundColor rgbValue.

    "Created: / 17.11.1998 / 23:55:42 / cg"
!

_MFramePeer_pHide:nativeContext
    ^ self _WComponentPeer_hide:nativeContext

    "Created: / 28.1.1998 / 22:27:04 / cg"
!

_MFramePeer_pReshape:nativeContext
    self commonReshapeComponent:nativeContext

    "Created: / 28.1.1998 / 22:28:00 / cg"
    "Modified: / 28.1.1998 / 22:29:34 / cg"
!

_MFramePeer_pSetTitle:nativeContext
    self _WWindowPeer__setTitle:nativeContext

    "Created: / 28.1.1998 / 22:30:23 / cg"
!

_MFramePeer_pShow:nativeContext
    |view|

    view := self viewForWPeer:nativeContext.

    "/ frame views are under my browsers own control
    (view isMemberOf:JavaEmbeddedFrameView) ifFalse:[
	view beVisible.
	view realize.
    ].

"/    view windowGroup notNil ifTrue:[
"/        windowServer addGroup:(view windowGroup)
"/    ].

    ^ nil

"/ self halt.

    "Modified: / 25.1.1998 / 09:54:07 / cg"
    "Created: / 18.11.1998 / 00:19:59 / cg"
!

_MFramePeer_setInsets:nativeContext

    "Created: / 17.11.1998 / 23:55:32 / cg"
!

_MFramePeer_setResizable:nativeContext
    |view onOff|

    view := self viewForWPeer:nativeContext.

    onOff := (nativeContext argAt:1) == 1.
    view isTopView ifTrue:[
	onOff ifTrue:[
	    view minExtent:10@10.
	    view maxExtent:(Screen current extent).
	] ifFalse:[
	    view minExtent:view extent.
	    view maxExtent:view extent.
	]
    ] ifFalse:[
	(view isMemberOf:JavaEmbeddedFrameView) ifFalse:[
	    self halt.
	]
    ].

"/ 'JAVA: WWindowPeer_setResizable: ' print. view print. ' yes/no: ' print. onOff printNL.

    ^ nil

    "Modified: / 16.1.1998 / 18:08:00 / cg"
    "Created: / 17.11.1998 / 23:51:45 / cg"
!

_MToolkit_callbackLoop:nativeContext
    |toolKit|

    toolKit := nativeContext receiver.
^ self.
self halt.
    self wakeup:toolKit.
self halt.

    (JavaEventThread notNil and:[JavaEventThread isDead not]) ifTrue:[
	'JavaVM [warning]: oops - two threads executing eventLoop' errorPrintCR.
    ].

    JavaEventThread := Processor activeProcess.
    [
	[true] whileTrue:[
	    AbortSignal handle:[:ex |
		ex return
	    ] do:[
		self doWindowsEventThread.
	    ]
	].
    ] valueNowOrOnUnwindDo:[
	JavaEventThread := nil.
    ].

    "Created: / 17.11.1998 / 23:58:33 / cg"
    "Modified: / 8.1.1999 / 17:08:35 / cg"
!

_MToolkit_eventLoop:nativeContext
    |toolKit|

    (JavaEventThread notNil and:[JavaEventThread isDead not]) ifTrue:[
	'JavaVM [warning]: oops - two threads executing eventLoop' errorPrintCR.
    ].

    toolKit := nativeContext receiver.

    self wakeup:toolKit.
self halt.

    JavaEventThread := Processor activeProcess.
    [
	[true] whileTrue:[
	    AbortSignal handle:[:ex |
		ex return
	    ] do:[
		self doWindowsEventThread.
	    ]
	].
    ] valueNowOrOnUnwindDo:[
	JavaEventThread := nil.
    ].

    "Created: / 17.11.1998 / 23:04:29 / cg"
    "Modified: / 8.1.1999 / 17:08:21 / cg"
!

_MToolkit_init:nativeContext

    "Created: / 28.1.1998 / 22:21:54 / cg"
!

_MToolkit_loadSystemColors:nativeContext
    ^ self _WToolkit_loadSystemColors:nativeContext
!

_MToolkit_run:nativeContext

    "Created: / 28.1.1998 / 22:22:10 / cg"
!

_Math_IEEEremainder:nativeContext
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 18:52:36 / cg"
!

_Math_acos:nativeContext
    "arc cosine"

    |dVal|

    dVal := nativeContext argAt:1.
"/    (nativeContext argAt:2) ~~ DUMMY_DOUBLE_HIGHWORD ifTrue:[
"/        dVal isReal ifTrue:[
"/            'JAVAVM [info]: missing double flag in Math>>acos' infoPrintCR.
"/        ] ifFalse:[
"/            self halt:'expected double arg'
"/        ]
"/    ].
    ^ dVal arcCos

    "Created: / 7.5.1998 / 00:34:50 / cg"
    "Modified: / 11.11.1998 / 15:08:20 / cg"
!

_Math_asin:nativeContext
    "arc sine"

    |dVal|

    dVal := nativeContext argAt:1.
"/    (nativeContext argAt:2) ~~ DUMMY_DOUBLE_HIGHWORD ifTrue:[
"/        dVal isReal ifTrue:[
"/            'JAVAVM [info]: missing double flag in Math>>asin' infoPrintCR.
"/        ] ifFalse:[
"/            self halt:'expected double arg'
"/        ]
"/    ].
    ^ dVal arcSin

    "Created: / 7.5.1998 / 00:34:26 / cg"
    "Modified: / 11.11.1998 / 15:08:15 / cg"
!

_Math_atan2:nativeContext
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 18:52:52 / cg"
!

_Math_atan:nativeContext
    "arc tangens"

    |dVal|

    dVal := nativeContext argAt:1.
"/    (nativeContext argAt:2) ~~ DUMMY_DOUBLE_HIGHWORD ifTrue:[
"/        dVal isReal ifTrue:[
"/            'JAVAVM [info]: missing double flag in Math>>atan' infoPrintCR.
"/        ] ifFalse:[
"/            self halt:'expected double arg'
"/        ]
"/    ].
    ^ dVal arcTan

    "Created: / 6.2.1998 / 01:24:12 / cg"
    "Modified: / 11.11.1998 / 15:08:11 / cg"
!

_Math_ceil:nativeContext
    "ceiling"

    |dVal|

    dVal := nativeContext argAt:1.
"/    (nativeContext argAt:2) ~~ DUMMY_DOUBLE_HIGHWORD ifTrue:[
"/        dVal isReal ifTrue:[
"/            'JAVAVM [info]: missing double flag in Math>>ceil' infoPrintCR.
"/        ] ifFalse:[
"/            self halt:'expected double arg'
"/        ]
"/    ].
    ^ dVal ceilingAsFloat

    "Created: / 7.1.1998 / 15:43:00 / cg"
    "Modified: / 11.11.1998 / 15:08:04 / cg"
!

_Math_cos:nativeContext
    "cosine"

    |dVal|

    dVal := nativeContext argAt:1.
"/    (nativeContext argAt:2) ~~ DUMMY_DOUBLE_HIGHWORD ifTrue:[
"/        dVal isReal ifTrue:[
"/            'JAVAVM [info]: missing double flag in Math>>cos' infoPrintCR.
"/        ] ifFalse:[
"/            self halt:'expected double arg'
"/        ]
"/    ].
    ^ dVal cos

    "Created: / 7.1.1998 / 15:41:30 / cg"
    "Modified: / 11.11.1998 / 15:07:59 / cg"
!

_Math_exp:nativeContext
    "exponential"

    |dVal|

    dVal := nativeContext argAt:1.
"/    (nativeContext argAt:2) ~~ DUMMY_DOUBLE_HIGHWORD ifTrue:[
"/        dVal isReal ifTrue:[
"/            'JAVAVM [info]: missing double flag in Math>>exp' infoPrintCR.
"/        ] ifFalse:[
"/            self halt:'expected double arg'
"/        ]
"/    ].
    ^ dVal exp

    "Created: / 7.5.1998 / 00:36:19 / cg"
    "Modified: / 11.11.1998 / 15:07:50 / cg"
!

_Math_floor:nativeContext
    "floor"

    |dVal|

    dVal := nativeContext argAt:1.
"/    (nativeContext argAt:2) ~~ DUMMY_DOUBLE_HIGHWORD ifTrue:[
"/        dVal isReal ifTrue:[
"/            'JAVAVM [info]: missing double flag in Math>>floor' infoPrintCR.
"/        ] ifFalse:[
"/            self halt:'expected double arg'
"/        ]
"/    ].
    ^ dVal floorAsFloat

    "Created: / 7.1.1998 / 19:09:21 / cg"
    "Modified: / 11.11.1998 / 15:07:45 / cg"
!

_Math_log:nativeContext
    "natural logarithm"

    |dVal|

    dVal := nativeContext argAt:1.
"/    (nativeContext argAt:2) ~~ DUMMY_DOUBLE_HIGHWORD ifTrue:[
"/        dVal isReal ifTrue:[
"/            'JAVAVM [info]: missing double flag in Math>>log' infoPrintCR.
"/        ] ifFalse:[
"/            self halt:'expected double arg'
"/        ]
"/    ].
    ^ dVal ln

    "Created: / 7.1.1998 / 15:42:19 / cg"
    "Modified: / 30.12.1998 / 17:41:42 / cg"
!

_Math_pow:nativeContext
    "power"

    |dVal1 dVal2|

    dVal1 := nativeContext argAt:1.
"/    (nativeContext argAt:2) ~~ DUMMY_DOUBLE_HIGHWORD ifTrue:[
"/        dVal1 isReal ifTrue:[
"/            'JAVAVM [info]: missing double flag in Math>>pow' infoPrintCR.
"/        ] ifFalse:[
"/            self halt:'expected double arg'
"/        ]
"/    ].
    dVal2 := nativeContext argAt:3.
"/    (nativeContext argAt:4) ~~ DUMMY_DOUBLE_HIGHWORD ifTrue:[
"/        dVal2 isReal ifTrue:[
"/            'JAVAVM [info]: missing double flag in Math>>pow' infoPrintCR.
"/        ] ifFalse:[
"/            self halt:'expected double arg'
"/        ]
"/    ].
    ^ dVal1 raisedTo:dVal2

    "Created: / 7.1.1998 / 15:44:13 / cg"
    "Modified: / 11.11.1998 / 15:07:33 / cg"
!

_Math_rint:nativeContext
    |dVal|

    dVal := nativeContext argAt:1.
    ^ dVal rounded asFloat.
!

_Math_sin:nativeContext
    "sine"

    |dVal|

    dVal := nativeContext argAt:1.
"/    (nativeContext argAt:2) ~~ DUMMY_DOUBLE_HIGHWORD ifTrue:[
"/        dVal isReal ifTrue:[
"/            'JAVAVM [info]: missing double flag in Math>>sin' infoPrintCR.
"/        ] ifFalse:[
"/            self halt:'expected double arg'
"/        ]
"/    ].
    ^ dVal sin

    "Created: / 7.1.1998 / 15:41:40 / cg"
    "Modified: / 11.11.1998 / 15:07:09 / cg"
!

_Math_sqrt:nativeContext
    "square root"

    |dVal|

    dVal := nativeContext argAt:1.
"/    (nativeContext argAt:2) ~~ DUMMY_DOUBLE_HIGHWORD ifTrue:[
"/        dVal isReal ifTrue:[
"/            'JAVAVM [info]: missing double flag in Math>>sqrt' infoPrintCR.
"/        ] ifFalse:[
"/            self halt:'expected double arg'
"/        ]
"/    ].

    "/ how about domain errors ?
    dVal < 0 ifTrue:[
	^ 0.0
    ].
    ^ dVal sqrt

    "Created: / 7.1.1998 / 15:42:40 / cg"
    "Modified: / 29.12.1998 / 13:22:36 / cg"
!

_Math_tan:nativeContext
    "tangent"

    |dVal|

    dVal := nativeContext argAt:1.
"/    (nativeContext argAt:2) ~~ DUMMY_DOUBLE_HIGHWORD ifTrue:[
"/        dVal isReal ifTrue:[
"/            'JAVAVM [info]: missing double flag in Math>>tan' infoPrintCR.
"/        ] ifFalse:[
"/            self halt:'expected double arg'
"/        ]
"/    ].
    ^ dVal tan

    "Created: / 7.5.1998 / 00:34:03 / cg"
    "Modified: / 11.11.1998 / 15:07:14 / cg"
!

_MemoryAdvice_register0:nativeContext
    "private native void register0()"

    "/ UnimplementedNativeMethodSignal raise
!

_Method_getModifiers:nativeContext
    |jMethod mthd retVal|

    jMethod := nativeContext receiver.

    mthd := JavaMethods at:jMethod ifAbsent:nil.
    mthd isNil ifTrue:[
	self halt.
	^ 0
    ].
    ^ mthd accessFlags

    "Modified: / 9.4.1998 / 17:50:01 / cg"
!

_Method_invoke:nativeContext
    "invoke a javaMethod"

    |jMethod mthd rec args retVal|

    jMethod := nativeContext receiver.
    rec := nativeContext argAt:1.
    args := nativeContext argAt:2.

    mthd := JavaMethods at:jMethod ifAbsent:nil.
    mthd isNil ifTrue:[
	self halt.
    ].

    "/ check for arguments to match the expected types ...

    mthd argSignature keysAndValuesDo:[:index :argSig |
	|cls arg|

	cls := Java at:argSig.
	arg := args at:index.
	(arg isKindOf:cls) ifFalse:[
	    self halt.
	]
    ].

    mthd isStatic ifTrue:[
	retVal := mthd valueWithReceiver:(mthd javaClass) arguments:args selector:mthd selector.        
	^ retVal
    ] ifFalse:[
	self halt.
    ].

    self halt.

    "Created: / 13.2.1998 / 15:15:28 / cg"
    "Modified: / 13.2.1998 / 15:35:54 / cg"
!

_MozillaAppletContext_pMochaOnLoad:nativeContext
    |id|

    id := nativeContext argAt:1.
"/ 'JAVA: MozillaAppletContext_pMochaOnLoad: ' print. id printNL.
    ^ nil

    "Created: / 6.1.1998 / 20:37:13 / cg"
    "Modified: / 6.2.1998 / 02:13:09 / cg"
!

_MozillaAppletContext_pShowDocument:nativeContext
    |jAppletContext s1 s2 s3 js|

    jAppletContext := nativeContext receiver.
    js := nativeContext argAt:1.
    s1 := Java as_ST_String:js.
    js := nativeContext argAt:2.
    s2 := Java as_ST_String:js.
    js := nativeContext argAt:3.
    s2 := Java as_ST_String:js.

    "/ somehow pass it to the html browser ....
Transcript show:'pShowDocument: '; show:s1; show:' / '; 
	   show:s2; show:' / '; showCR:s3.

    ^ nil

    "Created: / 29.3.1998 / 15:53:17 / cg"
    "Modified: / 29.12.1998 / 13:32:41 / cg"
!

_MozillaAppletContext_pShowStatus:nativeContext
    |s js|

    js := nativeContext argAt:1.
    js isNil ifTrue:[
	s := ''
    ] ifFalse:[
	s := Java as_ST_String:js.
    ].

    self activityNotification:s.
"/ Transcript showCR:s.
    ^ nil

    "Created: / 6.1.1998 / 18:31:34 / cg"
    "Modified: / 22.10.1998 / 01:17:46 / cg"
!

_MozillaAppletContext_setConsoleState0:nativeContext
    "/ void setConsoleState0 (int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:23:22 / cg"
!

_ObjectInputStream_allocateNewArray:nativeContext
    "/ java.lang.Object allocateNewArray (java.lang.Class int)
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 19:01:48 / cg"
    "Created: / 12.11.1998 / 19:02:52 / cg"
!

_ObjectInputStream_allocateNewObject:nativeContext
    "/ java.lang.Object allocateNewObject (java.lang.Class java.lang.Class)
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 19:01:48 / cg"
    "Created: / 12.11.1998 / 19:02:40 / cg"
!

_ObjectInputStream_inputClassFields:nativeContext
    "/ void inputClassFields (java.lang.Object java.lang.Class int[])
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 19:01:48 / cg"
    "Created: / 12.11.1998 / 19:02:22 / cg"
!

_ObjectInputStream_invokeDefaultReadObject:nativeContext
    "/ void invokeDefaultReadObject (java.lang.Object java.lang.Class)

    UnimplementedNativeMethodSignal raise

    "Created: / 27.1.2000 / 03:00:47 / cg"
!

_ObjectInputStream_invokeObjectReader:nativeContext
    "/ boolean invokeObjectReader (java.lang.Object java.lang.Class)
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 19:01:48 / cg"
    "Created: / 12.11.1998 / 19:03:06 / cg"
!

_ObjectInputStream_invokeReadObject:nativeContext
    "/ void invokeReadObject (java.lang.Object java.lang.Class)

    UnimplementedNativeMethodSignal raise

    "Created: / 27.1.2000 / 03:01:02 / cg"
!

_ObjectInputStream_loadClass0:nativeContext
    "/ java.lang.Class loadClass0 (java.lang.Class java.lang.String)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:01:15 / cg"
    "Modified: / 12.11.1998 / 19:01:48 / cg"
!

_ObjectOutputStream_invokeDefaultWriteObject:nativeContext
    "/ void invokeDefaultWriteObject (java.lang.Object java.lang.Class)

    UnimplementedNativeMethodSignal raise

    "Created: / 27.1.2000 / 03:01:36 / cg"
!

_ObjectOutputStream_invokeObjectWriter:nativeContext
    "/ boolean invokeObjectWriter (java.lang.Object java.lang.Class)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:00:36 / cg"
    "Modified: / 12.11.1998 / 19:01:45 / cg"
!

_ObjectOutputStream_invokeWriteObject:nativeContext
    "/ void invokeWriteObject (java.lang.Object java.lang.Class)

    UnimplementedNativeMethodSignal raise

    "Created: / 27.1.2000 / 03:01:52 / cg"
!

_ObjectOutputStream_outputClassFields:nativeContext
    "/ void outputClassFields (java.lang.Object java.lang.Class int[])
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:00:09 / cg"
    "Modified: / 12.11.1998 / 19:01:42 / cg"
!

_ObjectStreamClass_doMismatchedRead:nativeContext
    "/ void doMismatchedRead (java.io.ObjectInputStream java.lang.Object)

    UnimplementedNativeMethodSignal raise

    "Created: / 27.1.2000 / 02:50:55 / cg"
!

_ObjectStreamClass_findObjectMethod0:nativeContext
    "/ boolean findObjectMethod0 (java.lang.Class int)

    UnimplementedNativeMethodSignal raise

    "Created: / 27.1.2000 / 02:51:50 / cg"
!

_ObjectStreamClass_getClassAccess:nativeContext
    "/ int getClassAccess (java.lang.Class)
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 19:01:48 / cg"
    "Created: / 12.11.1998 / 19:04:19 / cg"
!

_ObjectStreamClass_getClassDefinedUID:nativeContext
    "/ long getClassDefinedUID (java.lang.Class)

    UnimplementedNativeMethodSignal raise

    "Created: / 27.1.2000 / 02:51:33 / cg"
!

_ObjectStreamClass_getFieldAccess:nativeContext
    "/ int getFieldAccess (java.lang.Class java.lang.String)
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 19:01:48 / cg"
    "Created: / 12.11.1998 / 19:05:19 / cg"
!

_ObjectStreamClass_getFieldSignatures:nativeContext
    "/ java.lang.String[] getFieldSignatures (java.lang.Class)
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 19:01:48 / cg"
    "Created: / 12.11.1998 / 19:05:04 / cg"
!

_ObjectStreamClass_getFields0:nativeContext
    "/ java.io.ObjectStreamField[] getFields0 (java.lang.Class)
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 19:01:48 / cg"
    "Created: / 12.11.1998 / 19:05:32 / cg"
!

_ObjectStreamClass_getMethodAccess:nativeContext
    "/ int getMethodAccess (java.lang.Class java.lang.String)
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 19:01:48 / cg"
    "Created: / 12.11.1998 / 19:04:51 / cg"
!

_ObjectStreamClass_getMethodSignatures:nativeContext
    "/ java.lang.String[] getMethodSignatures (java.lang.Class)
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 19:01:48 / cg"
    "Created: / 12.11.1998 / 19:04:34 / cg"
!

_ObjectStreamClass_getSerialVersionUID:nativeContext
    "/ long getSerialVersionUID (java.lang.Class)
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 19:01:48 / cg"
    "Created: / 12.11.1998 / 19:05:43 / cg"
!

_ObjectStreamClass_hasWriteObject:nativeContext
    "/ boolean hasWriteObject (java.lang.Class)
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 19:01:48 / cg"
    "Created: / 12.11.1998 / 19:05:53 / cg"
!

_OffScreenImageSource_sendPixels:nativeContext
    "/ self halt.
    "/ UnimplementedNativeMethodSignal raise

    "Modified: / 16.1.1998 / 18:22:23 / cg"
    "Created: / 17.1.1998 / 12:36:25 / cg"
!

_PackedColorModel_initIDs:nativeContext
    "/ new with jdk1.2 ...

    "Created: / 28.1.1998 / 22:19:35 / cg"
!

_PlainDatagramSocketImpl_bind:nativeContext
    |jsock jaddr port sock hostName ok err|

    jsock := nativeContext receiver.
    port := nativeContext argAt:1.
    jaddr := nativeContext argAt:2.

    hostName := jaddr instVarNamed:'hostName'.
    hostName isNil ifTrue:[
	self halt.
    ] ifFalse:[
	hostName := Java as_ST_String:hostName
    ].

    sock := self validateFile:jsock.
    sock notNil ifTrue:[
	FileIOTrace ifTrue:[
	    ('JAVA: socket bind to ' , hostName printString, ' port ' , port printString) infoPrintCR
	].

	ok := sock bindTo:port address:nil "hostName".
	ok ifFalse:[
	    err := OperatingSystem lastErrorString.
	    Transcript showCR:'sock err: ' , err printString.
	    self throwIOExceptionWithMessage:'bind failed'.
	]
    ].

    "Created: / 4.2.1998 / 15:06:20 / cg"
    "Modified: / 30.12.1998 / 20:10:16 / cg"
!

_PlainDatagramSocketImpl_datagramSocketClose:nativeContext
    |jsock sock|

    jsock := nativeContext receiver.

    sock := self validateFile:jsock.
    sock notNil ifTrue:[
	FileIOTrace ifTrue:[
	    'JAVA: datagram close socket' infoPrintCR
	].
	sock close.
    ].

    "Modified: / 21.8.1997 / 17:09:40 / cg"
    "Created: / 25.1.1998 / 20:04:24 / cg"
!

_PlainDatagramSocketImpl_datagramSocketCreate:nativeContext
    |jsock fd sock fileNo|

    jsock := nativeContext receiver.

    fd := jsock instVarNamed:'fd'.
    (fd instVarNamed:'fd') ~~ 0 ifTrue:[
	self halt:'file already open'.
	self internalError:'file already open'.
	self throwIOExceptionWithMessage:'file already open in socketCreate'.
	^ self.
    ].

    FileOpenTrace ifTrue:[
	('JAVA: create datagram socket') infoPrintCR.
    ].

    sock := Socket newUDP.
    sock isNil ifTrue:[
	self throwIOExceptionWithMessage:'socketCreate failed'.
    ].

    fileNo := self addOpenFile:sock.
    fd instVarNamed:'fd' put:fileNo.

    "Created: / 25.1.1998 / 19:59:25 / cg"
    "Modified: / 30.12.1998 / 20:10:38 / cg"
!

_PlainDatagramSocketImpl_join:nativeContext
    "/ native void join (InetAddress arg1)

    |jsock addr sock ok err|

    jsock := nativeContext receiver.
    addr := nativeContext argAt:1.

    sock := self validateFile:jsock.
    sock notNil ifTrue:[
	FileIOTrace ifTrue:[
	    ('JAVA: socket join ' , addr printString) infoPrintCR
	].
	self throwIOExceptionWithMessage:'unimplemented: join'.
self halt.
	^ nil.  "/ void
    ].

    "Created: / 4.2.1998 / 15:06:20 / cg"
    "Modified: / 30.12.1998 / 20:10:16 / cg"
!

_PlainDatagramSocketImpl_receive:nativeContext
    |jsock jdatagramPacket sock ok|

    jsock := nativeContext receiver.
    jdatagramPacket := nativeContext argAt:1.

    sock := self validateFile:jsock.
    sock notNil ifTrue:[
	FileIOTrace ifTrue:[
	    ('JAVA: socket receive') infoPrintCR
	].
	^ -1.
    ].
    ^ -1

    "Created: / 4.2.1998 / 15:06:20 / cg"
    "Modified: / 30.12.1998 / 20:10:16 / cg"
!

_PlainDatagramSocketImpl_send:nativeContext
    |jsock jdatagramPacket sock ok|

    jsock := nativeContext receiver.
    jdatagramPacket := nativeContext argAt:1.

    sock := self validateFile:jsock.
    sock notNil ifTrue:[
	FileIOTrace ifTrue:[
	    ('JAVA: socket send') infoPrintCR
	].
	^ -1.
    ].
    ^ -1

    "Created: / 4.2.1998 / 15:06:20 / cg"
    "Modified: / 30.12.1998 / 20:10:16 / cg"
!

_PlainDatagramSocketImpl_socketGetOption:nativeContext
    |jsock opt port sock hostName ok err|

    jsock := nativeContext receiver.
    opt := nativeContext argAt:1.

    sock := self validateFile:jsock.
    sock notNil ifTrue:[
	FileIOTrace ifTrue:[
	    ('JAVA: socket getOption ' , opt printString) infoPrintCR
	].
	self throwIOExceptionWithMessage:'unimplemented: getOption'.
self halt.
	^ -1.
    ].
    ^ -1.

    "Created: / 4.2.1998 / 15:06:20 / cg"
    "Modified: / 30.12.1998 / 20:10:16 / cg"
!

_PlainDatagramSocketImpl_socketSetOption:nativeContext
    "/ native void socketSetOption (int arg1, java.lang.Object arg2)

    |jsock opt optVal sock ok err jSocketOptions|

    jsock := nativeContext receiver.
    opt := nativeContext argAt:1.
    optVal := nativeContext argAt:2.

    sock := self validateFile:jsock.
    sock notNil ifTrue:[
	FileIOTrace ifTrue:[
	    ('JAVA: socket setOption ' , opt printString) infoPrintCR
	].

	jSocketOptions := Java at:'java.net.SocketOptions'.
	(opt == (jSocketOptions instVarNamed:'TCP_NODELAY')) ifTrue:[
	] ifFalse:[
	    (opt == (jSocketOptions instVarNamed:'SO_BINDADDR')) ifTrue:[
	    ] ifFalse:[
		(opt == (jSocketOptions instVarNamed:'SO_REUSEADDR')) ifTrue:[
		] ifFalse:[
		    (opt == (jSocketOptions instVarNamed:'IP_MULTICAST_IF')) ifTrue:[
		    ] ifFalse:[
			(opt == (jSocketOptions instVarNamed:'SO_LINGER')) ifTrue:[
			] ifFalse:[
			    (opt == (jSocketOptions instVarNamed:'SO_TIMEOUT')) ifTrue:[
			    ] ifFalse:[
				self throwIOExceptionWithMessage:'bad arg to setOption'.
			    ]
			]
		    ]
		]
	    ]
	].
	self throwIOExceptionWithMessage:'unimplemented: setOption'.
self halt.
	^ nil.  "/ void
    ].

    "Created: / 4.2.1998 / 15:06:20 / cg"
    "Modified: / 30.12.1998 / 20:10:16 / cg"
!

_PlainSocketImpl_socketAccept:nativeContext
    |jsock fd newJSock sock newSock fileNo|

    jsock := nativeContext receiver.

    sock := self validateFile:jsock.
    sock isNil ifTrue:[
	self throwIOExceptionWithMessage:'nil socket in accept'.
	^ self.
    ].

    newJSock := nativeContext argAt:1.
    fd := newJSock instVarNamed:'fd'.
    (fd instVarNamed:'fd') ~~ 0 ifTrue:[
	self halt:'file already open'.
	self internalError:'file already open'.
	self throwIOExceptionWithMessage:'socket already open in socketAccept'.
	^ self.
    ].
    FileIOTrace ifTrue:[
	'JAVA: socket accept' infoPrintCR
    ].
    newSock := sock accept.
    newSock isNil ifTrue:[
	self throwIOExceptionWithMessage:'accept failed'.
    ].
    fileNo := self addOpenFile:newSock.
    fd instVarNamed:'fd' put:fileNo.

    "Created: / 4.2.1998 / 15:26:49 / cg"
    "Modified: / 30.12.1998 / 20:10:01 / cg"
!

_PlainSocketImpl_socketAvailable:nativeContext
    |jSock sock n|

    jSock := nativeContext receiver.

    sock := self validateFile:jSock.
    sock isNil ifTrue:[
	self throwIOExceptionWithMessage:'socketAvailable on closed socket'.
	^ self.
    ].

    n := sock numAvailable.
    ^ n

    "Created: / 4.2.1998 / 16:58:49 / cg"
    "Modified: / 30.12.1998 / 20:10:08 / cg"
!

_PlainSocketImpl_socketBind:nativeContext
    |jsock jaddr port sock hostName ok err|

    jsock := nativeContext receiver.
    jaddr := nativeContext argAt:1.
    port := nativeContext argAt:2.

    hostName := jaddr instVarNamed:'hostName'.
    hostName isNil ifTrue:[
	self halt.
    ] ifFalse:[
	hostName := Java as_ST_String:hostName
    ].

    sock := self validateFile:jsock.
    sock notNil ifTrue:[
	FileIOTrace ifTrue:[
	    ('JAVA: socket bind to ' , hostName printString, ' port ' , port printString) infoPrintCR
	].

	ok := sock bindTo:port address:nil "hostName".
	ok ifFalse:[
	    err := OperatingSystem lastErrorString.
	    Transcript showCR:'sock err: ' , err printString.
	    self throwIOExceptionWithMessage:'bind failed'.
	]
    ].

    "Created: / 4.2.1998 / 15:06:20 / cg"
    "Modified: / 30.12.1998 / 20:10:16 / cg"
!

_PlainSocketImpl_socketClose:nativeContext
    |jsock sock|

    jsock := nativeContext receiver.

    sock := self validateFile:jsock.
    sock notNil ifTrue:[
	FileIOTrace ifTrue:[
	    'JAVA: close socket' infoPrintCR
	].
	sock close.
    ].

    "Modified: / 21.8.1997 / 17:09:40 / cg"
    "Created: / 25.1.1998 / 20:04:24 / cg"
!

_PlainSocketImpl_socketConnect:nativeContext
    |jsock jaddr port sock addr hostName ok|

    jsock := nativeContext receiver.
    jaddr := nativeContext argAt:1.
    port := nativeContext argAt:2.

    hostName := jaddr instVarNamed:'hostName'.
    hostName notNil ifTrue:[
        hostName := Java as_ST_String:hostName
    ] ifFalse:[
        addr := jaddr instVarNamed:'address'.
        addr notNil ifTrue:[
            hostName := ByteArray new:4.
            hostName at:4 put:(addr bitAnd:16rFF).
            addr := addr bitShift:-8.
            hostName at:3 put:(addr bitAnd:16rFF).
            addr := addr bitShift:-8.
            hostName at:2 put:(addr bitAnd:16rFF).
            addr := addr bitShift:-8.
            hostName at:1 put:(addr bitAnd:16rFF).
        ].
    ].
    hostName isNil ifTrue:[
        self halt.
    ].

    sock := self validateFile:jsock.
    sock notNil ifTrue:[
        FileIOTrace ifTrue:[
            ('JAVA: socket connect to ' , hostName printString , ' port ' , port printString) infoPrintCR
        ].
        SocketConnectConfirmation ifTrue:[
            (PermittedHostConnects isNil 
            or:[(PermittedHostConnects includes:hostName) not]) ifTrue:[
                (self confirm:'connect to host: ' , hostName printString , ' - ok ?')
                ifFalse:[
                    self throwIOExceptionWithMessage:'connect permission denied'.
                ].

                (self confirm:('JAVA Security check\\Always permit connects to this host (''' , hostName printString , ''') ?') withCRs)
                ifTrue:[
                    PermittedHostConnects isNil ifTrue:[
                        PermittedHostConnects := Set new
                    ].
                    PermittedHostConnects add:hostName.
                ]
            ]
        ].

        ok := sock connectTo:hostName port:port.
        ok ifFalse:[
            self throwIOExceptionWithMessage:'connect failed'.
        ]
    ].

    "Created: / 25.1.1998 / 20:02:27 / cg"
    "Modified: / 30.12.1998 / 20:10:28 / cg"
!

_PlainSocketImpl_socketCreate:nativeContext
    |jsock isStream fd sock fileNo|

    jsock := nativeContext receiver.
    isStream := (nativeContext argAt:1) == 1.

    fd := jsock instVarNamed:'fd'.
    (fd instVarNamed:'fd') ~~ 0 ifTrue:[
	self halt:'file already open'.
	self internalError:'file already open'.
	self throwIOExceptionWithMessage:'file already open in socketCreate'.
	^ self.
    ].

    FileOpenTrace ifTrue:[
	('JAVA: create socket') infoPrintCR.
    ].

    isStream ifTrue:[
	sock := Socket newTCP
    ] ifFalse:[
	sock := Socket newUDP
    ].
    sock isNil ifTrue:[
	self throwIOExceptionWithMessage:'socketCreate failed'.
    ].

    fileNo := self addOpenFile:sock.
    fd instVarNamed:'fd' put:fileNo.

    "Created: / 25.1.1998 / 19:59:25 / cg"
    "Modified: / 30.12.1998 / 20:10:38 / cg"
!

_PlainSocketImpl_socketListen:nativeContext
    |jSock time sock ok|

    jSock := nativeContext receiver.
    time := nativeContext argAt:1.

    sock := self validateFile:jSock.
    sock notNil ifTrue:[
	FileIOTrace ifTrue:[
	    ('JAVA: socket listen with timeout ' , time printString) infoPrintCR.
	].
	ok := sock listenWithBacklog:5.
	ok ifFalse:[
	    self throwIOExceptionWithMessage:'listen failed'.
	    ^ self.
	].
	time ~~ 0 ifTrue:[
	    sock readWaitWithTimeoutMs:time
	]
    ].

    "Created: / 4.2.1998 / 15:17:48 / cg"
    "Modified: / 30.12.1998 / 20:10:46 / cg"
!

_PlatformFont_initIDs:nativeContext
    "/ new with jdk1.2 ...

    "Created: / 28.1.1998 / 22:30:41 / cg"
!

_PrintStream_isOutputStreamLocalised:nativeContext
    "/ boolean isOutputStreamLocalised (java.io.DataOutputStream)

    UnimplementedNativeMethodSignal raise

    "Created: / 27.1.2000 / 03:00:20 / cg"
!

_RandomAccessFile_close:nativeContext
    ^ self anyStream_close:nativeContext

    "Created: / 4.2.1998 / 13:26:53 / cg"
    "Modified: / 4.2.1998 / 15:21:08 / cg"
!

_RandomAccessFile_length:nativeContext
    |file sz|

    file := self validateFile:(nativeContext receiver).

    FileIOTrace ifTrue:[
	('JAVA: length of ' , file pathName) infoPrintCR.
    ].

    sz := file size.
    ^ sz.

    "Created: / 4.2.1998 / 13:27:58 / cg"
!

_RandomAccessFile_read:nativeContext
    |file byte|

    file := self validateFile:(nativeContext receiver).

    FileIOTrace ifTrue:[
	('JAVA: read 1 byte from ' , file pathName) infoPrintCR.
    ].

    byte := file nextByte.
    byte isNil ifTrue:[
	^ -1
    ].
    ^ byte

    "Modified: / 5.1.1998 / 02:17:25 / cg"
    "Created: / 27.1.1999 / 19:01:15 / cg"
!

_RandomAccessFile_readBytes:nativeContext
    ^ self anyStream_readBytes:nativeContext

    "Modified: / 4.2.1998 / 15:23:27 / cg"
!

_RandomAccessFile_seek:nativeContext
    |file pos|

    file := self validateFile:(nativeContext receiver).

    FileIOTrace ifTrue:[
	('JAVA: seek on ' , file pathName) infoPrintCR.
    ].

    pos := nativeContext argAt:1.
    file position:pos+1 "/ ST/X position starts at 1

    "Created: / 4.2.1998 / 13:25:38 / cg"
    "Modified: / 4.2.1998 / 13:28:12 / cg"
!

_RandomAccessFile_writeBytes:nativeContext
    ^ self anyStream_writeBytes:nativeContext

    "Modified: / 4.2.1998 / 15:24:20 / cg"
    "Created: / 4.2.1998 / 15:24:35 / cg"
!

_Runtime_buildLibName:nativeContext
    |jPath jFileName path fileName libName|

    jPath := nativeContext argAt:1.
    jFileName := nativeContext argAt:2.

    path := Java as_ST_String:jPath.
    fileName := Java as_ST_String:jFileName.

    path = '__builtIn__' ifTrue:[
	libName := path , '/' , fileName
    ] ifFalse:[
	libName := path , '/lib' , fileName , '.so'.
    ].
    ^ Java as_String:libName.

    "Modified: / 8.8.1997 / 12:05:05 / cg"
    "Created: / 4.1.1998 / 19:07:14 / cg"
!

_Runtime_execInternal:nativeContext
    "Run a unix-command; return a process object."

    |cmdAndArgArray envArray cmd jProcessClass jProcess|

    cmdAndArgArray := nativeContext argAt:1.
    envArray := nativeContext argAt:2.

    cmd := cmdAndArgArray at:1.

    OperatingSystem isUNIXlike ifTrue:[
	jProcessClass := Java classForName:'java.lang.UNIXProcess'.
    ] ifFalse:[
	jProcessClass := Java classForName:'java.lang.Win32Process'.
    ].
"/
    jProcessClass notNil ifTrue:[
self halt.
	jProcess := jProcessClass newCleared.
	jProcess
	    perform:#'<init>([Ljava/lang/String;[Ljava/lang/String;)V'
	    with:cmdAndArgArray
	    with:envArray.
	^ jProcess
    ].
self halt.
    self throwIOExceptionWithMessage:'Process execution disabled/unimplemented'.
    ^ nil

    "Created: / 15.1.1998 / 01:50:31 / cg"
    "Modified: / 11.12.1998 / 13:09:36 / cg"
!

_Runtime_exitInternal:nativeContext
    "exit - here, we only shut down java threads"

    |enteredMonitors|

    ExitDebug == true ifTrue:[
	self halt:'Java code called exit'.
    ].

    self syncMonitorCache.
    (enteredMonitors := self enteredMonitors) size > 0 ifTrue:[
	enteredMonitors do:[:handle | 
	    | mon |

	    mon := LockTable at:handle ifAbsent:nil.
	    mon isNil ifTrue:[
		self halt:'no monitor in exitInternal'.
	    ] ifFalse:[
		mon exit.
('====> terminateThread - exit monitor for ' , handle displayString , ' in ' , Processor activeProcess name , ' ...') infoPrintCR. 
	    ].
	].
    ].

    "/ TODO: shut down all threads created by this one ...

    AbortSignal raise.
    self halt.

    "Created: / 7.1.1998 / 22:48:51 / cg"
    "Modified: / 8.1.1999 / 14:09:36 / cg"
!

_Runtime_freeMemory:nativeContext
    "free memory - Returns the number of free bytes"

    ^ ObjectMemory freeListSpace + ObjectMemory freeSpace

    "Created: / 12.1.1998 / 12:59:53 / cg"
!

_Runtime_initializeLinkerInternal:nativeContext
    "init sharedLib linker, return searchPath as javaString"

    |path|

    "/ mhmh - what is done here ?

    path := ''.
    LibPath do:[:comp | path size == 0 ifTrue:[
			    path := path , comp
			] ifFalse:[
			    path := path , ':' , comp
			]
	       ].

    ^ Java as_String:path

    "Modified: / 7.8.1997 / 21:17:03 / cg"
    "Created: / 4.1.1998 / 17:53:15 / cg"
!

_Runtime_isInputStreamLocalised:nativeContext
    "/ boolean isInputStreamLocalised (java.io.DataInputStream)

UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 03:03:01 / cg"
!

_Runtime_isOutputStreamLocalised:nativeContext
    "/ boolean isOutputStreamLocalised (java.io.DataOutputStream)

UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 03:02:49 / cg"
!

_Runtime_loadFileInternal:nativeContext
    "load a sharedLib, return boolean 0 (false) if fail; 1 (true) if ok"

    |ret|

    ret := self _Runtime_loadFileInternalI:nativeContext.
    ret < 0 ifTrue:[ ret := 0 ].
    ^ ret

    "Created: / 4.1.1998 / 19:10:20 / cg"
    "Modified: / 4.1.1998 / 19:11:04 / cg"
!

_Runtime_loadFileInternalI:nativeContext
    "1.1b3 change; load a sharedLib like 'loadFileInternal',
     but return integer:
	-1   outOfMemory error
	0    failed to load
	1    loaded or already loaded (i.e. ok)"

    |jLibName libName libHandle|

    jLibName := nativeContext argAt:1.
    libName := Java as_ST_String:jLibName.

    (SimulatedLibs includes:libName) ifTrue:[
"/        ('JAVA: builtIn libLoad simulated: ' , libName) printNL.
	^ 1
    ].
    (LoadedLibs notNil and:[LoadedLibs includesKey:libName]) ifTrue:[
"/        ('JAVA: already loaded: ' , libName) printNL.
	^ 1
    ].

    libName asFilename exists ifFalse:[
	('JAVA: no file to load: ' , libName) printNL.
	^ 0
    ].

    (self confirm:'permission to load native library: ' , libName , ' ?') ifFalse:[
	^ 0
    ].

    libHandle := ObjectFileLoader loadLibrary:libName.
    libHandle isNil ifTrue:[
	('JAVA: failed to load: ' , libName) printNL.
	^ 0
    ].

    LoadedLibs isNil ifTrue:[
	LoadedLibs := Dictionary new.
    ].

    LoadedLibs at:libName put:libHandle.
    ^ 1

    "Created: / 4.1.1998 / 19:10:54 / cg"
    "Modified: / 6.2.1998 / 03:11:59 / cg"
!

_Runtime_runFinalization:nativeContext
    "/ void runFinalization ()
"/    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 18:52:07 / cg"
    "Created: / 12.11.1998 / 18:59:01 / cg"
!

_Runtime_runFinalizersOnExit0:nativeContext
    ""

    |onOff|

    onOff := nativeContext argAt:1.
    ^ 1

    "Modified: / 6.2.1998 / 03:11:59 / cg"
    "Created: / 15.10.1998 / 23:34:55 / cg"
!

_Runtime_setInputStreamLocalised:nativeContext

UnimplementedNativeMethodSignal raise.

    "Modified: / 27.1.2000 / 03:02:27 / cg"
!

_Runtime_setOutputStreamLocalised:nativeContext

UnimplementedNativeMethodSignal raise.

    "Modified: / 27.1.2000 / 03:02:32 / cg"
!

_Runtime_totalMemory:nativeContext
    "free memory - Returns the total number of bytes"

    ^ ObjectMemory oldSpaceSize + ObjectMemory newSpaceSize

    "Created: / 12.1.1998 / 12:59:23 / cg"
!

_Runtime_traceInstructions:nativeContext
    "/ void traceInstructions (boolean)
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 18:52:07 / cg"
    "Created: / 12.11.1998 / 18:59:18 / cg"
!

_Runtime_traceMethodCalls:nativeContext
    "/ void traceMethodCalls (boolean)
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 18:52:07 / cg"
    "Created: / 12.11.1998 / 18:59:37 / cg"
!

_ScrollPane_initIDs:nativeContext
    "/ new with jdk1.2 ...

    "Created: / 28.1.1998 / 22:19:23 / cg"
!

_SecurityManager_classDepth:nativeContext
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 18:52:07 / cg"
    "Created: / 12.11.1998 / 18:56:27 / cg"
!

_SecurityManager_classLoaderDepth:nativeContext
    |con depth|

    con := thisContext sender.
    depth := 1.
    [con notNil] whileTrue:[
	con receiver == JavaClassReader classLoaderQuerySignal ifTrue:[
	    con selector == #handle:do: ifTrue:[
		depth := depth + 1
	    ]
	].
	con := con sender.
    ].
'JAVA: classLoaderDepth -> ' infoPrint. depth infoPrintCR.
    ^ depth.

    "Created: / 13.1.1998 / 09:21:46 / cg"
    "Modified: / 13.1.1998 / 09:33:43 / cg"
!

_SecurityManager_currentClassLoader:nativeContext
    |loader|

    loader := JavaClassReader classLoaderQuerySignal query.
"/ 'JAVA: currentClassLoader -> ' infoPrint. loader displayString infoPrintCR.
    ^ loader.

    "Created: / 13.1.1998 / 09:23:28 / cg"
    "Modified: / 11.12.1998 / 12:39:59 / cg"
!

_SecurityManager_currentLoadedClass0:nativeContext
    UnimplementedNativeMethodSignal raise

    "Modified: / 12.11.1998 / 18:52:07 / cg"
    "Created: / 12.11.1998 / 18:56:41 / cg"
!

_SocketInputStream_socketRead:nativeContext
    ^ self anyStream_readBytes:nativeContext

    "Created: / 25.1.1998 / 20:56:53 / cg"
    "Modified: / 4.2.1998 / 15:52:31 / cg"
!

_SocketOutputStream_socketWrite:nativeContext
    ^ self anyStream_writeBytes:nativeContext

    "Created: / 25.1.1998 / 21:06:55 / cg"
    "Modified: / 4.2.1998 / 15:52:40 / cg"
!

_String_compareTo:nativeContext
    "int compareTo (java.lang.String)"

    |jString1 jString2|

    jString1 := nativeContext receiver.
    jString2 := nativeContext argAt:1.
UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 02:28:59 / cg"
!

_String_equals:nativeContext
    |jString1 jString2|

    jString1 := nativeContext receiver.
    jString2 := nativeContext argAt:1.
    ^ (jString1 instVarAt:1) = (jString2 instVarAt:1)

    "Created: / 18.11.1998 / 00:52:03 / cg"
    "Modified: / 18.11.1998 / 00:53:01 / cg"
!

_String_equalsIgnoreCase:nativeContext
    "boolean equalsIgnoreCase (java.lang.String)"

    |jString1 jString2|

self halt:'untested'.

    jString1 := nativeContext receiver.
    jString2 := nativeContext argAt:1.
    ^ (jString1 instVarAt:1) sameAs: (jString2 instVarAt:1)

    "Modified: / 18.11.1998 / 00:53:01 / cg"
    "Created: / 27.1.2000 / 02:27:46 / cg"
!

_String_indexOf:nativeContext
    "int indexOf (java.lang.String int)"

    |jString1 jString2 idx|

    jString1 := nativeContext receiver.
    jString2 := nativeContext argAt:1.
    idx := nativeContext argAt:2.
UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 02:30:22 / cg"
!

_String_lastIndexOf:nativeContext
    "int lastIndexOf (java.lang.String int)"

    |jString1 jString2 idx|

    jString1 := nativeContext receiver.
    jString2 := nativeContext argAt:1.
    idx := nativeContext argAt:2.
UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 02:33:59 / cg"
!

_String_length:nativeContext
    |jString|

    jString := nativeContext receiver.
    ^ (jString instVarAt:3)

    "Created: / 18.11.1998 / 00:53:50 / cg"
    "Modified: / 18.11.1998 / 00:54:18 / cg"
!

_String_regionMatches2:nativeContext
    "boolean regionMatches (boolean int java.lang.String int int)"

    |jString1 bool jString2 idx1 idx2|

    jString1 := nativeContext receiver.
    bool := nativeContext argAt:1.
    jString2 := nativeContext argAt:2.
    idx1 := nativeContext argAt:3.
    idx2 := nativeContext argAt:4.
UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 02:33:40 / cg"
!

_String_regionMatches:nativeContext
    "boolean regionMatches (int java.lang.String int int)"

    |jString1 jString2 idx1 idx2|

    jString1 := nativeContext receiver.
    jString2 := nativeContext argAt:1.
    idx1 := nativeContext argAt:2.
    idx2 := nativeContext argAt:3.
UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 02:32:29 / cg"
!

_String_startsWith:nativeContext
    "boolean startsWith (java.lang.String int)"

    |jString1 jString2 idx|

    jString1 := nativeContext receiver.
    jString2 := nativeContext argAt:1.
    idx := nativeContext argAt:2.
UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 02:31:40 / cg"
!

_SystemColor_GetSysColor:nativeContext
    "/ int GetSysColor (int)
    UnimplementedNativeMethodSignal raise

    "Created: / 27.1.2000 / 02:44:41 / cg"
!

_SystemResourceManager_getEntryFromKey:nativeContext
    "get a resource by name"

    |key s|

    key := nativeContext argAt:1.

    s := Java effectiveClassPath at:(key+1) ifAbsent:nil.
    s isNil ifTrue:[^ nil].
    ^ Java as_String:s

    "Modified: / 22-11-2010 / 13:44:15 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_SystemResourceManager_validateSystemResource:nativeContext
    "check a resource"

    |bool str1 str2|

    bool := nativeContext argAt:1.
    str1 := nativeContext argAt:2.
    str2 := nativeContext argAt:3.
    ^ 1 "/ true
!

_System_getCallerClass:nativeContext
    "/ introduced with jdk1.2

    |senderContext cls|

    senderContext := nativeContext sender.
    [senderContext receiver == (Java at:'java.lang.System')] whileTrue:[
	senderContext := senderContext sender.
    ].

    senderContext method isStatic ifTrue:[
	cls := senderContext receiver
    ] ifFalse:[
	cls := senderContext receiver class
    ].
    cls isJavaClass ifTrue:[
	^ self javaClassObjectForClass:cls
    ].
    (cls isMemberOf:(Java at:'java.lang.Class')) ifTrue:[
	^ Java at:'java.lang.Class'
    ].
    self halt.
    ^ nil

    "Modified: / 27.1.1998 / 18:33:13 / cg"
!

_System_validateSecurityManager:nativeContext
    "void validateSecurityManager (java.lang.SecurityManager)"

UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 02:43:25 / cg"
!

_ThreadGroup_initMainThreadGroup0:nativeContext
    "void initMainThreadGroup0 (java.lang.ThreadGroup)"

UnimplementedNativeMethodSignal raise.

    "Created: / 27.1.2000 / 02:45:52 / cg"
!

_Thread_countStackFrames:nativeContext
    "/ int countStackFrames ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:06:21 / cg"
!

_Thread_interrupt0:nativeContext
    "ask if a thread is interrupted (clear interruptState if arg is true)"

    |jThread stProcess|

    jThread := nativeContext receiver.
    stProcess := self stProcessForJavaThread:jThread.
    stProcess isNil ifTrue:[
	self halt.
	^ 0
    ].

    stProcess markInterrupted

    "Modified: / 2.1.1998 / 21:49:06 / cg"
    "Created: / 10.4.1998 / 15:21:43 / cg"
!

_Thread_resume0:nativeContext
    "yield"

    |jThread stProcess|

    jThread := nativeContext receiver.
    stProcess := JavaVM stProcessForJavaThread:jThread.
    stProcess isNil ifTrue:[
	ThreadTrace == true ifTrue:[
	    ('JAVA: no stProcess for javaThread: ' , jThread displayString) printNL.
	].
	^ nil "void"
    ].
    stProcess resume

    "Created: / 8.1.1998 / 01:06:27 / cg"
    "Modified: / 6.2.1998 / 02:15:08 / cg"
!

_Thread_start:nativeContext
    "start the thread"

    |jThread jName name stProcess|

    jThread := nativeContext receiver.
    (jThread instVarNamed:'priority') < 1 ifTrue:[
        self halt.
        jThread instVarNamed:'priority' put:1.
    ].

    stProcess := JavaProcess 
                    for:[   
                          |procName|

                          Object abortSignal handle:[:ex |
                            procName := stProcess name.
                            (procName startsWith:'JAVA-AWT-EventQueue') ifTrue:[
                                ('JAVA [info]: thread ' , procName , ' aborted - restarting process.') infoPrintCR.
                                ex restart.
                            ] ifFalse:[
                                (stProcess == JavaScreenUpdaterThread 
                                or:[stProcess == JavaEventQueueThread]) ifTrue:[
                                    ('JAVA [info]: thread ' , procName , ' aborted - restarting process.') infoPrintCR.
                                    ex restart
                                ] ifFalse:[
                                    ('JAVA [info]: thread ' , procName , ' aborted.') infoPrintCR.
                                ]
                            ].
                          ] do:[ 
                            [
                                JavaVM javaExceptionSignal handle:[:ex |
                                    |exClass|

                                    procName := stProcess name.
                                    exClass := ex parameter class.

                                    exClass == (Java at:'java.lang.ThreadDeath') ifTrue:[
                                        ('JAVA: thread ' , procName , ' terminated') infoPrintCR.
                                    ] ifFalse:[
                                        Transcript 
                                            showCR:('JAVA: thread ''' 
                                                    , procName 
                                                    , ''' terminated with exception: ' 
                                                    , exClass name).
                                    ].
                                    ex return.
                                ] do:[
                                    Object messageNotUnderstoodSignal handle:[:ex |
                                        "/ remap doesNotUnderstand with nil-receiver to
                                        "/ a nullPointerException ...
                                        |con m|

                                        con := ex suspendedContext.
                                        con receiver isNil ifTrue:[
                                            ((m := con sender method) notNil
                                            and:[m isJavaMethod]) ifTrue:[
                                                self throwNullPointerException.
                                                AbortSignal raise. "/ ex proceed.
                                            ]
                                        ].
                                        ex reject.
                                    ] do:[
"/ Transcript showCR:(Timestamp now printString , 'start thread: ', stProcess name).
                                        jThread perform:#'run()V'.
                                        ThreadTrace == true ifTrue:[
                                            ('JAVA: thread ' , stProcess name , ' terminated') infoPrintCR.
                                        ].
                                        jThread perform:#'exit()V'.
                                        ThreadTrace == true ifTrue:[
                                            ('JAVA: after exit of thread ' , stProcess name) infoPrintCR.
                                        ]
                                    ]
                                ]
                            ] ensure:[
                                |monitors|

                                monitors := EnteredMonitorsPerProcess at:stProcess ifAbsent:nil.
                                monitors notNil ifTrue:[
                                    monitors do:[:obj |
                                        | mon |

                                        mon := self monitorFor:obj.
                                        mon notNil ifTrue:[
                                            mon owningProcess == stProcess ifTrue:[
                                                ('JAVA: release monitor owned by dying thread: ' , stProcess name) infoPrintCR.
                                                mon exit
                                            ].
                                        ].
                                    ].
                                    EnteredMonitorsPerProcess removeKey:stProcess.

                                    stProcess == JavaScreenUpdaterThread ifTrue:[
                                        JavaScreenUpdaterThread := nil.
                                    ].
                                    stProcess == JavaEventQueueThread ifTrue:[
                                        JavaEventQueueThread := nil.
                                    ].
"/                                    screenUpdaterClass := Java at:'sun.awt.ScreenUpdater'.    
"/                                    screenUpdaterClass notNil ifTrue:[
"/                                        screenUpdaterClass instVarNamed:'updater' put:nil.
"/                                    ].
                                ].
                                Java threads removeKey:jThread ifAbsent:[].
                            ]
                          ]
                        ] 
                    priority:(Processor activePriority).

    jName := jThread instVarNamed:'name'.
    jName isString ifFalse:[
        name := Java as_ST_String:jName.
    ] ifTrue:[
        name := jName
    ].

    "/ kludge - remember the ScreenUpdater ...
    name = 'Screen Updater' ifTrue:[
        JavaScreenUpdaterThread := stProcess.
    ] ifFalse:[
        name = 'AWT-Windows' ifTrue:[
            JavaEventThread := stProcess.
        ] ifFalse:[
            (name startsWith:'AWT-EventQueue') ifTrue:[
                JavaEventQueueThread := stProcess.
            ].
        ]
    ].

"/name = 'UserDialogShowThread' ifTrue:[
"/self halt
"/].
    "/ when that process terminates, wakup any waiters
    stProcess addExitAction:[self wakeup:jThread].

    stProcess name:'JAVA-' , name.
    stProcess restartable:true.
    stProcess resume.

    Java threads at:jThread put:stProcess.

    ^ nil

    "Created: / 3.1.1998 / 02:05:52 / cg"
    "Modified: / 24.12.1999 / 03:14:33 / cg"
!

_Thread_stop0:nativeContext
    "terminate a thread"

    |jThread stProcess death|

    jThread := nativeContext receiver.

    stProcess := JavaVM stProcessForJavaThread:jThread.
    stProcess isNil ifTrue:[
        ThreadTrace == true ifTrue:[
            ('JAVA: no stProcess for javaThread: ' , jThread displayString) printNL.
        ].
        ^ nil "void"
    ].
stProcess == JavaScreenUpdaterThread ifTrue:[self halt].
stProcess == JavaEventQueueThread ifTrue:[self halt].

    death := nativeContext argAt:1.
    stProcess 
        interruptWith:[
                        JavaVM javaExceptionSignal handle:[:ex |
Processor activeProcess == JavaScreenUpdaterThread ifTrue:[self halt].
Processor activeProcess == JavaEventQueueThread ifTrue:[self halt].
                            Processor activeProcess terminate
                        ] do:[
                            ThreadTrace == true ifTrue:[
                                ('JAVA: thread exit: ' , jThread displayString) infoPrintNL.
                            ].
                            jThread perform:#'exit()V'.
                            self throwException:death.
                        ]
                      ].
    stProcess resume.

    [stProcess isDead] whileFalse:[
        stProcess resume.
        'JavaVM: wait for death' infoPrintCR.
        Delay waitForSeconds:0.1
    ].
    stProcess terminate

    "Created: / 8.1.1998 / 13:11:17 / cg"
    "Modified: / 24.12.1999 / 02:32:45 / cg"
!

_Thread_suspend0:nativeContext
    "yield"

    |jThread stProcess|

    jThread := nativeContext receiver.
    stProcess := JavaVM stProcessForJavaThread:jThread.
    stProcess isNil ifTrue:[
	ThreadTrace == true ifTrue:[
	    ('JAVA: no stProcess for javaThread: ' , jThread displayString) printNL.
	].
	^ nil "void"
    ].
    stProcess suspend

    "Created: / 8.1.1998 / 01:05:49 / cg"
    "Modified: / 6.2.1998 / 02:15:23 / cg"
!

_Thread_yield:nativeContext
    "yield"

    |jThread stProcess|

    Processor yield.
"/    jThread := nativeContext receiver.
"/    stProcess := JavaVM stProcessForJavaThread:jThread.
"/    stProcess isNil ifTrue:[
"/        ThreadTrace == true ifTrue:[
"/            ('JAVA: no stProcess for javaThread: ' , jThread displayString) printNL.
"/        ].
"/        ^ nil "void"
"/    ].
"/    stProcess == Processor activeProcess ifTrue:[
"/        Processor yield.
"/    ] ifFalse:[
"/        self halt.
"/    ].

    "Created: / 5.1.1998 / 02:03:51 / cg"
    "Modified: / 23.12.1998 / 19:19:17 / cg"
!

_Throwable_printStackTrace0:nativeContext
    |out outStream exceptionObject contextList|

    outStream := nativeContext argAt:1.
    exceptionObject := nativeContext receiver.

    contextList := exceptionObject instVarNamed:'backtrace'.

    out := self javaConsoleStream.
    out cr.
    out nextPutLine:'JAVA: stackTrace:'.

    contextList do:[:con |
	out 
	    nextPutAll:'  '; 
	    nextPutAll:(con method javaClass fullName);
	    nextPutAll:'.';
	    nextPutAll:(con method selector);
	    nextPutAll:' ['; 
	    nextPutAll:(con method javaClass sourceFile); 
	    nextPutAll:' '; 
	    nextPutAll:(con quickLineNumber displayString); 
	    nextPutAll:']'.
	out cr
    ].
    out nextPutLine:'----------------------------------------------------'

    "Created: / 4.1.1998 / 14:27:40 / cg"
    "Modified: / 10.11.1998 / 14:19:32 / cg"
!

_URLConnection_close:nativeContext
    "/ void close ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:26:03 / cg"
!

_URLConnection_finalize:nativeContext
    "/ void finalize ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:25:22 / cg"
!

_URLConnection_getContentLength0:nativeContext
    "/ int getContentLength0 ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:25:34 / cg"
!

_URLConnection_getContentType0:nativeContext
    "/ java.lang.String getContentType0 ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:25:42 / cg"
!

_URLConnection_getHeaderField0:nativeContext
    "/ java.lang.String getHeaderField0 (java.lang.String)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:25:53 / cg"
!

_URLConnection_pCreate:nativeContext
    "/ void pCreate (java.lang.String java.lang.String)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:25:14 / cg"
!

_URLInputStream_available:nativeContext
    "/ int available ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:24:26 / cg"
!

_URLInputStream_open:nativeContext
    "/ void open ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:24:01 / cg"
!

_URLInputStream_read:nativeContext
    "/ int read (byte[] int int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:24:12 / cg"
!

_URLOutputStream_open:nativeContext
    "/ void open ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:24:38 / cg"
!

_URLOutputStream_pClose:nativeContext
    "/ void pClose ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:25:02 / cg"
!

_URLOutputStream_write:nativeContext
    "/ void write (int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:24:45 / cg"
!

_URLOutputStream_writeBytes:nativeContext
    "/ void writeBytes (byte[] int int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:24:55 / cg"
!

_URLStreamHandlerFactory_pInit:nativeContext
    "/ self unimplementedNativeMethod.

    "Created: / 10.1.1998 / 15:47:24 / cg"
!

_URLStreamHandlerFactory_pSupportsProtocol:nativeContext
    "/ boolean pSupportsProtocol (java.lang.String)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:23:43 / cg"
!

_VM_getState:nativeContext
    "/ int getState ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:06:44 / cg"
!

_VM_resetJavaMonitor:nativeContext
    "/ void resetJavaMonitor ()
    UnimplementedNativeMethodSignal raise

    "Created: / 14.11.1998 / 10:43:23 / cg"
!

_VM_resumeJavaMonitor:nativeContext
    "/ void resumeJavaMonitor ()
    UnimplementedNativeMethodSignal raise

    "Created: / 14.11.1998 / 10:42:49 / cg"
!

_VM_suspendJavaMonitor:nativeContext
    "/ void suspendJavaMonitor ()
    UnimplementedNativeMethodSignal raise

    "Created: / 14.11.1998 / 10:43:07 / cg"
!

_VM_threadsSuspended:nativeContext
    "/ boolean threadsSuspended ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:07:10 / cg"
!

_VM_unsuspendSomeThreads:nativeContext
    "/ void unsuspendSomeThreads ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:07:29 / cg"
!

_VM_unsuspendThreads:nativeContext
    "/ void unsuspendThreads ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:07:20 / cg"
!

_VM_writeJavaMonitorReport:nativeContext
    "/ void writeJavaMonitorReport ()
    UnimplementedNativeMethodSignal raise

    "Created: / 14.11.1998 / 10:43:37 / cg"
!

_WButtonPeer_create:nativeContext
    |jButtonPeer jButton jFrame frame button
     lbl|

    jButtonPeer := nativeContext receiver.
    jButton := jButtonPeer instVarNamed:'target'.

    jFrame := nativeContext argAt:1.
    frame := jFrame instVarNamed:'pData'.

    button := Button in:frame.
    button sizeFixed:true.
    button action:[
			jButtonPeer perform:#'handleAction()V'.
		  ].

    lbl := jButton instVarNamed:'label'.
    lbl notNil ifTrue:[
	lbl := Java as_ST_String:lbl.
	button label:lbl
    ].
    self createdWindowsView:button for:jButtonPeer.

    WindowCreationTrace == true ifTrue:[
	'WButtonPeer_create: ' print. frame print. ' -> ' print. button printNL.
    ].

    "Created: / 5.1.1998 / 01:53:30 / cg"
    "Modified: / 11.12.1998 / 00:19:22 / cg"
!

_WButtonPeer_setLabel:nativeContext
    |label jString|

    jString := nativeContext argAt:1.

    label := self viewForWPeer:nativeContext.
    label label:(Java as_ST_String:jString)

    "Modified: / 8.1.1998 / 17:35:50 / cg"
    "Created: / 1.2.1998 / 17:05:47 / cg"
!

_WCanvasPeer_create:nativeContext
    |jCanvasPeer jFrame frame subView|

    jCanvasPeer := nativeContext receiver.

    jFrame := nativeContext argAt:1.
    jFrame isNil ifTrue:[
	self halt:'no frame in canvasPeer create'.
	subView := JavaView new.
"/        self internalError:'no frame in canvasPeer create'.     
"/        ^ self.
    ] ifFalse:[
	frame := jFrame instVarNamed:'pData'.
	subView := JavaView in:frame.
    ].

    subView delegate:self.
    subView javaPeer:jCanvasPeer.

    self createdWindowsView:subView for:jCanvasPeer.

    WindowCreationTrace == true ifTrue:[
	'WCanvasPeer_create: ' print. frame print. ' -> ' print. subView printNL.
    ].

    "Created: / 5.1.1998 / 00:59:19 / cg"
    "Modified: / 16.1.1998 / 13:40:00 / cg"
!

_WCheckboxMenuItemPeer_setState:nativeContext
    "/ void setState (boolean)
"/    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:14:35 / cg"
    "Modified: / 3.12.1998 / 21:41:13 / cg"
!

_WCheckboxPeer_create:nativeContext
    |jCheckboxPeer jCheckbox jFrame frame checkBox lbl|

    jCheckboxPeer := nativeContext receiver.
    jCheckbox := jCheckboxPeer instVarNamed:'target'.

    jFrame := nativeContext argAt:1.
    frame := jFrame instVarNamed:'pData'.

    checkBox := CheckBox in:frame.
    checkBox action:[
			jCheckboxPeer 
			    perform:#'handleAction(Z)V' 
			    with:(checkBox isOn ifTrue:[1] ifFalse:[0])
		    ].

    lbl := jCheckbox instVarNamed:'label'.
    lbl notNil ifTrue:[
	lbl := Java as_ST_String:lbl.
	checkBox label:lbl
    ].

    self createdWindowsView:checkBox for:jCheckboxPeer.

    WindowCreationTrace == true ifTrue:[
	'WCheckboxPeer_create: ' print. frame print. ' -> ' print. checkBox printNL.
    ].

    "Created: / 7.1.1998 / 21:48:03 / cg"
    "Modified: / 15.1.1998 / 12:27:04 / cg"
!

_WCheckboxPeer_setCheckboxGroup:nativeContext
    |checkBox jGroup|

    checkBox := self viewForWPeer:nativeContext.

    jGroup := nativeContext argAt:1.

    "Created: / 7.1.1998 / 21:48:47 / cg"
    "Modified: / 25.1.1998 / 01:20:42 / cg"
!

_WCheckboxPeer_setLabel:nativeContext
    "/ void setLabel (java.lang.String)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:14:53 / cg"
!

_WCheckboxPeer_setState:nativeContext
    |checkBox state|

    checkBox := self viewForWPeer:nativeContext.

    state := nativeContext argAt:1.
    state ~~ 0 ifTrue:[
	checkBox turnOn
    ] ifFalse:[
	checkBox turnOff
    ].

    "Created: / 7.1.1998 / 21:49:13 / cg"
    "Modified: / 25.1.1998 / 01:26:18 / cg"
!

_WChoicePeer_addItem:nativeContext
    |jString index comboBox|

    comboBox := self viewForWPeer:nativeContext.

    jString := nativeContext argAt:1.
    index := nativeContext argAt:2.

    comboBox model list addLast:(Java as_ST_String:jString).
    comboBox model changed:#list.

    "Created: / 7.1.1998 / 21:45:12 / cg"
    "Modified: / 24.1.1998 / 18:51:32 / cg"
!

_WChoicePeer_create:nativeContext
    |jChoicePeer jChoice jFrame frame comboBox|

    jChoicePeer := nativeContext receiver.
    jChoice := jChoicePeer instVarNamed:'target'.

    jFrame := nativeContext argAt:1.
    frame := jFrame instVarNamed:'pData'.

    comboBox := ComboListView in:frame.
    comboBox model:(SelectionInList new list:(OrderedCollection new)).
    comboBox action:[:index | 
			jChoicePeer 
			    perform:#'handleAction(I)V' 
			    with:(comboBox model selectionIndex - 1)
		    ].

    self createdWindowsView:comboBox for:jChoicePeer.

    WindowCreationTrace == true ifTrue:[
	'WChoicePeer_create: ' print. frame print. ' -> ' print. comboBox printNL.
    ].

    "Created: / 7.1.1998 / 21:44:31 / cg"
    "Modified: / 28.1.1998 / 23:19:17 / cg"
!

_WChoicePeer_remove:nativeContext
    "/ void remove (int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:12:20 / cg"
!

_WChoicePeer_reshape:nativeContext
    self commonReshapeComponent:nativeContext.
"/    self pReshape:nativeContext.
    ^ self.

    "Created: / 7.1.1998 / 21:46:18 / cg"
    "Modified: / 23.12.1998 / 19:08:07 / cg"
!

_WChoicePeer_select:nativeContext
    |comboBox index|

    comboBox := self viewForWPeer:nativeContext.

    index := nativeContext argAt:1.
    comboBox model selectionIndex:(index + 1).  "/ JAVA indexing starts at 0

    "Created: / 7.1.1998 / 21:45:43 / cg"
    "Modified: / 25.1.1998 / 09:55:05 / cg"
!

_WClipboard_getClipboardText:nativeContext
    "/ java.lang.String getClipboardText ()

    |str|

    str := Screen current rootView getTextSelection.
    str isNil ifTrue:[
	str := ''.
    ].
    ^ Java as_String:''.

    "Modified: / 10.12.1998 / 21:28:29 / cg"
!

_WClipboard_init:nativeContext
"/ self halt.

    "Modified: / 18.3.1997 / 18:43:18 / cg"
    "Created: / 4.1.1998 / 19:03:59 / cg"
!

_WClipboard_setClipboardText:nativeContext
    "/ void setClipboardText (java.awt.datatransfer.StringSelection)

    |strSel data|

    strSel := nativeContext argAt:1.
    data := strSel instVarNamed:'data'.
    data class == (Java at:'java.lang.String') ifTrue:[
	Screen current rootView setTextSelection:(Java as_ST_String:data)
    ].
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:15:31 / cg"
    "Modified: / 10.12.1998 / 21:25:20 / cg"
!

_WColor_getDefaultColor:nativeContext
    |clrIndex jClr clr |

    clrIndex := nativeContext argAt:1.
    "/ windows defaults:
    "/  1: view background

    clrIndex == 1 ifTrue:[
	clr := View defaultViewBackgroundColor.
	clr isColor ifFalse:[
	    clr := Color gray:50.
	].
    ].
    clrIndex == 2 ifTrue:[
	clr := Color black.
    ].
    clr isNil ifTrue:[
	self halt.
	self internalError:'breakpoint'.
	^ nil.
    ].

    clr := clr on:(Screen current).

    jClr := (Java classForName:'java.awt.Color') new.

    jClr instVarNamed:'pData' put:clr.
    jClr instVarNamed:'value' put:(clr rgbValue).
"/ self halt.
    ^ jClr.

    "Created: / 15.8.1997 / 15:38:10 / cg"
    "Modified: / 4.1.1998 / 18:06:51 / cg"
!

_WComponentPeer__beginValidate:nativeContext
    "/ void _beginValidate ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:10:08 / cg"
!

_WComponentPeer__dispose:nativeContext
    |view jPeer|

    view := self viewForWPeer:nativeContext.

    Object errorSignal catch:[
	view destroy.
    ].
    JavaWindowGroup removeView:view.

    jPeer := nativeContext receiver.
    jPeer instVarNamed:'pData' put:0.

    "Created: / 7.1.1998 / 22:36:25 / cg"
    "Modified: / 25.1.1998 / 16:43:06 / cg"
!

_WComponentPeer__setBackground:nativeContext
    |rgb clr view|

    view := self viewForWPeer:nativeContext.
    view isNil ifTrue:[^ self].

    rgb := nativeContext argAt:1.
    clr := Color rgbValue:rgb.

"/ self halt.
"/ self internalError:'breakPoint'.

    clr := clr on:(view device).

"/    (view superView isMemberOf:JavaEmbeddedFrameView) ifTrue:[
"/        view viewBackground:(view superView viewBackground).
"/        view backgroundPaint:(view superView viewBackground).
"/    ] ifFalse:[
"/        (view isMemberOf:JavaView) ifTrue:[
"/            view viewBackground:clr.
"/            view backgroundPaint:clr.
"/        ]
"/    ].

    (view isKindOf:ScrollableView) ifTrue:[
	view := view scrolledView
    ].
    view viewBackground:clr.
    view backgroundPaint:clr.

    "Created: / 4.1.1998 / 18:07:39 / cg"
    "Modified: / 4.12.1998 / 17:26:06 / cg"
!

_WComponentPeer__setForeground:nativeContext
    |rgb clr view|

    view := self viewForWPeer:nativeContext.

    rgb := nativeContext argAt:1.
    clr := Color rgbValue:rgb.

"/ self halt.
"/ self internalError:'breakPoint'.

    clr := clr on:(view device).

    view paint:clr.

    "Created: / 4.1.1998 / 18:08:13 / cg"
    "Modified: / 8.1.1998 / 17:32:45 / cg"
!

_WComponentPeer_disable:nativeContext
    |view|

    view := self viewForWPeer:nativeContext.

    Object errorSignal handle:[:ex |
    ] do:[
	view disable
    ]

    "Created: / 6.1.1998 / 18:26:36 / cg"
    "Modified: / 8.1.1998 / 17:32:53 / cg"
!

_WComponentPeer_enable:nativeContext
    |view|

    view := self viewForWPeer:nativeContext.

    Object errorSignal handle:[:ex |
    ] do:[
	view enable
    ]

    "Modified: / 8.1.1998 / 17:32:53 / cg"
    "Created: / 13.1.1998 / 23:08:05 / cg"
!

_WComponentPeer_endValidate:nativeContext
    "/ void endValidate ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:10:20 / cg"
!

_WComponentPeer_getLocationOnScreen:nativeContext
    "/ java.awt.Point getLocationOnScreen ()

    |view p jP|

    view := self viewForWPeer:nativeContext.
    view isNil ifTrue:[^ nil].

    p := view originRelativeTo:nil.
    jP := (Java classForName:'java.awt.Point') basicNew.
    jP instVarNamed:'x' put:p x.
    jP instVarNamed:'y' put:p y.
    ^ jP

    "Modified: / 5.12.1998 / 14:44:31 / cg"
!

_WComponentPeer_handleEvent:nativeContext
    "this is invoked by java, to let a widget handle any event which
     was not consumed (eaten) by java.
     If the view in question is some ST-widget, forward it.
     Ignore for JavaViews."

    |view jEv stEv ignore|

    view := self viewForWPeer:nativeContext.
    view notNil ifTrue:[
	jEv := nativeContext argAt:1.
	stEv := jEv instVarNamed:'data'.
	(stEv notNil and:[stEv ~~ 0]) ifTrue:[
	    ignore := true.
	    view isJavaView ifFalse:[
		ignore := false
	    ] ifTrue:[
		view isTopView ifTrue:[
		    stEv type == #terminate ifTrue:[
			ignore := false
		    ].
		]
	    ].

	    ignore ifFalse:[
		EventTrace == true ifTrue:[
		    ('JAVA: WComponent - handleEvent: ' , stEv type , ' for ' , view printString) infoPrintCR.
		].
		view dispatchEvent:stEv. 
		^ self.
	    ].

	    EventTrace == true ifTrue:[
		('JAVA: WComponent - handleEvent ignored:' , stEv type) infoPrintCR.
	    ].
	    ^ self
	]
    ].
    EventTrace == true ifTrue:[
	('JAVA: WComponent - handleEvent ignored') infoPrintCR.
    ]

    "Created: / 6.1.1998 / 21:10:17 / cg"
    "Modified: / 11.12.1998 / 01:04:14 / cg"
!

_WComponentPeer_hide:nativeContext
    |view|

    view := self viewForWPeer:nativeContext.
"/ view isPopUpView ifTrue:[self halt].

    Object errorSignal handle:[:ex |
    ] do:[
	view beInvisible
    ]

    "Created: / 7.1.1998 / 22:35:32 / cg"
    "Modified: / 4.12.1998 / 17:53:41 / cg"
!

_WComponentPeer_nativeHandleEvent:nativeContext
    "this is invoked by java, to let a widget handle any event which
     was not consumed (eaten) by java.
     If the view in question is some ST-widget, forward it.
     Ignore for JavaViews."

    |view jEv stEv|

^self.
    view := self viewForWPeer:nativeContext.
    view notNil ifTrue:[
	(view isKindOf:JavaView) ifFalse:[
	    jEv := nativeContext argAt:1.
	    stEv := jEv instVarNamed:'data'.
	    (stEv notNil and:[stEv ~~ 0]) ifTrue:[
		EventTrace == true ifTrue:[
		    ('JAVA: WComponent - handleEvent: ' , stEv type , ' for ' , view printString) infoPrintCR.
		].
		stEv sendEventWithFocusOn:nil.
		^ self.
	    ]
	]
    ].
    EventTrace == true ifTrue:[
	('JAVA: WComponent - handleEvent ignored') infoPrintCR.
    ]

    "Created: / 19.10.1998 / 21:26:16 / cg"
    "Modified: / 19.10.1998 / 23:26:37 / cg"
!

_WComponentPeer_requestFocus:nativeContext
    |view|

    view := self viewForWPeer:nativeContext.
"/ 'getFocus - ' print. view displayString printCR.

"/    view getKeyboardFocus

    "Created: / 7.1.1998 / 22:30:03 / cg"
    "Modified: / 4.12.1998 / 19:42:18 / cg"
!

_WComponentPeer_reshape:nativeContext
    self commonReshapeComponent:nativeContext

    "Modified: / 18.3.1997 / 19:30:21 / cg"
    "Created: / 4.1.1998 / 18:01:11 / cg"
!

_WComponentPeer_setBackground:nativeContext
    |jClr rgb clr view|

    view := self viewForWPeer:nativeContext.

    jClr := nativeContext argAt:1.
    rgb := jClr instVarNamed:'value'.
"/ self halt.
    clr := Color rgbValue:rgb.


    clr := clr on:(view device).

"/    (view superView isMemberOf:JavaEmbeddedFrameView) ifTrue:[
"/        view viewBackground:(view superView viewBackground).
"/        view backgroundPaint:(view superView viewBackground).
"/    ] ifFalse:[
"/        (view isMemberOf:JavaView) ifTrue:[
"/            view viewBackground:clr.
"/            view backgroundPaint:clr.
"/        ]
"/    ].

    (view isKindOf:ScrollableView) ifTrue:[
	view := view scrolledView
    ].
    view viewBackground:clr.
    view backgroundPaint:clr.

    "Created: / 16.10.1998 / 02:16:31 / cg"
    "Modified: / 16.10.1998 / 02:26:29 / cg"
!

_WComponentPeer_setCursor:nativeContext
    |view|

    view := self viewForWPeer:nativeContext.
"/ self halt.

    "Created: / 5.1.1998 / 01:52:30 / cg"
    "Modified: / 25.1.1998 / 01:21:52 / cg"
!

_WComponentPeer_setFont:nativeContext
    |view|

    view := self viewForWPeer:nativeContext.
"/ self halt.

    "Created: / 5.1.1998 / 00:55:17 / cg"
    "Modified: / 25.1.1998 / 01:22:19 / cg"
!

_WComponentPeer_setForeground:nativeContext
    |jClr rgb clr view|

    view := self viewForWPeer:nativeContext.

    jClr := nativeContext argAt:1.
    rgb := jClr instVarNamed:'value'.
"/ self halt.
    clr := Color rgbValue:rgb.


    clr := clr on:(view device).

    (view isKindOf:ScrollableView) ifTrue:[
	view := view scrolledView
    ].
    view paint:clr.

    "Created: / 16.10.1998 / 02:18:58 / cg"
    "Modified: / 16.10.1998 / 02:26:37 / cg"
!

_WComponentPeer_setZOrderPosition:nativeContext
    |view|

    view := self viewForWPeer:nativeContext.
"/    self unimplementedNativeMethod.
"/ self halt.
"/ self internalError:'breakPoint'

    "Created: / 4.1.1998 / 17:59:26 / cg"
    "Modified: / 25.1.1998 / 01:22:32 / cg"
!

_WComponentPeer_show:nativeContext
    |view|

    view := self viewForWPeer:nativeContext.

    "/ frame views are under my browsers own control
    (view isMemberOf:JavaEmbeddedFrameView) ifFalse:[
	view beVisible.
	view realize.
    ].

"/    view windowGroup notNil ifTrue:[
"/        windowServer addGroup:(view windowGroup)
"/    ].

    ^ nil

"/ self halt.

    "Created: / 5.1.1998 / 01:26:22 / cg"
    "Modified: / 4.12.1998 / 17:43:53 / cg"
!

_WComponentPeer_start:nativeContext
"/ self halt.

    "Modified: / 18.3.1997 / 18:43:18 / cg"
    "Created: / 5.1.1998 / 00:58:40 / cg"
!

_WContainerPeer_calculateInsets:nativeContext
    "/ new with ns4.0 ...

    "Created: / 16.10.1998 / 02:12:59 / cg"
!

_WDefaultFontCharset_canConvert:nativeContext
    ^ 1

    "Modified: / 21.8.1997 / 15:56:57 / cg"
    "Created: / 5.1.1998 / 01:55:47 / cg"
!

_WDialogPeer__hide:nativeContext
    |dialog|

    dialog := self viewForWPeer:nativeContext.

    dialog hide.

    "Created: / 7.1.1998 / 22:34:10 / cg"
    "Modified: / 8.1.1998 / 17:34:10 / cg"
!

_WDialogPeer__show:nativeContext
    |dialog|

    dialog := self viewForWPeer:nativeContext.
"/
"/ show does not work (yet); must setup windowgroup
"/ for it to get events ...
"/    dialog realize.

dialog show.
"/dialog fixSize.
"/dialog makeFullyVisible.
"/dialog openModal:[true] inGroup:JavaWindowGroup

    "Created: / 7.1.1998 / 21:52:15 / cg"
    "Modified: / 11.12.1998 / 14:43:05 / cg"
!

_WDialogPeer_create:nativeContext
    |jDialogPeer dialog|

    jDialogPeer := nativeContext receiver.

    dialog := ModalBox new.
    jDialogPeer instVarNamed:'pData' put:dialog.

    self createdWindowsView:dialog for:jDialogPeer.
    dialog windowGroup:JavaWindowGroup.
    JavaWindowGroup addTopView:dialog.

    WindowCreationTrace == true ifTrue:[
	'WDialogPeer_create: ' print. dialog printNL.
    ].

    "Created: / 7.1.1998 / 21:51:00 / cg"
    "Modified: / 15.1.1998 / 16:12:44 / cg"
!

_WDrawingSurfaceInfo_getDepth:nativeContext
    "/ int getDepth ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:21:00 / cg"
!

_WDrawingSurfaceInfo_getHBitmap:nativeContext
    "/ int getHBitmap ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:20:32 / cg"
!

_WDrawingSurfaceInfo_getHDC:nativeContext
    "/ int getHDC ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:20:50 / cg"
!

_WDrawingSurfaceInfo_getHPalette:nativeContext
    "/ int getHPalette ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:21:07 / cg"
!

_WDrawingSurfaceInfo_getHWnd:nativeContext
    "/ int getHWnd ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:20:23 / cg"
!

_WDrawingSurfaceInfo_getPBits:nativeContext
    "/ int getPBits ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:20:41 / cg"
!

_WDrawingSurfaceInfo_lock:nativeContext
    "/ int lock ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:20:00 / cg"
!

_WDrawingSurfaceInfo_unlock:nativeContext
    "/ void unlock ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:20:13 / cg"
!

_WEmbeddedFramePeer_create:nativeContext
    "/ void create (sun.awt.windows.WComponentPeer)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:16:09 / cg"
!

_WFileDialogPeer_show:nativeContext
    |jDialogPeer jDialog dialogView stDialog 
     title dir pattern f|

    jDialogPeer := nativeContext receiver.
    jDialog := jDialogPeer instVarNamed:'target'.
    dialogView := jDialogPeer instVarNamed:'pData'.

    stDialog := FileSelectionBox new.

    dir := jDialog instVarNamed:'dir'.
    dir notNil ifTrue:[
	stDialog directory:(Java as_ST_String:dir).
    ].
    pattern := jDialog instVarNamed:'file'.
    pattern notNil ifTrue:[
	stDialog pattern:(Java as_ST_String:pattern).
    ].
    title := jDialog instVarNamed:'title'.
    title notNil ifTrue:[
	stDialog title:(Java as_ST_String:title).
	stDialog label:(Java as_ST_String:title).
    ].

    stDialog show.

    stDialog accepted ifTrue:[
	f := stDialog pathName.

	"/ cannot use the one below - it has a builtIn fileSeparator if '\' (sigh)
	"/ jDialogPeer perform:#'handleSelected(Ljava/lang/String;)V' with:(Java as_String:f).

	jDialog 
	    perform:#'setFile(Ljava/lang/String;)V' 
	    with:(Java as_String:(f asFilename baseName)).
	jDialog 
	    perform:#'setDirectory(Ljava/lang/String;)V'
	    with:(Java as_String:(f asFilename directoryName , Filename separator asString)).
	jDialog 
	    perform:#'setVisible(Z)V'
	    with:0.
    ] ifFalse:[
	jDialogPeer 
	    perform:#'handleCancel()V'
    ].
"/ self halt.

    "Created: / 7.1.1998 / 22:38:45 / cg"
    "Modified: / 15.1.1998 / 13:04:05 / cg"
!

_WFontMetrics_bytesWidth:nativeContext
    "/ int bytesWidth (byte[] int int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:11:46 / cg"
!

_WFontMetrics_getMFCharSegmentWidth:nativeContext
    "get multi-font string-segment width.
     Not yet supported - use standard strings width"

    |jMetrics jFont jFontDescr stFont w
     bool1 cp offs lenght bp int1|

    jMetrics := nativeContext receiver.
    jFont := nativeContext argAt:1.
    jFontDescr := nativeContext argAt:2.
    bool1 := nativeContext argAt:3.
    cp := nativeContext argAt:4.
    offs := nativeContext argAt:5.
    lenght := nativeContext argAt:6.
    bp := nativeContext argAt:7.
    int1 := nativeContext argAt:8.

    stFont := jFont instVarNamed:'pData'.
    (stFont isNil or:[stFont == 0]) ifTrue:[
	self halt
    ].

    stFont device isNil ifTrue:[
	stFont := stFont on:Display.
	jFont instVarNamed:'pData' put:stFont.
    ].
    w := stFont widthOf:cp from:offs+1 to:offs+lenght.
    ^ w.

    "Created: / 5.1.1998 / 01:57:45 / cg"
    "Modified: / 13.1.1998 / 23:44:03 / cg"
!

_WFontMetrics_init:nativeContext
    |jMetrics jFont stFont widths family name style size|

    jMetrics := nativeContext receiver.
    jFont := jMetrics instVarNamed:'font'.

    family := jFont instVarNamed:'family'.
    family := Java as_ST_String:family.

    name := jFont instVarNamed:'name'.
    name := Java as_ST_String:name.

    style := jFont instVarNamed:'style'.
    size := jFont instVarNamed:'size'.

    stFont := Font family:family size:size.
    stFont isNil ifTrue:[
        stFont := Font family:'helvetica' size:size.
    ].
    stFont := stFont on:Display.
self halt.
"/    stFont := jFont instVarNamed:'pData'.
"/    stFont isNil ifTrue:[
"/        self halt
"/    ].

    stFont := stFont on:Display.
    jFont instVarNamed:'pData' put:stFont.

    jMetrics instVarNamed:'ascent'     put:stFont ascent.
    jMetrics instVarNamed:'descent'    put:stFont descent.
    jMetrics instVarNamed:'leading'    put:0.
    jMetrics instVarNamed:'height'     put:stFont height.
    jMetrics instVarNamed:'maxAscent'  put:stFont maxAscent.
    jMetrics instVarNamed:'maxDescent' put:stFont maxDescent.
    jMetrics instVarNamed:'maxHeight'  put:stFont maxHeight.
    jMetrics instVarNamed:'maxAdvance' put:stFont maxWidth.

    widths := Array new:256.
    0 to:255 do:[:i |
        widths at:(i+1) put:(stFont widthOf:(Character value:i))
    ].
    jMetrics instVarNamed:'widths' put:widths.
"/ self halt.

    "Modified: / 8.8.1997 / 12:06:53 / cg"
    "Created: / 5.1.1998 / 01:54:29 / cg"
!

_WFontMetrics_needsConversion:nativeContext
    |jFont jFontDescr stFont|

    jFont := nativeContext argAt:1.
    jFontDescr := nativeContext argAt:2.

    stFont := jFont instVarNamed:'pData'.
"/    stFont isNil ifTrue:[
"/        self halt
"/    ].
"/    stFont device isNil ifTrue:[
"/        stFont := stFont on:Display.
"/        jFont instVarNamed:'pData' put:stFont.
"/    ].
"/

    ^ 0

    "Modified: / 17.8.1997 / 17:16:29 / cg"
    "Created: / 5.1.1998 / 01:56:42 / cg"
!

_WFramePeer__setIconImage:nativeContext
    |frame imgRep image|

    frame := self viewForWPeer:nativeContext.
    imgRep := nativeContext argAt:1.
    imgRep notNil ifTrue:[
	image := imgRep instVarNamed:'pData'.
	(image notNil and:[image ~~ 0]) ifTrue:[
	    frame icon:image.
	]
    ].

    "Created: / 27.4.1998 / 17:15:09 / cg"
    "Modified: / 27.4.1998 / 17:18:24 / cg"
!

_WFramePeer_create:nativeContext
    |jFramePeer jFrame top frame pDataIdx|

    jFramePeer := nativeContext receiver.

    "/ for now: a kludge to create an embedded frame for
    "/ mozillaFrames

    jFrame := jFramePeer instVarNamed:'target'.
    (jFrame notNil 
    and:[(pDataIdx := jFrame class instVarOffsetOf:'pData') notNil])
    ifTrue:[
	((frame := jFrame instVarAt:pDataIdx) notNil 
	and:[frame ~~ 0]) ifTrue:[
	    WindowCreationTrace == true ifTrue:[
		'JAVA: targetFrame view already created: ' infoPrintCR.
	    ].
	    "/ sigh; pData was renamed to pNativeWidget in jdk1.2 ...
	    pDataIdx := jFramePeer class instVarOffsetOf:'pNativeWidget'.
	    pDataIdx isNil ifTrue:[
		"/ ok, we are < 1.2
		pDataIdx := jFramePeer class instVarOffsetOf:'pData'.
	    ].
	    jFramePeer instVarAt:pDataIdx put:frame.
	]
    ] ifFalse:[
	frame := jFramePeer instVarNamed:'pData'
    ].

    (frame notNil and:[frame ~~ 0]) ifTrue:[
	WindowCreationTrace == true ifTrue:[
	    'JAVA: frame view already created: ' infoPrint.
	    jFramePeer class name infoPrintCR.
	].
    ] ifFalse:[
"/ OLD
"/        frame := StandardSystemView new.
"/        self createdWindowsView:frame for:jFramePeer.
"/        JavaWindowGroup addTopView:frame.

	frame := JavaTopView new.
	frame delegate:self.
	frame javaPeer:jFramePeer.
	self createdWindowsView:frame for:jFramePeer.
	JavaWindowGroup addTopView:frame.

"/        top := StandardSystemView new.
"/        frame := JavaView origin:0.0@0.0 corner:1.0@1.0 in:top.
"/        frame delegate:self.
"/        frame javaPeer:jFramePeer.
"/        self createdWindowsView:frame for:jFramePeer.
"/        JavaWindowGroup addTopView:top.
        
    ].

    WindowCreationTrace == true ifTrue:[
	'JAVA: WFramePeer_create: ' print. jFramePeer displayString print.
	' frame: ' print. frame printNL.
    ].

    "Created: / 4.1.1998 / 17:56:39 / cg"
    "Modified: / 3.12.1998 / 00:10:21 / cg"
!

_WFramePeer_setMenuBar0:nativeContext
    |frame jMenuBarPeer menuPanel|

    frame := self viewForWPeer:nativeContext.

    jMenuBarPeer := nativeContext argAt:1.
    jMenuBarPeer isNil ifTrue:[
	"/ mhmh - JAVA wants to remove the frames menuPanel.
	"/ but I have no handle on it (for destroy).
	"/ search it in subViews of the frame.
	frame subViews copy do:[:v |
	    (v isKindOf:MenuPanel) ifTrue:[
		v destroy
	    ]
	]
    ] ifFalse:[
	menuPanel := jMenuBarPeer instVarNamed:'pData'.

	menuPanel origin:0.0@0.0 corner:1.0@(menuPanel preferredExtent y).
	frame addSubView:menuPanel.
    ].
    ^ nil

    "Created: / 7.1.1998 / 21:41:35 / cg"
    "Modified: / 8.1.1998 / 17:35:04 / cg"
!

_WFramePeer_setResizable:nativeContext
    |view onOff|

    view := self viewForWPeer:nativeContext.

    onOff := (nativeContext argAt:1) == 1.
    view isTopView ifTrue:[
	onOff ifTrue:[
	    view minExtent:10@10.
	    view maxExtent:(Screen current extent).
	] ifFalse:[
	    view minExtent:view extent.
	    view maxExtent:view extent.
	]
    ] ifFalse:[
	(view isMemberOf:JavaEmbeddedFrameView) ifFalse:[
	    self halt.
	]
    ].

"/ 'JAVA: WWindowPeer_setResizable: ' print. view print. ' yes/no: ' print. onOff printNL.

    ^ nil

    "Modified: / 16.1.1998 / 18:08:00 / cg"
    "Created: / 16.10.1998 / 02:21:34 / cg"
!

_WFramePeer_setTitle:nativeContext
    |view jString string|

    view := self viewForWPeer:nativeContext.

    jString := nativeContext argAt:1.
    string := Java as_ST_String:jString.

"/ 'JAVA: WFramePeer_pSetTitle: ' print. string print. ' ' print. view printNL.

    view label:string.
    ^ nil

    "Modified: / 8.1.1998 / 17:37:41 / cg"
    "Created: / 27.1.1998 / 21:42:57 / cg"
!

_WGraphics__dispose:nativeContext
    "/ void _dispose()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:17:51 / cg"
!

_WGraphics_changeClip:nativeContext        
    |gc x y w h r bool|

    gc := self gcForWGraphics:nativeContext.

    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    w := nativeContext argAt:3.
    h := nativeContext argAt:4.
    bool := (nativeContext argAt:5) ~~ 0.

    r := Rectangle left:x top:y width:w height:h.
"/ 'WGraphics_changeClip: ' infoPrint. r infoPrintCR.
    gc clippingRectangle:r.

    "Created: / 6.1.1998 / 20:57:21 / cg"
    "Modified: / 20.10.1998 / 19:40:10 / cg"
!

_WGraphics_clearRect:nativeContext
    |gc x y w h|

    gc := self gcForWGraphics:nativeContext.
"/    gc isNil ifTrue:[^ self].

    gc realized ifFalse:[
	'JAVA: drawing on unrealized gc - ignored' infoPrintCR.
	^ self
    ].

    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    w := nativeContext argAt:3.
    h := nativeContext argAt:4.

"/ self halt.
"/ self internalError:'breakPoint'.

    gc clearRectangleX:x y:y width:w height:h.

    "Created: / 8.1.1998 / 00:16:00 / cg"
    "Modified: / 8.1.1998 / 00:21:09 / cg"
!

_WGraphics_close:nativeContext
    "/ void close (sun.awt.windows.WPrintJob)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:19:40 / cg"
!

_WGraphics_copyArea:nativeContext
    |gc srcX srcY w h deltaX deltaY|

    gc := self gcForWGraphics:nativeContext.
"/    gc isNil ifTrue:[^ self].

    gc realized ifFalse:[
	'JAVA: copyArea on unrealized gc - ignored' infoPrintCR.
	^ self
    ].

    srcX := nativeContext argAt:1.
    srcY := nativeContext argAt:2.
    w := nativeContext argAt:3.
    h := nativeContext argAt:4.
    deltaX := nativeContext argAt:5.
    deltaY := nativeContext argAt:6.

    gc
	copyFrom:gc
	x:srcX y:srcY 
	toX:srcX+deltaX y:srcY+deltaY 
	width:w height:h

    "Created: / 8.1.1998 / 00:16:00 / cg"
    "Modified: / 9.4.1998 / 22:01:32 / cg"
!

_WGraphics_createFromComponent:nativeContext
    |jGraphics jWin view|

    jGraphics := nativeContext receiver.
    jWin := nativeContext argAt:1.

    view := KnownWindows at:jWin ifAbsent:nil.
    view isNil ifTrue:[
	self halt.
	^ self
    ].
    view clippingRectangle:nil.

"/    "/ just a consistency check ...
"/    (jWin instVarNamed:'xid') ~~ view ifTrue:[
"/        self halt:'consistency check'
"/    ].

    jGraphics instVarNamed:'pData' put:view.

    "Created: / 6.1.1998 / 20:55:18 / cg"
    "Modified: / 20.10.1998 / 19:38:18 / cg"
!

_WGraphics_createFromGraphics:nativeContext
    |jGraphics graphics gc|

    jGraphics := nativeContext receiver.
    graphics := nativeContext argAt:1.
    gc := graphics instVarNamed:'pData'.

    jGraphics instVarNamed:'pData' put:gc.
    gc clippingRectangle:nil.

    "Created: / 8.1.1998 / 00:47:39 / cg"
    "Modified: / 20.10.1998 / 19:37:58 / cg"
!

_WGraphics_createFromHDC:nativeContext
    "/ void createFromHDC (int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:17:32 / cg"
!

_WGraphics_createFromPrintJob:nativeContext
    "/ void createFromPrintJob (sun.awt.windows.WPrintJob)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:17:20 / cg"
!

_WGraphics_dispose:nativeContext
    |gc|

    gc := self gcForWGraphics:nativeContext.
    gc isNil ifTrue:[^ self].
    gc clippingRectangle:nil.

    "Created: / 6.1.1998 / 20:58:38 / cg"
    "Modified: / 20.10.1998 / 19:35:05 / cg"
!

_WGraphics_drawArc:nativeContext
    |gc x y w h startAngle endAngle|

    gc := self gcForWGraphics:nativeContext.
"/    gc isNil ifTrue:[^ self].
    gc realized ifFalse:[^ self].

    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    w := nativeContext argAt:3.
    h := nativeContext argAt:4.
    startAngle := nativeContext argAt:5.
    endAngle := nativeContext argAt:6.

    DrawOPTrace ifTrue:[
	'drawArc x/y= ' print. x print. '@' print. y print. 
	       ' w/h= ' print. w print. '@' print. h print.
	       ' startAngle= ' print. startAngle print. ' endAngle= ' print. endAngle printCR.
    ].
    gc 
	displayArcX:x y:y 
	width:w height:h 
	from:startAngle angle:(endAngle - startAngle).

    "Created: / 6.1.1998 / 21:00:15 / cg"
    "Modified: / 28.1.1999 / 17:38:45 / cg"
!

_WGraphics_drawBytes:nativeContext
    "/ void drawBytes (byte[] int int int int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:18:56 / cg"
!

_WGraphics_drawLine:nativeContext        
    |gc x y x2 y2|

    gc := self gcForWGraphics:nativeContext.
"/    gc isNil ifTrue:[^ self].
    gc realized ifFalse:[^ self].

    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    x2 := nativeContext argAt:3.
    y2 := nativeContext argAt:4.

    DrawOPTrace ifTrue:[
	'drawLine x/y= ' print. x print. '@' print. y print. ' x2/y2= ' print. x2 print. '@' print. y2 printCR.
    ].
    gc displayLineFromX:x y:y toX:x2 y:y2

    "Created: / 6.1.1998 / 20:59:27 / cg"
    "Modified: / 8.1.1998 / 00:34:23 / cg"
!

_WGraphics_drawMFCharsConvertedSegment:nativeContext
    "/ int drawMFCharsConvertedSegment (java.awt.Font sun.awt.FontDescriptor byte[] int int int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:18:44 / cg"
!

_WGraphics_drawMFCharsSegment:nativeContext       
    |jFont jFontDescr s gc x y offs len|

    gc := self gcForWGraphics:nativeContext.
    gc realized ifFalse:[^ self].

    jFont := nativeContext argAt:1.
    jFontDescr := nativeContext argAt:2.
    s := nativeContext argAt:3.
    offs := nativeContext argAt:4.
    len := nativeContext argAt:5.
    x := nativeContext argAt:6.
    y := nativeContext argAt:7.

    DrawOPTrace ifTrue:[
	'drawMFCharsSegment x/y= ' print. x print. '@' print. y print. ' s= ' print. s printCR.
    ].
    gc displayString:s from:offs+1 to:offs+len x:x y:y.
    ^ (gc font onDevice:(gc graphicsDevice)) widthOf:s.

    "Created: / 6.1.1998 / 21:01:07 / cg"
    "Modified: / 25.1.1998 / 20:45:55 / cg"
!

_WGraphics_drawOval:nativeContext
    |gc x y w h|

    gc := self gcForWGraphics:nativeContext.
"/    gc isNil ifTrue:[^ self].
    gc realized ifFalse:[^ self].

    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    w := nativeContext argAt:3.
    h := nativeContext argAt:4.

    DrawOPTrace ifTrue:[
	'drawOval x/y= ' print. x print. '@' print. y print. 
		' w/h= ' print. w print. '@' print. h printCR.
    ].
    gc displayArcX:x y:y width:w height:h from:0 angle:360.

    "Created: / 8.1.1998 / 00:44:31 / cg"
    "Modified: / 9.4.1998 / 22:10:23 / cg"
!

_WGraphics_drawPolygon:nativeContext        
    |gc xVector yVector count points|

    gc := self gcForWGraphics:nativeContext.
"/    gc isNil ifTrue:[^ self].
    gc realized ifFalse:[^ self].

    xVector := nativeContext argAt:1.
    yVector := nativeContext argAt:2.
    count := nativeContext argAt:3.

    DrawOPTrace ifTrue:[
	'drawPolgon' printCR.
    ].

    points := (1 to:count) collect:[:i | (xVector at:i) @ (yVector at:i)].
    gc displayPolygon:points

    "Created: / 8.1.1998 / 00:57:28 / cg"
    "Modified: / 8.1.1998 / 00:57:49 / cg"
!

_WGraphics_drawPolyline:nativeContext
    "/ void drawPolyline (int[] int[] int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:19:07 / cg"
!

_WGraphics_drawRect:nativeContext
    |gc x y w h|

    gc := self gcForWGraphics:nativeContext.
"/    gc isNil ifTrue:[^ self].
    gc realized ifFalse:[^ self].

    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    w := nativeContext argAt:3.
    h := nativeContext argAt:4.

"/ self halt.
"/ self internalError:'breakPoint'.

    gc displayRectangleX:x y:y width:w height:h.

    "Modified: / 8.1.1998 / 00:34:33 / cg"
    "Created: / 8.1.1998 / 00:59:05 / cg"
!

_WGraphics_drawRoundRect:nativeContext
    |gc x y w h|

    gc := self gcForWGraphics:nativeContext.
"/    gc isNil ifTrue:[^ self].
    gc realized ifFalse:[^ self].

    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    w := nativeContext argAt:3.
    h := nativeContext argAt:4.

"/ self halt.
"/ self internalError:'breakPoint'.

    gc displayRectangleX:x y:y width:w height:h.

    "Modified: / 8.1.1998 / 00:34:33 / cg"
    "Created: / 8.1.1998 / 00:59:26 / cg"
!

_WGraphics_drawSFChars:nativeContext
    "/ void drawSFChars (char[]s, int pos1, int len, int x, int y)

    |gc str x y idx1 nChars|

    gc := self gcForWGraphics:nativeContext.
    gc realized ifFalse:[^ self].

    str := nativeContext argAt:1.
    idx1 := nativeContext argAt:2.
    nChars := nativeContext argAt:3.
    x := nativeContext argAt:4.
    y := nativeContext argAt:5.

    DrawOPTrace ifTrue:[
	'drawSFChars x/y= ' print. x print. '@' print. y print. 
	       ' s= ' print. str printCR.
    ].
    gc displayString:str from:idx1+1 to:idx1+nChars x:x y:y

    "Created: / 6.1.1998 / 21:11:31 / cg"
    "Modified: / 8.1.1998 / 00:33:59 / cg"

!

_WGraphics_fillArc:nativeContext
    |gc x y w h startAngle endAngle|

    gc := self gcForWGraphics:nativeContext.
"/    gc isNil ifTrue:[^ self].
    gc realized ifFalse:[^ self].

    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    w := nativeContext argAt:3.
    h := nativeContext argAt:4.
    startAngle := nativeContext argAt:5.
    endAngle := nativeContext argAt:6.

    DrawOPTrace ifTrue:[
	'fillArc x/y= ' print. x print. '@' print. y print. 
	       ' w/h= ' print. w print. '@' print. h print.
	       ' startAngle= ' print. startAngle print. ' endAngle= ' print. endAngle printCR.
    ].
    gc fillArcX:x y:y width:w height:h from:startAngle angle:(endAngle - startAngle)

    "Created: / 6.1.1998 / 21:11:31 / cg"
    "Modified: / 8.1.1998 / 00:33:59 / cg"
!

_WGraphics_fillOval:nativeContext
    |gc x y w h|

    gc := self gcForWGraphics:nativeContext.
"/    gc isNil ifTrue:[^ self].
    gc realized ifFalse:[^ self].

    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    w := nativeContext argAt:3.
    h := nativeContext argAt:4.

    DrawOPTrace ifTrue:[
	'drawOval x/y= ' print. x print. '@' print. y print. 
		' w/h= ' print. w print. '@' print. h printCR.
    ].
    gc fillArcX:x y:y width:w height:h from:0 angle:360

    "Created: / 8.1.1998 / 00:46:00 / cg"
    "Modified: / 8.1.1998 / 00:46:20 / cg"
!

_WGraphics_fillPolygon:nativeContext        
    |gc xVector yVector count points|

    gc := self gcForWGraphics:nativeContext.
"/    gc isNil ifTrue:[^ self].
    gc realized ifFalse:[^ self].

    xVector := nativeContext argAt:1.
    yVector := nativeContext argAt:2.
    count := nativeContext argAt:3.

    DrawOPTrace ifTrue:[
	'fillPolgon' printCR.
    ].

    points := (1 to:count) collect:[:i | (xVector at:i) @ (yVector at:i)].
    gc fillPolygon:points

    "Created: / 8.1.1998 / 00:58:09 / cg"
    "Modified: / 25.1.1998 / 11:03:19 / cg"
!

_WGraphics_fillRect:nativeContext
    |gc x y w h|

    gc := self gcForWGraphics:nativeContext.
"/    gc isNil ifTrue:[^ self].
    gc realized ifFalse:[^ self].

    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    w := nativeContext argAt:3.
    h := nativeContext argAt:4.

"/ self halt.
"/ self internalError:'breakPoint'.

    gc fillRectangleX:x y:y width:w height:h.

    "Created: / 15.8.1997 / 15:43:10 / cg"
    "Modified: / 8.1.1998 / 00:34:33 / cg"
!

_WGraphics_fillRoundRect:nativeContext
    |gc x y w h|

    gc := self gcForWGraphics:nativeContext.
"/    gc isNil ifTrue:[^ self].
    gc realized ifFalse:[^ self].

    x := nativeContext argAt:1.
    y := nativeContext argAt:2.
    w := nativeContext argAt:3.
    h := nativeContext argAt:4.

"/ self halt.
"/ self internalError:'breakPoint'.

    gc displayRectangleX:x y:y width:w height:h.

    "Modified: / 8.1.1998 / 00:34:33 / cg"
    "Created: / 8.1.1998 / 00:59:36 / cg"
!

_WGraphics_getClipBounds:nativeContext        
    |gc rect r x y w h|

    gc := self gcForWGraphics:nativeContext.
"/    gc isNil ifTrue:[^ nil].

    rect := (Java classForName:'java.awt.Rectangle') basicNew.

    (gc isMemberOf:JavaView) ifTrue:[
	"/ r := gc clippingRectangleOrNil. 
	r := gc getNextUpdateRectangle.
    ].
    r isNil ifTrue:[
	r := gc clippingRectangleOrNil. 
    ].

    r isNil ifTrue:[
	x := y := 0.
	w := (gc width).
	h := (gc height).
    ] ifFalse:[
	x := (r left).
	y := (r top).
	w := (r width).
	h := (r height).
    ].
    rect instVarNamed:'x' put:x.
    rect instVarNamed:'y' put:y.
    rect instVarNamed:'width' put:w.
    rect instVarNamed:'height' put:h.

"/ 'WGraphics__getClipBounds ' infoPrint. (x@y extent:w@h) infoPrintCR.

    ^ rect

    "Created: / 6.1.1998 / 20:58:07 / cg"
    "Modified: / 23.12.1998 / 20:14:09 / cg"
!

_WGraphics_imageCreate:nativeContext        
    |jGraphics imgRep|

    jGraphics := nativeContext receiver.
    imgRep := nativeContext argAt:1.

    jGraphics instVarNamed:'pData' put:(imgRep instVarNamed:'pData').
"/ self halt.

    "Created: / 11.1.1998 / 16:34:30 / cg"
    "Modified: / 17.1.1998 / 12:37:18 / cg"
!

_WGraphics_pSetFont:nativeContext
    |gc jFont stFont|

    gc := self gcForWGraphics:nativeContext.
    jFont := nativeContext argAt:1.

    stFont := jFont instVarNamed:'pData'.
    (stFont isNil or:[stFont == 0]) ifTrue:[
"/ self halt.
    ] ifFalse:[
	gc font:stFont
    ].

    "Created: / 6.1.1998 / 20:56:47 / cg"
    "Modified: / 15.1.1998 / 12:31:20 / cg"
!

_WGraphics_pSetForeground:nativeContext
    |gc rgb clr|

    gc := self gcForWGraphics:nativeContext.

    rgb := nativeContext argAt:1.
    rgb isInteger ifFalse:[
        "/ its a java.awt.Color
        rgb := rgb instVarNamed:'value'.
    ].
    clr := Color rgbValue:rgb.
    gc paint:(clr nearestOn:gc device).

"/ self halt.
"/ self internalError:'breakPoint'.

    "Created: / 6.1.1998 / 20:56:14 / cg"
    "Modified: / 23.12.1998 / 20:10:49 / cg"
!

_WGraphics_print:nativeContext
    "/ void print (sun.awt.windows.WComponentPeer)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:19:25 / cg"
!

_WGraphics_removeClip:nativeContext
    "/ void removeClip ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:18:05 / cg"
!

_WGraphics_setPaintMode:nativeContext
    |gc|

    gc := self gcForWGraphics:nativeContext.
    gc function:#copy.

    true "DrawOPTrace" ifTrue:[
	'copyMode' infoPrintCR.
    ].

    "Created: / 8.1.1998 / 00:33:44 / cg"
    "Modified: / 28.1.1998 / 23:25:56 / cg"
!

_WGraphics_setXORMode:nativeContext
    |gc jColor rgb invColor device|

    gc := self gcForWGraphics:nativeContext.
    jColor := nativeContext argAt:1.
    device := gc graphicsDevice.

"/    "/ on trueColor systems, use the provided
"/    "/ rgb value for inverting.
"/    "/ on palette systems, use white ^ black
"/
"/    device visualType == #TrueColor ifTrue:[
"/        rgb := jColor instVarNamed:'value'.
"/        rgb := rgb bitAnd:16rFFFFFF.
"/        rgb == 0 ifTrue:[
"/            rgb := 16rFFFFFF.
"/        ].
"/        invColor := rgb
"/    ] ifFalse:[
"/        invColor := device blackpixel bitXor:device whitepixel.
"/    ].

    invColor := device blackpixel bitXor:device whitepixel.

"/    gc foreground:(Color colorId:invColor)
"/       background:device blackColor.
    device 
	setForeground:invColor background:0
	in:gc gcId.
    gc function:#xor.

    true "DrawOPTrace" ifTrue:[
	'xorMode' infoPrintCR.
    ].

    "Created: / 8.1.1998 / 00:36:17 / cg"
    "Modified: / 28.1.1998 / 23:45:03 / cg"
!

_WLabelPeer_create:nativeContext
    |jLabelPeer jLabel jFrame frame label
     lbl|

    jLabelPeer := nativeContext receiver.
    jLabel := jLabelPeer instVarNamed:'target'.

    lbl := jLabel instVarNamed:'text'.
    lbl notNil ifTrue:[
	lbl := Java as_ST_String:lbl
    ].

    jFrame := nativeContext argAt:1.
    frame := jFrame instVarNamed:'pData'.

    label := Label in:frame.
    label sizeFixed:true.
    lbl notNil ifTrue:[
	label label:lbl
    ].
    self createdWindowsView:label for:jLabelPeer.

    WindowCreationTrace == true ifTrue:[
	'WLabelPeer_create: ' print. frame print. ' -> ' print. label printNL.
    ].

    "Created: / 7.1.1998 / 21:42:31 / cg"
    "Modified: / 13.1.1998 / 22:10:47 / cg"
!

_WLabelPeer_setAlignment:nativeContext
    |label alignNr|

    alignNr := nativeContext argAt:1.
    label := self viewForWPeer:nativeContext.
    label notNil ifTrue:[
    ].

    "Created: / 7.1.1998 / 21:43:12 / cg"
    "Modified: / 8.1.1998 / 17:35:29 / cg"
!

_WLabelPeer_setText:nativeContext
    |label jString str|

    jString := nativeContext argAt:1.

    label := self viewForWPeer:nativeContext.
    jString notNil ifTrue:[
	str := Java as_ST_String:jString
    ].
    label label:str

    "Created: / 7.1.1998 / 21:43:51 / cg"
    "Modified: / 3.12.1998 / 14:59:18 / cg"
!

_WListPeer__addItem:nativeContext
    |jString index1 length selListView m|

    selListView := self viewForWPeer:nativeContext.

    jString := nativeContext argAt:1.
    index1 := nativeContext argAt:2.
    length := nativeContext argAt:3.

    (m := selListView model) notNil ifTrue:[
	m list addLast:(Java as_ST_String:jString).
	m changed:#list.
    ].

    "Created: / 26.10.1998 / 20:11:30 / cg"
    "Modified: / 14.11.1998 / 01:21:03 / cg"
!

_WListPeer_addItem:nativeContext
    |jString index selListView m|

    selListView := self viewForWPeer:nativeContext.

    jString := nativeContext argAt:1.
    index := nativeContext argAt:2.

    m := selListView model.
    m isNil ifTrue:[
	Transcript showCR:'JAVA: access to listModel of closed view'.
    ] ifFalse:[
	m list addLast:(Java as_ST_String:jString).
	m changed:#list.
    ]

    "Created: / 24.1.1998 / 21:10:05 / cg"
    "Modified: / 2.11.1998 / 17:12:52 / cg"
!

_WListPeer_create:nativeContext
    |jListPeer jFrame frame selectionInListView|

    jListPeer := nativeContext receiver.

    jFrame := nativeContext argAt:1.
    frame := jFrame instVarNamed:'pData'.

    selectionInListView := ScrollableView for:SelectionInListView in:frame.
    selectionInListView action:[:index | jListPeer perform:#'handleListChanged(I)V' with:(index - 1)].
    selectionInListView doubleClickAction:[:index | jListPeer perform:#'handleAction(I)V' with:(index - 1)].
    selectionInListView model:(SelectionInList new list:(List new)).
    selectionInListView useIndex:true.

    self createdWindowsView:selectionInListView for:jListPeer.

    WindowCreationTrace == true ifTrue:[
	'WTextAreaPeer_create: ' print. frame print. ' -> ' print. selectionInListView printNL.
    ].

    "Created: / 24.1.1998 / 19:58:54 / cg"
    "Modified: / 9.4.1998 / 22:19:07 / cg"
!

_WListPeer_delItems:nativeContext
    |jString index1 index2 selListView model list|

    selListView := self viewForWPeer:nativeContext.

    index1 := (nativeContext argAt:1) + 1. "/ java indices are 0-based.
    index2 := (nativeContext argAt:2) + 1. "/ st indices are 1-based.

    model := selListView model.
    model isNil ifTrue:[^ self].
    list := model list.
    list size >= index1 ifTrue:[
	list removeFromIndex:index1 toIndex:(index2 min:list size).
	model changed:#list.
    ].

    "Created: / 9.4.1998 / 22:19:25 / cg"
    "Modified: / 30.12.1998 / 20:00:50 / cg"
!

_WListPeer_deselect:nativeContext
    "/ void deselect (int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:15:10 / cg"
!

_WListPeer_getMaxWidth:nativeContext
    "/ int getMaxWidth ()

    ^ 1000 "/ a dummy value

"/    UnimplementedNativeMethodSignal raise

    "Created: / 14.11.1998 / 10:44:29 / cg"
!

_WListPeer_isSelected:nativeContext
    |selectionInListView index model|

    selectionInListView := self viewForWPeer:nativeContext.

    index := nativeContext argAt:1.
    (model := selectionInListView model) notNil ifTrue:[
	(model selectionIndex == (index + 1))  "/ JAVA indexing starts at 0
	ifTrue:[
	    ^ 1
	]
    ].
    ^ 0.

    "Created: / 24.1.1998 / 22:42:31 / cg"
    "Modified: / 25.1.1998 / 01:35:32 / cg"
!

_WListPeer_makeVisible:nativeContext
    |selectionInListView lineNr|

    selectionInListView := self viewForWPeer:nativeContext.

    lineNr := nativeContext argAt:1.

    selectionInListView makeLineVisible:(lineNr + 1)

    "Modified: / 24.1.1998 / 20:01:06 / cg"
    "Created: / 20.10.1998 / 14:14:50 / cg"
!

_WListPeer_select:nativeContext
    |selectionInListView index model|

    selectionInListView := self viewForWPeer:nativeContext.

    index := nativeContext argAt:1.
    (model := selectionInListView model) notNil ifTrue:[
	model selectionIndex:(index + 1).  "/ JAVA indexing starts at 0
    ]

    "Created: / 24.1.1998 / 22:32:35 / cg"
    "Modified: / 25.1.1998 / 01:28:46 / cg"
!

_WListPeer_setMultipleSelections:nativeContext
    |selectionInListView onOff|

    selectionInListView := self viewForWPeer:nativeContext.

    onOff := (nativeContext argAt:1) ~~ 0.

    selectionInListView multipleSelectOk:onOff.

    "Modified: / 24.1.1998 / 20:01:06 / cg"
!

_WListPeer_updateMaxItemWidth:nativeContext
    |selectionInListView lineNr|

    selectionInListView := self viewForWPeer:nativeContext.

    "Created: / 26.10.1998 / 20:09:46 / cg"
!

_WMenuBarPeer_addMenu:nativeContext
    "/ void addMenu (java.awt.Menu)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:14:00 / cg"
!

_WMenuBarPeer_create:nativeContext
    |jMenuBarPeer jMenuBar jFrame frame menuBar|

    jMenuBarPeer := nativeContext receiver.
    jMenuBar := jMenuBarPeer instVarNamed:'target'.

    jFrame := nativeContext argAt:1.
    frame := jFrame instVarNamed:'pData'.

    menuBar := MenuPanel in:frame.
    menuBar verticalLayout:false.
    menuBar realize.

    self createdWindowsView:menuBar for:jMenuBarPeer.

    WindowCreationTrace == true ifTrue:[
	'WMenuBarPeer_create: ' print. frame print. ' -> ' print. menuBar printNL.
    ].

    "Created: / 7.1.1998 / 21:38:31 / cg"
    "Modified: / 25.1.1998 / 13:19:03 / cg"
!

_WMenuBarPeer_delMenu:nativeContext
    "/ void delMenu (int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:14:11 / cg"
!

_WMenuItemPeer__dispose:nativeContext
    |jMenuItemPeer item|

    jMenuItemPeer := nativeContext receiver.
    item := jMenuItemPeer instVarNamed:'pData'.

"/ what should be done here ?

    "Created: / 29.3.1998 / 17:16:05 / cg"
    "Modified: / 29.3.1998 / 17:16:35 / cg"
!

_WMenuItemPeer__setLabel:nativeContext
    "/ void _setLabel (java.lang.String)

    |jMenuItemPeer item label|

    jMenuItemPeer := nativeContext receiver.
    item := jMenuItemPeer instVarNamed:'pData'.
    (item isNil or:[item == 0]) ifTrue:[
	'JAVA [warning]: NULL menu item in setLabel' infoPrintCR.
	^ self
    ].

    label := nativeContext argAt:1.
    label isNil ifTrue:[
	label := ''
    ] ifFalse:[
	label := Java as_ST_String:label
    ].
    item label:label.

    "Modified: / 11.12.1998 / 16:40:18 / cg"
!

_WMenuItemPeer_create:nativeContext
    |jMenuItemPeer jMenuItem jMenuPeer menu item lbl|

    jMenuItemPeer := nativeContext receiver.
    jMenuItem := jMenuItemPeer instVarNamed:'target'.

    jMenuPeer := nativeContext argAt:1.
    menu := jMenuPeer instVarNamed:'pData'.
    (menu isNil or:[menu == 0]) ifTrue:[
	'JAVA: no menu to create item in' infoPrintCR.
	^ self
    ].
    item := menu createAtIndex:nil.
    item value:[
		jMenuItemPeer perform:#'handleAction(I)V' with:0
	       ].

    lbl := jMenuItem instVarNamed:'label'.
    lbl notNil ifTrue:[
	lbl := Java as_ST_String:lbl.
	item label:lbl
    ].

    jMenuItemPeer instVarNamed:'pData' put:item.

    WindowOPTrace == true ifTrue:[
	'WMenuItem_create: ' print. menu print. ' -> ' print. item printNL.
    ].

    "Created: / 7.1.1998 / 21:40:44 / cg"
    "Modified: / 3.12.1998 / 20:43:20 / cg"
!

_WMenuItemPeer_enable:nativeContext
    |jMenuItemPeer item state|

    jMenuItemPeer := nativeContext receiver.
    item := jMenuItemPeer instVarNamed:'pData'.
    (item isNil or:[item == 0]) ifTrue:[
	'JAVA [warning]: NULL menu item in enable' infoPrintCR.
	^ self
    ].

    state := nativeContext argAt:1.
    item enabled:(state ~~ 0)

    "Created: / 7.1.1998 / 22:41:38 / cg"
    "Modified: / 11.12.1998 / 16:40:26 / cg"
!

_WMenuPeer_addSeparator:nativeContext
    "/ void addSeparator ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:13:14 / cg"
!

_WMenuPeer_createMenu:nativeContext
    |jMenuPeer jMenu jMenuBarPeer menuPanel menu
     lbl item|

    jMenuPeer := nativeContext receiver.
    jMenu := jMenuPeer instVarNamed:'target'.

    jMenuBarPeer := nativeContext argAt:1.
    menuPanel := jMenuBarPeer instVarNamed:'pData'.

    item := menuPanel createAtIndex:nil.
    lbl := jMenu instVarNamed:'label'.
    lbl notNil ifTrue:[
	lbl := Java as_ST_String:lbl.
	item label:lbl
    ].

    menu := MenuPanel new.
    item submenu:menu.

    jMenuPeer instVarNamed:'pData' put:menu.

'createMenuPeer: ' print. menuPanel print. ' -> ' print. menu printNL.

    "Created: / 7.1.1998 / 21:39:50 / cg"
    "Modified: / 13.1.1998 / 22:11:09 / cg"
!

_WMenuPeer_createSubMenu:nativeContext
    "/ void createSubMenu (sun.awt.windows.WMenuPeer)
"/    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:13:43 / cg"
    "Modified: / 3.12.1998 / 21:41:07 / cg"
!

_WMenuPeer_delItem:nativeContext
    "/ void delItem (int)
    |jMenuPeer jMenu menuPanel itemIndex|

    jMenuPeer := nativeContext receiver.
    menuPanel := jMenuPeer instVarNamed:'pData'.

    itemIndex := nativeContext argAt:1.
    menuPanel remove:itemIndex.

"/    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:13:30 / cg"
    "Modified: / 10.12.1998 / 21:12:29 / cg"
!

_WPanelPeer_calculateInsets:nativeContext
    "/ new with jdk1.2 ...

    "Created: / 27.1.1998 / 21:40:00 / cg"
!

_WPopupMenuPeer__show:nativeContext
    "/ void _show (java.awt.Event)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:12:53 / cg"
!

_WPopupMenuPeer_createMenu:nativeContext
    "/ void createMenu (sun.awt.windows.WComponentPeer)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:12:43 / cg"
!

_WPrintJob_end:nativeContext
    "/ void end ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:11:28 / cg"
!

_WScrollPanePeer__getHScrollbarHeight:nativeContext
    |scrollPane|

    scrollPane := self viewForWPeer:nativeContext.
    ^ HorizontalScrollBar new preferredExtent y.

    "Created: / 9.4.1998 / 17:30:56 / cg"
    "Modified: / 10.4.1998 / 14:59:28 / cg"
!

_WScrollPanePeer__getVScrollbarWidth:nativeContext
    |scrollPane|

    scrollPane := self viewForWPeer:nativeContext.
    ^ ScrollBar new preferredExtent x.

    "Created: / 9.4.1998 / 17:29:48 / cg"
    "Modified: / 10.4.1998 / 15:00:33 / cg"
!

_WScrollPanePeer_create:nativeContext
    |jScrollPanePeer jScrollPane jFrame frame scrollPane
     lbl|

    jScrollPanePeer := nativeContext receiver.
    jScrollPane := jScrollPanePeer instVarNamed:'target'.

    jFrame := nativeContext argAt:1.
    frame := jFrame instVarNamed:'pData'.

    "/ create with a simple view ...
    scrollPane := ScrollableView for:JavaView in:frame.

    self createdWindowsView:scrollPane for:jScrollPanePeer.

    WindowCreationTrace == true ifTrue:[
	'WScrollPanePeer_create: ' print. frame print. ' -> ' print. scrollPane printNL.
    ].

    "Created: / 9.4.1998 / 17:25:08 / cg"
    "Modified: / 9.4.1998 / 22:06:09 / cg"
!

_WScrollPanePeer_getOffset:nativeContext
    "/ int getOffset (int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:16:29 / cg"
!

_WScrollPanePeer_getScrollChild:nativeContext
    "/ java.awt.Component getScrollChild ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:17:00 / cg"
!

_WScrollPanePeer_setInsets:nativeContext

    "Modified: / 9.4.1998 / 17:26:11 / cg"
    "Created: / 9.4.1998 / 17:29:10 / cg"
!

_WScrollPanePeer_setScrollPosition:nativeContext
    "/ void setScrollPosition (int int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:16:44 / cg"
!

_WScrollPanePeer_setSpans:nativeContext

    "Created: / 9.4.1998 / 17:31:44 / cg"
!

_WScrollbarPeer__setValues:nativeContext
    |scrollBar value visibleAmount min max|

    scrollBar := self viewForWPeer:nativeContext.

    value := nativeContext argAt:1.
    visibleAmount := nativeContext argAt:2.
    min := nativeContext argAt:3.
    max := nativeContext argAt:4.

    (min ~~ 0 or:[max ~~ 100]) ifTrue:[
	scrollBar thumb start:min stop:max.
    ].

    scrollBar thumbOrigin:value thumbHeight:visibleAmount.

    "Created: / 13.1.1998 / 22:13:57 / cg"
    "Modified: / 14.10.1998 / 14:53:00 / cg"
!

_WScrollbarPeer_create:nativeContext
    |jScrollbarPeer jScrollbar jFrame frame scrollBar
     min max|

    jScrollbarPeer := nativeContext receiver.
    jScrollbar := jScrollbarPeer instVarNamed:'target'.

    jFrame := nativeContext argAt:1.
    frame := jFrame instVarNamed:'pData'.

    (jScrollbar instVarNamed:'orientation') == 0 "HORIZONTAL" ifTrue:[
	scrollBar := HorizontalScrollBar in:frame.
    ] ifFalse:[
	scrollBar := ScrollBar in:frame.
    ].
    min := jScrollbar instVarNamed:'minimum'.
    max := jScrollbar instVarNamed:'maximum'.

    scrollBar scrollDownAction:[
			scrollBar thumbOrigin:(scrollBar thumbOrigin + ((max-min)/10) min:max).
			jScrollbarPeer perform:#'dragAbsolute(I)V' with:scrollBar thumbOrigin rounded.
		     ].
    scrollBar scrollUpAction:[
			scrollBar thumbOrigin:(scrollBar thumbOrigin - ((max-min)/10) max:min).
			jScrollbarPeer perform:#'dragAbsolute(I)V' with:scrollBar thumbOrigin rounded.
		     ].
    scrollBar scrollAction:[:org |
			jScrollbarPeer perform:#'dragAbsolute(I)V' with:org rounded.
		     ].
    self createdWindowsView:scrollBar for:jScrollbarPeer.

    WindowCreationTrace == true ifTrue:[
	'WScrollbarPeer_create: ' print. frame print. ' -> ' print. scrollBar printNL.
    ].

    "Created: / 5.1.1998 / 01:53:30 / cg"
    "Modified: / 14.10.1998 / 15:36:19 / cg"
!

_WScrollbarPeer_setLineIncrement:nativeContext
    |scrollBar inc|

Transcript showCR:'JavaVM: WScrollbarPeer_setLineIncrement unimplemented'.

    scrollBar := self viewForWPeer:nativeContext.

    inc := nativeContext argAt:1.
"/    scrollBar thumb lineIncrement:inc.

    "Created: / 25.1.1998 / 11:52:19 / cg"
    "Modified: / 14.10.1998 / 14:53:56 / cg"
!

_WScrollbarPeer_setPageIncrement:nativeContext
    |scrollBar inc|

Transcript showCR:'JavaVM: WScrollbarPeer_setPageIncrement unimplemented'.

    scrollBar := self viewForWPeer:nativeContext.

    inc := nativeContext argAt:1.
"/    scrollBar thumb pageIncrement:inc.

    "Created: / 25.1.1998 / 11:52:01 / cg"
    "Modified: / 14.10.1998 / 14:54:04 / cg"
!

_WTextAreaPeer_create:nativeContext
    |jTextAreaPeer jFrame frame editTextView|

    jTextAreaPeer := nativeContext receiver.

    jFrame := nativeContext argAt:1.
    frame := jFrame instVarNamed:'pData'.

    editTextView := HVScrollableView for:EditTextView in:frame.

    self createdWindowsView:editTextView for:jTextAreaPeer.

    WindowCreationTrace == true ifTrue:[
	'WTextAreaPeer_create: ' print. frame print. ' -> ' print. editTextView printNL.
    ].

    "Created: / 7.1.1998 / 21:49:49 / cg"
    "Modified: / 15.1.1998 / 12:56:18 / cg"
!

_WTextAreaPeer_insertText:nativeContext
    |textView pos string jstring|

    textView := self viewForWPeer:nativeContext.
    (textView isKindOf:ScrollableView) ifTrue:[
	textView := textView scrolledView
    ].

    jstring := nativeContext argAt:1.
    string := Java as_ST_String:jstring.
    pos := nativeContext argAt:2.

    textView insert:string at:pos.
    textView cursorToCharacterPosition:pos + string size.
    textView makeCursorVisible.
"/ textView invalidateRepairNow:true.
    ^ nil

    "Created: / 7.1.1998 / 21:50:23 / cg"
    "Modified: / 5.4.1998 / 17:37:24 / cg"
!

_WTextAreaPeer_replaceText:nativeContext
    "/ void replaceText (java.lang.String int int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:11:14 / cg"
!

_WTextComponentPeer_enableEditing:nativeContext
    |textView enabled|

    textView := self viewForWPeer:nativeContext.
    enabled := (nativeContext argAt:1) ~~ 0.

    ^ textView readOnly:enabled not

    "Created: / 5.1.1998 / 01:29:38 / cg"
    "Modified: / 25.1.1998 / 16:29:56 / cg"
!

_WTextComponentPeer_getSelectionEnd:nativeContext
    |textView|

    textView := self viewForWPeer:nativeContext.

    ^ textView characterPositionOfSelectionEnd

    "Created: / 8.1.1998 / 17:41:56 / cg"
    "Modified: / 15.1.1998 / 15:47:18 / cg"
!

_WTextComponentPeer_getSelectionStart:nativeContext
    |textView|

    textView := self viewForWPeer:nativeContext.

    ^ textView characterPositionOfSelection - 1

    "Created: / 15.8.1997 / 15:45:45 / cg"
    "Modified: / 15.1.1998 / 15:46:51 / cg"
!

_WTextComponentPeer_getText:nativeContext
    |textView string jString|

    textView := self viewForWPeer:nativeContext.

    string := textView contents asString.
    jString := Java as_String:string.
    ^ jString

    "Created: / 6.1.1998 / 21:05:15 / cg"
    "Modified: / 8.1.1998 / 17:36:52 / cg"
!

_WTextComponentPeer_select:nativeContext
    |textView selStart selEnd|

    textView := self viewForWPeer:nativeContext.
    selStart := nativeContext argAt:1.
    selEnd := nativeContext argAt:2.

    selStart == selEnd ifTrue:[
	"/ clear selection
	textView unselect.
	"/ and set caret
	textView cursorToCharacterPosition:selStart + 1
    ] ifFalse:[
	"/ change selection
	textView selectFromCharacterPosition:selStart+1 to:selEnd
    ].

    "Created: / 15.8.1997 / 15:45:58 / cg"
    "Modified: / 15.1.1998 / 21:55:57 / cg"
!

_WTextComponentPeer_setText:nativeContext
    |textView string jstring|

    textView := self viewForWPeer:nativeContext.

    jstring := nativeContext argAt:1.
    jstring notNil ifTrue:[
	string := Java as_ST_String:jstring
    ].

    textView contents:string.

    "Created: / 5.1.1998 / 01:28:23 / cg"
    "Modified: / 11.12.1998 / 12:16:46 / cg"
!

_WTextFieldPeer_create:nativeContext
    |jTextFieldPeer jFrame frame editField|

    jTextFieldPeer := nativeContext receiver.

    jFrame := nativeContext argAt:1.
    frame := jFrame instVarNamed:'pData'.

    editField := EditField in:frame.

    self createdWindowsView:editField for:jTextFieldPeer.

    editField crAction:[
			jTextFieldPeer perform:#handleAction.
		  ].
    WindowCreationTrace == true ifTrue:[
	'WTextFieldPeer_create: ' print. frame print. ' -> ' print. editField printNL.
    ].

    "Created: / 5.1.1998 / 01:27:37 / cg"
    "Modified: / 4.11.1998 / 21:07:30 / cg"
!

_WTextFieldPeer_setEchoCharacter:nativeContext
    |editField char|

    editField := self viewForWPeer:nativeContext.

    char := nativeContext argAt:1.
    editField passwordCharacter:(Character value:char).

    "Created: / 25.1.1998 / 16:28:30 / cg"
!

_WToolkit_beep:nativeContext
    "/ void beep ()

    Screen current beep

    "Created: / 12.11.1998 / 19:09:23 / cg"
    "Modified: / 11.12.1998 / 12:15:23 / cg"
!

_WToolkit_eventLoop:nativeContext
    (JavaEventThread notNil and:[JavaEventThread isDead not]) ifTrue:[
	'JavaVM [warning]: oops - two threads executing eventLoop' errorPrintCR.
    ].

    JavaEventThread := Processor activeProcess.
    [
	[true] whileTrue:[
	    AbortSignal handle:[:ex |
		ex return
	    ] do:[
		self doWindowsEventThread.
	    ]
	].
    ] valueNowOrOnUnwindDo:[
	JavaEventThread := nil.
    ].

    "Created: / 6.1.1998 / 21:01:44 / cg"
    "Modified: / 8.1.1999 / 17:08:00 / cg"
!

_WToolkit_getComboHeightOffset:nativeContext
    ^ 0

    "Modified: / 20.3.1997 / 13:50:04 / cg"
    "Created: / 22.10.1998 / 00:59:14 / cg"
!

_WToolkit_getScreenHeight:nativeContext
    ^ Screen current height

    "Modified: / 20.3.1997 / 13:50:04 / cg"
    "Created: / 13.1.1998 / 09:24:45 / cg"
!

_WToolkit_getScreenResolution:nativeContext
    ^ Screen current resolution x rounded

    "Modified: / 20.3.1997 / 13:50:04 / cg"
    "Created: / 17.1.1998 / 21:54:48 / cg"
!

_WToolkit_getScreenWidth:nativeContext
    ^ Screen current width

    "Modified: / 20.3.1997 / 13:50:04 / cg"
    "Created: / 13.1.1998 / 09:24:37 / cg"
!

_WToolkit_init:nativeContext

    "Created: / 3.1.1998 / 02:30:57 / cg"
!

_WToolkit_loadSystemColors:nativeContext
"/ self halt.

    "Modified: / 18.3.1997 / 18:43:26 / cg"
    "Created: / 5.1.1998 / 02:19:09 / cg"
!

_WToolkit_makeColorModel:nativeContext
    "/ java.awt.image.ColorModel makeColorModel ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:08:47 / cg"
!

_WToolkit_sync:nativeContext
    "/ void sync ()
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:09:14 / cg"
!

_WWindowPeer__setResizable:nativeContext
    |view onOff|

    view := self viewForWPeer:nativeContext.

    onOff := (nativeContext argAt:1) == 1.
    view isTopView ifTrue:[
	onOff ifTrue:[
	    view minExtent:10@10.
	    view maxExtent:(Screen current extent).
	] ifFalse:[
	    view minExtent:view extent.
	    view maxExtent:view extent.
	]
    ] ifFalse:[
	(view isMemberOf:JavaEmbeddedFrameView) ifFalse:[
	    self halt.
	]
    ].

"/ 'JAVA: WWindowPeer_setResizable: ' print. view print. ' yes/no: ' print. onOff printNL.

    ^ nil

    "Created: / 5.1.1998 / 00:57:59 / cg"
    "Modified: / 16.1.1998 / 18:08:00 / cg"
!

_WWindowPeer__setTitle:nativeContext
    |view jString string|

    view := self viewForWPeer:nativeContext.

    jString := nativeContext argAt:1.
    string := Java as_ST_String:jString.

"/ 'JAVA: WWindowPeer_pSetTitle: ' print. string print. ' ' print. view printNL.

    view label:string.
    ^ nil

    "Created: / 5.1.1998 / 00:57:17 / cg"
    "Modified: / 8.1.1998 / 17:37:41 / cg"
!

_WWindowPeer_create:nativeContext
    "/ void create (sun.awt.windows.WComponentPeer)
    |jWindowPeer jWindow top window pDataIdx|

    jWindowPeer := nativeContext receiver.

    jWindow := jWindowPeer instVarNamed:'target'.
    window := jWindowPeer instVarNamed:'pData'.

    (window notNil and:[window ~~ 0]) ifTrue:[
	WindowCreationTrace == true ifTrue:[
	    'JAVA: window view already created: ' infoPrint.
	    jWindowPeer class name infoPrintCR.
	].
    ] ifFalse:[
"/ OLD
"/        window := StandardSystemView new.
"/        self createdWindowsView:window for:jWindowPeer.
"/        JavaWindowGroup addTopView:window.

	window := JavaPopUpView new.
	window borderWidth:0.
	window level:0.
	window delegate:self.
	window javaPeer:jWindowPeer.
	self createdWindowsView:window for:jWindowPeer.
	JavaWindowGroup addTopView:window.

"/        top := StandardSystemView new.
"/        window := JavaView origin:0.0@0.0 corner:1.0@1.0 in:top.
"/        window delegate:self.
"/        window javaPeer:jWindowPeer.
"/        self createdWindowsView:window for:jWindowPeer.
"/        JavaWindowGroup addTopView:top.

    ].

    WindowCreationTrace == true ifTrue:[
	'JAVA: WWindowPeer_create: ' print. jWindowPeer displayString print.
	' window: ' print. window printNL.
    ].

    "Created: / 4.1.1998 / 17:56:39 / cg"
    "Modified: / 4.12.1998 / 17:37:59 / cg"
!

_WWindowPeer_getContainerElement:nativeContext
    "/ java.awt.Component getContainerElement (java.awt.Container int)
    UnimplementedNativeMethodSignal raise

    "Created: / 12.11.1998 / 19:10:54 / cg"
!

_WWindowPeer_toBack:nativeContext
    |view|

    view := self viewForWPeer:nativeContext.
    view lower.

    "Created: / 7.5.1998 / 00:23:03 / cg"
!

_WWindowPeer_toFront:nativeContext
    |view|

    view := self viewForWPeer:nativeContext.
    view raise.

    "Created: / 9.4.1998 / 22:17:28 / cg"
!

_WWindowPeer_updateInsets:nativeContext
"/ self halt.

    "Modified: / 18.3.1997 / 18:43:18 / cg"
    "Created: / 4.1.1998 / 18:09:04 / cg"
!

_Win32Process_create:nativeContext
    "really create a win32 process"

    |env cmd jProcess p inPipe outPipe errorPipe|

    jProcess := nativeContext receiver.
    cmd := nativeContext argAt:1.
    cmd := Java as_ST_String:cmd.

    env := nativeContext argAt:2.
    env notNil ifTrue:[
	self halt
    ].
self halt.

    p := Win32Process new.
    p command:cmd.
    p environment:env.
    p inStream:inPipe.
    p outStream:outPipe.
    p errorStream:errorPipe.
    p directory:nil.
    p startProcess.
self halt.

    jProcess instVarNamed:'handle' put:p.

    "Created: / 10.11.1998 / 19:50:31 / cg"
    "Modified: / 10.11.1998 / 21:34:18 / cg"
!

_X11FontMetrics_getMFCharSegmentWidth:nativeContext
    "get multi-font string-segment width.
     Not yet supported - use standard strings width"

    |jMetrics jFont jFontDescr stFont w
     bool1 cp offs lenght bp int1|

    jMetrics := nativeContext receiver.
    jFont := nativeContext argAt:1.
    jFontDescr := nativeContext argAt:2.
    cp := nativeContext argAt:3.
    lenght := nativeContext argAt:4.

    stFont := jFont instVarNamed:'pData'.
    (stFont isNil or:[stFont == 0]) ifTrue:[
        self halt
    ].

    stFont device isNil ifTrue:[
        stFont := stFont on:Display.
        jFont instVarNamed:'pData' put:stFont.
    ].
    w := stFont widthOf:cp from:1 to:lenght.
    ^ w.
!

_X11FontMetrics_init:nativeContext
    ^ self _WFontMetrics_init:nativeContext
!

_X11GraphicsDevice_getConfigType:nativeContext
    "/ new with jdk1.2 ...

    |configNr cls|

    "/ for now, only one config.
    configNr := nativeContext argAt:1.

    cls := Java classNamed:'java.awt.GraphicsDevice'.
    ^ cls instVarNamed:'TYPE_RASTER_SCREEN'.

    "Created: / 28.1.1998 / 22:19:05 / cg"
!

_X11GraphicsDevice_getNumConfigs:nativeContext
    "/ new with jdk1.2 ...

    ^ 1

    "Created: / 28.1.1998 / 22:13:26 / cg"
    "Modified: / 28.1.1998 / 22:14:33 / cg"
!

_X11GraphicsEnvironment_getNumScreens:nativeContext
    "/ new with jdk1.2 ...

    "/ could return the actual number of screens ...

    ^ 1

    "Created: / 28.1.1998 / 01:50:22 / cg"
    "Modified: / 28.1.1998 / 22:12:32 / cg"
!

_X11GraphicsEnvironment_initDisplay:nativeContext
    "/ new with jdk1.2 ...

    "Created: / 28.1.1998 / 01:50:22 / cg"
!

_X11Graphics_changeClip:nativeContext
    ^ self _WGraphics_changeClip:nativeContext
!

_X11Graphics_createFromComponent:nativeContext
    ^ self _WGraphics_createFromComponent:nativeContext
!

_X11Graphics_disposeImpl:nativeContext
    ^ self _WGraphics_dispose:nativeContext
!

_X11Graphics_drawMFCharsSegment:nativeContext
    ^ self _WGraphics_drawMFCharsSegment:nativeContext
!

_X11Graphics_drawRect:nativeContext
    ^ self _WGraphics_drawRect:nativeContext
!

_X11Graphics_fillOval:nativeContext
    ^ self _WGraphics_fillOval:nativeContext
!

_X11Graphics_fillRect:nativeContext
    ^ self _WGraphics_fillRect:nativeContext
!

_X11Graphics_pSetFont:nativeContext
    ^ self _WGraphics_pSetFont:nativeContext
!

_X11Graphics_pSetForeground:nativeContext
    ^ self _WGraphics_pSetForeground:nativeContext
! !

!JavaVM class methodsFor:'native - sun.io'!

_sun_io_Win32ErrorMode_setErrorMode: nativeContext

    <javanative: 'sun/io/Win32ErrorMode' name: 'setErrorMode(J)J'>

    "FIXME: Ignored for now"

    ^0
! !

!JavaVM class methodsFor:'native - sun.management'!

_sun_management_VMManagementImpl_getVersion0: nativeContext

    <javanative: 'sun/management/VMManagementImpl' name: 'getVersion0'>

    ^ UnimplementedNativeMethodSignal raise
! !

!JavaVM class methodsFor:'native - sun.misc'!

_sun_misc_Signal_findSignal: aJavaContext

    <javanative: 'sun/misc/Signal' name: 'findSignal'>

        | input signame |

    input := Java as_ST_String: (aJavaContext argAt: 1).
    OperatingSystem isUNIXlike ifTrue:[
        signame := 'SIG', (input asUppercase).
        ^UnixOperatingSystem signalNamed: signame asSymbol.
    ].
    OperatingSystem isMSWINDOWSlike ifTrue:[
        signame := 'sig', (input asUppercase).
        ^Win32OperatingSystem perform: signame asSymbol.
    ].
    self error: 'Unsupported OS'

    "Created: / 11-12-2010 / 15:22:07 / Jan Kurs <kurs.jan@post.cz>"
!

_sun_misc_Signal_handle0: aJavaContext

    <javanative: 'sun/misc/Signal' name: 'handle0'>

        self breakPoint: #libjava.
    ^ 0.

    "Created: / 11-12-2010 / 16:33:38 / Jan Kurs <kurs.jan@post.cz>"
!

_sun_misc_Unsafe_allocateInstance: nativeContext

    <javanative: 'sun/misc/Unsafe' name: 'allocateInstance'>

        "
    /** Allocate an instance but do not run any constructor.
        Initializes the class if it has not yet been. */
    public native Object allocateInstance(Class cls)
        throws InstantiationException;
    "
    | cls |
    cls := self reflection classForJavaClassObject: (nativeContext argAt:1).
    cls classInit.
    ^cls newCleared

    "Created: / 05-02-2011 / 23:10:04 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_allocateMemory: aJavaContext

    <javanative: 'sun/misc/Unsafe' name: 'allocateMemory'>

    
    | size |
    size := aJavaContext argAt: 1.
    ^SimulatedNativeMemory malloc: size.

    "Created: / 07-12-2010 / 21:04:37 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 07-12-2010 / 23:46:10 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_arrayBaseOffset: nativeContext

    <javanative: 'sun/misc/Unsafe' name: 'arrayBaseOffset'>
    "
    /**
    * Report the offset of the first element in the storage allocation of a
    * given array class.  If {@link #arrayIndexScale} returns a non-zero value
    * for the same class, you may use that scale factor, together with this
    * base offset, to form new offsets to access elements of arrays of the
    * given class.
    *
    * @see #getInt(Object, long)
    * @see #putInt(Object, long, int)
    */
    public native int arrayBaseOffset(Class arrayClass);
    "

    ^ 1

    "Modified (comment): / 10-08-2011 / 01:22:43 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_arrayIndexScale: nativeContext

    <javanative: 'sun/misc/Unsafe' name: 'arrayIndexScale'>

    "
      /**
      * Report the scale factor for addressing elements in the storage
      * allocation of a given array class.  However, arrays of 'narrow' types
      * will generally not work properly with accessors like {@link
      * #getByte(Object, int)}, so the scale factor for such classes is reported
      * as zero.
      *
      * @see #arrayBaseOffset
      * @see #getInt(Object, long)
      * @see #putInt(Object, long, int)
      */
    public native int arrayIndexScale(Class arrayClass);
    "
    ^ 1

    "Modified: / 10-08-2011 / 01:26:02 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_compareAndSwapInt: aJavaContext

    <javanative: 'sun/misc/Unsafe' name: 'compareAndSwapInt'>

    ^self _sun_misc_Unsafe_compareAndSwapObject: aJavaContext

    "Created: / 22-11-2010 / 18:40:43 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 07-08-2011 / 21:50:25 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_compareAndSwapLong: aJavaContext

    <javanative: 'sun/misc/Unsafe' name: 'compareAndSwapInt'>

    ^self _sun_misc_Unsafe_compareAndSwapObject: aJavaContext

    "Modified: / 07-08-2011 / 21:50:33 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_compareAndSwapObject: aJavaContext

    <javanative: 'sun/misc/Unsafe' name: 'compareAndSwapInt'>

        "
    /**
     * Atomically update Java variable to <tt>x</tt> if it is currently
     * holding <tt>expected</tt>.
     * @return <tt>true</tt> if successful
     */
    public final native boolean compareAndSwapInt(Object o, long offset,
                                                  int expected,
                                                  int new);
    "
    | o offset expected real new ok |
    o := aJavaContext argAt:1.
    offset := aJavaContext argAt:2.
    "offset is long, so aJavaContext at:3 is dummy nil!!!!!!"
    expected := aJavaContext argAt:4.
    new := aJavaContext argAt:5.

    OperatingSystem blockInterrupts.
    real := o instVarAt: offset.
    (real == expected)
            ifTrue:[o instVarAt: offset put: new. ok := 1]
            ifFalse:[ok := 1].
    OperatingSystem unblockInterrupts.
    ^ok

    "Modified: / 07-08-2011 / 21:53:22 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_defineClass: nativeContext

    <javanative: 'sun/misc/Unsafe' name: 'defineClass'>

        "
    /**
     * Tell the VM to define a class, without security checks.  By default, the
     * class loader and protection domain come from the caller's class.
     */
    public native Class defineClass(String name, byte[] b, int off, int len,
                                    ClassLoader loader,
                                    ProtectionDomain protectionDomain);
    "
    | name b off len loader protectionDomain bs cls |
    name := nativeContext argAt: 1.
    b := nativeContext argAt: 2.
    off := nativeContext argAt: 3.
    len := nativeContext argAt: 4.
    loader := nativeContext argAt: 5.
    protectionDomain := nativeContext argAt: 6.

    bs := (off = 0 and: [len = b size]) 
            ifTrue:[b readStream]
            ifFalse:[(b copyFrom: off + 1 to: off + len) readStream].

    cls := JavaClassReader readStream: bs.
    cls classLoader: loader.

    ^self reflection javaClassObjectForClass: cls.

    "Created: / 05-02-2011 / 22:57:36 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_ensureClassInitialized: aJavaContext

    <javanative: 'sun/misc/Unsafe' name: 'ensureClassInitialized'>

        |class|

    class := self reflection classForJavaClassObject:(aJavaContext argAt:1).
     "Sometimes there is a nil. I don't know why, so I did quickfix"
    self breakPoint:#libjava.
    class ifNotNil:[class classInit.].

    "Created: / 11-12-2010 / 15:01:36 / Jan Kurs <kurs.jan@post.cz>"
    "Modified: / 25-12-2010 / 09:43:12 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 08-01-2011 / 15:11:21 / Jan Kurs <kurs.jan@post.cz>"
    "Modified: / 28-01-2011 / 15:19:31 / Marcel Hlopko <hlopik@gmail.com>"
!

_sun_misc_Unsafe_freeMemory: aJavaContext

    <javanative: 'sun/misc/Unsafe' name: 'freeMemory'>

         | address  |
    address := aJavaContext argAt: 1.
    ^SimulatedNativeMemory free: address

    "Created: / 09-12-2010 / 17:56:52 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_getByte: aJavaContext

    <javanative: 'sun/misc/Unsafe' name: 'getByte'>

    
     | address  |
    address := aJavaContext argAt: 1.
    ^SimulatedNativeMemory byteAt: address

    "Created: / 09-12-2010 / 17:29:27 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_getObject: nativeContext

    <javanative: 'sun/misc/Unsafe' name: 'getObject'>
    "
    /**
    * Fetches a reference value from a given Java variable.
    * @see #getInt(Object, long)
    */
    public native Object getObject(Object o, long offset);
    "
    | o offset |
    o := nativeContext argAt: 1.
    offset := nativeContext argAt: 2.
    ^o instVarAt: offset

    "Modified: / 10-08-2011 / 01:40:13 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_getObjectVolatile: nativeContext

    <javanative: 'sun/misc/Unsafe' name: 'getObjectVolatile(Ljava/lang/Object;J)Ljava/lang/Object;'>
    "
    /**
    * Fetches a reference value from a given Java variable, with volatile
    * load semantics. Otherwise identical to {@link #getObject(Object, long)}
    */
    public native Object getObjectVolatile(Object o, long offset);
    "

    | o offset |
    o := nativeContext argAt: 1.
    offset := nativeContext argAt: 2.
    ^o instVarAt: offset

    "Modified (comment): / 17-08-2011 / 09:42:54 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_objectFieldOffset: aJavaContext

    <javanative: 'sun/misc/Unsafe' name: 'objectFieldOffset'>

    
    | javaFieldObject |
    javaFieldObject := aJavaContext argAt: 1.
    ^javaFieldObject instVarNamed: #slot

    "Created: / 22-11-2010 / 17:58:13 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_pageSize: nativeContext

    <javanative: 'sun/misc/Unsafe' name: 'pageSize'>

    ^ UnimplementedNativeMethodSignal raise
!

_sun_misc_Unsafe_putInt: nativeContext

    <javanative: 'sun/misc/Unsafe' name: 'putInt'>

    ^ UnimplementedNativeMethodSignal raise
!

_sun_misc_Unsafe_putLong: aJavaContext

    <javanative: 'sun/misc/Unsafe' name: 'putLong'>

    
    | address value |
    address := aJavaContext argAt: 1.
    value := aJavaContext argAt: 3. 
        "3!!!!!! since at index 2 there is dummy long high word"
        "Ask JV for more details"

    SimulatedNativeMemory longAt: address put: value

    "Created: / 07-12-2010 / 23:50:47 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 09-12-2010 / 17:31:45 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_putObject: nativeContext

    <javanative: 'sun/misc/Unsafe' name: 'putObject'>

    "
    /**
     * Stores a reference value into a given Java variable.
     * <p>
     * Unless the reference <code>x</code> being stored is either null
     * or matches the field type, the results are undefined.
     * If the reference <code>o</code> is non-null, car marks or
     * other store barriers for that object (if the VM requires them)
     * are updated.
     * @see #putInt(Object, int, int)
     */
     public native void putObject(Object o, long offset, Object x);
     "
     | o offset x |
     o := nativeContext argAt: 1.
     offset := nativeContext argAt: 2.
     x := nativeContext argAt: 4.
     ^o instVarAt: offset put: x.

    "Modified: / 10-08-2011 / 01:40:03 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_registerNatives: aJavaContext

    <javanative: 'sun/misc/Unsafe' name: 'registerNatives'>

    
     "Nothing to do, native method are bound lazily"

    "Created: / 25-10-2010 / 16:14:46 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_staticFieldBase: nativeContext

    <javanative: 'sun/misc/Unsafe' name: 'staticFieldBase(Ljava/lang/reflect/Field;)Ljava/lang/Object;'>
    "
      /**
      * Report the location of a given static field, in conjunction with {@link
      * #staticFieldOffset}.
      * <p>Fetch the base 'Object', if any, with which static fields of the
      * given class can be accessed via methods like {@link #getInt(Object,
      * long)}.  This value may be null.  This value may refer to an object
      * which is a 'cookie', not guaranteed to be a real Object, and it should
      * not be used in any way except as argument to the get and put routines in
      * this class.
      */
      public native Object staticFieldBase(Field f);
    "
     | javaFieldObject javaClassObject |
     javaFieldObject := nativeContext argAt: 1.
     javaClassObject := javaFieldObject instVarNamed: #clazz.
     ^self classForJavaClassObject: javaClassObject.

    "Modified: / 17-08-2011 / 09:42:01 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_Unsafe_staticFieldOffset: nativeContext

    <javanative: 'sun/misc/Unsafe' name: 'staticFieldOffset(Ljava/lang/reflect/Field;)J'>

    | javaFieldObject |
    javaFieldObject := nativeContext argAt: 1.
    ^javaFieldObject instVarNamed: #slot

    "Modified: / 17-08-2011 / 09:12:17 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_misc_VM_initialize: aJavaContext

    <javanative: 'sun/misc/VM' name: 'initialize'>

    
    "Nothing to do"

    "Created: / 26-11-2010 / 18:43:10 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!JavaVM class methodsFor:'native - sun.reflect'!

_sun_reflect_ConstantPool_getDoubleAt0: nativeContext

    <javanative: 'sun/reflect/ConstantPool' name: 'getDoubleAt0'>

        | cpool  index  double |

    cpool := self reflection constantPoolFor:(nativeContext receiver).
    self breakPoint:#mh.
    index := nativeContext at:3.
     "TODO: why 3?"
    double := cpool at:index.
    self assert:double isFloat description:'Not a float constant!!'.
    ^ double

    "Modified: / 25-02-2011 / 18:40:32 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Created: / 28-02-2011 / 17:24:17 / Marcel Hlopko <hlopik@gmail.com>"
!

_sun_reflect_ConstantPool_getIntAt0: nativeContext

    <javanative: 'sun/reflect/ConstantPool' name: 'getIntAt0'>

        | cpool  index  int |

    cpool := self reflection constantPoolFor:(nativeContext receiver).
    index := nativeContext at:3.
     "TODO: why 3?"
    int := cpool at:index.
    self assert:int isInteger description:'Not an integer constant!!'.
    ^ int

    "Modified: / 25-02-2011 / 18:40:32 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Created: / 28-02-2011 / 17:28:10 / Marcel Hlopko <hlopik@gmail.com>"
!

_sun_reflect_ConstantPool_getLongAt0: nativeContext

    <javanative: 'sun/reflect/ConstantPool' name: 'getLongAt0'>

        | cpool  index  long |

    cpool := self reflection constantPoolFor:(nativeContext receiver).
    index := nativeContext at:3.
     "TODO: why 3?"
    long := cpool at:index.
    self assert:long isInteger description:'Not a float constant!!'.
    ^ long

    "Modified: / 28-02-2011 / 17:40:02 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 28-02-2011 / 18:54:32 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_reflect_ConstantPool_getUTF8At0: nativeContext

    <javanative: 'sun/reflect/ConstantPool' name: 'getUTF8At0'>

    
    | cpool index string |
    cpool := self reflection constantPoolFor: (nativeContext receiver).
    index := nativeContext at: 3. 
    "TODO: why 3?"

    string := cpool at: index.
    self assert: string isString description: 'Not an UTF8 constant!!'.
    ^Java as_String: string

    "Created: / 06-02-2011 / 12:56:21 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_reflect_NativeConstructorAccessorImpl_newInstance0: aJavaContext

    <javanative: 'sun/reflect/NativeConstructorAccessorImpl' name: 'newInstance0'>

    
    | ctor args method instance |
    ctor := aJavaContext argAt: 1.
    args := aJavaContext argAt: 2.
    args ifNil:[args := #()] ifNotNil:[args := args asArray].
    method := self reflection methodForJavaConstructorObject: ctor.
    instance := method javaClass new.
    method valueWithReceiver:instance arguments:args.
    ^instance

    "Created: / 26-11-2010 / 11:41:16 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 04-02-2011 / 18:47:13 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 09-02-2011 / 01:12:10 / Marcel Hlopko <hlopik@gmail.com>"
!

_sun_reflect_NativeMethodAccessorImpl_invoke0: nativeContext

    <javanative: 'sun/reflect/NativeMethodAccessorImpl' name: 'invoke0'>
    "
    private static native Object invoke0(Method m, Object obj, Object[] args);
    "
    | m obj args method descriptor adescriptors bargs retval retcls |
    m := nativeContext argAt: 1.
    obj := nativeContext argAt: 2.
    args := nativeContext argAt: 3.

    method := self reflection methodForJavaMethodObject: m.


    (obj isNil and:[method isStatic not]) ifTrue:[
        self throwNullPointerException.
        ^nil.            
    ].

    descriptor := method descriptor.

    "Possibly box/unbox arguments"
    args notEmptyOrNil ifTrue:[
        adescriptors := descriptor parameters.
        bargs := Array new: args size.
        1 to: args size do:[:i|
            bargs at: i put: ((adescriptors at: i) javaClass javaUnbox: (args at:i))
        ].
    ] ifFalse:[
        bargs := #()
    ].
    "Fire the method"
    method isStatic ifTrue:[
        retval := method valueWithReceiver: method javaClass arguments: bargs.
    ] ifFalse:[
        retval := obj perform: method selector withArguments: bargs.
    ].
    retcls := descriptor return.
    retcls notNil ifTrue:[
        retval := retcls javaClass javaBox: retval.
    ].
    ^retval.

    "Created: / 06-02-2011 / 00:00:25 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-02-2011 / 16:57:31 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 19-08-2011 / 15:06:00 / cg"
    "Modified: / 22-08-2011 / 15:45:46 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_reflect_Reflection_getCallerClass: aJavaContext

    <javanative: 'sun/reflect/Reflection' name: 'getCallerClass'>

    
    | framesToSkip framesSkipped frame |
    framesToSkip := aJavaContext argAt: 1.
    framesSkipped := 0.
    frame := aJavaContext.
    [ framesSkipped == framesToSkip ] whileFalse:
        [frame := frame sender.
        framesSkipped := framesSkipped + 1].

    ^JavaVM javaClassObjectForClass:
        (frame receiver class theNonMetaclass)

    "Created: / 25-10-2010 / 16:32:41 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_sun_reflect_Reflection_getClassAccessFlags: aJavaContext

    <javanative: 'sun/reflect/Reflection' name: 'getClassAccessFlags'>

        |class|

    class := self reflection classForJavaClassObject:(aJavaContext argAt:1).
    ^ class accessFlags

    "Created: / 26-11-2010 / 10:20:23 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-01-2011 / 15:19:28 / Marcel Hlopko <hlopik@gmail.com>"
! !

!JavaVM class methodsFor:'queries'!

booted

    | jVM |

    jVM := Java at:'sun.misc.VM'.
    ^jVM notNil and:[(jVM instVarNamed: #booted) == 1].

    "
    JavaVM booted        
    "

    "Created: / 08-08-2011 / 10:04:54 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!JavaVM class methodsFor:'semaphores & monitors'!

enteredMonitors
    ^ self enteredMonitorsOfProcess:(Processor activeProcess)

    "Modified: / 8.1.1999 / 14:02:15 / cg"
!

enteredMonitorsOfProcess:aProcess
    |monitors|

    monitors := EnteredMonitorsPerProcess at:aProcess ifAbsent:nil.
    monitors isNil ifTrue:[
	monitors := OrderedCollection new.
	EnteredMonitorsPerProcess at:aProcess put:monitors.
    ].
    ^ monitors

    "Created: / 8.1.1999 / 14:02:02 / cg"
!

monitorFor:someObject
    |mon|

    LockTableAccess critical:[
	mon := LockTable at:someObject ifAbsent:nil.
	mon isNil ifTrue:[
	    LockTable at:someObject put:(mon := Monitor new)
	]
    ].
    ^ mon

    "Created: / 2.1.1998 / 19:01:52 / cg"
!

releaseAndSignalForAllSemaphoreFor:someObject
    |sema|

    WaitTableAccess critical:[
	sema := WaitTable at:someObject ifAbsent:nil.
"/        sema notNil ifTrue:[
"/            WaitTable removeKey:someObject
"/        ]
    ].

    sema notNil ifTrue:[
	sema signalForAll
    ]

    "Created: / 2.1.1998 / 18:21:51 / cg"
    "Modified: / 3.2.1998 / 16:11:58 / cg"
!

releaseAndSignalSemaphoreFor:someObject
    |sema|

    WaitTableAccess critical:[
	sema := WaitTable at:someObject ifAbsent:nil.
"/        sema notNil ifTrue:[
"/            WaitTable removeKey:someObject
"/        ]
    ].

    sema notNil ifTrue:[
	sema signal
    ]

    "Created: / 2.1.1998 / 18:20:20 / cg"
    "Modified: / 3.2.1998 / 16:11:51 / cg"
!

releaseSemaphoreFor:someObject
    WaitTableAccess critical:[
	WaitTable removeKey:someObject ifAbsent:nil
    ]

    "Created: / 2.1.1998 / 18:17:14 / cg"
    "Modified: / 2.1.1998 / 21:52:03 / cg"
!

semaphoreFor:someObject
    |sema|

    WaitTableAccess critical:[
	sema := WaitTable at:someObject ifAbsent:nil.
	sema isNil ifTrue:[
	    WaitTable at:someObject put:(sema := Semaphore new)
	]
    ].
    ^ sema

    "Created: / 2.1.1998 / 18:15:59 / cg"
    "Modified: / 2.1.1998 / 18:20:31 / cg"
!

syncMonitorCache
    |mO mC mP mon wasBlocked enteredMonitors|

    wasBlocked := OperatingSystem blockInterrupts.
    (mO := EnteredMonitorObject) notNil ifTrue:[
	mC := EnteredMonitorObjectCount.
	mP := EnteredMonitorProcess.
	mon := self monitorFor:mO.
	mon fakeEnter:mP count:mC.
	enteredMonitors := self enteredMonitorsOfProcess:mP.
	mC timesRepeat:[
	    enteredMonitors addLast:mO
	].
	EnteredMonitorObject := EnteredMonitorProcess := LeftMonitorObject := nil.
    ].
    wasBlocked ifFalse:[ OperatingSystem unblockInterrupts].

    "Created: / 8.1.1999 / 13:59:17 / cg"
    "Modified: / 9.1.1999 / 00:39:55 / cg"
!

waitFor:sema state:pState timeOut:tmo
    "wait"

    |wasBlocked thisProcess enteredMonitors|

"/    self syncMonitorCache.

    thisProcess := Processor activeProcess.

    "/ temporarily leave all entered monitors.

    wasBlocked := OperatingSystem blockInterrupts.
    self syncMonitorCache.

    enteredMonitors := self enteredMonitorsOfProcess:thisProcess.
    enteredMonitors size > 0 ifTrue:[
	MonitorTrace ifTrue:[
	    ('====> wait - exit ' , enteredMonitors size printString , ' monitors in ' , Processor activeProcess name , ' ...') infoPrintCR.
	].
	enteredMonitors do:[:handle | 
	    |mon|

	    mon := LockTable at:handle ifAbsent:nil.
	    mon isNil ifTrue:[
		self halt:'no monitor in wait'.
	    ] ifFalse:[
		MonitorTrace ifTrue:[
		    ('====> wait - exit monitor for ' , handle displayString , ' in ' , Processor activeProcess name , ' ...') infoPrintCR. 
		].
		mon exit.
	    ].
	].
	EnteredMonitorsPerProcess removeKey:thisProcess.
    ].

    wasBlocked ifFalse:[ OperatingSystem unblockInterrupts].

    pState notNil ifTrue:[thisProcess state:pState].
    sema isNil ifTrue:[
	Delay waitForMilliseconds:tmo
    ] ifFalse:[
	(tmo isNil or:[tmo = 0]) ifTrue:[
	    sema wait.
	] ifFalse:[
	    sema waitWithTimeout:tmo / 1000.
	].
    ].

    "/ re-enter monitors.

    enteredMonitors size > 0 ifTrue:[
	wasBlocked := OperatingSystem blockInterrupts.
	self syncMonitorCache.

	MonitorTrace ifTrue:[
	    ('====> wait - reenter ' , enteredMonitors size printString , ' monitors in ' , Processor activeProcess name , ' ...') infoPrintCR.
	].
	enteredMonitors do:[:handle | 
	    |mon|

	    LockTableAccess critical:[
		mon := LockTable at:handle ifAbsent:nil.
		mon isNil ifTrue:[
		    LockTable at:handle put:(mon := Monitor new)
		]
	    ].
	    MonitorTrace ifTrue:[
		('====> wait - reenter monitor for ' , handle displayString , ' in ' , Processor activeProcess name , ' ...') infoPrintCR. 
	    ].
	    mon enter.
	].
	EnteredMonitorsPerProcess at:thisProcess put:enteredMonitors.
	wasBlocked ifFalse:[ OperatingSystem unblockInterrupts].
    ].

    "Created: / 30.12.1998 / 19:19:35 / cg"
    "Modified: / 8.1.1999 / 17:29:24 / cg"
! !

!JavaVM class methodsFor:'vm support'!

_ANEWARRAY2:classRef _:size 
    "vm helper method for new resolving - creates new array of class identified by classRef"
    
    |javaClass|

    classRef ifNil:[ self halt:'cant create array from nil ref' ].
    javaClass := classRef resolve.
    javaClass ifNil:[ self halt:'cant create array from nil javaClass' ].
    self assert:javaClass javaArrayClass isJavaArrayClass. 
    ^ javaClass javaArrayClass new:size

    "Created: / 18-05-2011 / 21:04:59 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
    "Modified: / 11-06-2011 / 23:42:29 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_ANEWARRAY:classRef _:size 
    |ref|

    ref := classRef.
    ref isUnresolved ifTrue:[ ref := ref javaClass ].
    self assert:ref javaArrayClass isJavaArrayClass.
    ^ ref javaArrayClass new:size

    "Created: / 17-12-2010 / 14:28:29 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 25-04-2011 / 20:21:25 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_ARRAYLENGTH:arr
    arr isNil ifTrue:[
        "/self halt:'should not happen'.
        self throwNullPointerException.
    ].
    ^ arr size

    "Created: / 08-01-1999 / 14:38:27 / cg"
    "Modified: / 31-05-2011 / 10:09:00 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_ATHROW:aJavaException

    <resource: #skipInDebuggersWalkBack>

    aJavaException isNil ifTrue:[
        self halt:'cannot happen'
    ].
    self throwException:aJavaException.

    "Created: / 08-01-1999 / 14:15:36 / cg"
    "Modified: / 04-03-2011 / 00:07:59 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_CHECKCAST2: object _: aJavaClassRef 
    "Trampouline for unhandled cases ..."
    
    | class |

    aJavaClassRef isJavaRef 
        ifTrue: [ class := aJavaClassRef resolve ]
        ifFalse: [ self halt: 'I expected classRefs only - maybe I was wrong' ].
    (object isNil or: [ (self canCast: object class to: class) not ]) 
        ifTrue: 
            [ self throwClassCastException.
            ^ false ].
    "
    (self canCast: object class to: class) not
        ifTrue: 
            [ self throwClassCastException.
            ^ false ].
    "
    ^ true.

    "Created: / 19-05-2011 / 10:12:23 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
    "Modified: / 13-08-2011 / 01:33:21 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_CHECKCAST:object _: classOrClassRef
    "Trampouline for unhandled cases ..."

    | class |

    class := classOrClassRef javaClass.

    "
    Java VM Spec, 3rd edition, p 280:

    If objectref is null, the checkcast instruction throws a ClassCastException.
    "
    ("object isNil"false or:[(self canCast: object class to: class) not])
        ifTrue:[self throwClassCastException. ^false].
    ^true

    "Created: / 08-01-1999 / 14:53:51 / cg"
    "Modified: / 09-01-1999 / 00:45:21 / cg"
    "Modified: / 25-04-2011 / 20:26:29 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_D2I:op1
    |v|

    v := op1 asInteger.
    v > 16r7FFFFFFF ifTrue:[
	self halt.
	v := 16r7FFFFFFF
    ] ifFalse:[
	v < 16r80000000 negated ifTrue:[
	    self halt.
	    v := 16r80000000 negated
	]
    ].
    ^ v

    "Modified: / 17.10.1998 / 21:55:49 / cg"
    "Created: / 8.1.1999 / 14:47:13 / cg"
!

_D2L:op1
    |v|

    v := op1 asInteger.
    v > 16r7FFFFFFFFFFFFFFF ifTrue:[
	self halt.
	v := 16r7FFFFFFFFFFFFFFF
    ] ifFalse:[
	v < 16r8000000000000000 negated ifTrue:[
	    self halt.
	    v := 16r8000000000000000 negated
	]
    ].
    ^ v

    "Modified: / 17.10.1998 / 21:55:49 / cg"
    "Created: / 8.1.1999 / 14:46:44 / cg"
!

_DADD:op1 _:op2
    ^ op1 asFloat + op2 asFloat

    "Created: / 8.1.1999 / 15:11:59 / cg"
!

_DDIV:op1 _:op2
    ^ op1 asFloat / op2 asFloat.

    "Created: / 8.1.1999 / 15:09:10 / cg"
!

_DMUL:op1 _:op2
    ^ op1 asFloat * op2 asFloat

    "Created: / 8.1.1999 / 14:49:52 / cg"
!

_DNEG:op
    ^ op asFloat negated

    "Created: / 8.1.1999 / 15:06:15 / cg"
!

_DSUB:op1 _:op2
    ^ op1 asFloat - op2 asFloat

    "Created: / 8.1.1999 / 15:10:59 / cg"
!

_F2I:op1
    ^ self _D2I:op1

    "Created: / 8.1.1999 / 14:47:42 / cg"
!

_F2L:op1
    ^ self _D2L:op1

    "Created: / 8.1.1999 / 14:47:53 / cg"
!

_FADD:op1 _:op2
    ^ op1 asShortFloat + op2 asShortFloat

    "Created: / 8.1.1999 / 15:11:36 / cg"
!

_FDIV:op1 _:op2
    ^ op1 asShortFloat / op2 asShortFloat.

    "Created: / 8.1.1999 / 15:09:32 / cg"
!

_FMUL:op1 _:op2
    ^ op1 asShortFloat * op2 asShortFloat

    "Created: / 8.1.1999 / 14:50:10 / cg"
!

_FNEG:op
    ^ op asShortFloat negated

    "Created: / 8.1.1999 / 15:06:33 / cg"
!

_FSUB:op1 _:op2
    ^ op1 asShortFloat - op2 asShortFloat

    "Created: / 8.1.1999 / 15:08:17 / cg"
!

_INSTANCEOF2: object _: classRef 
    |class|
    classRef isJavaRef ifFalse: [self halt: 'expected only classRefs - maybe I was wrong'].
    class := classRef resolve.
    object ifNil: [ ^ 0 ].
    ^ (self canCast: object class to: class) ifTrue: [ 1 ] ifFalse: [ 0 ].

    "Created: / 19-05-2011 / 10:14:18 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

_INSTANCEOF:object _:class

    object ifNil:[^0].

    ^(self canCast: object class to: class)
        ifTrue:[1]
        ifFalse:[0]

    "Created: / 08-01-1999 / 14:52:54 / cg"
    "Modified: / 27-01-1999 / 20:56:25 / cg"
    "Modified: / 25-02-2011 / 18:31:06 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_L2D:op1
    ^ op1 asFloat

    "Created: / 8.1.1999 / 14:46:09 / cg"
!

_L2F:op1
    ^ op1 asShortFloat

    "Created: / 8.1.1999 / 14:46:18 / cg"
    "Modified: / 8.1.1999 / 14:50:18 / cg"
!

_LADD:op1 _:op2
    |sum|

    sum := (op1 + op2) bitAnd:16rFFFFFFFFFFFFFFFF.
    ^ sum

    "Created: / 8.1.1999 / 15:07:39 / cg"
!

_LAND:op1 _:op2
    |rslt|

    (op1 < 0 or:[op2 < 0]) ifTrue:[
	self halt.
    ].
    rslt := op1 bitAnd: op2.
    ^ rslt

    "Modified: / 7.1.1998 / 21:21:53 / cg"
    "Created: / 8.1.1999 / 14:54:22 / cg"
!

_LDIV:op1 _:op2
    |quo|

    quo := op1 quo: op2.
    ^ quo

    "Created: / 8.1.1999 / 15:04:47 / cg"
!

_LMUL:op1 _:op2
    |prod o1 o2 sign|

"/ self halt.
    "/ ST's largeIntegers compute a correct result;
    "/ but here, we want the overflow to flow into the
    "/ sign bit ... (sigh)

    sign := 1.
    (o1 := op1) < 0 ifTrue:[
	sign := -1.
	o1 := o1 negated.
    ].
    (o2 := op2) < 0 ifTrue:[
	sign := sign negated.
	o2 := o2 negated.
    ].

    prod := (o1 * o2) bitAnd:16rFFFFFFFFFFFFFFFF.
    (prod bitAnd:16r8000000000000000) ~~ 0 ifTrue:[
    ].
    sign == -1 ifTrue:[
	prod := prod negated
    ].
    ^ prod

    "Created: / 8.1.1999 / 15:10:04 / cg"
!

_LNEG:op
    ^ op asInteger negated

    "Created: / 8.1.1999 / 15:06:59 / cg"
!

_LOR:op1 _:op2
    |rslt|

    (op1 < 0 or:[op2 < 0]) ifTrue:[
	self halt.
    ].
    rslt := op1 bitOr: op2.
    ^ rslt

    "Created: / 8.1.1999 / 15:05:10 / cg"
!

_LREM:op1 _:op2
    |rem|

    rem := op1 rem: op2.
    ^ rem

    "Modified: / 7.1.1998 / 00:23:11 / cg"
    "Created: / 8.1.1999 / 15:04:23 / cg"
!

_LSHL:op1 _:op2
    |rslt|

    (op1 < 0) ifTrue:[
	self halt.
    ].
    rslt := (op1 bitShift:op2) bitAnd:16rFFFFFFFFFFFFFFFF.
    ^ rslt

    "Created: / 8.1.1999 / 14:51:08 / cg"
!

_LSHR:op1 _:op2
    |rslt|

    op1 < 0 ifTrue:[
	self halt
    ].

    (op1 < 0) ifTrue:[
	self halt.
    ].
    rslt := (op1 bitShift:op2 negated) bitAnd:16rFFFFFFFFFFFFFFFF.
    ^ rslt

    "Created: / 8.1.1999 / 14:51:57 / cg"
!

_LSUB:op1 _:op2
    |diff|

    diff := (op1 - op2) bitAnd:16rFFFFFFFFFFFFFFFF.
    ^ diff

    "Created: / 8.1.1999 / 15:10:33 / cg"
!

_LUSHR:op1 _:op2
    |rslt|

    op1 < 0 ifTrue:[
	self halt
    ].

    (op1 < 0) ifTrue:[
	self halt.
    ].
    rslt := (op1 bitShift:op2 negated) bitAnd:16rFFFFFFFFFFFFFFFF.
    ^ rslt

    "Modified: / 7.1.1998 / 21:22:17 / cg"
    "Created: / 8.1.1999 / 14:51:32 / cg"
!

_LXOR:op1 _:op2
    |rslt|

    (op1 < 0 or:[op2 < 0]) ifTrue:[
	self halt.
    ].
    rslt := op1 bitXor: op2.
    ^ rslt

    "Created: / 8.1.1999 / 15:12:28 / cg"
!

_MONITORENTER:someObject
    |mon thisProcess objString |

    someObject isNil ifTrue:[
        self throwNullPointerException.
        self halt.
        ^ self
    ].

    self syncMonitorCache.

    LeftMonitorObject := nil.

    thisProcess := Processor activeProcess.

    mon := self monitorFor:someObject.

    MonitorTrace ifTrue:[
        someObject isJavaClass ifTrue:[
            objString := someObject name
        ] ifFalse:[
            objString := someObject class name , '@' , someObject identityHash printString.
        ].

        ('====> entering monitor for ' , objString , ' in ' , thisProcess name , ' ...') printCR.
    ].
    mon enter.
    MonitorTrace ifTrue:[
        ('====> entered it in ' , thisProcess name , ' ...') printCR.
    ].

    (self enteredMonitorsOfProcess:thisProcess) add:someObject.

    "Created: / 08-01-1999 / 14:23:10 / cg"
    "Modified: / 08-01-1999 / 18:47:26 / cg"
    "Modified: / 10-08-2011 / 20:19:52 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_MONITOREXIT:someObject
    |mon thisProcess wasBlocked lastMon objString |

    someObject isNil ifTrue:[
        self throwNullPointerException.
        self halt.
        ^ self
    ].

    self syncMonitorCache.

    thisProcess := Processor activeProcess.

    mon := self monitorFor:someObject.

    MonitorTrace ifTrue:[
        someObject isJavaClass ifTrue:[
            objString := someObject name
        ] ifFalse:[
            objString := someObject class name , '@' , someObject identityHash printString.
        ].

        ('====> leaving monitor for ' , objString , ' in ' , thisProcess name , ' ...') printCR.
    ].
    mon exit.
    MonitorTrace ifTrue:[
        ('====> left it in ' , thisProcess name , ' ...') printCR.
    ].

    lastMon := (self enteredMonitorsOfProcess:thisProcess) removeLast.
    lastMon ~~ someObject ifTrue:[
        self halt:'oops - monitor enter/exit nesting wrong'
    ].

    wasBlocked := OperatingSystem blockInterrupts.
    mon count == 0 ifTrue:[
        LeftMonitorObject := someObject
    ].
    wasBlocked ifFalse:[ OperatingSystem unblockInterrupts ]

    "Created: / 08-01-1999 / 14:23:19 / cg"
    "Modified: / 08-01-1999 / 18:47:08 / cg"
    "Modified: / 10-08-2011 / 20:20:00 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_MULTINEW2: classRef _: dim1 
    | arr |
    classRef isJavaClassRef ifFalse: [self halt: 'expected only classRefs'].
    arr := classRef resolve new: dim1.
    ^ arr.

    "Created: / 19-05-2011 / 10:46:28 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

_MULTINEW2: classRef _: dim1 _: dim2 
    | arr |

    arr := classRef resolve new: dim2.
    1 to: dim2
        do: [:idx | arr at: idx put: (self _MULTINEW2: classRef _: dim1) ].
    ^ arr.

    "Created: / 19-05-2011 / 10:47:42 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

_MULTINEW2: classRef _: dim1 _: dim2 _: dim3 
    | arr |

    1 to: dim3
        do: 
            [:idx | 
            arr at: idx
                put: (self 
                        _MULTINEW2: classRef
                        _: dim1
                        _: dim2) ].

    
    ^ arr.

    "Created: / 19-05-2011 / 10:47:50 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

_MULTINEW:typeRef _:dim1 

    |arr|

    arr := typeRef new:dim1.

    ^ arr

    "Created: / 08-01-1999 / 14:15:42 / cg"
    "Modified: / 08-01-1999 / 18:03:05 / cg"
    "Modified: / 16-03-2011 / 16:20:18 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_MULTINEW: typeRef _: dim1 _: dim2 
    | arr |

    arr := typeRef new: dim2.
    1 to: dim2
        do: [:idx | arr at: idx put: (self _MULTINEW: typeRef javaComponentClass _: dim1) ].
    ^ arr

    "Created: / 08-01-1999 / 14:15:46 / cg"
    "Modified: / 08-01-1999 / 17:58:11 / cg"
    "Modified: / 16-03-2011 / 16:19:36 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

_MULTINEW:typeRef _:dim1 _:dim2 _:dim3 
    |clsRef cls arr elType elSizes|

    clsRef := typeRef asClassPointerRef.
    cls := clsRef javaArrayClass.
    arr := cls new:dim3.
    elType := typeRef deref.
    1 to:dim3
        do:
            [:idx | 
            arr at:idx
                put:(self 
                        _MULTINEW:elType
                        _:dim1
                        _:dim2) ].
    
"/ self halt.
    
    ^ arr

    "Modified: / 6.1.1998 / 23:34:35 / cg"
    "Created: / 8.1.1999 / 14:15:49 / cg"
! !

!JavaVM class methodsFor:'windows - events'!

awtEventsForEvent:anEvent javaWindow:jWin
    "given an ST/X event, create corresponding AWT event(s) for it"

    |jEv jEv1 jEv2
     modifiers key keyChar untranslatedKey id 
     type x y w h view menu resized moved
     eventArgs clickCount jRect
     jKeyEventClass jInputEventClass jMouseEventClass
     jWindowEventClass jPaintEventClass jComponentEventClass|

    type := anEvent type.
    eventArgs := anEvent arguments.

    key := 0.
    modifiers := 0.
    x := 0.
    y := 0.


    ((type == #'exposeX:y:width:height:') 
    or:[(type == #'graphicExposeX:y:width:height:')
    or:[(type == #damage)]]) ifTrue:[
"/        jWindowEventClass := Java classForName:'java.awt.event.WindowEvent'.
"/        id := (jPaintEventClass instVarNamed:'PAINT').

	jPaintEventClass := Java classForName:'java.awt.event.PaintEvent'.
	id := (jPaintEventClass instVarNamed:'UPDATE').

	((type == #'exposeX:y:width:height:') 
	or:[(type == #'graphicExposeX:y:width:height:')]) ifTrue:[
	    x := eventArgs at:1.
	    y := eventArgs at:2.
	    w := eventArgs at:3.
	    h := eventArgs at:4.
	] ifFalse:[
	    x := eventArgs left.
	    y := eventArgs top.
	    w := eventArgs width.
	    h := eventArgs height.
	].
	jRect := (Java classForName:'java.awt.Rectangle') basicNew.
	jRect instVarNamed:'x' put:x.
	jRect instVarNamed:'y' put:y.
	jRect instVarNamed:'width' put:w.
	jRect instVarNamed:'height' put:h.

	jEv := jPaintEventClass newCleared "basicNew".
	jEv instVarNamed:'id'        put:id.
	jEv instVarNamed:'updateRect' put:jRect.

"/        jEv instVarNamed:'g'         put:jWin.

	^ Array with:jEv.
    ].

    (anEvent isKeyEvent 
    or:[anEvent isButtonEvent
    or:[anEvent isPointerEnterLeaveEvent]]) ifTrue:[
	jInputEventClass := Java classForName:'java.awt.event.InputEvent'.

	anEvent hasAlt ifTrue:[
	    modifiers := modifiers bitOr:(jInputEventClass instVarNamed:'ALT_MASK')
	].
	anEvent hasCtrl ifTrue:[
	    modifiers := modifiers bitOr:(jInputEventClass instVarNamed:'CTRL_MASK')
	].
	anEvent hasMeta ifTrue:[
	    modifiers := modifiers bitOr:(jInputEventClass instVarNamed:'META_MASK')
	].
	anEvent hasShift ifTrue:[
	    modifiers := modifiers bitOr:(jInputEventClass instVarNamed:'SHIFT_MASK')
	].
	anEvent hasButton1 ifTrue:[
	    modifiers := modifiers bitOr:(jInputEventClass instVarNamed:'BUTTON1_MASK')
	].
	anEvent hasButton2 ifTrue:[
	    modifiers := modifiers bitOr:(jInputEventClass instVarNamed:'BUTTON2_MASK')
	].
	anEvent hasButton3 ifTrue:[
	    modifiers := modifiers bitOr:(jInputEventClass instVarNamed:'BUTTON3_MASK')
	].

	anEvent isPointerEnterLeaveEvent ifFalse:[
	    "/ ST/X does not (yet) record this information
	    "/ with pointerLeave events.

	    x := anEvent x.
	    y := anEvent y.
	].
    ].

    anEvent isKeyEvent ifTrue:[
	jKeyEventClass := Java classForName:'java.awt.event.KeyEvent'.

	key := 0.
	keyChar := 0.

	key := anEvent key.
	key isCharacter ifTrue:[
	    key := keyChar := key asciiValue
	] ifFalse:[
	    untranslatedKey := anEvent view device keyboardMap keyAtValue:key ifAbsent:key.
	    untranslatedKey == #Insert ifTrue:[
		key := jKeyEventClass instVarNamed:'VK_INSERT' 
	    ].
	    untranslatedKey == #Delete ifTrue:[
		key := jKeyEventClass instVarNamed:'VK_DELETE' "/ 127
	    ].
	    untranslatedKey == #BackSpace ifTrue:[
		key := jKeyEventClass instVarNamed:'VK_BACK_SPACE' "/ 8
	    ].
	    untranslatedKey == #Return ifTrue:[
		key := jKeyEventClass instVarNamed:'VK_ENTER' "/ 13
	    ].
	    untranslatedKey == #Tab ifTrue:[
		key := jKeyEventClass instVarNamed:'VK_TAB' "/ 9
	    ].
	    untranslatedKey == #Home ifTrue:[
		key := jKeyEventClass instVarNamed:'VK_HOME'
	    ].
	    untranslatedKey == #End ifTrue:[
		key := jKeyEventClass instVarNamed:'VK_END'
	    ].
	    (key == #PreviousPage or:[untranslatedKey == #Prior]) ifTrue:[
		key := jKeyEventClass instVarNamed:'VK_PAGE_UP'
	    ].
	    (key == #NextPage or:[key == #EndOfText]) ifTrue:[
		key := jKeyEventClass instVarNamed:'VK_PAGE_DOWN'
	    ].
	    untranslatedKey == #CursorUp ifTrue:[
		key := jKeyEventClass instVarNamed:'VK_UP'
	    ].
	    untranslatedKey == #CursorDown ifTrue:[
		key := jKeyEventClass instVarNamed:'VK_DOWN'
	    ].
	    untranslatedKey == #CursorLeft ifTrue:[
		key := jKeyEventClass instVarNamed:'VK_LEFT'
	    ].
	    untranslatedKey == #CursorRight ifTrue:[
		key := jKeyEventClass instVarNamed:'VK_RIGHT'
	    ].
	    (#( F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12)
	    includes:untranslatedKey) ifTrue:[
		key := jKeyEventClass instVarNamed:('VK_' , untranslatedKey)
	    ].
	].
	(type == #'keyPress:x:y:') ifTrue:[
	    id := jKeyEventClass instVarNamed:'KEY_PRESSED'
	] ifFalse:[
	    id := jKeyEventClass instVarNamed:'KEY_RELEASED'
	].
	jEv := jKeyEventClass newCleared "basicNew".
	jEv instVarNamed:'modifiers' put:modifiers.
	jEv instVarNamed:'keyCode'   put:key.
	jEv instVarNamed:'keyChar'   put:keyChar.
	jEv instVarNamed:'id'        put:id.
"/        jEv instVarNamed:'x'         put:x.
"/        jEv instVarNamed:'y'         put:y.
	jEv instVarNamed:'when'      put:(OperatingSystem getMillisecondTime).
	^ Array with:jEv
    ].

    (anEvent isButtonEvent 
    or:[anEvent isPointerEnterLeaveEvent]) ifTrue:[
	jMouseEventClass := Java classForName:'java.awt.event.MouseEvent'.
	clickCount := 1.

	(type == #'buttonPress:x:y:') ifTrue:[
	    id := jMouseEventClass instVarNamed:'MOUSE_PRESSED'.
	] ifFalse:[
	    (type == #'buttonRelease:x:y:') ifTrue:[
		id := jMouseEventClass instVarNamed:'MOUSE_RELEASED'.
	    ] ifFalse:[
		(type == #'buttonMotion:x:y:') ifTrue:[
		    (anEvent state bitAnd:(anEvent view device anyButtonMotionMask)) == 0 ifTrue:[
			id := jMouseEventClass instVarNamed:'MOUSE_MOVED'.
		    ] ifFalse:[
			id := jMouseEventClass instVarNamed:'MOUSE_DRAGGED'.
		    ].
		] ifFalse:[
"/                    (type == #'pointerMotion:x:y:') ifTrue:[
"/                        id := jMouseEventClass instVarNamed:'MOUSE_MOVED'.
"/                    ] ifFalse:[
			(type == #'pointerEnter:x:y:') ifTrue:[
			    id := jMouseEventClass instVarNamed:'MOUSE_ENTERED'.
			] ifFalse:[
			    (type == #'pointerLeave:') ifTrue:[
				id := jMouseEventClass instVarNamed:'MOUSE_EXITED'.
			    ] ifFalse:[
				(type == #'buttonMultiPress:x:y:') ifTrue:[
				    id := jMouseEventClass instVarNamed:'MOUSE_PRESSED'.
				    clickCount := 2.
				] ifFalse:[
				    self halt.
				]
			    ]
"/                        ]
		    ]
		]
	    ]
	].
	jEv := jMouseEventClass newCleared "basicNew".
	jEv instVarNamed:'modifiers' put:modifiers.
	jEv instVarNamed:'id'        put:id.
	jEv instVarNamed:'x'         put:x.
	jEv instVarNamed:'y'         put:y.
	jEv instVarNamed:'when'      put:(OperatingSystem getMillisecondTime).
	^ Array with:jEv
    ].


    (type == #'configureX:y:width:height:') ifTrue:[
	view := anEvent view.
	x := eventArgs at:1.
	y := eventArgs at:2.
	w := eventArgs at:3.
	h := eventArgs at:4.

	resized := (w ~~ view width or:[h ~~ view height]).
	moved :=  (x ~~ view left or:[y ~~ view top]).

"/        (view isTopView or:[view isPopUpView]) ifTrue:[
	    "/ view must update its origin/extent.
	    view dispatchEvent:anEvent.
"/        ].

	"/
	"/ must change the components extent
	"/ is there no cleaner way to do this ?
	"/
	view isTopView ifTrue:[
	    view isPopUpView ifFalse:[
		"/
		"/ sigh - don't include the menu.
		"/
		menu := self topViewsMenu:view.
		menu notNil ifTrue:[
		    "/ must add the menus height
		    h := h - menu height
		]
	    ]
	].

	jWin instVarNamed:'width' put:w.
	jWin instVarNamed:'height' put:h.
	jWin instVarNamed:'x' put:x.
	jWin instVarNamed:'y' put:y.

	jComponentEventClass := Java classForName:'java.awt.event.ComponentEvent'.
	moved ifTrue:[
	    id := (jComponentEventClass instVarNamed:'COMPONENT_MOVED').
	    jEv1 := jComponentEventClass newCleared "basicNew".
	    jEv1 instVarNamed:'id'        put:id.
	].
	resized ifTrue:[
	    id := (jComponentEventClass instVarNamed:'COMPONENT_RESIZED').
	    jEv2 := jComponentEventClass newCleared "basicNew".
	    jEv2 instVarNamed:'id'        put:id.
	].
	jEv1 isNil ifTrue:[
	    jEv2 isNil ifTrue:[^ nil].
	    ^ Array with:jEv2
	] ifFalse:[
	    jEv2 isNil ifTrue:[
		^ Array with:jEv1
	    ]
	].
	^ Array with:jEv1 with:jEv2.
    ].
    (type == #'focusIn') ifTrue:[
"/ 'focusIn' printCR.
	jComponentEventClass := Java classForName:'java.awt.event.FocusEvent'.
	id := (jComponentEventClass instVarNamed:'FOCUS_GAINED').
	jEv := jComponentEventClass newCleared "basicNew".
	jEv instVarNamed:'id'        put:id.
	^ Array with:jEv.
    ].
    (type == #'focusOut') ifTrue:[
"/ 'focusOut' printCR.
	jComponentEventClass := Java classForName:'java.awt.event.FocusEvent'.
	id := (jComponentEventClass instVarNamed:'FOCUS_LOST').
	jEv := jComponentEventClass newCleared "basicNew".
	jEv instVarNamed:'id'        put:id.
	^ Array with:jEv.
    ].
    (type == #'mapped') ifTrue:[
"/ 'mapped' printCR.
	jComponentEventClass := Java classForName:'java.awt.event.ComponentEvent'.
	id := (jComponentEventClass instVarNamed:'COMPONENT_SHOWN').
"/        x := eventArgs at:1.
"/        y := eventArgs at:2.
	jEv := jComponentEventClass newCleared "basicNew".
	jEv instVarNamed:'id'        put:id.
	^ Array with:jEv.
    ].
    (type == #'unmapped') ifTrue:[
"/ 'unmapped' printCR.
	jComponentEventClass := Java classForName:'java.awt.event.ComponentEvent'.
	id := (jComponentEventClass instVarNamed:'COMPONENT_HIDDEN').
"/        x := eventArgs at:1.
"/        y := eventArgs at:2.
	jEv := jComponentEventClass newCleared "basicNew".
	jEv instVarNamed:'id'        put:id.
	^ Array with:jEv.
    ].

    (type == #terminate) ifTrue:[
	jWindowEventClass := Java classForName:'java.awt.event.WindowEvent'.
"NEW
	id := (jWindowEventClass instVarNamed:'WINDOW_CLOSING').
"
"OLD "
	id := (jWindowEventClass instVarNamed:'WINDOW_CLOSED').
"    "
	jEv := jWindowEventClass newCleared "basicNew".
	jEv instVarNamed:'id'        put:id.
	^ Array with:jEv.
    ].

    EventTrace == true ifTrue:[
	('JAVA: unhandled event:' , type) infoPrintCR.
    ].
    ^ nil.

    "Created: / 6.1.1998 / 20:38:58 / cg"
    "Modified: / 9.1.1999 / 09:29:58 / cg"
!

delegatesTo:someOne
    ^ false

    "Created: / 25.9.1999 / 16:11:48 / cg"
!

doWindowsEventThread
    "invoked in an endless loop by the WToolkit-eventLoop
     native method."

    |sensor event more|

    (JavaWindowGroup isNil or:[KnownWindows isNil]) ifTrue:[
	"/ '*** eventThread: no windowGroup / views ...' printCR.
	self waitFor:FirstWindowCreationSemaphore state:#eventWait timeOut:nil.
	"/ Delay waitForSeconds:0.1.
	^ self
    ].

    "/ wait for an event to arrive ...

    sensor := JavaWindowGroup sensor.
    [sensor hasEvents or:[sensor damageCount ~~ 0]] whileFalse:[
	EventTrace ifTrue:[
	    '*** eventThread waiting ...' printCR.
	].
	Processor activeProcess state:#eventWait.
	self waitFor:sensor eventSemaphore state:#eventWait timeOut:nil.
    ].

    EventTrace ifTrue:[
	'*** eventThread event arrived ...' printCR.
    ].

    "/ EventTrace := true
    more := true.
    [more] whileTrue:[
	sensor hasDamage ifTrue:[
	    EventTrace ifTrue:[
		'*** eventThread: damage arrived ...' printCR.
	    ].
	    event := sensor nextDamage.
	] ifFalse:[
	    event := sensor nextEvent.
	].
	event isNil ifTrue:[
	    EventTrace == true ifTrue:[
		'*** eventThread: nil event ignored' printCR.
	    ].
	    ^ self
	].

	more := self processEvent:event
    ]

    "Created: / 6.1.1998 / 21:02:40 / cg"
    "Modified: / 30.12.1998 / 19:21:36 / cg"
!

processEvent:event
    |evQ jEvents jWToolKitClass jWToolKit jWinPeer jWin v eventConsumed|

    KnownWindows isNil ifTrue:[
	^ false
    ].

    v := event view.
    jWinPeer := self jPeerForView:v.
    jWinPeer isNil ifTrue:[
	v isJavaView ifTrue:[
	    "/ mhmh - an event for a JavaView,
	    "/ which has no peer (anyMore ?)
	    "/ should not happen.
	] ifFalse:[
	    "/ mhmh - an event for a subcomponent of an ST widget.
	    "/ let it be handled normally.
	    EventTrace ifTrue:[
		('*** eventThread: ' , event type , '-event for unknown java-view - passed to view.') printCR.
	    ].
	    event view dispatchEvent:event.
	].
	^ true
    ].

    "/ change:
    "/ in the previous version, events for ST/X widgets (i.e. buttons etc)
    "/ where not passed to java, but instead forwarded directly to the widget
    "/ by the code below.
    "/ This has changed, to pass it to Java, which eventually passes it to the
    "/ peer via the handleEvent native method (unless the event got consumed).
    "/ This is req'd to let java keep track of keyboard/mouse input for widgets.

(event isDamage and:[v isJavaView]) ifTrue:[
"/    "/ most views handle their events themself (being ST/X views) ...
"/
"/    v class ~~ JavaView ifTrue:[
"/"/        v class ~~ StandardSystemView ifTrue:[
"/"/            EventTrace ifTrue:[
"/"/                    ('*** eventThread: event handled by view itself (' , v class name , ')') printCR.
"/"/            ].
"/"/            event sendEventWithFocusOn:nil.
"/"/            ^ self.
"/"/        ].
"/        (event type == #'exposeX:y:width:height'
"/        or:[event type == #'graphicsExposeX:y:width:height']) ifTrue:[
"/            "/ send to view, but also handle in JAVA
"/            event sendEventWithFocusOn:nil.
"/        ]
"/    ].

    (#(
	#'mapped'
	#'unmapped'
	#'configureX:y:width:height:'
	#'exposeX:y:width:height:'
	#'graphicsExposeX:y:width:height:'
     ) includes:event type) ifTrue:[
	event sendEventWithFocusOn:nil.
    ].
].

    "/ what a kludge - some events are passed back to
    "/ ST via the WComponent-handleEvent native method.
    "/ However, repaints are not.
    "/ In order to let ST widgets do the drawing,
    "/ selectively filter exposeEvents from Java ...

    eventConsumed := false.
    v isJavaView ifTrue:[
	"/ all events handled by Java ...
    ] ifFalse:[
	eventConsumed := true.

	"/ let widget handle it.
	event view dispatchEvent:event.

	"/ some are not passed to Java ...
	event isDamage ifTrue:[
	    (v isKindOf:Button) ifTrue:[
		^ true
	    ].
	    (v isKindOf:TextView) ifTrue:[
		^ true
	    ].
	    (v isKindOf:Label) ifTrue:[
		^ true
	    ].
	    (v isKindOf:ComboBoxView) ifTrue:[
		^ true
	    ].
	    (v isKindOf:ScrollBar) ifTrue:[
		^ true
	    ].
	    (v isKindOf:Scroller) ifTrue:[
		^ true
	    ].
	    (v isKindOf:MenuPanel) ifTrue:[
		^ true
	    ].
	].
    ].

    jWin := jWinPeer instVarNamed:'target'.

    EventTrace ifTrue:[
	('*** eventThread: event (' , event type , ') handled by JAVA: ') infoPrint.
	jWinPeer class name infoPrint. ' (' infoPrint.
	jWin class name infoPrint. ')' infoPrintCR.
    ].

    "/ create an event

    jEvents := self awtEventsForEvent:event javaWindow:jWin.
    jEvents isNil ifTrue:[
	EventTrace ifTrue:[
	    ('*** eventThread: event ignored: ' , event type) printCR.
	].
	^ true
    ].

"/    v superView isNil ifTrue:[
"/        ('*** eventThread: event ignored for topView: ' , event type) printCR.
"/        ^ self
"/    ].

    jWToolKitClass := Java classForName:'java.awt.Toolkit'.
    "/ jWToolKit := jWToolKitClass perform:#getDefaultToolkit.
    jWToolKit := jWToolKitClass performStatic:#'getDefaultToolkit()Ljava/awt/Toolkit;'.

    jEvents do:[:jEv |
	jEv instVarNamed:'source'   put:jWin.
	jEv instVarNamed:'consumed' put:0.
	eventConsumed ifFalse:[
	    "/ the first gets the original event as data
	    jEv instVarNamed:'data' put:event.
	    eventConsumed := true
	].

	"/ post it (them) to the event queue
	EventTrace == true ifTrue:[
	    'postEvent to Java ...' printCR.
	].
	jWToolKit "class" perform:#'postEvent(Ljava/awt/AWTEvent;)V' with:jEv.
    ].

    ^ false

    "Created: / 6.1.1998 / 20:36:36 / cg"
    "Modified: / 10.12.1998 / 19:36:59 / cg"
! !

!JavaVM methodsFor:'initialization'!

systemProperties
    |props|

    (props := SystemProperties) isNil ifTrue:[
	props := SystemProperties := Dictionary new.
	self initializeSystemPropertiesInto:props.
    ].
    ^ props

    "Modified: / 3.1.1998 / 14:32:38 / cg"
    "Created: / 9.1.1999 / 14:48:22 / cg"
! !

!JavaVM::Reflection class methodsFor:'documentation'!

documentation
"
Reflection class holds information about 
which java classes are loaded, hides workarounds
allowing java classes to behave like smalltalk ones,
(remember everything is instance of some class rule?:)
allows you to access java classes by their name, 
transform ST specific objects to java alternatives
and vice versa (java string and ST string are 
undoubtely very different), manages constant
pools..

Correct me if I'm wrong, but one day this class will
be able to update constant pool and therefore 
incremental compilation of java classes.
"

    "Created: / 03-02-2011 / 00:56:27 / Marcel Hlopko <hlopik@gmail.com>"
! !

!JavaVM::Reflection class methodsFor:'instance creation'!

for: aJavaVM

    ^self new setVM: aJavaVM.

    "Created: / 21-12-2010 / 19:42:55 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

new
    "return an initialized instance"

    ^ self basicNew initialize.
! !

!JavaVM::Reflection methodsFor:'debugging'!

returnNilIfMissing
    ^ returnNilIfMissing.

    "Created: / 28-01-2011 / 15:14:37 / Marcel Hlopko <hlopik@gmail.com>"
!

returnNilIfMissing:aBoolean
    returnNilIfMissing:= aBoolean.

    "Created: / 28-01-2011 / 15:25:35 / Marcel Hlopko <hlopik@gmail.com>"
! !

!JavaVM::Reflection methodsFor:'initialization'!

initialize
    constantPoolMapping := IdentityDictionary new.
    javaClasses := Dictionary new.
    javaArrayClasses := IdentityDictionary new.
    javaMethods := IdentityDictionary new.

    "Created: / 21-12-2010 / 19:46:49 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 09-02-2011 / 00:24:28 / Marcel Hlopko <hlopik@gmail.com>"
!

setVM: aJavaVM

    "Now, aJavaVM == JavaVM (i.e, the class JavaVM 
    itself, not its instance)"

    vm := aJavaVM

    "Created: / 21-12-2010 / 19:44:07 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!JavaVM::Reflection methodsFor:'reflection - classes'!

classForJavaClassObject:aJavaClassObject

    "
        Given an instance of java.lang.Class, answers
        real (Java) class associated with it. The instance
        of java.lang.Class should be first created by myself
        (by sending #javaClassObjectForClass:)
    "

    (javaClasses at: aJavaClassObject ifAbsent:[123]) == (Java at: 'stx.libjava.tests.junir.JUnit3Tests') 
        ifTrue:[self breakPoint: #jv].


    ^ javaClasses 
        at:aJavaClassObject 
        ifAbsent:
            [vm internalError:'No class associated with given java.lang.Class!!'.
            "/Please, no nils
            self returnNilIfMissing ifTrue: nil].

    "Created: / 28-01-2011 / 15:22:39 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 05-02-2011 / 20:26:16 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

javaArrayClassObjectForClass:aClass 
    ^ javaArrayClasses at:aClass ifAbsent:[self returnNilIfMissing ifTrue:nil].

    "Created: / 28-01-2011 / 14:56:19 / Marcel Hlopko <hlopik@gmail.com>"
!

javaArrayClassObjectForClass:aClass ifAbsentPut:classOfaClass
    ^ javaArrayClasses at:aClass ifAbsentPut: classOfaClass.

    "Created: / 28-01-2011 / 14:59:21 / Marcel Hlopko <hlopik@gmail.com>"
!

javaClassObjectArrayForClasses:classes 
    "
        Answers an instance of java.lang.Class[] for given
        real (Java) classes."
    
    |array|

    array := (vm classForName:'java.lang.Class') javaArrayClass 
                new:classes size.
    classes isNilOrEmptyCollection ifTrue:[ ^ array ].
    classes 
        withIndexDo:[:cls :idx | array at:idx put:(self javaClassObjectForClass:cls) ].
    ^ array

    "Modified: / 28-01-2011 / 15:15:44 / Marcel Hlopko <hlopik@gmail.com>"
    "Created: / 04-02-2011 / 22:08:18 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 11-02-2011 / 10:21:37 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

javaClassObjectForClass:aClass 

    ^self javaClassObjectForClass:aClass init: true.

    "Modified: / 28-01-2011 / 15:15:44 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 12-08-2011 / 19:07:29 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

javaClassObjectForClass:aClass init: init 
    "
        Answers an instance of java.lang.Class for given
        real (Java) class.
    "

    | javaClassObj |

    self assert: aClass isBehavior message: 'aClass is not behavior'.
    self assert: aClass ~~ Array message: 'aClass should not be Array (old impl)'.

    javaClasses at: aClass ifPresent:[:javaClassObj|^javaClassObj].
    "/ class must be initialized (with all of its superclasses ?).
    false ifTrue:[
        aClass isJavaClass ifTrue:[aClass classInit].
    ].
    javaClassObj := (vm classForName: 'java.lang.Class') new.
    javaClasses at: aClass put: javaClassObj.
    javaClasses at: javaClassObj put: aClass.
    ^javaClassObj

    "Modified: / 28-01-2011 / 15:15:44 / Marcel Hlopko <hlopik@gmail.com>"
    "Created: / 12-08-2011 / 19:07:16 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

javaClassObjectForClassNamed: className 
    "
        Answers an instance of java.lang.Class for given
        (java) class name. The className may be name of primitive
        type, i.e. 'int', 'double'."
    
    | cls |

    cls := JavaDescriptor baseTypesByTypeName at: className
                ifAbsent: [ vm classForName: className ].
    ^ self javaClassObjectForClass: cls.

    "Created: / 03-02-2011 / 21:12:02 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 08-04-2011 / 14:45:41 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
! !

!JavaVM::Reflection methodsFor:'reflection - constant pool'!

constantPoolFor:javaConstantPoolObject 
    ^ constantPoolMapping at:javaConstantPoolObject
        ifAbsent:[self error:'Given ConstantPool was not created by JVM']

    "Created: / 21-12-2010 / 19:56:31 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-01-2011 / 14:56:54 / Marcel Hlopko <hlopik@gmail.com>"
!

javaConstantPoolObjectFor: aConstantPool

    ^constantPoolMapping at: aConstantPool ifAbsent:
        [| javaConstantPoolObject |
        javaConstantPoolObject := (vm classForName:'sun.reflect.ConstantPool') new.
        constantPoolMapping at: aConstantPool put: javaConstantPoolObject.
        constantPoolMapping at: javaConstantPoolObject put: aConstantPool.
        javaConstantPoolObject]

    "Created: / 21-12-2010 / 19:54:02 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!JavaVM::Reflection methodsFor:'reflection - methods & ctors'!

javaConstructorObjectForMethod:method 
     "given a real method, return the corresponding java.lang.reflect.Constructor
      instance for it."

    | jCtor |

    javaMethods at:method ifPresent:[:existingCtor|^existingCtor].

    jCtor := (Java classForName:'java.lang.reflect.Constructor') new.
    self javaMethodObjectLikeSlotsInto: jCtor forMethod: method.

    javaMethods at:method put: jCtor.
    javaMethods at:jCtor put:method.

    ^ jCtor

    "Created: / 09-02-2011 / 10:28:12 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 11-02-2011 / 06:44:45 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

javaMethodObjectForMethod:method 
     "given a real method, return the corresponding java.lang.reflect.Constructor
      instance for it."
     | jMethod |

    javaMethods at:method ifPresent:[:existingCtor|^existingCtor].

    jMethod := (Java classForName:'java.lang.reflect.Method') new.
    self javaMethodObjectLikeSlotsInto: jMethod forMethod: method.

    javaMethods at:method put: jMethod.
    javaMethods at:jMethod put:method.

    jMethod 
        instVarNamed: #name       put: (self javaStringObjectForString: (method selector upTo:$() interned: true);
        instVarNamed: #returnType put: (method descriptor returnClassObject);
        instVarNamed: #annotationDefault put: (method annotations default bytes);

        yourself.

    ^jMethod

    "Created: / 09-02-2011 / 10:29:46 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 03-03-2011 / 23:50:44 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

javaMethodObjectLikeSlotsInto: jMethod forMethod: method 
    "
       Fill in slots of given instance of java.lang.Method or
       java.lang.Constructor"
    
    | desc |

    desc := method descriptor.
    jMethod
        instVarNamed: #clazz put: (self javaClassObjectForClass: method javaClass);
        instVarNamed: #slot put: 0;
        instVarNamed: #modifiers put: method accessFlags;
        instVarNamed: #signature
            put: (self javaStringObjectForString: method signature interned: true);
        instVarNamed: #parameterTypes
            put: (self javaClassObjectArrayForClasses: desc parameterClasses);
        instVarNamed: #exceptionTypes
            put: (self javaClassObjectArrayForClasses: method javaExceptionTable);
        instVarNamed: #annotations put: (method annotations runtimeVisible bytes);
        yourself.
    ^ jMethod

    "Created: / 11-02-2011 / 06:44:26 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 03-03-2011 / 23:07:29 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 04-06-2011 / 17:17:04 / Marcel Hlopko <hlopkmar@fel.cvut.cz>"
!

methodForJavaConstructorObject:constructor 
     "given a java.lang.reflect.Constructor, return the corresponding method
      it."
    
    |class signature|
    class := self classForJavaClassObject:(constructor instVarNamed:#clazz).
    signature := Java as_ST_String:(constructor instVarNamed:#signature).
    class methodsDo:[:mthd|
        mthd signature = signature ifTrue:[
            ^mthd
        ].
    ].
    self error: 'No ctor found for java ctor object'

    "Created: / 09-02-2011 / 10:36:07 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 14-08-2011 / 18:36:30 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

methodForJavaMethodObject:aJavaMethodObject 
     "
         Given an instance of java.lang.reflect.Method, answers
         real method associated with it. 
    "
    |class name signature |

    class := self classForJavaClassObject:(aJavaMethodObject instVarNamed:#clazz).
    name := Java as_ST_String:(aJavaMethodObject instVarNamed:#name).
    signature := Java as_ST_String:(aJavaMethodObject instVarNamed:#signature).
    class methodsDo:[:mthd|
        (mthd name = name and:[mthd signature = signature]) ifTrue:[
            ^mthd
        ]
    ].
    self assert: false description: 'No such method, malformed java.lang.reflect.Method object?'.
    ^nil.

    "Created: / 09-02-2011 / 10:32:14 / Marcel Hlopko <hlopik@gmail.com>"
    "Modified: / 17-08-2011 / 09:50:04 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!JavaVM::Reflection methodsFor:'reflection - other'!

javaStringObjectForString:string 
    ^ self javaStringObjectForString: string interned: false

    "Created: / 09-02-2011 / 10:34:57 / Marcel Hlopko <hlopik@gmail.com>"
!

javaStringObjectForString:string interned:intern  
    | s |
    s := Java as_String: string.
    ^intern ifTrue:[Java intern: s] ifFalse:[s]

    "Modified: / 22-11-2010 / 17:57:43 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Created: / 09-02-2011 / 10:34:29 / Marcel Hlopko <hlopik@gmail.com>"
! !

!JavaVM class methodsFor:'documentation'!

version
    ^ '$Header: /cvs/stx/stx/libjava/JavaVM.st,v 1.186 2011-08-22 14:49:28 vrany Exp $'
!

version_CVS
    ^ '$Header: /cvs/stx/stx/libjava/JavaVM.st,v 1.186 2011-08-22 14:49:28 vrany Exp $'
!

version_SVN
    ^ '§Id: JavaVM.st,v 1.184 2011/08/18 18:42:48 vrany Exp §'
! !

JavaVM initialize!